diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index caa61bb773de..3441d7bb6db3 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -115,6 +115,11 @@ jobs: needs: detect uses: ./.github/workflows/uv-lockfile-check.yml + infographic-check: + name: Check no committed infographics + needs: detect + uses: ./.github/workflows/infographic-check.yml + lockfile-diff: name: package-lock.json diff needs: detect @@ -130,7 +135,10 @@ jobs: docker: name: Build&Test Docker image needs: detect - if: needs.detect.outputs.python == 'true' || needs.detect.outputs.frontend == 'true' || needs.detect.outputs.docker_meta == 'true' + # Trusted main pushes run docker.yml directly so its container-publish + # environment secrets never cross this reusable-workflow call. PR runs + # remain build/test-only and secret-free. + if: needs.detect.outputs.event_name == 'pull_request' && (needs.detect.outputs.python == 'true' || needs.detect.outputs.frontend == 'true' || needs.detect.outputs.docker_meta == 'true') uses: ./.github/workflows/docker.yml supply-chain: @@ -166,9 +174,8 @@ jobs: # whatever results are available, and upserts it via the # ```` marker. # - # The poller exits when all non-infra jobs are completed (or on - # timeout). ci-timings' review_status is picked up automatically when - # its artifact becomes available — the poller downloads and merges it. + # When the visible job set goes quiet, the poller waits 10 seconds and polls + # once more so downstream jobs created by an aggregate gate get included. # ───────────────────────────────────────────────────────────────────── comment-live: name: CI review comment (live) @@ -302,8 +309,8 @@ jobs: # report with a gantt chart + per-step breakdown. The report is uploaded # as an artifact and a markdown summary is written to $GITHUB_STEP_SUMMARY. # - # The live comment poller picks up ci-timings' completion automatically — - # it reads review-status.json from the artifact when the job finishes. + # The live comment poller can read the standalone review-status artifact + # after the HTML report is uploaded, so its link points straight at that report. # ───────────────────────────────────────────────────────────────────── ci-timings: name: CI timing report @@ -334,27 +341,46 @@ jobs: --baseline ci-timings-baseline.json \ --output ci-timings-report.html \ --json-out ci-timings.json \ - --summary-out ci-timings-summary.md \ - --review-status-out review-status.json + --summary-out ci-timings-summary.md - - name: Upload HTML report + review status + - name: Upload HTML report # Advisory report — artifact-service blips must not fail the job. continue-on-error: true uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 - id: ci-timings-artifact + id: ci-timings-html with: name: ci-timings-report - path: | - ci-timings-report.html - review-status.json + path: ci-timings-report.html + retention-days: 14 + + - name: Build linked review status + if: hashFiles('ci-timings.json') != '' + env: + CI_TIMINGS_REPORT_URL: ${{ steps.ci-timings-html.outputs.artifact-url }} + run: | + python3 scripts/ci/timings_report.py \ + --from-json ci-timings.json \ + --baseline ci-timings-baseline.json \ + --review-status-out review-status.json \ + --review-status-only + + - name: Upload review status + if: hashFiles('review-status.json') != '' + continue-on-error: true + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7 + with: + name: ci-timings-review-status + path: review-status.json retention-days: 14 - name: Output summary env: - REPORT_URL: ${{ steps.ci-timings-artifact.outputs.artifact-url}} + REPORT_URL: ${{ steps.ci-timings-html.outputs.artifact-url}} run: | - echo "# CI Timing report" >> "$GITHUB_STEP_SUMMARY" - echo "[View the full interactive report]($REPORT_URL)" >> "$GITHUB_STEP_SUMMARY" + { + echo "# CI Timing report" + echo "[View the full interactive report]($REPORT_URL)" + } >> "$GITHUB_STEP_SUMMARY" cat ci-timings-summary.md >> "$GITHUB_STEP_SUMMARY" - name: Save baseline cache (main only) diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 16165a9e64b6..6f45592f936e 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -1,8 +1,15 @@ name: Docker Build, Test, and Publish on: + # Trusted main pushes run this workflow directly so environment-scoped + # Docker Hub secrets are resolved by the top-level workflow, never across + # a reusable-workflow boundary. + push: + branches: [main] release: types: [published] + # CI calls this only for untrusted PR build/test coverage. Those runs never + # reach the protected publish or merge jobs below. workflow_call: permissions: @@ -81,6 +88,11 @@ jobs: # --------------------------------------------------------------------- - name: Install uv (for docker tests) uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0 + with: + # Pinned: unpinned setup-uv fetches a 'latest' manifest from + # raw.githubusercontent.com every job; transient fetch failures + # fail the job (2026-07-28 incident). Keep in sync with tests.yml. + version: "0.9.28" - name: Set up Python 3.11 (for docker tests) run: uv python install 3.11 diff --git a/.github/workflows/e2e-desktop.yml b/.github/workflows/e2e-desktop.yml index e9131c725224..bdaaa6d6cbb3 100644 --- a/.github/workflows/e2e-desktop.yml +++ b/.github/workflows/e2e-desktop.yml @@ -52,6 +52,11 @@ jobs: - name: Install uv uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0 with: + # Pin the uv version: unpinned, setup-uv resolves "latest" by + # fetching a manifest from raw.githubusercontent.com on EVERY job — + # a transient fetch failure fails the whole job (2026-07-28 slice-5 + # incident). Pinned, the binary downloads directly; no manifest hop. + version: "0.9.28" enable-cache: true cache-dependency-glob: | pyproject.toml diff --git a/.github/workflows/infographic-check.yml b/.github/workflows/infographic-check.yml new file mode 100644 index 000000000000..288f6f493a05 --- /dev/null +++ b/.github/workflows/infographic-check.yml @@ -0,0 +1,78 @@ +name: Infographic Check + +# Rejects PRs that commit PR-infographic images into the repo. +# +# PR infographics are rendered to an image-provider URL (fal.media) and +# embedded in the PR *description*. The PR body is the archive; the binary +# never belongs in git history. +# +# This has now leaked twice. PR #48261 removed the first batch, PR #54564 +# removed a second batch and added `infographic/` to `.gitignore` — but +# `.gitignore` only stops *accidental* `git add`. It does nothing against +# `git add -f`, and it does nothing for a path that does not literally match +# the ignore pattern. Nine more PNGs (~14MB) were committed in the four +# weeks AFTER that rule landed, plus PR #70552 caught an `infograficos/` +# spelling that sidestepped the pattern entirely. +# +# A passive ignore rule cannot enforce a policy. This check can. + +on: + workflow_call: + outputs: + review_status: + description: "JSON array of review_status objects for the synthesizer." + value: ${{ jobs.check-no-committed-infographics.outputs.review_status }} + +permissions: + contents: read + +jobs: + check-no-committed-infographics: + runs-on: ubuntu-latest + timeout-minutes: 10 + outputs: + review_status: ${{ steps.infographic-check.outputs.review_status }} + steps: + - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 + + - id: infographic-check + name: Reject committed PR-infographic images + run: | + # Match on the IMAGE, not on a directory name. Keying this to + # `infographic/` is what let `infograficos/` through in #70552 — + # any localized or typo'd directory would sidestep it again. + # Instead: find tracked raster images whose path contains an + # infographic-ish segment, in any spelling, at any depth. + # + # `docs/assets` and `website/` legitimately hold product imagery + # and are excluded; those are referenced from shipped docs pages. + OFFENDERS=$(git ls-files -z \ + | tr '\0' '\n' \ + | grep -iE '(^|/)(infograph|infograf)[^/]*/' \ + | grep -iE '\.(png|jpe?g|webp|gif)$' \ + || true) + + if [ -n "$OFFENDERS" ]; then + COUNT=$(printf '%s\n' "$OFFENDERS" | wc -l | tr -d ' ') + STATUS='[{"source":"committed infographics","results":[{"kind":"action_required","title":"PR infographic committed to the repo","summary":"Infographic images belong in the PR description, never in git.","detail":"","how_to_fix":"Untrack the image and reference the provider URL from the PR body instead:\n```\ngit rm --cached \n```\nThen put it in the PR description:\n```\n## Infographic\n\n![slug](https://)\n```\n"}]}]' + echo "review_status=${STATUS}" >> "$GITHUB_OUTPUT" + echo "" + echo "::error::${COUNT} PR-infographic image(s) are tracked in git." + echo "" + printf '%s\n' "$OFFENDERS" | sed 's/^/ /' + echo "" + echo "PR infographics are rendered to an image-provider URL and" + echo "embedded in the PR DESCRIPTION. The PR body is the archive —" + echo "the binary never enters git history." + echo "" + echo "This rule has been re-established twice already (#48261," + echo "#54564) and leaked both times, because .gitignore cannot stop" + echo "'git add -f' or a differently-spelled directory (#70552)." + echo "" + echo "To fix:" + echo " git rm --cached # keeps your local copy" + echo " # then embed the provider URL in the PR description" + exit 1 + fi + echo "::notice::No committed PR-infographic images." + echo "review_status=[]" >> "$GITHUB_OUTPUT" diff --git a/.github/workflows/js-tests.yml b/.github/workflows/js-tests.yml index 4e4622f72d04..25786b1c95b6 100644 --- a/.github/workflows/js-tests.yml +++ b/.github/workflows/js-tests.yml @@ -10,7 +10,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 20 outputs: - packages: ${{ steps.set-matrix.outputs.packages }} + checks: ${{ steps.set-matrix.outputs.checks }} steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 @@ -22,21 +22,40 @@ jobs: command: npm ci --ignore-scripts - id: set-matrix run: | - PACKAGES=$(npm query .workspace | jq -c '[.[].location]') - if [ "$PACKAGES" = "[]" ] || [ -z "$PACKAGES" ]; then - echo "::error::Workspace discovery produced an empty package list — refusing to emit a zero-length matrix (would skip all JS/TS checks silently)." - exit 1 - fi - echo "packages=$PACKAGES" >> "$GITHUB_OUTPUT" + node -e ' + const { execSync } = require("child_process"); + const pkgs = JSON.parse(execSync("npm query .workspace", { encoding: "utf-8" })); + if (pkgs.length === 0) { + console.error("::error::Workspace discovery produced an empty package list — refusing to emit a zero-length matrix (would skip all JS/TS checks silently)."); + process.exit(1); + } + const checks = []; + for (const pkg of pkgs) { + const scripts = pkg.scripts || {}; + const subs = Object.keys(scripts).filter(s => /^check:.+$/.test(s)); + if (subs.length > 0) { + for (const script of subs) { + checks.push({ package: pkg.location, script }); + } + } else if (scripts.check) { + checks.push({ package: pkg.location, script: "check" }); + } + } + if (checks.length === 0) { + console.error("::error::No check scripts found in any workspace package."); + process.exit(1); + } + process.stdout.write("checks=" + JSON.stringify(checks) + "\n"); + ' >> "$GITHUB_OUTPUT" check: - name: Typecheck & Test + name: ${{ matrix.package }} / ${{ matrix.script }} needs: workspaces runs-on: ubuntu-latest timeout-minutes: 20 strategy: matrix: - package: ${{ fromJson(needs.workspaces.outputs.packages) }} + include: ${{ fromJson(needs.workspaces.outputs.checks) }} fail-fast: false # report all failures, not just the first one steps: - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 @@ -47,5 +66,4 @@ jobs: - uses: ./.github/actions/retry with: command: npm ci - - run: npm run --prefix ${{ matrix.package }} check - - run: npm run --prefix ${{ matrix.package }} fix + - run: npm run --prefix ${{ matrix.package }} ${{ matrix.script }} diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 670b6f2a44a2..3ae120f71f31 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -40,6 +40,11 @@ jobs: - name: Install uv uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0 + with: + # Pinned: unpinned setup-uv fetches a 'latest' manifest from + # raw.githubusercontent.com every job; transient fetch failures + # fail the job (2026-07-28 incident). Keep in sync with tests.yml. + version: "0.9.28" - name: Install ruff + ty uses: ./.github/actions/retry @@ -129,6 +134,11 @@ jobs: - name: Install uv uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0 + with: + # Pinned: unpinned setup-uv fetches a 'latest' manifest from + # raw.githubusercontent.com every job; transient fetch failures + # fail the job (2026-07-28 incident). Keep in sync with tests.yml. + version: "0.9.28" - name: Install ruff uses: ./.github/actions/retry diff --git a/.github/workflows/publish-e2e-evidence.yml b/.github/workflows/publish-e2e-evidence.yml index 23c471ce2642..3d7fe32d7806 100644 --- a/.github/workflows/publish-e2e-evidence.yml +++ b/.github/workflows/publish-e2e-evidence.yml @@ -33,6 +33,8 @@ jobs: # v1.2.0 resolves to 44f4b93ecbbe22de6c45fa2f62f519aee564ca8c. - name: Install gh-image + env: + GH_TOKEN: ${{ github.token }} run: gh extension install drogers0/gh-image --pin v1.2.0 - name: Download and attach evidence diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index cdae2e037a59..bd3985121788 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -74,6 +74,11 @@ jobs: - name: Install uv uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0 with: + # Pin the uv version: unpinned, setup-uv resolves "latest" by + # fetching a manifest from raw.githubusercontent.com on EVERY job — + # a transient fetch failure fails the whole job (2026-07-28 slice-5 + # incident). Pinned, the binary downloads directly; no manifest hop. + version: "0.9.28" # Persist uv's download/wheel cache (~/.cache/uv) across runs. # Keyed on the dependency manifests, so the cache is reused until # pyproject.toml or uv.lock changes. `uv sync` still runs every @@ -188,6 +193,11 @@ jobs: - name: Install uv uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0 with: + # Pin the uv version: unpinned, setup-uv resolves "latest" by + # fetching a manifest from raw.githubusercontent.com on EVERY job — + # a transient fetch failure fails the whole job (2026-07-28 slice-5 + # incident). Pinned, the binary downloads directly; no manifest hop. + version: "0.9.28" # Persist uv's download/wheel cache (~/.cache/uv) across runs. # Keyed on the dependency manifests, so the cache is reused until # pyproject.toml or uv.lock changes. `uv sync` still runs every diff --git a/.github/workflows/uv-lockfile-check.yml b/.github/workflows/uv-lockfile-check.yml index aff4f0eb8cbd..e0ba3ea7d508 100644 --- a/.github/workflows/uv-lockfile-check.yml +++ b/.github/workflows/uv-lockfile-check.yml @@ -70,6 +70,11 @@ jobs: - name: Install uv uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # 8.2.0 + with: + # Pinned: unpinned setup-uv fetches a 'latest' manifest from + # raw.githubusercontent.com every job; transient fetch failures + # fail the job (2026-07-28 incident). Keep in sync with tests.yml. + version: "0.9.28" # `uv lock --check` re-resolves the project from pyproject.toml and # compares the result to uv.lock, exiting non-zero if they disagree. diff --git a/.gitignore b/.gitignore index 294896331045..cd05306af00b 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,8 @@ .DS_Store /venv/ /venv.old/ +/venv.stale.runtime-*/ +/.hermes-runtime/ /_pycache/ *.pyc* __pycache__/ @@ -150,6 +152,11 @@ docs/superpowers/* .update-incomplete .update-incomplete.lock +# Checkout fingerprint the __pycache__ tree was last validated against +# (launch-time stale-bytecode sweep). Runtime state, never a code change. +.bytecode-fingerprint +.bytecode-fingerprint.tmp + # Installer-written method stamp in the managed checkout root (scripts/install.sh). # Runtime metadata only — never a code change. Ignore so `git status` stays clean # and `hermes update`'s untracked autostash does not treat it as a local edit (#66189 / #54855). @@ -173,5 +180,13 @@ apps/desktop/demo/ # image-provider (fal.media) URL — they are NEVER committed to the repo. The # PR body is the archive. See the hermes-agent-dev skill's # pr-infographic-workflow reference (storage rule + lapse #8 / #COMMIT-1). +# +# Spelling variants are listed because a single `infographic/` pattern was +# sidestepped by an `infograficos/` directory (#70552). .gitignore is only +# the first line of defence and cannot stop `git add -f` at all — the +# infographic-check CI job is what actually enforces this. infographic/ +infographics/ +infograficos/ +infografico/ native/fts5_cjk/*.so diff --git a/.lazy-refresh-incomplete b/.lazy-refresh-incomplete new file mode 100644 index 000000000000..b9745a74b12f --- /dev/null +++ b/.lazy-refresh-incomplete @@ -0,0 +1,2 @@ +started=1785343166.9711895 +pid=2093896 diff --git a/AGENTS.md b/AGENTS.md index cb53e95eb0b9..d623ba59bbf1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -325,7 +325,7 @@ class AIAgent: provider: str = None, api_mode: str = None, # "chat_completions" | "codex_responses" | ... model: str = "", # empty → resolved from config/provider later - max_iterations: int = 90, # tool-calling iterations (shared with subagents) + max_iterations: int = 500, # tool-calling iterations (shared with subagents) enabled_toolsets: list = None, disabled_toolsets: list = None, quiet_mode: bool = False, diff --git a/Dockerfile b/Dockerfile index 388056faacde..6d6e9ac2d91c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,3 +1,45 @@ +# Debian 13 still ships SQLite 3.46.1, which contains the upstream WAL-reset +# corruption bug. Build a pinned shared library for the runtime image instead +# of relying on a distro backport that trixie does not currently provide. +# See #70480 and https://sqlite.org/wal.html#walresetbug. +FROM debian:13.4 AS sqlite_build +ARG SQLITE_AUTOCONF_VERSION=3530400 +ARG SQLITE_SHA256=0e9483900e92cd5de8fd48d16bf9200145a61f7fd5be542a5ac81d8a9516eb9c +RUN apt-get -o Acquire::Retries=3 update && \ + apt-get -o Acquire::Retries=3 install -y --no-install-recommends \ + build-essential ca-certificates curl && \ + rm -rf /var/lib/apt/lists/* && \ + (curl -fsSL --retry 1 --retry-all-errors --connect-timeout 15 --max-time 60 \ + -o /tmp/sqlite.tar.gz \ + "https://sqlite.org/2026/sqlite-autoconf-${SQLITE_AUTOCONF_VERSION}.tar.gz" || \ + curl -fsSL --retry 3 --retry-all-errors --connect-timeout 15 --max-time 120 \ + -o /tmp/sqlite.tar.gz \ + "https://sources.buildroot.net/sqlite/sqlite-autoconf-${SQLITE_AUTOCONF_VERSION}.tar.gz") && \ + printf '%s %s\n' "${SQLITE_SHA256}" /tmp/sqlite.tar.gz > /tmp/sqlite.sha256 && \ + sha256sum -c /tmp/sqlite.sha256 && \ + tar -xzf /tmp/sqlite.tar.gz -C /tmp && \ + cd "/tmp/sqlite-autoconf-${SQLITE_AUTOCONF_VERSION}" && \ + CFLAGS="-O2 \ + -DSQLITE_ENABLE_FTS3 \ + -DSQLITE_ENABLE_FTS3_PARENTHESIS \ + -DSQLITE_ENABLE_FTS4 \ + -DSQLITE_ENABLE_FTS5 \ + -DSQLITE_ENABLE_RTREE \ + -DSQLITE_ENABLE_GEOPOLY \ + -DSQLITE_ENABLE_COLUMN_METADATA \ + -DSQLITE_ENABLE_UNLOCK_NOTIFY \ + -DSQLITE_ENABLE_DBSTAT_VTAB \ + -DSQLITE_ENABLE_DBPAGE_VTAB \ + -DSQLITE_ENABLE_MATH_FUNCTIONS \ + -DSQLITE_ENABLE_PREUPDATE_HOOK \ + -DSQLITE_ENABLE_SESSION \ + -DSQLITE_SECURE_DELETE \ + -DSQLITE_THREADSAFE=1 \ + -DSQLITE_MAX_VARIABLE_NUMBER=250000" \ + ./configure --prefix=/opt/sqlite-fixed --disable-static && \ + make -j"$(nproc)" && \ + make install + FROM ghcr.io/astral-sh/uv:0.11.6-python3.13-trixie@sha256:b3c543b6c4f23a5f2df22866bd7857e5d304b67a564f4feab6ac22044dde719b AS uv_source # Node 22 LTS source stage. Debian trixie's bundled nodejs is pinned to 20.x # which reached EOL in April 2026 — we copy node + npm + corepack from the @@ -31,6 +73,23 @@ RUN apt-get -o Acquire::Retries=3 update && \ ca-certificates curl iputils-ping python3 python-is-python3 ripgrep ffmpeg gcc g++ make cmake python3-dev python3-venv libffi-dev libolm-dev procps git openssh-client docker-cli xz-utils && \ rm -rf /var/lib/apt/lists/* +# Prefer the fixed SQLite over Debian's vulnerable libsqlite3.so.0. Keep the +# public library name stable so both the system interpreter and the uv-created +# venv resolve the replacement without changing Python import paths. +COPY --from=sqlite_build /opt/sqlite-fixed/lib/libsqlite3.so.3.53.4 /usr/local/lib/ +RUN ln -sf libsqlite3.so.3.53.4 /usr/local/lib/libsqlite3.so.0 && \ + ln -sf libsqlite3.so.3.53.4 /usr/local/lib/libsqlite3.so && \ + printf '/usr/local/lib\n' > /etc/ld.so.conf.d/000-sqlite-fixed.conf && \ + ldconfig && \ + python3 -c "import sqlite3, sys; \ +v = sqlite3.sqlite_version_info; \ +sys.exit(f'linked SQLite {sqlite3.sqlite_version} still has the WAL-reset bug') if v < (3, 51, 3) else None; \ +db = sqlite3.connect(':memory:'); \ +db.execute(\"CREATE VIRTUAL TABLE docs USING fts5(content, tokenize='trigram')\"); \ +db.execute(\"INSERT INTO docs VALUES ('hermes')\"); \ +sys.exit('SQLite FTS5 trigram self-test failed') if db.execute(\"SELECT count(*) FROM docs WHERE docs MATCH 'erm'\").fetchone()[0] != 1 else None; \ +db.close()" + # ---------- s6-overlay install ---------- # s6-overlay provides supervision for the main hermes process, the dashboard, # and per-profile gateways. /init becomes PID 1 below — see ENTRYPOINT. @@ -141,6 +200,22 @@ RUN npm install --prefer-offline --no-audit --fetch-retries=5 && \ done && \ npm cache clean --force +# ---------- Photon iMessage sidecar deps (baked, NS-606) ---------- +# The photon plugin's Node sidecar needs its own node_modules +# (spectrum-ts). The install tree is immutable at runtime, so a lazy +# `npm ci` on first connect would hit EROFS — bake the deps here instead +# (deterministic installs, NS-559). The patch script is copied alongside +# the manifests because package.json's postinstall runs it, which also +# means the spectrum-ts patch is applied at build time. Layer-cached: +# only re-runs when the sidecar manifests/patch change. +COPY plugins/platforms/photon/sidecar/package.json \ + plugins/platforms/photon/sidecar/package-lock.json \ + plugins/platforms/photon/sidecar/patch-spectrum-mixed-attachments.mjs \ + plugins/platforms/photon/sidecar/ +RUN cd plugins/platforms/photon/sidecar && \ + npm ci --no-audit --fetch-retries=5 && \ + npm cache clean --force + # ---------- Layer-cached Python dependency install ---------- # Copy only pyproject.toml + uv.lock so the Python dep resolve + wheel # download + native-extension compile layer is cached unless those inputs @@ -152,7 +227,7 @@ RUN npm install --prefer-offline --no-audit --fetch-retries=5 && \ # frontend stats the readme path during dep resolution, so we `touch` an # empty placeholder — the real README is restored by `COPY . .` below. # -# `uv sync --frozen --no-install-project --extra all --extra messaging` +# `uv sync --frozen --no-install-project --extra all --extra messaging --extra otlp` # installs the deps reachable through the composite `[all]` extra # (handpicked set intended for the production image — excludes `[dev]`), # plus gateway messaging adapters that should work in the published image @@ -165,6 +240,10 @@ RUN npm install --prefer-offline --no-audit --fetch-retries=5 && \ # so Docker users can use these providers without requiring runtime # lazy-install access to PyPI (often blocked in containerized envs). # +# The [otlp] extra contains the SDK/exporter imported by Hermes when Gateway +# Health export is enabled. Collector and observability-backend dependencies +# remain external and are not part of the Hermes production image. +# # The hindsight memory provider's client (hindsight-client) is baked in # for the same reason: it lazy-installs into /opt/hermes/.venv at first # use, which lives inside the (immutable) image layer rather than the @@ -182,7 +261,7 @@ RUN npm install --prefer-offline --no-audit --fetch-retries=5 && \ # The editable link is created after the source copy below. COPY pyproject.toml uv.lock ./ RUN touch ./README.md -RUN uv sync --frozen --no-install-project --extra all --extra messaging --extra anthropic --extra bedrock --extra azure-identity --extra hindsight --extra matrix +RUN uv sync --frozen --no-install-project --extra all --extra messaging --extra otlp --extra anthropic --extra bedrock --extra azure-identity --extra hindsight --extra matrix # ---------- Frontend build (cached independently from Python source) ---------- # Copy only the frontend source trees first so that Python-only changes don't diff --git a/SECURITY.es.md b/SECURITY.es.md index 30b43716ebbb..086656d4f73f 100644 --- a/SECURITY.es.md +++ b/SECURITY.es.md @@ -173,9 +173,13 @@ modelo de autorización, pero las reglas a continuación se aplican uniformement **Superficies en Hermes Agent:** -- **Adaptadores de plataforma del gateway.** Integraciones de mensajería en - `gateway/platforms/` (Telegram, Discord, Slack, email, SMS, etc.) - y adaptadores análogos incluidos como plugins. +- **Adaptadores de plataforma del gateway.** La mayoría de las integraciones + de mensajería se distribuyen como plugins empaquetados en + `plugins/platforms//` (Telegram, Discord, Slack, email, SMS, etc.). + Los tipos base compartidos y un conjunto menor de adaptadores + legacy/directos viven en `gateway/platforms/` (`base.py`, Signal, servidor + API, webhooks, …), con descubrimiento y carga diferida vía + `gateway/platform_registry.py`. - **Superficies HTTP expuestas en red.** El adaptador del servidor API, el plugin del dashboard, los endpoints HTTP del plugin kanban, y cualquier otro plugin que vincule un socket de escucha. diff --git a/SECURITY.md b/SECURITY.md index 2579c6eaec56..7f5fd42db7b4 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -177,9 +177,12 @@ authorization model, but the rules below apply uniformly. **Surfaces in Hermes Agent:** -- **Gateway platform adapters.** Messaging integrations in - `gateway/platforms/` (Telegram, Discord, Slack, email, SMS, etc.) - and analogous adapters shipped as plugins. +- **Gateway platform adapters.** Most messaging integrations ship as + bundled plugins under `plugins/platforms//` (Telegram, Discord, + Slack, email, SMS, etc.). Shared base types and a smaller set of + legacy/direct adapters live under `gateway/platforms/` + (`base.py`, Signal, API server, webhooks, …), with discovery and + deferred loading via `gateway/platform_registry.py`. - **Network-exposed HTTP surfaces.** The API server adapter, the dashboard plugin, the kanban plugin's HTTP endpoints, and any other plugin that binds a listening socket. diff --git a/acp_adapter/entry.py b/acp_adapter/entry.py index 55773536122a..fb9ed95450c3 100644 --- a/acp_adapter/entry.py +++ b/acp_adapter/entry.py @@ -32,6 +32,7 @@ else: import argparse import asyncio import logging +import os import sys from pathlib import Path from hermes_constants import get_hermes_home @@ -251,11 +252,13 @@ def main(argv: list[str] | None = None) -> None: # MCP servers dynamically via asyncio.to_thread inside the event # loop; that path is unaffected.) Moved from model_tools.py module # scope to avoid freezing the gateway's loop on lazy import (#16856). - try: - from tools.mcp_tool import discover_mcp_tools - discover_mcp_tools() - except Exception: - logger.debug("MCP tool discovery failed at ACP startup", exc_info=True) + # Metadata-only hosts can opt out of unrelated global MCP startup. + if os.environ.get("HERMES_ACP_SKIP_CONFIGURED_MCP", "").strip() != "1": + try: + from tools.mcp_tool import discover_mcp_tools + discover_mcp_tools() + except Exception: + logger.debug("MCP tool discovery failed at ACP startup", exc_info=True) agent = HermesACPAgent() try: diff --git a/acp_adapter/server.py b/acp_adapter/server.py index cc19f855d9b2..7fee2d932f84 100644 --- a/acp_adapter/server.py +++ b/acp_adapter/server.py @@ -85,6 +85,110 @@ from tools.approval import ( logger = logging.getLogger(__name__) + +def _named_custom_provider_catalogs() -> list[tuple[str, str, list[tuple[str, str]]]]: + """Return ``(slug, label, [(model_id, description), ...])`` for named endpoints. + + Covers both the v12 ``providers:`` mapping and the legacy + ``custom_providers:`` list. These endpoints never appear in canonical + provider enumeration, so without this the ACP model selector hides every + named endpoint that the TUI ``/model`` picker already renders (#47039 + implemented named-endpoint rows for the TUI surface only). + + Model lists come from the entry's declared models (``default_model`` + + ``models``), refreshed from the endpoint's live ``/models`` listing when a + credential is available and ``discover_models`` is not disabled. Declared + models are kept even when live discovery fails — some OpenAI-compatible + endpoints (e.g. Bedrock Mantle Responses) expose no ``/models`` route at + all yet serve the declared models fine. + + Slugs use the ``custom:`` shape that ``parse_model_input`` and + ``resolve_runtime_provider`` already resolve, so encoded choice ids + (``custom::``) round-trip through ``set_session_model`` + unchanged. + """ + try: + from hermes_cli.config import ( + get_compatible_custom_providers, + is_provider_enabled, + load_config, + ) + from hermes_cli.models import fetch_api_models + except ImportError: + return [] + + try: + cfg = load_config() + entries = get_compatible_custom_providers(cfg) + except Exception: + logger.debug("Could not load named custom providers", exc_info=True) + return [] + + # ``get_compatible_custom_providers`` drops the ``enabled`` flag during + # normalization, so collect explicitly disabled provider keys from the + # raw config and skip their entries below. + disabled_keys: set[str] = set() + raw_providers = cfg.get("providers") if isinstance(cfg, dict) else None + if isinstance(raw_providers, dict): + for raw_key, raw_entry in raw_providers.items(): + if isinstance(raw_entry, dict) and not is_provider_enabled(raw_entry): + disabled_keys.add(str(raw_key).strip().lower()) + + catalogs: list[tuple[str, str, list[tuple[str, str]]]] = [] + for entry in entries: + if not isinstance(entry, dict): + continue + provider_key = str(entry.get("provider_key", "") or "").strip() + if provider_key.lower() in disabled_keys: + continue + name = str(entry.get("name", "") or "").strip() + base_url = str(entry.get("base_url", "") or "").strip() + if not name or not base_url: + continue + slug_source = provider_key or name + slug = "custom:" + slug_source.strip().lower().replace(" ", "-") + + api_key = str(entry.get("api_key", "") or "").strip() + if not api_key: + key_env = str(entry.get("key_env", "") or "").strip() + api_key = os.environ.get(key_env, "").strip() if key_env else "" + + declared: list[str] = [] + default_model = str(entry.get("model", "") or "").strip() + if default_model: + declared.append(default_model) + models_cfg = entry.get("models") + if isinstance(models_cfg, dict): + for mid in models_cfg: + mid = str(mid or "").strip() + if mid and mid not in declared: + declared.append(mid) + + if not api_key and not declared: + # No credential to discover with and nothing declared: + # not addressable from the selector. + continue + + model_ids = list(declared) + discover = entry.get("discover_models", True) + if isinstance(discover, str): + discover = discover.lower() not in {"false", "no", "0"} + if discover and api_key: + try: + live = fetch_api_models( + api_key, base_url, api_mode=entry.get("api_mode") + ) + except Exception: + live = None + if live: + model_ids = declared + [m for m in live if m not in declared] + + if not model_ids: + continue + catalogs.append((slug, name, [(mid, "") for mid in model_ids])) + + return catalogs + try: from hermes_cli import __version__ as HERMES_VERSION except Exception: @@ -97,6 +201,13 @@ _executor = ThreadPoolExecutor(max_workers=4, thread_name_prefix="acp-agent") # does not expose a client-side limit, so this is a fixed cap that clients # paginate against using `cursor` / `next_cursor`. _LIST_SESSIONS_PAGE_SIZE = 50 +# Per-provider cap for the ACP model selector. ACP clients (Zed, Buzz) render +# the whole `availableModels` array in one dropdown, so an unbounded +# cross-provider catalog degrades the picker. Mirrors the cap the MoA picker +# already uses (`hermes_cli/moa_cmd.py`). This bounds each provider's row, not +# the total; aggregator providers stay intentionally uncapped inside the shared +# inventory, and the current model is always kept via the fallback insert below. +ACP_MAX_MODELS_PER_PROVIDER = 200 _MAX_ACP_RESOURCE_BYTES = 512 * 1024 _TEXT_RESOURCE_MIME_PREFIXES = ("text/",) _TEXT_RESOURCE_MIME_TYPES = { @@ -585,46 +696,108 @@ class HermesACPAgent(acp.Agent): return f"{raw_provider}:{raw_model}" def _build_model_state(self, state: SessionState) -> SessionModelState | None: - """Return the ACP model selector payload for editors like Zed.""" + """Return authenticated providers and their models for ACP clients. + + The shared Hermes inventory is also used by ``hermes model``, the TUI, + and the dashboard. Keeping ACP on that substrate prevents its selector + from silently collapsing to the current provider's curated list. + """ model = str(state.model or getattr(state.agent, "model", "") or "").strip() provider = getattr(state.agent, "provider", None) or detect_provider() or "openrouter" try: - from hermes_cli.models import curated_models_for_provider, normalize_provider, provider_label + from hermes_cli.inventory import build_models_payload, load_picker_context + from hermes_cli.models import normalize_provider, provider_label normalized_provider = normalize_provider(provider) - provider_name = provider_label(normalized_provider) + context = load_picker_context().with_overrides( + current_provider=normalized_provider, + current_model=model, + current_base_url=str(getattr(state.agent, "base_url", "") or ""), + ) + payload = build_models_payload( + context, + explicit_only=True, + include_unconfigured=False, + picker_hints=False, + canonical_order=True, + pricing=False, + capabilities=False, + refresh=False, + probe_custom_providers=False, + probe_current_custom_provider=False, + max_models=ACP_MAX_MODELS_PER_PROVIDER, + ) + available_models: list[ModelInfo] = [] seen_ids: set[str] = set() - - for model_id, description in curated_models_for_provider(normalized_provider): - rendered_model = str(model_id or "").strip() - if not rendered_model: + for row in payload.get("providers") or []: + row_provider = normalize_provider(str(row.get("slug") or "").strip()) + if not row_provider: continue - choice_id = self._encode_model_choice(normalized_provider, rendered_model) - if choice_id in seen_ids: - continue - desc_parts = [f"Provider: {provider_name}"] - if description: - desc_parts.append(str(description).strip()) - if rendered_model == model: - desc_parts.append("current") - available_models.append( - ModelInfo( - model_id=choice_id, - name=rendered_model, - description=" • ".join(part for part in desc_parts if part), - ) + provider_name = str(row.get("name") or "").strip() or provider_label( + row_provider ) - seen_ids.add(choice_id) + for model_entry in row.get("models") or []: + if isinstance(model_entry, dict): + rendered_model = str( + model_entry.get("id") + or model_entry.get("model") + or model_entry.get("name") + or "" + ).strip() + else: + rendered_model = str(model_entry or "").strip() + if not rendered_model: + continue + choice_id = self._encode_model_choice(row_provider, rendered_model) + if choice_id in seen_ids: + continue + is_current = ( + row_provider == normalized_provider and rendered_model == model + ) + description = f"Provider: {provider_name}" + if is_current: + description += " • current" + available_models.append( + ModelInfo( + model_id=choice_id, + name=f"{provider_name} · {rendered_model}", + description=description, + ) + ) + seen_ids.add(choice_id) + + # Named user-defined endpoints (providers: / custom_providers:) + # are invisible to canonical provider enumeration — append them + # so editor clients can select them like the TUI /model picker. + for named_slug, named_label, named_catalog in _named_custom_provider_catalogs(): + for named_model, named_desc in named_catalog: + named_choice = self._encode_model_choice(named_slug, named_model) + if not named_choice or named_choice in seen_ids: + continue + named_parts = [f"Provider: {named_label}"] + if named_desc: + named_parts.append(str(named_desc).strip()) + if named_slug == normalized_provider and named_model == model: + named_parts.append("current") + available_models.append( + ModelInfo( + model_id=named_choice, + name=named_model, + description=" • ".join(part for part in named_parts if part), + ) + ) + seen_ids.add(named_choice) current_model_id = self._encode_model_choice(normalized_provider, model) if current_model_id and current_model_id not in seen_ids: + provider_name = provider_label(normalized_provider) available_models.insert( 0, ModelInfo( model_id=current_model_id, - name=model, + name=f"{provider_name} · {model}", description=f"Provider: {provider_name} • current", ), ) @@ -1588,7 +1761,16 @@ class HermesACPAgent(acp.Agent): clear_session_vars, set_session_vars, ) - session_tokens = set_session_vars(session_key=session_id) + # ``cwd`` pins the logical working directory for this context, + # which is what the system prompt's "Current working directory" + # line reports (agent/prompt_builder.py -> resolve_agent_cwd). + # Without it the prompt advertises the global Hermes workspace + # while the tools are rooted at the client's project, so the + # model emits absolute paths under ~/.hermes/workspace and the + # edit silently lands outside the editor's workspace. + session_tokens = set_session_vars( + session_key=session_id, cwd=state.cwd, + ) except Exception: session_tokens = None clear_session_vars = None # type: ignore[assignment] @@ -1875,8 +2057,26 @@ class HermesACPAgent(acp.Agent): if handler is None: return None # not a known command — let the LLM handle it - try: + # Slash handlers run on the event-loop thread, OUTSIDE the per-turn + # contextvars.copy_context() that pins the session cwd for the agent + # call. ``/compress`` and ``/model`` reach code that REBUILDS the + # system prompt (agent._build_system_prompt -> resolve_agent_cwd), so + # an unpinned handler bakes the Hermes install tree into the session's + # cached prompt — persisted, and therefore poisoning every later turn + # even though the turn itself is pinned. Pin inside a fresh context so + # the write can't leak into other concurrent ACP sessions and needs no + # teardown. + def _dispatch() -> str | None: + try: + from agent.runtime_cwd import set_session_cwd + + set_session_cwd(state.cwd) + except Exception: + logger.debug("Could not pin ACP session cwd for slash command", exc_info=True) return handler(args, state) + + try: + return contextvars.copy_context().run(_dispatch) except Exception as e: logger.error("Slash command /%s error: %s", cmd, e, exc_info=True) return f"Error executing /{cmd}: {e}" @@ -1936,8 +2136,8 @@ class HermesACPAgent(acp.Agent): return "No tools available." lines = [f"Available tools ({len(tools)}):"] for t in tools: - name = t.get("function", {}).get("name", "?") - desc = t.get("function", {}).get("description", "") + name = (t.get("function") or {}).get("name", "?") + desc = (t.get("function") or {}).get("description", "") # Truncate long descriptions if len(desc) > 80: desc = desc[:77] + "..." diff --git a/agent/agent_init.py b/agent/agent_init.py index a6d3b0481411..ea473632c6a5 100644 --- a/agent/agent_init.py +++ b/agent/agent_init.py @@ -69,6 +69,43 @@ def _ra(): return run_agent +def _moa_reference_output_allowed(agent: Any) -> bool: + """Keep MoA display events off only the machine-readable ``-Q`` surface.""" + return not ( + getattr(agent, "platform", None) == "cli" + and getattr(agent, "tool_progress_mode", "all") == "off" + ) + + +def _relay_moa_reference_event(agent: Any, event: str, **kwargs: Any) -> None: + """Relay MoA display events while preserving the ``-Q`` stdout contract.""" + if not _moa_reference_output_allowed(agent): + return + cb = getattr(agent, "tool_progress_callback", None) + if cb is None: + return + try: + if event == "moa.reference": + cb( + "moa.reference", + str(kwargs.get("label") or ""), + str(kwargs.get("text") or ""), + None, + moa_index=kwargs.get("index"), + moa_count=kwargs.get("count"), + ) + elif event == "moa.aggregating": + cb( + "moa.aggregating", + str(kwargs.get("aggregator") or ""), + None, + None, + moa_ref_count=kwargs.get("ref_count"), + ) + except Exception: + pass + + def _normalize_route_base_url(base_url: Any) -> str: """Canonicalize an endpoint URL for model-route identity comparisons.""" return normalize_route_base_url(base_url) @@ -81,7 +118,7 @@ def _provider_default_routes(provider: str) -> set[str]: from hermes_cli.providers import HERMES_OVERLAYS, get_provider overlay = HERMES_OVERLAYS.get(provider) - provider_def = get_provider(provider) + provider_def = get_provider(provider, allow_network=False) for value in ( getattr(overlay, "base_url_override", ""), getattr(provider_def, "base_url", ""), @@ -418,7 +455,7 @@ def init_agent( command: str = None, args: list[str] | None = None, model: str = "", - max_iterations: int = 90, # Default tool-calling iterations (shared with subagents) + max_iterations: int = 500, # Default tool-calling iterations (shared with subagents) tool_delay: float = 1.0, enabled_toolsets: List[str] = None, disabled_toolsets: List[str] = None, @@ -480,6 +517,7 @@ def init_agent( checkpoint_max_total_size_mb: int = 500, checkpoint_max_file_size_mb: int = 10, pass_session_id: bool = False, + requested_provider: str = None, ): """ Initialize the AI Agent. @@ -488,9 +526,10 @@ def init_agent( base_url (str): Base URL for the model API (optional) api_key (str): API key for authentication (optional, uses env var if not provided) provider (str): Provider identifier (optional; used for telemetry/routing hints) + requested_provider (str): Original provider identity before runtime canonicalization api_mode (str): API mode override: "chat_completions" or "codex_responses" model (str): Model name to use (default: "anthropic/claude-opus-4.6") - max_iterations (int): Maximum number of tool calling iterations (default: 90) + max_iterations (int): Maximum number of tool calling iterations (default: 500) tool_delay (float): Delay between tool calls in seconds (default: 1.0) enabled_toolsets (List[str]): Only enable tools from these toolsets (optional) disabled_toolsets (List[str]): Disable tools from these toolsets (optional) @@ -568,6 +607,11 @@ def init_agent( agent.base_url = base_url or "" provider_name = provider.strip().lower() if isinstance(provider, str) and provider.strip() else None agent.provider = provider_name or "" + agent.requested_provider = ( + requested_provider.strip().lower() + if isinstance(requested_provider, str) and requested_provider.strip() + else agent.provider + ) agent._credential_pool = credential_pool agent.acp_command = acp_command or command agent.acp_args = list(acp_args or args or []) @@ -601,6 +645,13 @@ def init_agent( # AWS Bedrock — auto-detect from provider name or base URL # (bedrock-runtime..amazonaws.com). agent.api_mode = "bedrock_converse" + elif agent.provider in {"nous", "nous-portal", "nousresearch"}: + # Portal is dual-wire: anthropic/* → Messages, everything else → + # chat_completions. Callers that already pass api_mode win above; + # this covers direct AIAgent construction without a resolved runtime. + from hermes_cli.providers import nous_api_mode + + agent.api_mode = nous_api_mode(agent.model) else: agent.api_mode = "chat_completions" @@ -779,9 +830,10 @@ def init_agent( # Anthropic prompt caching: auto-enabled for Claude models on native # Anthropic, OpenRouter, and third-party gateways that speak the # Anthropic protocol (``api_mode == 'anthropic_messages'``). Reduces - # input costs by ~75% on multi-turn conversations. Uses system_and_3 - # strategy (4 breakpoints). See ``_anthropic_prompt_cache_policy`` - # for the layout-vs-transport decision. + # input costs by ~75% on multi-turn conversations. Uses four breakpoints: + # the static system prefix, full system prompt, and last two messages + # (falling back to system-and-3 when no static prefix is available). See + # ``_anthropic_prompt_cache_policy`` for the layout-vs-transport decision. agent._use_prompt_caching, agent._use_native_cache_layout = ( agent._anthropic_prompt_cache_policy() ) @@ -835,8 +887,10 @@ def init_agent( # report cumulative micros spent. Surfaced behind HERMES_DEV_CREDITS. agent._credits_state = None agent._credits_session_start_micros = None - # Threshold-notice latch (L4): active sticky-notice keys + the warn90 crossing gate. - agent._credits_latch = {"active": set(), "seen_below_90": False, "usage_band": None} + # Threshold-notice latch (L4): active sticky-notice keys + the crossing gates. + from agent.credits_tracker import new_credits_latch + + agent._credits_latch = new_credits_latch() # OpenRouter response cache hit counter — incremented when # X-OpenRouter-Cache-Status: HIT is seen in streaming response headers. @@ -906,12 +960,6 @@ def init_agent( agent._stream_writer_tls = threading.local() agent._stream_writer_dropped = 0 - # Displayed reasoning text streamed during the current model response, - # captured only when a surface consumed it via a reasoning callback. Used - # by active-turn redirect to checkpoint what the user actually saw without - # ever persisting hidden provider reasoning. - agent._current_streamed_reasoning_text = "" - # Optional current-turn user-message override used when the API-facing # user message intentionally differs from the persisted transcript # (e.g. CLI voice mode adds a temporary prefix for the live call only). @@ -1018,49 +1066,20 @@ def init_agent( elif isinstance(effective_key, str) and len(effective_key) > 12: print(f"🔑 Using token: {effective_key[:8]}...{effective_key[-4:]}") elif agent.provider == "moa": - from agent.moa_loop import MoAClient + from agent.moa_loop import build_moa_facade agent.api_mode = "chat_completions" - # Route reference-model outputs to the agent's tool_progress_callback so + # build_moa_facade wires the reference relay that routes + # reference-model outputs to the agent's tool_progress_callback so # every surface that already consumes it (CLI spinner/scrollback, TUI, - # desktop, gateway) can show each reference's answer as a labelled block - # before the aggregator acts. The facade emits "moa.reference" and - # "moa.aggregating" events; we forward them through the same callback - # the tool lifecycle uses. Best-effort and cache-safe — these are - # display-only events, they never touch the message history. - def _moa_reference_relay(event: str, **kwargs: Any) -> None: - cb = getattr(agent, "tool_progress_callback", None) - if cb is None: - return - try: - if event == "moa.reference": - label = str(kwargs.get("label") or "") - text = str(kwargs.get("text") or "") - idx = kwargs.get("index") - count = kwargs.get("count") - cb( - "moa.reference", - label, - text, - None, - moa_index=idx, - moa_count=count, - ) - elif event == "moa.aggregating": - cb( - "moa.aggregating", - str(kwargs.get("aggregator") or ""), - None, - None, - moa_ref_count=kwargs.get("ref_count"), - ) - except Exception: - pass - - agent.client = MoAClient( - agent.model or "default", - reference_callback=_moa_reference_relay, - ) + # desktop, gateway) can show each reference's answer as a labelled + # block before the aggregator acts. The facade emits "moa.reference", + # "moa.progress", "moa.phase", and "moa.aggregating" events, forwarded + # through the same callback the tool lifecycle uses. Best-effort and + # cache-safe — display-only events, they never touch the message + # history. The factory is shared with the fallback-restore/recovery + # paths so a restored facade keeps emitting these events (#53802). + agent.client = build_moa_facade(agent, agent.model) agent._client_kwargs = {} agent.api_key = api_key or "moa-virtual-provider" agent.base_url = "moa://local" @@ -1139,6 +1158,10 @@ def init_agent( elif base_url_host_matches(effective_base, "chatgpt.com"): from agent.auxiliary_client import _codex_cloudflare_headers client_kwargs["default_headers"] = _codex_cloudflare_headers(api_key) + elif base_url_host_matches(effective_base, "x.ai"): + from tools.xai_http import hermes_xai_default_headers + + client_kwargs["default_headers"] = hermes_xai_default_headers() elif "default_headers" not in client_kwargs: # Fall back to profile.default_headers for providers that # declare custom headers (e.g. Kimi User-Agent on non-kimi.com @@ -1326,6 +1349,13 @@ def init_agent( print("⚠️ Warning: API key appears invalid or missing") except Exception as e: raise RuntimeError(f"Failed to initialize OpenAI client: {e}") + + # Keep a stable identity for the pool entry that supplied this runtime. + # OAuth refreshes can replace the runtime token before a failed request is + # recovered, so the mutable API-key value alone cannot reliably attribute + # the failure to its source entry. + from agent.agent_runtime_helpers import sync_credential_pool_entry_id + sync_credential_pool_entry_id(agent) # Provider fallback chain — ordered list of backup providers tried # when the primary is exhausted (rate-limit, overload, connection @@ -1472,6 +1502,9 @@ def init_agent( # Cached system prompt -- built once per session, only rebuilt on compression agent._cached_system_prompt: Optional[str] = None + # Cross-session-stable prefix of the cached prompt. It remains separate + # from the persisted string and is used only to place an early cache marker. + agent._cached_system_prompt_static: Optional[str] = None # Filesystem checkpoint manager (transparent — not a tool) from tools.checkpoint_manager import CheckpointManager @@ -1803,6 +1836,28 @@ def init_agent( compression_enabled = str(_compression_cfg.get("enabled", True)).lower() in {"true", "1", "yes"} compression_target_ratio = float(_compression_cfg.get("target_ratio", 0.20)) compression_protect_last = int(_compression_cfg.get("protect_last_n", 20)) + # Minimum REAL (actionable) user messages guaranteed to survive in the + # uncompressed tail (compression.min_tail_user_messages). Default 1 + # preserves current behavior exactly — the existing single-user tail + # anchor. Values > 1 extend the guarantee to the last N actionable + # user turns. Booleans rejected (bool subclasses int), non-int-like + # values fall back to 1, floor at 1. + _raw_min_tail_users = _compression_cfg.get("min_tail_user_messages", 1) + if isinstance(_raw_min_tail_users, bool): + compression_min_tail_users = 1 + elif isinstance(_raw_min_tail_users, int): + compression_min_tail_users = _raw_min_tail_users + elif isinstance(_raw_min_tail_users, float): + compression_min_tail_users = ( + int(_raw_min_tail_users) if _raw_min_tail_users.is_integer() else 1 + ) + else: + try: + compression_min_tail_users = int(str(_raw_min_tail_users).strip()) + except (TypeError, ValueError): + compression_min_tail_users = 1 + if compression_min_tail_users < 1: + compression_min_tail_users = 1 # Cap on compression retry rounds before a turn gives up with "max # compression attempts reached" (compression.max_attempts). Hardcoding 3 # strands sessions that legitimately need more rounds — e.g. a restart @@ -1831,6 +1886,39 @@ def init_agent( if compression_max_attempts < 1: compression_max_attempts = 3 compression_max_attempts = min(compression_max_attempts, 10) + + def _parse_prune_int(raw, default): + # Same parser semantics as compression.max_attempts above: reject + # booleans (bool subclasses int — YAML `true` would coerce to 1), + # reject fractional floats rather than truncating them, accept + # integral floats and numeric strings, fall back to the default on + # anything else. + if isinstance(raw, bool): + return default + if isinstance(raw, int): + return raw + if isinstance(raw, float): + return int(raw) if raw.is_integer() else default + try: + return int(str(raw).strip()) + except (TypeError, ValueError): + return default + + # Opt-in proactive tool-result prune trigger (0 = disabled — the + # default, so an unset key is behavior-neutral). Negative values are + # treated as disabled rather than erroring. + compression_proactive_prune_tokens = max( + 0, _parse_prune_int(_compression_cfg.get("proactive_prune_tokens", 0), 0) + ) + compression_proactive_prune_min_chars = _parse_prune_int( + _compression_cfg.get("proactive_prune_min_result_chars", 8000), 8000 + ) + compression_proactive_prune_min_reclaim = max( + 0, + _parse_prune_int( + _compression_cfg.get("proactive_prune_min_reclaim_tokens", 4096), 4096 + ), + ) # protect_first_n is the number of non-system messages to protect at # the head, in addition to the system prompt (which is always # implicitly protected by the compressor). Floor at 0 — a value of @@ -1871,8 +1959,12 @@ def init_agent( # parent_session_id chain, no `name #N` renumber). See #38763 and # agent/conversation_compression.py. Consumed by compress_context(), not the # compressor, so it rides on the agent. + # Default True must match DEFAULT_CONFIG["compression"]["in_place"] + # (#38763). default=False here previously flipped agents into rotation + # mode whenever the merged config omitted the key (partial configs, + # load_config failure → {}), re-arming the pre-lease drift abort. compression_in_place = is_truthy_value( - _compression_cfg.get("in_place"), default=False + _compression_cfg.get("in_place"), default=True ) codex_app_server_auto_compaction = str( _compression_cfg.get("codex_app_server_auto", "native") or "native" @@ -2186,7 +2278,18 @@ def init_agent( # AFTER the custom_providers branch so per-model overrides aren't lost. agent._config_context_length = _config_context_length - agent._ensure_lmstudio_runtime_loaded(_config_context_length) + _lmstudio_runtime_context_length = agent._ensure_lmstudio_runtime_loaded( + _config_context_length + ) + if agent._lmstudio_load_was_unverified(_lmstudio_runtime_context_length): + _ra().logger.warning( + "LM Studio model activation was rejected or completed without a " + "verifiable active context length; falling back to configured context" + ) + _effective_context_length = agent._effective_lmstudio_context_length( + _config_context_length, + _lmstudio_runtime_context_length, + ) @@ -2263,7 +2366,7 @@ def init_agent( agent.model, base_url=agent.base_url, api_key=getattr(agent, "api_key", ""), - config_context_length=_config_context_length, + config_context_length=_effective_context_length, provider=agent.provider, custom_providers=_custom_providers, ) @@ -2298,13 +2401,17 @@ def init_agent( quiet_mode=agent.quiet_mode, base_url=agent.base_url, api_key=getattr(agent, "api_key", ""), - config_context_length=_config_context_length, + config_context_length=_effective_context_length, provider=agent.provider, api_mode=agent.api_mode, abort_on_summary_failure=compression_abort_on_summary_failure, max_tokens=agent.max_tokens, model_thresholds=compression_model_thresholds, threshold_tokens_cap=compression_threshold_tokens, + proactive_prune_tokens=compression_proactive_prune_tokens, + proactive_prune_min_result_chars=compression_proactive_prune_min_chars, + proactive_prune_min_reclaim_tokens=compression_proactive_prune_min_reclaim, + min_tail_user_messages=compression_min_tail_users, ) _bind_session_state = getattr(agent.context_compressor, "bind_session_state", None) if callable(_bind_session_state): @@ -2323,7 +2430,13 @@ def init_agent( # Reject models whose context window is below the minimum required # for reliable tool-calling workflows (64K tokens). _ctx = getattr(agent.context_compressor, "context_length", 0) - if _ctx and _ctx < MINIMUM_CONTEXT_LENGTH: + _allow_lmstudio_explicit_below_floor = ( + str(getattr(agent, "provider", "") or "").strip().lower() == "lmstudio" + and isinstance(agent._config_context_length, int) + and not isinstance(agent._config_context_length, bool) + and agent._config_context_length > 0 + ) + if _ctx and _ctx < MINIMUM_CONTEXT_LENGTH and not _allow_lmstudio_explicit_below_floor: raise ValueError( f"Model {agent.model} has a context window of {_ctx:,} tokens, " f"which is below the minimum {MINIMUM_CONTEXT_LENGTH:,} required " @@ -2569,6 +2682,7 @@ def init_agent( agent._primary_runtime = { "model": agent.model, "provider": agent.provider, + "requested_provider": agent.requested_provider, "base_url": agent.base_url, "api_mode": agent.api_mode, "api_key": getattr(agent, "api_key", ""), diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py index 263cf1563a27..1b592c206986 100644 --- a/agent/agent_runtime_helpers.py +++ b/agent/agent_runtime_helpers.py @@ -249,12 +249,42 @@ def sanitize_tool_call_arguments( *, logger=None, session_id: str = None, + cursor: Optional[dict] = None, ) -> int: - """Repair corrupted assistant tool-call argument JSON in-place.""" + """Repair corrupted assistant tool-call argument JSON in-place. + + ``cursor`` (optional) is a caller-owned dict used to skip re-validating + messages already validated on a previous call. It stores, under + ``"prefix"``, the exact message *objects* (strong references) validated + last time, in order. On the next call, the longest contiguous prefix of + ``messages`` whose objects are ``is``-identical to the stored prefix is + skipped; scanning starts at the first divergence (conservative: any + reordering, truncation, compression rewrite, or mid-list insertion breaks + identity at that index and everything from there is re-scanned). + + Safety argument for skipping: a message in the matched prefix was fully + scanned before — every tool_call argument was either already valid JSON + or was rewritten to ``"{}"`` (valid). The only code paths that mutate + ``function["arguments"]`` on live history dicts between calls are the + surrogate / non-ASCII sanitizers, which substitute characters *inside* + JSON string values and cannot invalidate JSON syntax. Compression, + repair, undo, and steer paths replace or reorder message dicts, which + breaks the identity match and forces a re-scan. Holding strong + references (the objects themselves, not ``id()``s) makes address reuse + aliasing (#50372-style) impossible. + """ log = logger or logging.getLogger(__name__) if not isinstance(messages, list): return 0 + start_index = 0 + if cursor is not None: + prev_prefix = cursor.get("prefix") + if isinstance(prev_prefix, list): + limit = min(len(prev_prefix), len(messages)) + while start_index < limit and messages[start_index] is prev_prefix[start_index]: + start_index += 1 + repaired = 0 marker = _ra().AIAgent._TOOL_CALL_ARGUMENTS_CORRUPTION_MARKER @@ -275,7 +305,7 @@ def sanitize_tool_call_arguments( existing_text = str(existing) tool_msg["content"] = f"{marker}\n{existing_text}" - message_index = 0 + message_index = start_index while message_index < len(messages): msg = messages[message_index] if not isinstance(msg, dict) or msg.get("role") != "assistant": @@ -356,6 +386,12 @@ def sanitize_tool_call_arguments( message_index += 1 + if cursor is not None: + # Strong references to the exact objects validated this call, in + # order. Any future divergence (compression, undo, repair, steer) + # breaks identity at the divergent index and re-scans from there. + cursor["prefix"] = messages[:] + return repaired @@ -850,6 +886,25 @@ def strip_think_blocks(agent, content: str) -> str: +def sync_credential_pool_entry_id(agent) -> None: + """Rebind ``agent._credential_pool_entry_id`` from the current pool + key. + + OAuth refreshes can replace the runtime token before a failed request is + recovered, so the mutable API-key value alone cannot reliably attribute + the failure to its source entry. This resolves the stable pool-entry ID + for the agent's current ``api_key`` and clears it when no pool is bound. + """ + pool = getattr(agent, "_credential_pool", None) + try: + agent._credential_pool_entry_id = ( + pool.entry_id_for_api_key(getattr(agent, "api_key", None)) + if pool is not None + else None + ) + except Exception: + agent._credential_pool_entry_id = None + + def recover_with_credential_pool( agent, *, @@ -922,6 +977,43 @@ def recover_with_credential_pool( ) return False, has_retried_429 + # Attribute the failure to the API key the agent actually dispatched the + # request with, not to pool.current(). The current() pointer is shared, + # mutable state — round-robin select() advances it on every call, and + # concurrent turns or a second process (gateway/dashboard) reloading the + # pool reset it to None — so by the time recovery runs it routinely points + # at a DIFFERENT, healthy entry. Marking that entry exhausted copies this + # request's error/reset time onto it and can take the whole pool offline + # from a single rate-limited key (#43747). ``_swap_credential`` keeps + # ``agent.api_key`` in sync with the entry in use, so it identifies the + # failing entry exactly; fall back to current()'s key only when the agent + # carries no key at all. + _api_key_hint = getattr(agent, "api_key", None) or None + _raw_credential_id = getattr(agent, "_credential_pool_entry_id", None) + _credential_id = ( + _raw_credential_id + if isinstance(_raw_credential_id, str) and _raw_credential_id + else None + ) + if not _api_key_hint: + _cur = pool.current() + if _cur: + _api_key_hint = getattr(_cur, "runtime_api_key", None) + if not _credential_id: + _current_id = getattr(_cur, "id", None) + if isinstance(_current_id, str) and _current_id: + _credential_id = _current_id + + def _rotate_failed_credential(rotate_status: int): + kwargs = { + "status_code": rotate_status, + "error_context": error_context, + "api_key_hint": _api_key_hint, + } + if _credential_id: + kwargs["credential_id"] = _credential_id + return pool.mark_exhausted_and_rotate(**kwargs) + effective_reason = classified_reason if effective_reason is None: if status_code == 402: @@ -952,14 +1044,10 @@ def recover_with_credential_pool( if effective_reason == FailoverReason.billing: rotate_status = status_code if status_code is not None else 402 - next_entry = pool.mark_exhausted_and_rotate( - status_code=rotate_status, - error_context=error_context, - # Runtime credentials can be resolved by a separate pool instance, - # leaving this recovery pool without ``current_id``. Match the key - # that actually failed instead of quarantining a different account. - api_key_hint=getattr(agent, "api_key", None), - ) + # Runtime credentials can be resolved by a separate pool instance, + # leaving this recovery pool without ``current_id``. Match the key + # that actually failed instead of quarantining a different account. + next_entry = _rotate_failed_credential(rotate_status) if next_entry is not None: _ra().logger.info( "Credential %s (billing) — rotated to pool entry %s", @@ -975,7 +1063,21 @@ def recover_with_credential_pool( # rotate immediately. This prevents the "cancel-between-429s" trap # where has_retried_429 (a local var) gets reset on each new prompt, # causing the pool to retry the same exhausted credential forever. - current_entry = pool.current() + # Prefer the entry matching the failing key over the shared current() + # pointer, for the same attribution reason as above. + current_entry = None + if _credential_id: + current_entry = next( + (e for e in pool.entries() if e.id == _credential_id), + None, + ) + if _api_key_hint: + current_entry = current_entry or next( + (e for e in pool.entries() if e.runtime_api_key == _api_key_hint), + None, + ) + if current_entry is None: + current_entry = pool.current() current_last_status = getattr(current_entry, "last_status", None) if current_entry else None if current_last_status == STATUS_EXHAUSTED: _ra().logger.info( @@ -983,7 +1085,7 @@ def recover_with_credential_pool( current_last_status, ) rotate_status = status_code if status_code is not None else 429 - next_entry = pool.mark_exhausted_and_rotate(status_code=rotate_status, error_context=error_context) + next_entry = _rotate_failed_credential(rotate_status) if next_entry is not None: _ra().logger.info( "Credential %s (rate limit, pre-exhausted) — rotated to pool entry %s", @@ -1007,7 +1109,7 @@ def recover_with_credential_pool( if not has_retried_429 and not usage_limit_reached: return False, True rotate_status = status_code if status_code is not None else 429 - next_entry = pool.mark_exhausted_and_rotate(status_code=rotate_status, error_context=error_context) + next_entry = _rotate_failed_credential(rotate_status) if next_entry is not None: _ra().logger.info( "Credential %s (rate limit) — rotated to pool entry %s", @@ -1022,7 +1124,7 @@ def recover_with_credential_pool( # Subscription/entitlement 403s look like auth failures on the wire # but refresh cannot fix them — the OAuth token is already valid, # the account simply lacks the entitlement. Without this guard, - # ``try_refresh_current()`` keeps minting fresh tokens against the + # the refresh path keeps minting fresh tokens against the # same unsubscribed account and the main agent loop spins re-issuing # the same 403 until the user Ctrl+C's. # @@ -1075,9 +1177,16 @@ def recover_with_credential_pool( agent.provider or "provider", ) return False, has_retried_429 - refreshed = pool.try_refresh_current() + # Refresh the entry that supplied the failing key, not current(): + # the shared pointer can reference a different, healthy entry, and + # refreshing it would consume that entry's single-use refresh token + # (or mark it exhausted on failure) for a failure it never had. + refresh_kwargs = {"api_key_hint": _api_key_hint} + if _credential_id: + refresh_kwargs["credential_id"] = _credential_id + refreshed = pool.try_refresh_matching(**refresh_kwargs) if refreshed is not None: - # ``try_refresh_current()`` re-mints a fresh OAuth token and reports + # ``try_refresh_matching()`` re-mints a fresh OAuth token and reports # success even when the upstream keeps rejecting it — a single-entry # pool (common for OAuth/Max subscribers) has nothing to rotate to, # so a bare "refreshed → retry" loop spins forever on the same dead @@ -1105,9 +1214,9 @@ def recover_with_credential_pool( agent._swap_credential(refreshed) return True, has_retried_429 # Refresh failed — rotate to next credential instead of giving up. - # The failed entry is already marked exhausted by try_refresh_current(). + # The failed entry is already marked exhausted by the refresh attempt. rotate_status = status_code if status_code is not None else 401 - next_entry = pool.mark_exhausted_and_rotate(status_code=rotate_status, error_context=error_context) + next_entry = _rotate_failed_credential(rotate_status) if next_entry is not None: _ra().logger.info( "Credential %s (auth refresh failed) — rotated to pool entry %s", @@ -1148,15 +1257,29 @@ def try_recover_primary_transport( if agent._is_openrouter_url(): return False provider_lower = (agent.provider or "").strip().lower() - if provider_lower in {"nous", "nous-research"}: + # Portal OpenAI-wire traffic still rides aggregator retry infra, so one + # more rebuilt OpenAI client won't help. Portal Claude on the native + # Messages route holds a local Anthropic SDK client whose connection + # pool *does* need the rebuild every other anthropic_messages provider + # already gets — don't blanket-skip the dual-wire path. + if ( + provider_lower in {"nous", "nous-portal", "nousresearch"} + and getattr(agent, "api_mode", None) != "anthropic_messages" + ): return False try: - # Close existing client to release stale connections + # Retire the existing client to release stale connections. #70773: + # never hard-close the shared client here — this runs on the + # conversation-loop thread while workers from stale-killed streaming + # attempts may still be unwinding their SSL BIOs on the old pool. + # ``_retire_shared_openai_client`` shuts the sockets down (FD-safe + # from any thread) and defers the FD release to GC, which cannot + # complete until every borrowing thread has unwound. if getattr(agent, "client", None) is not None: try: - agent._close_openai_client( - agent.client, reason="primary_recovery", shared=True, + agent._retire_shared_openai_client( + agent.client, reason="primary_recovery", ) except Exception: pass @@ -1166,6 +1289,7 @@ def try_recover_primary_transport( agent._client_kwargs = dict(rt["client_kwargs"]) agent.model = rt["model"] agent.provider = rt["provider"] + agent.requested_provider = rt.get("requested_provider", agent.provider) agent.base_url = rt["base_url"] agent.api_mode = rt["api_mode"] if hasattr(agent, "_transport_cache"): @@ -1182,6 +1306,14 @@ def try_recover_primary_transport( ) agent._is_anthropic_oauth = rt["is_anthropic_oauth"] agent.client = None + elif (agent.provider or "").strip().lower() == "moa": + # MoA is a virtual provider with empty client_kwargs — rebuilding + # via _create_openai_client would raise "api_key client option + # must be set". Recreate the facade through the shared factory so + # the reference_callback relay survives recovery (#53802). + from agent.moa_loop import build_moa_facade + + agent.client = build_moa_facade(agent, agent.model) else: agent.client = agent._create_openai_client( dict(rt["client_kwargs"]), @@ -1329,6 +1461,7 @@ def restore_primary_runtime(agent) -> bool: # ── Core runtime state ── agent.model = rt["model"] agent.provider = rt["provider"] + agent.requested_provider = rt.get("requested_provider", agent.provider) agent.base_url = rt["base_url"] # setter updates _base_url_lower agent.api_mode = rt["api_mode"] if hasattr(agent, "_transport_cache"): @@ -1344,7 +1477,18 @@ def restore_primary_runtime(agent) -> bool: ) # ── Rebuild client for the primary provider ── - if agent.api_mode == "anthropic_messages": + if agent.provider == "moa": + # MoA is a virtual chat-completions provider. It never has real + # OpenAI client kwargs; restoring it after a fallback must recreate + # the facade, not call OpenAI() with an empty api_key. Use the + # shared factory so the restored facade keeps the reference_callback + # relay wired at init — a bare MoAClient() would silently stop + # emitting moa.reference/moa.aggregating display events (#53802). + from agent.moa_loop import build_moa_facade + + agent.client = build_moa_facade(agent, agent.model) + agent._anthropic_client = None + elif agent.api_mode == "anthropic_messages": from agent.anthropic_adapter import build_anthropic_client agent._anthropic_api_key = rt["anthropic_api_key"] agent._anthropic_base_url = rt["anthropic_base_url"] @@ -1397,6 +1541,7 @@ def restore_primary_runtime(agent) -> bool: pool_matches_primary = False if pool is not None and pool_provider and not pool_matches_primary: agent._credential_pool = None + agent._credential_pool_entry_id = None try: from agent.credential_pool import load_pool @@ -1416,6 +1561,7 @@ def restore_primary_runtime(agent) -> bool: # the pool for its current best entry and swap the live credential in. # When the pool is absent, empty, or the entry has no usable key, we # keep the snapshot key (the existing behavior). Fixes #25205. + agent._credential_pool_entry_id = None pool = getattr(agent, "_credential_pool", None) if pool is not None and pool.has_available(): entry = pool.select() @@ -1793,7 +1939,15 @@ def anthropic_prompt_cache_policy( if is_native_anthropic: return True, True - if (is_openrouter or is_nous_portal) and (is_claude or is_kimi): + # Envelope layout is an OpenAI-wire construct. Portal Claude on the native + # Messages route must fall through to the third-party anthropic_messages + # branch below, which emits inner-block cache_control breakpoints; the + # envelope form would be dropped and serve 0% cache hits. + if ( + (is_openrouter or is_nous_portal) + and (is_claude or is_kimi) + and not is_anthropic_wire + ): return True, False # Nous Portal Qwen (e.g. qwen3.6-plus) takes the same envelope-layout # cache_control path as Portal Claude. Portal proxies to OpenRouter @@ -1957,8 +2111,11 @@ def switch_model(agent, new_model, new_provider, api_key='', base_url='', api_mo from hermes_cli.providers import determine_api_mode # ── Determine api_mode if not provided ── + # Pass model so dual-wire providers (Nous Portal anthropic/* → Messages) + # resolve correctly; without it determine_api_mode falls back to the + # openai_chat overlay default. if not api_mode: - api_mode = determine_api_mode(new_provider, base_url) + api_mode = determine_api_mode(new_provider, base_url, model=new_model) # Defense-in-depth: ensure OpenCode base_url doesn't carry a trailing # /v1 into the anthropic_messages client, which would cause the SDK to @@ -1993,6 +2150,7 @@ def switch_model(agent, new_model, new_provider, api_key='', base_url='', api_mo for name in ( "model", "provider", + "requested_provider", "base_url", "api_mode", "api_key", @@ -2011,6 +2169,19 @@ def switch_model(agent, new_model, new_provider, api_key='', base_url='', api_mo # restore the original pool (issue #52727: pool reload is part of this # switch and must be reversible on rollback). _snapshot["_credential_pool"] = getattr(agent, "_credential_pool", _MISSING) + _snapshot["_credential_pool_entry_id"] = getattr( + agent, "_credential_pool_entry_id", _MISSING + ) + + def _restore_snapshot() -> None: + for _name, _value in _snapshot.items(): + if _value is _MISSING: + # Attribute did not exist before the swap — don't fabricate it. + continue + try: + setattr(agent, _name, _value) + except Exception: # noqa: BLE001 + pass try: # Clear the per-config context_length override so the new model's @@ -2021,6 +2192,7 @@ def switch_model(agent, new_model, new_provider, api_key='', base_url='', api_mo # ── Swap core runtime fields ── agent.model = new_model agent.provider = new_provider + agent.requested_provider = new_provider # Use the new base_url when provided. When it's empty AND the # provider is actually changing, do NOT fall back to the current # (old provider's) URL — that silently pairs the new provider label @@ -2066,6 +2238,7 @@ def switch_model(agent, new_model, new_provider, api_key='', base_url='', api_mo # A pool bound to the old provider is worse than no pool: the # recovery guard rejects it and every later 401/429 skips rotation. agent._credential_pool = None + agent._credential_pool_entry_id = None try: from agent.credential_pool import load_pool agent._credential_pool = load_pool(new_provider) @@ -2075,10 +2248,9 @@ def switch_model(agent, new_model, new_provider, api_key='', base_url='', api_mo "continuing without pool rotation this turn", new_provider, _pool_exc, ) - # ── Build new client ── if (new_provider or "").strip().lower() == "moa": - from agent.moa_loop import MoAClient + from agent.moa_loop import build_moa_facade # The MoA virtual provider speaks only chat.completions via the # MoAClient facade — the aggregator's real transport @@ -2095,7 +2267,7 @@ def switch_model(agent, new_model, new_provider, api_key='', base_url='', api_mo agent.api_key = api_key or "moa-virtual-provider" agent.base_url = "moa://local" agent._client_kwargs = {} - agent.client = MoAClient(agent.model or "default") + agent.client = build_moa_facade(agent, agent.model) elif api_mode == "anthropic_messages": from agent.anthropic_adapter import ( build_anthropic_client, @@ -2171,22 +2343,50 @@ def switch_model(agent, new_model, new_provider, api_key='', base_url='', api_mo reason="switch_model", shared=True, ) + + sync_credential_pool_entry_id(agent) except Exception: # Rollback every mutated field to the pre-swap snapshot so the agent # is left consistent (old model + old provider + old client) and the # caller's exception handler can surface a meaningful warning. The # exception is re-raised; cli.py / gateway/run.py / tui_gateway catch # it and print "Agent swap failed; change applied to next session". - for _name, _value in _snapshot.items(): - if _value is _MISSING: - # Attribute did not exist before the swap — don't fabricate it. - continue - try: - setattr(agent, _name, _value) - except Exception: # noqa: BLE001 - pass + _restore_snapshot() raise + # ── LM Studio: preload before probing context length ── + _sm_custom_providers = None + try: + from hermes_cli.config import ( + get_compatible_custom_providers, + get_custom_provider_context_length, + load_config, + ) + + _sm_cfg = load_config() + _sm_custom_providers = get_compatible_custom_providers(_sm_cfg) + _destination_context_intent = get_custom_provider_context_length( + model=agent.model, + base_url=agent.base_url, + custom_providers=_sm_custom_providers, + ) + except Exception: + _destination_context_intent = None + agent._config_context_length = _destination_context_intent + _runtime_context_length = agent._ensure_lmstudio_runtime_loaded( + _destination_context_intent + ) + if agent._lmstudio_load_was_unverified(_runtime_context_length): + logger.warning( + "LM Studio model activation was rejected or completed without a " + "verifiable active context length during model switch; continuing " + "with configured context" + ) + _effective_context_length = agent._effective_lmstudio_context_length( + _destination_context_intent, + _runtime_context_length, + ) + # ── Re-evaluate prompt caching ── agent._use_prompt_caching, agent._use_native_cache_layout = ( agent._anthropic_prompt_cache_policy( @@ -2197,22 +2397,15 @@ def switch_model(agent, new_model, new_provider, api_key='', base_url='', api_mo ) ) - # ── LM Studio: preload before probing context length ── - agent._ensure_lmstudio_runtime_loaded() - # ── Update context compressor ── if hasattr(agent, "context_compressor") and agent.context_compressor: from agent.model_metadata import get_model_context_length - # Re-read custom_providers from live config so per-model - # context_length overrides are honored when switching to a - # custom provider mid-session (closes #15779). - _sm_custom_providers = None - try: - from hermes_cli.config import load_config, get_compatible_custom_providers - _sm_cfg = load_config() - _sm_custom_providers = get_compatible_custom_providers(_sm_cfg) - except Exception: - _sm_custom_providers = None + if _sm_custom_providers is None: + try: + from hermes_cli.config import get_compatible_custom_providers, load_config + _sm_custom_providers = get_compatible_custom_providers(load_config()) + except Exception: + _sm_custom_providers = None # ``agent.api_key`` may be a callable (Azure Foundry Entra ID # token provider). ``get_model_context_length`` expects a # string for its live-probe paths; for Foundry the context @@ -2224,7 +2417,7 @@ def switch_model(agent, new_model, new_provider, api_key='', base_url='', api_mo base_url=agent.base_url, api_key=_ctx_api_key, provider=agent.provider, - config_context_length=getattr(agent, "_config_context_length", None), + config_context_length=_effective_context_length, custom_providers=_sm_custom_providers, ) agent.context_compressor.update_model( @@ -2270,6 +2463,7 @@ def switch_model(agent, new_model, new_provider, api_key='', base_url='', api_mo agent._primary_runtime = { "model": agent.model, "provider": agent.provider, + "requested_provider": agent.requested_provider, "base_url": agent.base_url, "api_mode": agent.api_mode, "api_key": getattr(agent, "api_key", ""), @@ -2346,7 +2540,8 @@ def invoke_tool(agent, function_name: str, function_args: dict, effective_task_i tool_call_id: Optional[str] = None, messages: list = None, pre_tool_block_checked: bool = False, skip_tool_request_middleware: bool = False, - tool_request_middleware_trace: Optional[List[Dict[str, Any]]] = None) -> str: + tool_request_middleware_trace: Optional[List[Dict[str, Any]]] = None, + skip_tool_execution_middleware: bool = False) -> str: """Invoke a single tool and return the result string. No display logic. Handles both agent-level tools (todo, memory, etc.) and registry-dispatched @@ -2504,6 +2699,7 @@ def invoke_tool(agent, function_name: str, function_args: dict, effective_task_i _clarify_tool( question=next_args.get("question", ""), choices=next_args.get("choices"), + multi_select=next_args.get("multi_select", False), callback=agent.clarify_callback, ), next_args, @@ -2524,8 +2720,7 @@ def invoke_tool(agent, function_name: str, function_args: dict, effective_task_i return _finish_agent_tool(agent._dispatch_delegate_task(next_args), next_args) else: def _execute(next_args: dict) -> Any: - return _ra().handle_function_call( - function_name, next_args, effective_task_id, + dispatch_kwargs = dict( tool_call_id=tool_call_id, session_id=agent.session_id or "", turn_id=getattr(agent, "_current_turn_id", "") or "", @@ -2537,6 +2732,17 @@ def invoke_tool(agent, function_name: str, function_args: dict, effective_task_i disabled_toolsets=getattr(agent, "disabled_toolsets", None), tool_request_middleware_trace=list(_tool_middleware_trace), ) + if skip_tool_execution_middleware: + dispatch_kwargs["skip_tool_execution_middleware"] = True + return _ra().handle_function_call( + function_name, + next_args, + effective_task_id, + **dispatch_kwargs, + ) + + if skip_tool_execution_middleware: + return _execute(function_args) from hermes_cli.middleware import run_tool_execution_middleware @@ -2649,6 +2855,129 @@ def repair_tool_call(agent, tool_name: str) -> str | None: +# Placeholder substituted for an empty non-final message that would otherwise +# make the provider reject the whole request. Kept identical to the stub- +# creation placeholder in chat_completion_helpers so a healed transcript reads +# consistently whether the empty turn was caught at write time or send time. +_INTERRUPTED_PLACEHOLDER = "[response interrupted]" + + +def _msg_has_payload(msg: Dict[str, Any]) -> bool: + """True if ``msg`` carries anything the API treats as non-empty content. + + Covers string content, non-empty multimodal content lists, tool_calls, + tool_call_id linkage (tool results), and reasoning payloads. Mirrors the + emptiness checks used by ``AIAgent._is_thinking_only_assistant`` but is + role-agnostic so it can vet user/assistant/tool turns uniformly. + """ + content = msg.get("content") + if isinstance(content, str): + if content.strip(): + return True + elif isinstance(content, list): + for block in content: + if isinstance(block, dict): + # any typed block (text/image/tool_use/document/...) counts, + # as long as a text block is not itself blank + if block.get("type") == "text": + if isinstance(block.get("text"), str) and block["text"].strip(): + return True + continue + return True + elif block: + return True + elif content not in (None, ""): + return True + # Structural payloads that make an "empty-content" message still valid. + if msg.get("tool_calls"): + return True + if isinstance(msg.get("reasoning_content"), str) and msg["reasoning_content"].strip(): + return True + if msg.get("reasoning") or msg.get("reasoning_details"): + return True + # Codex Responses item carriers: a commentary-phase assistant turn + # persists with content:"" by DESIGN — its text lives in + # ``codex_message_items`` (delivered via the interim callback) and the + # structured items are replayed for prefix-cache hits. Same for + # ``codex_reasoning_items``. These turns are never wire-empty on any + # api_mode: the codex transport replays the items, and the + # chat-completions transport strips the carriers only after this repair + # pass has already run. Treat them as payload so the repair never + # rewrites a designed-empty codex turn (July 2026: a write-time pad that + # ignored this broke codex commentary replay in CI). + if msg.get("codex_message_items") or msg.get("codex_reasoning_items"): + return True + return False + + +def repair_empty_non_final_messages( + messages: List[Dict[str, Any]], +) -> List[Dict[str, Any]]: + """Heal empty-content non-final messages before they reach the provider. + + Root-cause context: a stream that dies with 0 recovered characters (peer + reset, stall-kill) could persist an assistant turn with ``content=None`` + and no tool_calls. The Anthropic message schema — and the litellm/Bedrock + proxies in front of it — reject ANY request whose transcript contains an + empty non-final message: + + "all messages must have non-empty content except for the optional + final assistant message" (HTTP 400 INVALID_REQUEST_BODY) + + Once such a message lands mid-transcript it poisons EVERY subsequent turn + of that session until it scrolls out of context. The write-time guard in + ``chat_completion_helpers`` stops NEW stubs, but sessions already carrying + one (persisted before the guard, or fed in from a host history) stay stuck + and previously needed a manual DB edit + gateway restart to recover. + + This pass is the self-healing counterpart: it runs unconditionally on the + per-call ``api_messages`` copy, so a poisoned transcript repairs itself + IN MEMORY on the very next send — no restart, no DB surgery. The final + message is left untouched (an empty final assistant turn is legal). The + stored conversation history is never mutated; only the wire copy is + repaired, so the UI/session trace stays faithful. + + Repair strategy is substitution, not deletion: dropping a mid-transcript + turn can break role alternation and tool-call pairing, whereas an honest + minimal placeholder keeps the sequence intact and reads correctly as an + interrupted turn on replay. + """ + if not messages or len(messages) < 2: + return messages + + repaired: List[Dict[str, Any]] = [] + healed = 0 + last_idx = len(messages) - 1 + for idx, msg in enumerate(messages): + if ( + idx != last_idx + and isinstance(msg, dict) + # tool results are validated by their own orphan/pairing pass; an + # empty tool result is a separate (and rarer) concern. + and msg.get("role") in ("assistant", "user") + and not _msg_has_payload(msg) + ): + # Shallow-copy so stored history / prompt caching stays byte-stable. + fixed = dict(msg) + fixed["content"] = _INTERRUPTED_PLACEHOLDER + repaired.append(fixed) + healed += 1 + else: + repaired.append(msg) + + if healed: + _ra().logger.warning( + "Pre-call sanitizer: healed %d empty non-final message(s) by " + "substituting placeholder content — an empty-content turn was in " + "the transcript and would 400 the request ('messages must have " + "non-empty content' / INVALID_REQUEST_BODY). Self-recovering the " + "poisoned transcript in memory; no restart needed.", + healed, + ) + return repaired + return messages + + def sanitize_api_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any]]: """Fix orphaned tool_call / tool_result pairs before every LLM call. @@ -2669,6 +2998,15 @@ def sanitize_api_messages(messages: List[Dict[str, Any]]) -> List[Dict[str, Any] filtered.append(msg) messages = filtered + # --- Heal empty-content non-final messages (self-recovery) --- + # A dead stream can leave an empty assistant stub (or an empty user turn) + # mid-transcript; the provider then 400s EVERY subsequent request until it + # scrolls out. Repair it here, on the per-call copy, so a poisoned session + # recovers itself in memory on the next send — no restart, no DB edit. + # Done first so a substituted turn participates normally in the tool-pair + # and dedup passes below. + messages = repair_empty_non_final_messages(messages) + # --- Drop empty / malformed tool_calls arrays on assistant messages --- # An assistant message carrying ``tool_calls: []`` (an empty array) — or a # non-list value under the key — is semantically identical to an assistant @@ -2993,89 +3331,17 @@ def intent_ack_continuation_enabled(agent) -> bool: def copy_reasoning_content_for_api(agent, source_msg: dict, api_msg: dict) -> None: - """Copy provider-facing reasoning fields onto an API replay message.""" - if source_msg.get("role") != "assistant": - return + """Copy provider-facing reasoning fields onto an API replay message. - needs_thinking_pad = agent._needs_thinking_reasoning_pad() + Forwarder — the strip-vs-repad POLICY is owned by + ``agent.message_sanitization.apply_reasoning_content_policy`` (audit F4); + this only supplies the agent's cached provider-direction flag. + """ + from agent.message_sanitization import apply_reasoning_content_policy - # 1. Explicit reasoning_content already set. - # - # When the active provider enforces the thinking-mode echo-back - # (DeepSeek / Kimi / MiMo), preserve it verbatim — that includes their - # own space-placeholder written at creation time and any valid reasoning - # from the same provider. Sessions persisted BEFORE #17341 have - # empty-string placeholders pinned at creation time; DeepSeek V4 Pro - # rejects those with HTTP 400, so upgrade "" → " " on replay. - # - # When the active provider does NOT enforce echo-back, strip the field - # entirely. Strict OpenAI-compatible providers (Mistral, Cerebras, Groq, - # SambaNova, …) reject ANY reasoning_content key in input messages with - # HTTP 400/422 ("Extra inputs are not permitted"), even an empty string - # or a single-space pad. This is the cross-provider fallback case: a - # reasoning primary (DeepSeek/Kimi/MiMo) pads history with " ", then a - # fallback to a strict provider replays that pad and 422s. Stripping - # here covers the rebuild path; reapply_reasoning_echo_for_provider() - # covers the already-built api_messages path. Refs #45655. - existing = source_msg.get("reasoning_content") - if isinstance(existing, str): - if not needs_thinking_pad: - api_msg.pop("reasoning_content", None) - elif existing == "": - api_msg["reasoning_content"] = " " - else: - api_msg["reasoning_content"] = existing - return - - # 2. Cross-provider poisoned history (#15748): on DeepSeek/Kimi, - # if the source turn has tool_calls AND a 'reasoning' field but no - # 'reasoning_content' key, the 'reasoning' text was written by a - # prior provider (e.g. MiniMax) — DeepSeek's own _build_assistant_message - # pins reasoning_content at creation time for tool-call turns, so the - # shape (reasoning set, reasoning_content absent, tool_calls present) - # is unreachable from same-provider DeepSeek history after this fix. - # Inject a single space to satisfy the API without leaking another - # provider's chain of thought to DeepSeek/Kimi. Space (not "") - # because DeepSeek V4 Pro rejects empty-string reasoning_content - # in thinking mode (refs #17341). - normalized_reasoning = source_msg.get("reasoning") - if ( - needs_thinking_pad - and source_msg.get("tool_calls") - and isinstance(normalized_reasoning, str) - and normalized_reasoning - ): - api_msg["reasoning_content"] = " " - return - - # 3. Healthy session: promote 'reasoning' field to 'reasoning_content' - # for providers that use the internal 'reasoning' key. - # This must happen before the unconditional empty-string fallback so - # genuine reasoning content is not overwritten (#15812 regression in - # PR #15478). Only promote for providers that enforce echo-back — - # strict providers reject the field (refs #45655). - if isinstance(normalized_reasoning, str) and normalized_reasoning: - if needs_thinking_pad: - api_msg["reasoning_content"] = normalized_reasoning - else: - api_msg.pop("reasoning_content", None) - return - - # 4. DeepSeek / Kimi thinking mode: all assistant messages need - # reasoning_content. Inject a single space to satisfy the provider's - # requirement when no explicit reasoning content is present. Covers - # both tool-call turns (already-poisoned history with no reasoning - # at all) and plain text turns. Space (not "") because DeepSeek V4 - # Pro tightened validation and rejects empty string with HTTP 400 - # ("The reasoning content in the thinking mode must be passed back - # to the API"). Refs #17341. - if needs_thinking_pad: - api_msg["reasoning_content"] = " " - return - - # 5. reasoning_content was present but not a string (e.g. None after - # context compaction). Don't pass null to the API. - api_msg.pop("reasoning_content", None) + apply_reasoning_content_policy( + source_msg, api_msg, agent._needs_thinking_reasoning_pad() + ) def reapply_reasoning_echo_for_provider(agent, api_messages: list) -> int: @@ -3107,25 +3373,74 @@ def reapply_reasoning_echo_for_provider(agent, api_messages: list) -> int: Returns the number of assistant turns whose reasoning_content was added or removed. """ - needs_pad = agent._needs_thinking_reasoning_pad() - changed = 0 - for api_msg in api_messages: - if api_msg.get("role") != "assistant": + from agent.message_sanitization import reapply_reasoning_echo + + return reapply_reasoning_echo( + api_messages, agent._needs_thinking_reasoning_pad() + ) + + +def _iter_httpx_pool_objects(http_client: Any): + """Yield httpcore pool objects reachable from an httpx client. + + Hermes' keepalive client (#10324 / ``_build_keepalive_http_client``) and + any ``HTTP(S)_PROXY`` configuration put live connections on *mounted* + transports (``client._mounts``), not only on the default + ``client._transport``. Walking the default transport alone makes + ``force_close_tcp_sockets`` return 0 while a stream is still mid-recv — + the interrupt logs success and the provider keeps burning the slot + (#72975). + """ + seen_pools: set[int] = set() + + def _emit(pool: Any): + if pool is None: + return + marker = id(pool) + if marker in seen_pools: + return + seen_pools.add(marker) + yield pool + + def _pools_for_transport(transport: Any): + if transport is None: + return + # Normal httpx.HTTPTransport / HTTPProxy-as-transport: connections + # live under ``_pool``. HTTPProxy itself *is* a ConnectionPool and + # may be mounted directly — then ``_connections`` is on the + # transport. + pool = getattr(transport, "_pool", None) + if pool is not None: + yield from _emit(pool) + return + if getattr(transport, "_connections", None) is not None: + yield from _emit(transport) + + try: + yield from _pools_for_transport(getattr(http_client, "_transport", None)) + mounts = getattr(http_client, "_mounts", None) or {} + for _pattern, mounted in list(mounts.items()): + yield from _pools_for_transport(mounted) + except Exception: + return + + +def _connection_candidates(conn: Any): + """Walk nested ``_connection`` wrappers (proxy tunnel → HTTP11/2).""" + seen: set[int] = set() + stack = [conn] + while stack: + candidate = stack.pop() + if candidate is None: continue - if needs_pad: - if api_msg.get("reasoning_content"): - continue - copy_reasoning_content_for_api(agent, api_msg, api_msg) - if api_msg.get("reasoning_content"): - changed += 1 - else: - # Strict provider — strip any stale reasoning_content pad left - # over from a reasoning primary so the fallback request doesn't - # 400/422 on it. - if "reasoning_content" in api_msg: - api_msg.pop("reasoning_content", None) - changed += 1 - return changed + marker = id(candidate) + if marker in seen: + continue + seen.add(marker) + yield candidate + inner = getattr(candidate, "_connection", None) + if inner is not None and id(inner) not in seen: + stack.append(inner) def _iter_pool_sockets(client: Any): @@ -3133,70 +3448,71 @@ def _iter_pool_sockets(client: Any): httpcore 1.x stores the concrete HTTP11/HTTP2 connection under ``conn._connection``; older versions exposed stream attributes directly - on the pool entry. Keep the traversal defensive because these are private - transport internals and vary across httpx/httpcore releases. + on the pool entry. Proxy tunnels wrap another layer + (``TunnelHTTPConnection`` / ``ForwardHTTPConnection``). Keep the + traversal defensive because these are private transport internals and + vary across httpx/httpcore releases. + + Also walks ``httpx`` mount transports — see ``_iter_httpx_pool_objects``. """ try: http_client = getattr(client, "_client", None) if http_client is None: - return - transport = getattr(http_client, "_transport", None) - if transport is None: - return - pool = getattr(transport, "_pool", None) - if pool is None: - return + # Some SDK wrappers *are* the httpx client (or expose the pool + # directly). Fall through so mount-aware discovery still runs. + http_client = client + pools = list(_iter_httpx_pool_objects(http_client)) + except Exception: + return + + if not pools: + return + + seen: set[int] = set() + for pool in pools: connections = ( getattr(pool, "_connections", None) or getattr(pool, "_pool", None) or [] ) - except Exception: - return - - seen: set[int] = set() - for conn in list(connections): - candidates = [conn] - inner = getattr(conn, "_connection", None) - if inner is not None: - candidates.append(inner) - for candidate in candidates: - stream = ( - getattr(candidate, "_network_stream", None) - or getattr(candidate, "_stream", None) - ) - if stream is None: - continue - sock = getattr(stream, "_sock", None) - if sock is None: - get_extra_info = getattr(stream, "get_extra_info", None) - if callable(get_extra_info): - try: - sock = get_extra_info("socket") - except Exception: - sock = None - if sock is None: - wrapped = getattr(stream, "stream", None) - if wrapped is not None: - sock = getattr(wrapped, "_sock", None) - if sock is None: - # anyio-backed streams expose the raw socket through - # SocketAttribute.raw_socket when available. - wrapped = getattr(stream, "_stream", None) - extra = getattr(wrapped, "extra", None) - if callable(extra): - try: - from anyio.abc import SocketAttribute - sock = extra(SocketAttribute.raw_socket) - except Exception: - sock = None - if sock is None: - continue - marker = id(sock) - if marker in seen: - continue - seen.add(marker) - yield sock + for conn in list(connections): + for candidate in _connection_candidates(conn): + stream = ( + getattr(candidate, "_network_stream", None) + or getattr(candidate, "_stream", None) + ) + if stream is None: + continue + sock = getattr(stream, "_sock", None) + if sock is None: + get_extra_info = getattr(stream, "get_extra_info", None) + if callable(get_extra_info): + try: + sock = get_extra_info("socket") + except Exception: + sock = None + if sock is None: + wrapped = getattr(stream, "stream", None) + if wrapped is not None: + sock = getattr(wrapped, "_sock", None) + if sock is None: + # anyio-backed streams expose the raw socket through + # SocketAttribute.raw_socket when available. + wrapped = getattr(stream, "_stream", None) + extra = getattr(wrapped, "extra", None) + if callable(extra): + try: + from anyio.abc import SocketAttribute + sock = extra(SocketAttribute.raw_socket) + except Exception: + sock = None + if sock is None: + continue + marker = id(sock) + if marker in seen: + continue + seen.add(marker) + yield sock def cleanup_dead_connections(agent) -> bool: diff --git a/agent/anthropic_adapter.py b/agent/anthropic_adapter.py index fd7596e7e3bf..0d59d94c9c32 100644 --- a/agent/anthropic_adapter.py +++ b/agent/anthropic_adapter.py @@ -23,7 +23,7 @@ from urllib.parse import urlparse from hermes_constants import get_hermes_home from typing import Any, Dict, List, Optional, Tuple -from utils import base_url_host_matches, normalize_proxy_env_vars +from utils import base_url_host_matches, base_url_hostname, normalize_proxy_env_vars # NOTE: `import anthropic` is deliberately NOT at module top — the SDK pulls # ~220 ms of imports (anthropic.types, anthropic.lib.tools._beta_runner, etc.) @@ -368,7 +368,7 @@ def _detect_claude_code_version() -> str: try: result = _sp.run( [cmd, "--version"], - capture_output=True, text=True, timeout=5, + capture_output=True, text=True, encoding='utf-8', errors='replace', timeout=5, ) if result.returncode == 0 and result.stdout.strip(): # Output is like "2.1.74 (Claude Code)" or just "2.1.74" @@ -546,15 +546,49 @@ def _is_deepseek_anthropic_endpoint(base_url: str | None) -> bool: return "/anthropic" in normalized.rstrip("/").lower() +def _is_nous_portal_endpoint(base_url: str | None) -> bool: + """Return True for Nous Portal's Anthropic Messages route. + + Portal serves its ``anthropic/*`` catalog natively at + ``https://inference-api.nousresearch.com/v1/messages``. Portal-specific + behaviours key off this: Bearer JWT auth, verbatim catalog model ids, + and native thinking-signature replay. + + Trusted hosts only: + + 1. Prod hostname ``inference-api.nousresearch.com`` + 2. The operator-set ``NOUS_INFERENCE_BASE_URL`` hostname (staging/preview) + + Lookalikes such as ``inference-api.nousresearch.com.attacker.test`` are + rejected (hostname match, not substring). + """ + if base_url_host_matches(base_url or "", "inference-api.nousresearch.com"): + return True + try: + from hermes_cli.auth import _nous_inference_env_override + + override = _nous_inference_env_override() + except Exception: + return False + if not override: + return False + # Exact host equality (not subdomain) so the env override can't broaden + # into sibling hosts the operator did not set. + override_host = base_url_hostname(override) + return bool(override_host) and base_url_hostname(base_url or "") == override_host + + def _requires_bearer_auth(base_url: str | None) -> bool: """Return True for Anthropic-compatible providers that require Bearer auth. Some third-party /anthropic endpoints implement Anthropic's Messages API but require Authorization: Bearer instead of Anthropic's native x-api-key header. MiniMax's global and China Anthropic-compatible endpoints, Azure AI - Foundry's Anthropic-style endpoint, and Palantir Foundry's LLM proxy - follow this pattern. + Foundry's Anthropic-style endpoint, Palantir Foundry's LLM proxy, and Nous + Portal's Messages route follow this pattern. """ + if _is_nous_portal_endpoint(base_url): + return True normalized = _normalize_base_url_text(base_url) if not normalized: return False @@ -721,7 +755,11 @@ def _build_anthropic_client_with_bearer_hook( if common_betas: kwargs["default_headers"] = {"anthropic-beta": ",".join(common_betas)} - return _anthropic_sdk.Anthropic(**kwargs) + client = _anthropic_sdk.Anthropic(**kwargs) + # Same env-inference trap as build_anthropic_client: auth_token-only + # construction would otherwise also send ANTHROPIC_API_KEY as X-Api-Key. + client.api_key = None + return client def build_anthropic_client( @@ -850,7 +888,16 @@ def build_anthropic_client( if common_betas: kwargs["default_headers"] = {"anthropic-beta": ",".join(common_betas)} - return _anthropic_sdk.Anthropic(**kwargs) + client = _anthropic_sdk.Anthropic(**kwargs) + # Bearer-only construction leaves ``api_key`` unset, so the SDK fills it + # from ``ANTHROPIC_API_KEY`` (Hermes loads that into the process env from + # ``~/.hermes/.env``). The result is dual auth — + # ``X-Api-Key: sk-ant-…`` *and* ``Authorization: Bearer `` — + # on every Portal / MiniMax / OAuth Messages request. Clear the env-filled + # key whenever we intentionally authenticated via auth_token alone. + if "auth_token" in kwargs and "api_key" not in kwargs: + client.api_key = None + return client def build_anthropic_bedrock_client(region: str): @@ -914,7 +961,7 @@ def _read_claude_code_credentials_from_keychain() -> Optional[Dict[str, Any]]: "-s", "Claude Code-credentials", "-w"], capture_output=True, - text=True, + text=True, encoding='utf-8', errors='replace', timeout=5, stdin=subprocess.DEVNULL, ) @@ -1881,6 +1928,28 @@ def _content_parts_to_anthropic_blocks(parts: Any) -> List[Dict[str, Any]]: return out +_EMPTY_TEXT_PLACEHOLDER = "(empty)" + + +def _safe_text(text: Any) -> str: + """Return ``text`` if it's non-whitespace, else a non-whitespace placeholder. + + The Anthropic Messages API rejects requests where a text content block is + empty or whitespace-only (HTTP 400 "text content blocks must contain + non-whitespace text"). When such a block gets stored in session history — + e.g. produced by context compression — it is replayed verbatim on every + subsequent turn, permanently wedging the session. Coercing to a + non-whitespace placeholder is self-healing: the next API call recovers. + + Mirrors ``bedrock_adapter._safe_text`` (#9486); ref #69512. + """ + if text is None: + return _EMPTY_TEXT_PLACEHOLDER + if not isinstance(text, str): + text = str(text) + return text if text.strip() else _EMPTY_TEXT_PLACEHOLDER + + def _sanitize_replay_block(b: Dict[str, Any]) -> Optional[Dict[str, Any]]: """Strip output-only fields from a stored Anthropic content block so it is valid as REQUEST input on replay. @@ -1898,7 +1967,18 @@ def _sanitize_replay_block(b: Dict[str, Any]) -> Optional[Dict[str, Any]]: return None btype = b.get("type") if btype == "text": - out: Dict[str, Any] = {"type": "text", "text": b.get("text", "")} + text_val = b.get("text", "") + # Bedrock and strict Anthropic-compatible endpoints reject text + # blocks where "text" is empty or whitespace-only (#69512). Drop the + # blank block (the caller relocates any cache_control it carried and + # falls back to a non-whitespace placeholder when nothing survives) + # rather than coercing in place — a coerced "(empty)" block would be + # model-visible noise next to surviving thinking/tool_use blocks. + # Type-safe: captured blocks can carry text=None from an invalid + # upstream payload, which a bare .strip() would crash on. + if not isinstance(text_val, str) or not text_val.strip(): + return None + out: Dict[str, Any] = {"type": "text", "text": text_val} # citations is input-valid ONLY when it's a non-empty list; the SDK # emits citations=None on responses, which the input schema rejects. cits = b.get("citations") @@ -1986,9 +2066,17 @@ def _convert_assistant_message(m: Dict[str, Any]) -> Dict[str, Any]: parsed_args = {} redacted_input_by_id[_sanitize_tool_id(tc.get("id", ""))] = parsed_args replayed: List[Dict[str, Any]] = [] + _relocated_replay_cache_control = None + _dropped_blank_text = False for b in ordered_blocks: clean = _sanitize_replay_block(b) if clean is None: + if isinstance(b, dict) and b.get("type") == "text": + _dropped_blank_text = True + if isinstance(b, dict) and isinstance(b.get("cache_control"), dict): + # A dropped blank text block can still carry the cache + # breakpoint marker -- relocate it rather than losing it. + _relocated_replay_cache_control = b["cache_control"] continue if clean.get("type") == "tool_use": # Override raw (un-redacted) input with the redacted copy when @@ -1998,20 +2086,90 @@ def _convert_assistant_message(m: Dict[str, Any]) -> Dict[str, Any]: if redacted is not None: clean["input"] = redacted replayed.append(clean) + # When every text block was blank and nothing cacheable survived + # (e.g. signed thinking + a blank text block, or a SOLE blank + # cache-marked block), emit the non-whitespace placeholder so the + # replayed message stays schema-valid (#69512) and a relocated cache + # marker still has a carrier instead of being silently lost. + _has_cacheable_replay = any( + isinstance(b, dict) and b.get("type") in {"text", "tool_use"} + for b in replayed + ) + if not _has_cacheable_replay and ( + _dropped_blank_text or _relocated_replay_cache_control is not None + ): + replayed.append({"type": "text", "text": _EMPTY_TEXT_PLACEHOLDER}) if replayed: + if _relocated_replay_cache_control is not None: + _apply_assistant_cache_control_to_last_cacheable_block( + replayed, _relocated_replay_cache_control + ) _apply_assistant_cache_control_to_last_cacheable_block( replayed, m.get("cache_control") ) + # apply_anthropic_cache_control marks an assistant turn with + # non-empty text by writing cache_control INTO ``content`` (see + # _apply_cache_marker's list branch), not at the top level. This + # branch rebuilds the message from ordered_blocks and never reads + # ``content``, so that marker would be dropped -- and because + # _can_carry_marker already counted this message as a carrier, the + # breakpoint is burned rather than relocated. #56195 covered the + # complementary shape (blank content -> top-level marker); this is + # the interleaved thinking + preamble-text + tool_use shape. + _inline_cc = None + _msg_content = m.get("content") + if isinstance(_msg_content, list): + for _blk in _msg_content: + if isinstance(_blk, dict) and isinstance( + _blk.get("cache_control"), dict + ): + _inline_cc = _blk["cache_control"] + break + if _inline_cc is not None: + _apply_assistant_cache_control_to_last_cacheable_block( + replayed, _inline_cc + ) return {"role": "assistant", "content": replayed} blocks = _extract_preserved_thinking_blocks(m) + # Cache markers dropped along with a blank block are relocated onto the + # last surviving cacheable block below (via + # _apply_assistant_cache_control_to_last_cacheable_block), rather than + # lost -- prompt_caching.py's _apply_cache_marker() sets cache_control + # directly on content[-1] for list content, so if that last part happens + # to be blank text, dropping it silently would lose the breakpoint. + _relocated_cache_control = None if content: if isinstance(content, list): converted_content = _convert_content_to_anthropic(content) if isinstance(converted_content, list): - blocks.extend(converted_content) + # Bedrock and strict Anthropic-compatible endpoints reject + # text blocks where "text" is empty or whitespace-only. The + # ordered-replay path enforces the same invariant via + # _sanitize_replay_block(). Type-safe against ANY invalid + # "text" value from an upstream payload -- None, or a + # truthy non-string like an int -- not just None: checking + # isinstance() first (rather than `blk.get("text") or ""`) + # means a non-string value is treated as blank/invalid + # instead of reaching .strip() and raising AttributeError. + for blk in converted_content: + _blk_text = blk.get("text") if isinstance(blk, dict) else None + if ( + isinstance(blk, dict) + and blk.get("type") == "text" + and (not isinstance(_blk_text, str) or not _blk_text.strip()) + ): + if isinstance(blk.get("cache_control"), dict): + _relocated_cache_control = blk["cache_control"] + continue + blocks.append(blk) else: - blocks.append({"type": "text", "text": str(content)}) + # Scalar (non-list) content: a whitespace-only string is the + # same invalid-payload case as an empty list block -- drop it + # rather than emitting a blank text block. + text_str = str(content) + if text_str.strip(): + blocks.append({"type": "text", "text": text_str}) for tc in m.get("tool_calls", []): if not tc or not isinstance(tc, dict): continue @@ -2027,9 +2185,6 @@ def _convert_assistant_message(m: Dict[str, Any]) -> Dict[str, Any]: "name": fn.get("name", ""), "input": parsed_args, }) - _apply_assistant_cache_control_to_last_cacheable_block( - blocks, m.get("cache_control") - ) # Kimi's /coding endpoint (Anthropic protocol) requires assistant # tool-call messages to carry reasoning_content when thinking is # enabled server-side. Preserve it as a thinking block so Kimi @@ -2055,10 +2210,26 @@ def _convert_assistant_message(m: Dict[str, Any]) -> Dict[str, Any]: ) if isinstance(reasoning_content, str) and not _already_has_thinking: blocks.insert(0, {"type": "thinking", "thinking": reasoning_content}) - # Anthropic rejects empty assistant content - effective = blocks or content - if not effective or effective == "": - effective = [{"type": "text", "text": "(empty)"}] + # Anthropic rejects empty assistant content. IMPORTANT: fall back only + # to the placeholder, never to the raw `content` variable -- `content` + # is the UNFILTERED original message content, and can itself be exactly + # the blank/whitespace-only payload the filtering above just removed + # (a sole blank text block, or scalar whitespace with no tool_calls). + # `blocks or content` there would silently restore the invalid provider + # payload this function exists to prevent (#69512). + effective = blocks if blocks else [{"type": "text", "text": _EMPTY_TEXT_PLACEHOLDER}] + # Applied here (after the empty-fallback resolution) rather than + # earlier against `blocks` directly, so a cache_control relocated from + # a dropped blank block that was the ONLY block still lands on the + # (empty) placeholder instead of being silently lost when blocks was + # empty at the point the marker would otherwise have been applied. + if _relocated_cache_control is not None: + _apply_assistant_cache_control_to_last_cacheable_block( + effective, _relocated_cache_control + ) + _apply_assistant_cache_control_to_last_cacheable_block( + effective, m.get("cache_control") + ) return {"role": "assistant", "content": effective} @@ -2292,10 +2463,22 @@ def _manage_thinking_signatures( replayed assistant tool-call messages. See hermes-agent#13848 (Kimi) and hermes-agent#16748 (DeepSeek). + Nous Portal's ``/v1/messages`` route is the exception among third-party + hosts: it proxies Claude to Anthropic/Vertex/Bedrock and validates the + same signed thinking blocks. Sticky ``session_id`` keeps a conversation + on one upstream instance so those signatures stay warm — stripping them + here would 400 the first tool-loop turn ("thinking must be passed back"). + Portal therefore takes the native Anthropic replay path below. + Mutates ``result`` in place. """ _THINKING_TYPES = frozenset(("thinking", "redacted_thinking")) - _is_third_party = _is_third_party_anthropic_endpoint(base_url) + # Portal speaks Anthropic's thinking contract end-to-end; do not treat it + # as a signature-blind proxy even though the host is not anthropic.com. + _is_third_party = ( + _is_third_party_anthropic_endpoint(base_url) + and not _is_nous_portal_endpoint(base_url) + ) last_assistant_idx = None for i in range(len(result) - 1, -1, -1): @@ -2552,7 +2735,12 @@ def build_anthropic_kwargs( ) anthropic_tools = convert_tools_to_anthropic(tools) if tools else [] - model = normalize_model_name(model, preserve_dots=preserve_dots) + # Nous Portal routes on its own catalog ids (``anthropic/claude-opus-4.8``); + # normalizing to the bare Anthropic slug would make the model unresolvable + # there. Skipping the call preserves the prefix AND the dots, so + # ``preserve_dots`` stays irrelevant for Portal. + if not _is_nous_portal_endpoint(base_url): + model = normalize_model_name(model, preserve_dots=preserve_dots) # effective_max_tokens = output cap for this call (≠ total context window) # Use the resolver helper so non-positive values (negative ints, # fractional floats, NaN, non-numeric) fail locally with a clear error @@ -2791,6 +2979,8 @@ def create_anthropic_message( *, log_prefix: str = "", prefer_stream: bool = True, + on_stream_event=None, + on_response=None, ) -> Any: """Create an Anthropic message, aggregating via stream when available. @@ -2800,6 +2990,20 @@ def create_anthropic_message( crash on ``.content``. Prefer ``messages.stream().get_final_message()`` to match the main turn path, falling back to ``create()`` only for providers that explicitly do not support streaming, such as restricted Bedrock roles. + + ``on_stream_event``: optional callable invoked once per streamed event + (best-effort, exceptions swallowed). Lets callers report forward progress + to liveness watchdogs — e.g. the auxiliary compression path ticking its + progress hook so a slow-but-generating summary model isn't treated as + hung. Only fires on the streaming path; the ``create()`` fallback has no + events to report. + + ``on_response``: optional callable invoked once with the underlying httpx + response before the message is aggregated (best-effort, exceptions + swallowed). Response *headers* carry out-of-band provider state that the + parsed ``Message`` drops — Nous Portal's ``x-nous-credits-*`` balance family + in particular. Only fires on the streaming path, which is the one the main + turn loop takes. """ sanitize_anthropic_kwargs(api_kwargs, log_prefix=log_prefix) @@ -2810,6 +3014,26 @@ def create_anthropic_message( stream_kwargs.pop("stream", None) try: with stream_fn(**stream_kwargs) as stream: + if callable(on_response): + try: + on_response(getattr(stream, "response", None)) + except Exception: + logger.debug( + "%son_response callback failed", + log_prefix, exc_info=True, + ) + if callable(on_stream_event): + # Consume the event stream manually so each event can + # tick the caller's progress callback; get_final_message + # then returns the accumulated snapshot. + for _event in stream: + try: + on_stream_event(_event) + except Exception: + logger.debug( + "%son_stream_event callback failed", + log_prefix, exc_info=True, + ) return stream.get_final_message() except Exception as exc: if not _is_stream_unavailable_error(exc): diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py index da49a695180a..426479560427 100644 --- a/agent/auxiliary_client.py +++ b/agent/auxiliary_client.py @@ -42,6 +42,7 @@ Payment / credit exhaustion fallback: import contextlib import contextvars +import functools import hashlib import inspect import json @@ -50,9 +51,10 @@ import os import re import threading import time +import uuid from pathlib import Path # noqa: F401 — used by test mocks from types import SimpleNamespace -from typing import Any, Dict, List, Optional, Tuple, TYPE_CHECKING +from typing import Any, Callable, Dict, List, Optional, Tuple, TYPE_CHECKING from urllib.parse import urlparse, parse_qs, urlunparse # NOTE: `from openai import OpenAI` is deliberately NOT at module top — the @@ -247,6 +249,50 @@ def aux_interrupt_protection(active: bool = True): _aux_interrupt_protection.active = prev +# ── Forward-progress hook for streamed auxiliary calls ─────────────────── +# Long auxiliary calls (context compression is the prime case) are watched by +# wall-clock deadlines in their hosts (gateway session hygiene). A fixed +# deadline punishes SLOW summary models exactly as hard as HUNG ones: a +# reasoning model happily streaming a large summary is killed mid-generation. +# This thread-local hook lets the host observe liveness instead: the wire +# consumers below tick it on every streamed token/SSE event, and the host +# extends its deadline while tokens are moving (see gateway/run.py session +# hygiene + CompressionCommitFence.touch_progress). Thread-local matches the +# call topology — the aux call and its stream consumption run synchronously +# on the thread that installed the hook. +_aux_progress = threading.local() + + +def _notify_aux_progress() -> None: + """Tick the installed forward-progress hook, if any. Never raises.""" + hook = getattr(_aux_progress, "hook", None) + if hook is None: + return + try: + hook() + except Exception: + logger.debug("aux progress hook failed", exc_info=True) + + +def _aux_progress_active() -> bool: + return getattr(_aux_progress, "hook", None) is not None + + +@contextlib.contextmanager +def aux_progress_hook(hook): + """Install *hook* as the current thread's aux forward-progress callback. + + ``hook=None`` is a no-op passthrough so callers can wire it + unconditionally. Re-entrant-safe: restores the previous hook on exit. + """ + prev = getattr(_aux_progress, "hook", None) + _aux_progress.hook = hook if callable(hook) else prev + try: + yield + finally: + _aux_progress.hook = prev + + def _safe_isinstance(obj: Any, maybe_type: Any) -> bool: """Return False instead of raising when a patched symbol is not a type.""" try: @@ -490,7 +536,7 @@ def _get_aux_model_for_provider(provider_id: str) -> str: # plus providers we intentionally keep pinned here (e.g. Anthropic predates # profiles). New providers should set default_aux_model on their profile instead. _API_KEY_PROVIDER_AUX_MODELS_FALLBACK: Dict[str, str] = { - "gemini": "gemini-3-flash-preview", + "gemini": "gemini-3.6-flash", "zai": "glm-4.5-flash", "kimi-coding": "kimi-k2-turbo-preview", "stepfun": "step-3.5-flash", @@ -499,7 +545,7 @@ _API_KEY_PROVIDER_AUX_MODELS_FALLBACK: Dict[str, str] = { "anthropic": "claude-haiku-4-5-20251001", "opencode-zen": "gemini-3-flash", "opencode-go": "glm-5", - "kilocode": "google/gemini-3-flash-preview", + "kilocode": "google/gemini-3.6-flash", "ollama-cloud": "nemotron-3-nano:30b", "tencent-tokenhub": "hy3-preview", # NB: no "deepinfra" entry — its aux model lives on the ProviderProfile @@ -714,8 +760,8 @@ NOUS_EXTRA_BODY = _nous_extra_body() auxiliary_is_nous: bool = False # Default auxiliary models per provider -_OPENROUTER_MODEL = "google/gemini-3-flash-preview" -_NOUS_MODEL = "google/gemini-3-flash-preview" +_OPENROUTER_MODEL = "google/gemini-3.6-flash" +_NOUS_MODEL = "google/gemini-3.6-flash" _NOUS_DEFAULT_BASE_URL = "https://inference-api.nousresearch.com/v1" _ANTHROPIC_DEFAULT_BASE_URL = "https://api.anthropic.com" _AUTH_JSON_PATH = get_hermes_home() / "auth.json" @@ -1058,16 +1104,29 @@ class _CodexCompletionsAdapter: # key in extra_body (not top-level) and GitHub/Copilot Responses opts # out of cache-key routing entirely — for those hosts, skip it here. try: - from agent.transports.codex import _content_cache_key + from agent.transports.codex import ( + _content_cache_key, + _default_prompt_cache_retention_for_request, + ) from utils import base_url_host_matches _host_src = str(getattr(self._client, "base_url", "") or "") _is_xai = base_url_host_matches(_host_src, "x.ai") or base_url_host_matches(_host_src, "api.x.ai") - _is_github = base_url_host_matches(_host_src, "githubcopilot.com") + _is_github = ( + base_url_host_matches(_host_src, "githubcopilot.com") + or base_url_host_matches(_host_src, "models.github.ai") + ) if not _is_xai and not _is_github and "prompt_cache_key" not in resp_kwargs: _cache_key = _content_cache_key(instructions, resp_kwargs.get("tools")) if _cache_key: resp_kwargs["prompt_cache_key"] = _cache_key + if "prompt_cache_retention" not in resp_kwargs: + _cache_retention = _default_prompt_cache_retention_for_request( + model, + _host_src, + ) + if _cache_retention: + resp_kwargs["prompt_cache_retention"] = _cache_retention except Exception: logger.debug( "Codex auxiliary: prompt_cache_key derivation skipped", exc_info=True @@ -1149,6 +1208,10 @@ class _CodexCompletionsAdapter: def _on_each_event(_event: Any) -> None: # Re-check timeout/cancellation per event, matching the # cadence the old in-line ``_check_cancelled()`` used. + # Each SSE event is also forward progress for hosts watching + # a progress hook (gateway session hygiene): a reasoning + # model streaming a long summary must not look hung. + _notify_aux_progress() _check_cancelled() event_stream = self._client.responses.create(**stream_kwargs) @@ -1301,10 +1364,32 @@ class AsyncCodexAuxiliaryClient: class _AnthropicCompletionsAdapter: """OpenAI-client-compatible adapter for Anthropic Messages API.""" - def __init__(self, real_client: Any, model: str, is_oauth: bool = False): + def __init__( + self, + real_client: Any, + model: str, + is_oauth: bool = False, + base_url: str | None = None, + ): self._client = real_client self._model = model self._is_oauth = is_oauth + # Prefer the caller-supplied URL (AnthropicAuxiliaryClient keeps the + # pre-strip Portal ``.../v1`` form). Only fall back to the SDK + # client's host for Nous Portal — a blanket fallback would flip + # MiniMax/Zhipu/etc. aux adapters from "unknown host = native + # Anthropic" to third-party (stripping thinking signatures). + self._base_url = base_url or None + if not self._base_url: + candidate = str(getattr(real_client, "base_url", "") or "") or None + if candidate: + try: + from agent.anthropic_adapter import _is_nous_portal_endpoint + + if _is_nous_portal_endpoint(candidate): + self._base_url = candidate + except Exception: + pass def create(self, **kwargs) -> Any: from agent.anthropic_adapter import build_anthropic_kwargs, create_anthropic_message @@ -1356,6 +1441,11 @@ class _AnthropicCompletionsAdapter: reasoning_config=_reasoning_cfg, tool_choice=normalized_tool_choice, is_oauth=self._is_oauth, + # Portal routes on ``anthropic/`` catalog ids and replays + # signed thinking like native Anthropic; both carve-outs key off + # base_url. Omitting it normalizes the id to a bare Anthropic + # slug and the Portal Messages route cannot resolve it. + base_url=self._base_url, ) # Opus 4.7+ rejects any non-default temperature/top_p/top_k; only set # temperature for models that still accept it. build_anthropic_kwargs @@ -1390,7 +1480,18 @@ class _AnthropicCompletionsAdapter: existing = {} anthropic_kwargs["extra_body"] = {**existing, **passthrough} - response = create_anthropic_message(self._client, anthropic_kwargs) + response = create_anthropic_message( + self._client, + anthropic_kwargs, + # Tick the aux forward-progress hook per streamed event so hosts + # watching liveness (gateway session hygiene) don't kill a + # slow-but-generating summary model. No-op when no hook is + # installed (None keeps the fast get_final_message path). + on_stream_event=( + (lambda _event: _notify_aux_progress()) + if _aux_progress_active() else None + ), + ) _transport = get_transport("anthropic_messages") _nr = _transport.normalize_response( response, strip_tool_prefix=self._is_oauth @@ -1438,7 +1539,9 @@ class AnthropicAuxiliaryClient: def __init__(self, real_client: Any, model: str, api_key: str, base_url: str, is_oauth: bool = False): self._real_client = real_client - adapter = _AnthropicCompletionsAdapter(real_client, model, is_oauth=is_oauth) + adapter = _AnthropicCompletionsAdapter( + real_client, model, is_oauth=is_oauth, base_url=base_url, + ) self.chat = _AnthropicChatShim(adapter) self.api_key = api_key self.base_url = base_url @@ -1703,7 +1806,7 @@ def _read_nous_auth() -> Optional[dict]: try: if not _AUTH_JSON_PATH.is_file(): return None - data = json.loads(_AUTH_JSON_PATH.read_text()) + data = json.loads(_AUTH_JSON_PATH.read_text(encoding="utf-8")) if data.get("active_provider") != "nous": return None provider = data.get("providers", {}).get("nous", {}) @@ -2303,6 +2406,62 @@ def _read_main_base_url() -> str: return "" +def _resolve_moa_aggregator(preset_name: Optional[str]) -> Tuple[Optional[str], Optional[str]]: + """Resolve a MoA preset to its aggregator (provider, model) pair. + + "moa" is a virtual provider — the acting model of a preset is its + aggregator slot, and there is no real "moa" HTTP endpoint. Auxiliary + tasks (title generation, compression, vision, commit messages, …) don't + need the reference fan-out, so every aux resolution layer maps + provider="moa"/model= to the aggregator's real provider+model + through this single helper (shared by ``_resolve_auto``, + ``_resolve_task_provider_model``, and ``resolve_provider_client`` so the + preset lookup and validation cannot drift between paths). + + Args: + preset_name: The MoA preset name (usually carried in the "model" + field), or None/"" to resolve the user's default preset. + + Returns: + (aggregator_provider, aggregator_model), or (None, None) when the + preset cannot be resolved (missing config, renamed/deleted preset, + or a malformed aggregator slot). + """ + try: + from hermes_cli.config import load_config + from hermes_cli.moa_config import resolve_moa_preset + + preset = resolve_moa_preset(load_config().get("moa") or {}, preset_name or None) + agg = preset.get("aggregator") or {} + agg_provider = str(agg.get("provider") or "").strip() + agg_model = str(agg.get("model") or "").strip() + if agg_provider and agg_model and agg_provider.lower() != "moa": + return agg_provider, agg_model + except Exception: + logger.debug( + "MoA aggregator resolution failed for preset %r", preset_name, exc_info=True + ) + return None, None + + +def _read_main_model_for_aux() -> str: + """Main model with MoA presets unwrapped to the aggregator's model. + + When the main provider is ``moa``, ``_read_main_model()`` returns a MoA + *preset name* (e.g. "opus-gpt") — never a valid wire model id on any + provider. Auxiliary fallback chains that pre-fill a missing model from + the main model must use this reader instead, so unset aux models default + to the preset's acting (aggregator) model. Returns "" when the main + provider is moa but the preset cannot be resolved — sending nothing is + strictly better than sending a preset name that 400s. + """ + model = _read_main_model() + if (_read_main_provider() or "").strip().lower() == "moa": + _, agg_model = _resolve_moa_aggregator(model) + return agg_model or "" + return model + + def _read_main_api_key_if_same_host(aux_base_url: str) -> str: """Return the main api_key only when *aux_base_url* points at the same host as the main model's base_url. @@ -2335,6 +2494,167 @@ _RUNTIME_MAIN_AUTH_MODE: str = "" _RUNTIME_MAIN_CONTEXT: contextvars.ContextVar[Optional[Dict[str, Any]]] = ( contextvars.ContextVar("auxiliary_runtime_main", default=None) ) + +_RELAY_AUX_CALL_CONTEXT: contextvars.ContextVar[Optional[Dict[str, Any]]] = ( + contextvars.ContextVar("auxiliary_relay_call", default=None) +) + + +def _relay_auxiliary_call(callback): + """Give every physical retry in one auxiliary call a shared Relay identity.""" + + @functools.wraps(callback) + def wrapped(*args, **kwargs): + task = args[0] if args else kwargs.get("task") + token = _RELAY_AUX_CALL_CONTEXT.set({ + "task": str(task or "unknown"), + "request_id": f"aux-{uuid.uuid4().hex}", + "attempt_count": 0, + "provider": "", + "model": "", + "api_mode": "chat_completions", + }) + try: + return callback(*args, **kwargs) + except BaseException: + _fail_relay_auxiliary_call() + raise + finally: + _RELAY_AUX_CALL_CONTEXT.reset(token) + + return wrapped + + +def _relay_auxiliary_call_async(callback): + """Async counterpart to :func:`_relay_auxiliary_call`.""" + + @functools.wraps(callback) + async def wrapped(*args, **kwargs): + task = args[0] if args else kwargs.get("task") + token = _RELAY_AUX_CALL_CONTEXT.set({ + "task": str(task or "unknown"), + "request_id": f"aux-{uuid.uuid4().hex}", + "attempt_count": 0, + "provider": "", + "model": "", + "api_mode": "chat_completions", + }) + try: + return await callback(*args, **kwargs) + except BaseException: + _fail_relay_auxiliary_call() + raise + finally: + _RELAY_AUX_CALL_CONTEXT.reset(token) + + return wrapped + + +def _set_relay_auxiliary_route( + provider: str | None, + model: str | None, + api_mode: str | None, +) -> None: + context = _RELAY_AUX_CALL_CONTEXT.get() + if context is None: + return + context["provider"] = str(provider or "auxiliary") + context["model"] = str(model or "unknown") + context["api_mode"] = str(api_mode or "chat_completions") + + +def _relay_auxiliary_metadata( + *, + provider: str | None = None, + api_mode: str | None = None, +) -> tuple[str, str, dict[str, Any]] | None: + context = _RELAY_AUX_CALL_CONTEXT.get() + if context is None: + return None + attempt_count = int(context.get("attempt_count") or 0) + context["attempt_count"] = attempt_count + 1 + provider_name = str(provider or context.get("provider") or "auxiliary") + model_name = str(context.get("model") or "unknown") + return provider_name, model_name, { + "api_mode": str(api_mode or context.get("api_mode") or "chat_completions"), + "api_request_id": str(context["request_id"]), + "call_role": f"auxiliary:{context['task']}", + "retry_count": attempt_count, + "auxiliary_task": str(context["task"]), + } + + +def _relay_sync_completion( + client: Any, + kwargs: dict[str, Any], + *, + provider: str | None = None, + api_mode: str | None = None, + create: Callable[[dict[str, Any]], Any] | None = None, +) -> Any: + callback = create or (lambda request: client.chat.completions.create(**request)) + route = _relay_auxiliary_metadata(provider=provider, api_mode=api_mode) + if route is None: + return callback(kwargs) + provider_name, fallback_model, metadata = route + from agent import relay_llm + + return relay_llm.execute_current( + kwargs, + callback, + name=provider_name, + model_name=str(kwargs.get("model") or fallback_model), + metadata=metadata, + defer_logical_completion=True, + ) + + +async def _relay_async_completion( + client: Any, + kwargs: dict[str, Any], + *, + provider: str | None = None, + api_mode: str | None = None, + create: Callable[[dict[str, Any]], Any] | None = None, +) -> Any: + callback = create or (lambda request: client.chat.completions.create(**request)) + route = _relay_auxiliary_metadata(provider=provider, api_mode=api_mode) + if route is None: + return await callback(kwargs) + provider_name, fallback_model, metadata = route + from agent import relay_llm + + return await relay_llm.execute_current_async( + kwargs, + callback, + name=provider_name, + model_name=str(kwargs.get("model") or fallback_model), + metadata=metadata, + defer_logical_completion=True, + ) + + +def _relay_sync_stream( + client: Any, + kwargs: dict[str, Any], + *, + provider: str | None = None, + api_mode: str | None = None, +) -> Any: + route = _relay_auxiliary_metadata(provider=provider, api_mode=api_mode) + if route is None: + return client.chat.completions.create(**kwargs) + provider_name, fallback_model, metadata = route + from agent import relay_llm + + return relay_llm.stream_current( + kwargs, + lambda request: client.chat.completions.create(**request), + name=provider_name, + model_name=str(kwargs.get("model") or fallback_model), + finalizer=dict, + metadata=metadata, + ) _RUNTIME_MAIN_COMPAT_SNAPSHOT: Tuple[Any, ...] = ("", "", "", "", "", "") _RUNTIME_MAIN_COMPAT_LOCK = threading.Lock() @@ -2378,6 +2698,7 @@ def set_runtime_main( provider: str, model: str, *, + requested_provider: str = "", base_url: str = "", api_key: Any = "", api_mode: str = "", @@ -2393,6 +2714,7 @@ def set_runtime_main( global _RUNTIME_MAIN_AUTH_MODE, _RUNTIME_MAIN_COMPAT_SNAPSHOT runtime = { "provider": (provider or "").strip().lower(), + "requested_provider": (requested_provider or "").strip().lower(), "model": (model or "").strip(), "base_url": (base_url or "").strip(), "api_key": ( @@ -2573,7 +2895,7 @@ def _try_custom_endpoint() -> Tuple[Optional[Any], Optional[str]]: return None, None if custom_base.lower().startswith(_CODEX_AUX_BASE_URL.lower()): return None, None - model = _read_main_model() or "gpt-4o-mini" + model = _read_main_model_for_aux() or "gpt-4o-mini" logger.debug("Auxiliary client: custom endpoint (%s, api_mode=%s)", model, custom_mode or "chat_completions") _clean_base, _dq = _extract_url_query_params(custom_base) _extra = {"default_query": _dq} if _dq else {} @@ -2635,7 +2957,13 @@ def _build_xai_oauth_aux_client(model: str) -> Tuple[Optional[Any], Optional[str return None, None api_key, base_url = resolved logger.debug("Auxiliary client: xAI OAuth (%s via Responses API)", model) - real_client = _create_openai_client(api_key=api_key, base_url=base_url) + from tools.xai_http import hermes_xai_default_headers + + real_client = _create_openai_client( + api_key=api_key, + base_url=base_url, + default_headers=hermes_xai_default_headers(), + ) return CodexAuxiliaryClient(real_client, model), model @@ -2865,6 +3193,7 @@ _AUTO_PROVIDER_LABELS = { } _MAIN_RUNTIME_FIELDS = ("provider", "model", "base_url", "api_key", "api_mode", "auth_mode") +_MAIN_RUNTIME_CONTEXT_FIELDS = _MAIN_RUNTIME_FIELDS + ("requested_provider",) def _normalize_main_runtime(main_runtime: Optional[Dict[str, Any]]) -> Dict[str, Any]: @@ -2887,7 +3216,7 @@ def _normalize_main_runtime(main_runtime: Optional[Dict[str, Any]]) -> Dict[str, if not isinstance(main_runtime, dict): return {} normalized: Dict[str, Any] = {} - for field in _MAIN_RUNTIME_FIELDS: + for field in _MAIN_RUNTIME_CONTEXT_FIELDS: value = main_runtime.get(field) # Preserve a callable api_key (Entra ID bearer provider) unchanged. if field == "api_key" and callable(value) and not isinstance(value, str): @@ -2895,9 +3224,10 @@ def _normalize_main_runtime(main_runtime: Optional[Dict[str, Any]]) -> Dict[str, continue if isinstance(value, str) and value.strip(): normalized[field] = value.strip() - provider = normalized.get("provider") - if isinstance(provider, str): - normalized["provider"] = provider.lower() + for identity_field in ("provider", "requested_provider"): + identity = normalized.get(identity_field) + if isinstance(identity, str): + normalized[identity_field] = identity.lower() return normalized @@ -3588,6 +3918,7 @@ def _retry_same_provider_sync( effective_timeout: float, effective_extra_body: dict, reasoning_config: Optional[dict], + extra_headers: Optional[Dict[str, str]] = None, ) -> Any: if task == "vision": _, retry_client, retry_model = resolve_vision_provider_client( @@ -3623,11 +3954,23 @@ def _retry_same_provider_sync( extra_body=effective_extra_body, reasoning_config=reasoning_config, base_url=retry_base or resolved_base_url, + task=task, ) + # Preserve per-request attribution headers (e.g. Copilot's + # ``x-initiator: user``) across the rebuilt-client retry — dropping them + # here would let a recovery retry silently lose capability gating (#60293). + if extra_headers: + retry_kwargs["extra_headers"] = dict(extra_headers) if _is_anthropic_compat_endpoint(resolved_provider, retry_base): retry_kwargs["messages"] = _convert_openai_images_to_anthropic(retry_kwargs["messages"]) return _validate_llm_response( - retry_client.chat.completions.create(**retry_kwargs), task, + _relay_sync_completion( + retry_client, + retry_kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + ), + task, ) @@ -3647,6 +3990,7 @@ async def _retry_same_provider_async( effective_timeout: float, effective_extra_body: dict, reasoning_config: Optional[dict], + extra_headers: Optional[Dict[str, str]] = None, ) -> Any: if task == "vision": _, retry_client, retry_model = resolve_vision_provider_client( @@ -3682,11 +4026,22 @@ async def _retry_same_provider_async( extra_body=effective_extra_body, reasoning_config=reasoning_config, base_url=retry_base or resolved_base_url, + task=task, ) + # Preserve per-request attribution headers across the rebuilt-client + # retry — see the sync variant above (#60293). + if extra_headers: + retry_kwargs["extra_headers"] = dict(extra_headers) if _is_anthropic_compat_endpoint(resolved_provider, retry_base): retry_kwargs["messages"] = _convert_openai_images_to_anthropic(retry_kwargs["messages"]) return _validate_llm_response( - await retry_client.chat.completions.create(**retry_kwargs), task, + await _relay_async_completion( + retry_client, + retry_kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + ), + task, ) @@ -3757,6 +4112,24 @@ def _refresh_provider_credentials(provider: str) -> bool: return False _evict_cached_clients(normalized) return True + if normalized == "vertex": + # Mirrors run_agent.py's _try_refresh_vertex_client_credentials + # for the main conversation loop. Without this branch, an + # auxiliary Vertex client (vision, title generation, reflection, + # context compression, ...) that 401s on its ~1h token expiry + # falls through to the final `return False` below: the stale + # client is never evicted from _client_cache (whose cache key + # ignores the rotating bearer token), so every subsequent + # auxiliary Vertex call keeps 401ing until process restart. + from agent.vertex_adapter import get_vertex_config + + token, base_url = get_vertex_config() + if not isinstance(token, str) or not token.strip(): + return False + if not isinstance(base_url, str) or not base_url.strip(): + return False + _evict_cached_clients(normalized) + return True except Exception as exc: logger.debug("Auxiliary provider credential refresh failed for %s: %s", normalized, exc) return False @@ -3870,10 +4243,10 @@ def _call_fallback_candidate_sync( temperature=temperature, max_tokens=max_tokens, tools=tools, timeout=effective_timeout, extra_body=effective_extra_body, reasoning_config=reasoning_config, - base_url=fb_base) + base_url=fb_base, task=task) try: return _validate_llm_response( - fb_client.chat.completions.create(**fb_kwargs), task) + _relay_sync_completion(fb_client, fb_kwargs, provider=fb_label), task) except Exception as fb_err: if not _is_auth_error(fb_err): raise @@ -3887,10 +4260,16 @@ def _call_fallback_candidate_sync( tools=tools, timeout=effective_timeout, extra_body=effective_extra_body, reasoning_config=reasoning_config, - base_url=str(getattr(retry_client, "base_url", "") or fb_base)) + base_url=str(getattr(retry_client, "base_url", "") or fb_base), task=task) try: return _validate_llm_response( - retry_client.chat.completions.create(**retry_kwargs), task) + _relay_sync_completion( + retry_client, + retry_kwargs, + provider=fb_provider, + ), + task, + ) except Exception as retry_err: if not _is_auth_error(retry_err): raise @@ -3936,10 +4315,16 @@ async def _call_fallback_candidate_async( temperature=temperature, max_tokens=max_tokens, tools=tools, timeout=effective_timeout, extra_body=effective_extra_body, reasoning_config=reasoning_config, - base_url=fb_base) + base_url=fb_base, task=task) try: return _validate_llm_response( - await fb_client.chat.completions.create(**fb_kwargs), task) + await _relay_async_completion( + fb_client, + fb_kwargs, + provider=fb_label, + ), + task, + ) except Exception as fb_err: if not _is_auth_error(fb_err): raise @@ -3954,10 +4339,16 @@ async def _call_fallback_candidate_async( tools=tools, timeout=effective_timeout, extra_body=effective_extra_body, reasoning_config=reasoning_config, - base_url=str(getattr(retry_client, "base_url", "") or fb_base)) + base_url=str(getattr(retry_client, "base_url", "") or fb_base), task=task) try: return _validate_llm_response( - await retry_client.chat.completions.create(**retry_kwargs), task) + await _relay_async_completion( + retry_client, + retry_kwargs, + provider=fb_provider, + ), + task, + ) except Exception as retry_err: if not _is_auth_error(retry_err): raise @@ -4025,6 +4416,7 @@ def _try_main_agent_model_fallback( failed_provider: str, task: str = None, reason: str = "error", + failed_model: Optional[str] = None, ) -> Tuple[Optional[Any], Optional[str], str]: """Last-resort fallback to the user's main agent provider + model. @@ -4033,20 +4425,56 @@ def _try_main_agent_model_fallback( layer: if nothing the user asked for can serve the request, try the main chat model before giving up. - Skips when the failed provider already IS the main provider (no point - retrying the same backend that just failed). + ``failed_model`` narrows the same-provider skip to the exact + (provider, model) pair that just failed, mirroring + :func:`_try_configured_fallback_chain`. This matters for self-hosted / + custom endpoints serving several models behind one provider label: the + aux compression model timing out says nothing about the health of the + main agent model deployed on the same URL (real incident: aux + ``glm-5.2`` hung and timed out while main ``macaron-v1-venti`` on the + identical endpoint was serving 448K-token turns fine — the + provider-label skip discarded the one fallback that would have worked). + + - Model-specific runtime failures (timeout, connection, rate limit, + model-incompatible, invalid response) pass ``failed_model``: skip the + main model only when it IS the exact model that failed. + - Provider-wide failures (auth 401, payment 402) and legacy callers + leave ``failed_model`` as None, keeping the whole-provider skip — + the shared credentials/account are broken, so the main model on the + same provider cannot help either. Returns: (client, model, provider_label) or (None, None, "") if no fallback. """ main_provider = (_read_main_provider() or "").strip() main_model = (_read_main_model() or "").strip() + if main_provider.lower() == "moa": + # MoA virtual provider: fall back to the preset's aggregator — the + # acting model — instead of the unreachable "moa"/ pair. + _agg_provider, _agg_model = _resolve_moa_aggregator(main_model) + if not _agg_provider or not _agg_model: + return None, None, "" + main_provider, main_model = _agg_provider, _agg_model if not main_provider or not main_model or main_provider.lower() in {"auto", ""}: return None, None, "" - skip = (failed_provider or "").lower().strip() - if main_provider.lower() == skip: - # The thing that failed IS the main model — nothing to fall back to. + # Identity + scope semantics owned by agent.backend_identity (#72468): + # model-scoped failures skip only the exact deployment that failed; + # provider-wide failures (no failed_model) skip the credential surface. + from agent.backend_identity import ( + BackendIdentity, + FailureScope, + should_skip_candidate, + ) + + skip_model = (failed_model or "").strip().lower() or None + if should_skip_candidate( + BackendIdentity.build(provider=main_provider, model=main_model), + BackendIdentity.build(provider=failed_provider, model=skip_model), + FailureScope.MODEL if skip_model else FailureScope.CREDENTIAL, + ): + # The thing that failed IS the main model (or the failure was + # provider-wide) — nothing to fall back to. return None, None, "" if _is_provider_unhealthy(main_provider): _log_skip_unhealthy(main_provider, task) @@ -4156,6 +4584,7 @@ def _try_configured_fallback_chain( task: str, failed_provider: str, reason: str = "error", + failed_model: Optional[str] = None, ) -> Tuple[Optional[Any], Optional[str], str]: """Try user-configured fallback_chain for a specific auxiliary task. @@ -4163,6 +4592,25 @@ def _try_configured_fallback_chain( entry in order. Each entry must have at least ``provider``; ``model``, ``base_url``, and ``api_key`` are optional. + ``failed_model`` narrows the skip check to the exact (provider, model) + pair that just failed, rather than the whole provider. Without it every + entry sharing the failed provider is skipped (the original behaviour). + Callers pass it only when a sibling model on the same provider could + plausibly recover: + + - Model-specific runtime failures (timeout, connection, rate limit, + model-incompatible, invalid response) pass ``failed_model`` so a + chain that intentionally lists several models under the same provider + — e.g. two more NVIDIA NIM models after the primary NIM model times + out — is not skipped wholesale. Only the exact model that failed is + skipped; the siblings still run instead of jumping straight to the + main-agent-model safety net. + - Provider-wide failures (auth 401, payment 402) and "no client could + be built" callers leave ``failed_model`` as None, keeping the whole + provider skipped — the shared credentials/account behind every model + on that provider are broken, so a sibling can't help and the + main-agent-model safety net should be reached instead. + Returns: (client, model, provider_label) or (None, None, "") if no fallback. """ @@ -4174,7 +4622,24 @@ def _try_configured_fallback_chain( if not chain or not isinstance(chain, list): return None, None, "" - skip = failed_provider.lower().strip() + skip_model = (failed_model or "").strip().lower() or None + # Identity + scope semantics owned by agent.backend_identity (#59561, + # #72468): a failed_model means the failure was model-scoped (timeout / + # connection / rate limit) — only the exact deployment is skipped; no + # failed_model means provider-wide (auth/payment) — the whole credential + # surface is skipped. + from agent.backend_identity import ( + BackendIdentity, + FailureScope, + should_skip_candidate, + ) + + failed_ident = BackendIdentity.build( + provider=failed_provider, model=skip_model, + ) + failure_scope = ( + FailureScope.MODEL if skip_model else FailureScope.CREDENTIAL + ) tried = [] min_ctx = _task_minimum_context_length(task) @@ -4182,9 +4647,20 @@ def _try_configured_fallback_chain( if not isinstance(entry, dict): continue fb_provider = str(entry.get("provider", "")).strip() - if not fb_provider or fb_provider.lower() == skip: + if not fb_provider: continue - fb_model = str(entry.get("model", "")).strip() or None + fb_model_raw = str(entry.get("model", "")).strip() + if should_skip_candidate( + BackendIdentity.build( + provider=fb_provider, + model=fb_model_raw, + base_url=str(entry.get("base_url") or ""), + ), + failed_ident, + failure_scope, + ): + continue + fb_model = fb_model_raw or None label = f"fallback_chain[{i}]({fb_provider})" @@ -4441,26 +4917,17 @@ def _resolve_auto( # model. Resolve the MoA preset to its aggregator slot and continue Step 1 # with that real provider+model. Mirrors the MoA context-length resolution. if main_provider == "moa": - try: - from hermes_cli.config import load_config - from hermes_cli.moa_config import resolve_moa_preset - - _preset = resolve_moa_preset(load_config().get("moa") or {}, main_model) - _agg = _preset.get("aggregator") or {} - _agg_provider = str(_agg.get("provider") or "").strip() - _agg_model = str(_agg.get("model") or "").strip() - if _agg_provider and _agg_model and _agg_provider.lower() != "moa": - main_provider = _agg_provider - main_model = _agg_model - # The MoA virtual runtime carries a non-HTTP base_url - # ("moa://local") and a placeholder api_key; they belong to the - # facade, not the aggregator's real provider. Drop them so the - # aggregator resolves through its own provider credentials. - runtime_base_url = "" - runtime_api_key = "" - runtime_api_mode = "" - except Exception: - logger.debug("MoA aux resolution to aggregator failed", exc_info=True) + _agg_provider, _agg_model = _resolve_moa_aggregator(main_model) + if _agg_provider and _agg_model: + main_provider = _agg_provider + main_model = _agg_model + # The MoA virtual runtime carries a non-HTTP base_url + # ("moa://local") and a placeholder api_key; they belong to the + # facade, not the aggregator's real provider. Drop them so the + # aggregator resolves through its own provider credentials. + runtime_base_url = "" + runtime_api_key = "" + runtime_api_mode = "" if (main_provider and main_model and main_provider not in {"auto", ""}): @@ -4624,6 +5091,10 @@ def _to_async_client(sync_client, model: str, is_vision: bool = False): async_kwargs["default_headers"] = {"User-Agent": "claude-code/0.1.0"} elif base_url_host_matches(sync_base_url, "integrate.api.nvidia.com"): async_kwargs["default_headers"] = build_nvidia_nim_headers(sync_base_url) + elif base_url_host_matches(sync_base_url, "x.ai"): + from tools.xai_http import hermes_xai_default_headers + + async_kwargs["default_headers"] = hermes_xai_default_headers() else: # Fall back to profile.default_headers for providers that declare # client-level headers on their ProviderProfile (e.g. attribution @@ -4715,6 +5186,27 @@ def resolve_provider_client( # Normalise aliases provider = _normalize_aux_provider(provider) + # MoA virtual provider chokepoint: "moa" is not a real HTTP provider — + # its acting model is the preset's aggregator slot. The two resolver + # layers above (_resolve_auto, _resolve_task_provider_model) already + # unwrap their own paths, but callers that route here directly (vision + # auto-detect, _try_main_agent_model_fallback, get_available_vision_backends, + # plugin code) would otherwise dead-end in the unknown-provider branch. + # ``model`` carries the preset name for moa calls; when the preset can't + # be resolved we leave the call untouched and let the normal + # missing-provider handling produce its diagnostic. + if provider == "moa": + _agg_provider, _agg_model = _resolve_moa_aggregator(model) + if _agg_provider and _agg_model: + original_provider = _agg_provider.strip().lower() + provider = _normalize_aux_provider(_agg_provider) + model = _agg_model + # The moa:// facade endpoint and placeholder key belong to the + # virtual runtime, not the aggregator's real provider. + if explicit_base_url and str(explicit_base_url).lower().startswith("moa://"): + explicit_base_url = None + explicit_api_key = None + # Universal model-resolution fallback for concrete providers. ``auto`` is # intentionally excluded: `_resolve_auto(main_runtime=...)` returns the # model paired with the provider it actually selected. Pre-filling an auto @@ -4735,6 +5227,10 @@ def resolve_provider_client( # the load-bearing step for OAuth providers: an xai-oauth user # with grok-4.3 configured gets grok-4.3 for title generation # instead of silently dropping to whatever Step-2 fallback (#31845). + # When the main provider is MoA, ``_read_main_model_for_aux()`` + # substitutes the preset's aggregator model — the preset NAME is + # never a valid wire model id, so unset aux models default to the + # preset's acting model instead. # # Each provider branch below sees a non-empty ``model`` whenever the # user has *anything* configured — no provider-specific empty-model @@ -4751,7 +5247,7 @@ def resolve_provider_client( # return the actual current runtime model when the caller did not explicitly # request one. (# compression-current-model) if not model and provider != "auto": - model = _get_aux_model_for_provider(provider) or _read_main_model() or model + model = _get_aux_model_for_provider(provider) or _read_main_model_for_aux() or model def _needs_codex_wrap(client_obj, base_url_str: str, model_str: str) -> bool: """Decide if a plain OpenAI client should be wrapped for Responses API. @@ -4835,10 +5331,11 @@ def resolve_provider_client( # ── Nous Portal (OAuth) ────────────────────────────────────────── if provider == "nous": - # Detect vision tasks: either explicit model override from - # _PROVIDER_VISION_MODELS, or caller passed a known vision model. + # Detect vision tasks: caller flag (strict vision backend), explicit + # model override from _PROVIDER_VISION_MODELS, or a known vision id. _is_vision = ( - model in _PROVIDER_VISION_MODELS.values() + is_vision + or model in _PROVIDER_VISION_MODELS.values() or (model or "").strip().lower() == "mimo-v2-omni" ) client, default = _try_nous(vision=_is_vision) @@ -4847,6 +5344,17 @@ def resolve_provider_client( "but Nous Portal not configured (run: hermes auth)") return None, None final_model = _normalize_resolved_model(model or default, provider) + # Dual-wire: anthropic/* → /v1/messages, everything else stays on + # /chat/completions. Derive from the catalog id (not a stale + # api_mode=chat_completions) so aux matches the main agent. + from hermes_cli.providers import nous_api_mode + + portal_mode = nous_api_mode(final_model) + api_key_str = str(getattr(client, "api_key", "") or "") + base_url_str = str(getattr(client, "base_url", "") or "") + client = _maybe_wrap_anthropic( + client, final_model, api_key_str, base_url_str, portal_mode, + ) return (_to_async_client(client, final_model, is_vision=is_vision) if async_mode else (client, final_model)) @@ -5025,7 +5533,7 @@ def resolve_provider_client( model or custom_entry.get("model") or (main_runtime.get("model") if main_runtime else None) - or _read_main_model() + or _read_main_model_for_aux() or "gpt-4o-mini", provider, ) @@ -5210,6 +5718,10 @@ def resolve_provider_client( )) elif base_url_host_matches(base_url, "integrate.api.nvidia.com"): headers.update(build_nvidia_nim_headers(base_url)) + elif base_url_host_matches(base_url, "x.ai"): + from tools.xai_http import hermes_xai_default_headers + + headers.update(hermes_xai_default_headers()) else: # Fall back to profile.default_headers for providers that declare # client-level attribution headers on their profile (e.g. GMI @@ -5260,7 +5772,7 @@ def resolve_provider_client( final_model = _normalize_resolved_model( model or (main_runtime.get("model") if main_runtime else None) - or _read_main_model(), + or _read_main_model_for_aux(), provider, ) if provider == "copilot-acp": @@ -5503,7 +6015,10 @@ def _resolve_strict_vision_backend( if provider == "openrouter": return _try_openrouter(model=model) if provider == "nous": - return _try_nous(vision=True) + # Must go through resolve_provider_client so anthropic/* vision + # recommendations wrap onto /v1/messages — _try_nous alone returns + # a bare OpenAI client and the call 404s. + return resolve_provider_client("nous", model, is_vision=True) if provider == "openai-codex": # Route through resolve_provider_client so the caller's explicit # model is used. There is no safe default Codex model (shifting @@ -5628,7 +6143,24 @@ def resolve_vision_provider_client( # 5. Stop main_provider = str(runtime.get("provider") or _read_main_provider()) main_model = str(runtime.get("model") or _read_main_model()) - if main_provider and main_provider not in {"auto", ""}: + if main_provider.strip().lower() == "moa": + # MoA virtual provider: main_model is a preset NAME, and every + # capability probe below (_PROVIDERS_WITHOUT_VISION, + # _main_model_supports_vision, _resolve_provider_vision_default) + # would run against a provider/model pair that doesn't exist on + # any wire. Unwrap to the preset's aggregator slot first so the + # checks and the eventual client target the real acting model. + _agg_provider, _agg_model = _resolve_moa_aggregator(main_model) + if _agg_provider and _agg_model: + main_provider, main_model = _agg_provider, _agg_model + # Drop the moa:// facade endpoint from the runtime view used + # below — it belongs to the virtual provider, not the + # aggregator's real provider. + runtime = dict(runtime) + runtime["base_url"] = "" + runtime["api_key"] = "" + runtime["api_mode"] = "" + if main_provider and main_provider not in {"auto", "", "moa"}: # A provider-specific vision default wins over the user's chat model: # static overrides (xiaomi/zai) and catalog-backed discovery (the # DeepInfra profile hook) both yield a *known* vision-capable model, @@ -6225,8 +6757,8 @@ def _resolve_task_provider_model( task: str = None, provider: str = None, model: str = None, - base_url: str = None, - api_key: str = None, + base_url: Optional[str] = None, + api_key: Optional[str] = None, ) -> Tuple[str, Optional[str], Optional[str], Optional[str], Optional[str]]: """Determine provider + model for a call. @@ -6269,12 +6801,57 @@ def _resolve_task_provider_model( # which downstream consumers like ContextCompressor accept as the task output. # The provider-side 'auto' is handled in _resolve_auto() via main_runtime # fallback, so dropping cfg_model to None here lets that path do its job. + # + # The explicit `model` kwarg needs the identical normalization: MoA slots + # (agent/moa_loop.py's _slot_runtime) forward a preset's `model:` field as + # this explicit argument rather than through auxiliary. config, so a + # user-configured `model: auto` on a MoA reference/aggregator slot reaches + # this function here, not as cfg_model. Only normalizing cfg_model let that + # literal "auto" slip through via `model or cfg_model` below. + if model and model.lower() == "auto": + model = None if cfg_model and cfg_model.lower() == "auto": cfg_model = None resolved_model = model or cfg_model resolved_api_mode = cfg_api_mode + # MoA virtual provider: an *explicit* `provider: moa` override (either the + # caller-passed `provider` arg or `auxiliary..provider` in + # config.yaml) reaches this function directly — it never goes through + # _resolve_auto(), which only unwraps the *implicit* "main provider is + # moa" case (#53827). Left as-is, "moa" is returned verbatim and + # resolve_provider_client() looks it up in PROVIDER_REGISTRY (which has + # no "moa" entry — it's not a real HTTP provider), falls to the + # unknown-provider dead end, and call_llm surfaces a nonsensical + # "MOA_API_KEY environment variable" error for a provider that was never + # meant to be reached over the wire. Auxiliary tasks don't need the + # reference fan-out — resolve to the preset's aggregator slot instead, + # exactly like the implicit path does (shared helper: _resolve_moa_aggregator). + def _unwrap_moa_provider(prov: str, mdl: Optional[str]) -> Tuple[str, Optional[str]]: + if prov.strip().lower() != "moa": + return prov, mdl + agg_provider, agg_model = _resolve_moa_aggregator(mdl) + if agg_provider and agg_model: + return agg_provider, agg_model + return prov, mdl + + if provider and str(provider).strip().lower() == "moa": + provider, resolved_model = _unwrap_moa_provider(provider, resolved_model) + # The moa:// virtual endpoint (if any explicit base_url/api_key was + # passed alongside provider="moa") belongs to the facade, not the + # aggregator's real provider — drop it so the aggregator resolves + # through its own provider credentials, mirroring _resolve_auto(). + if provider and provider.lower() != "moa": + base_url = None + api_key = None + elif cfg_provider and str(cfg_provider).strip().lower() == "moa": + cfg_provider, cfg_model = _unwrap_moa_provider(cfg_provider, resolved_model) + if cfg_provider and cfg_provider.lower() != "moa": + resolved_model = cfg_model + cfg_base_url = None + cfg_api_key = None + # Convenience aliases for direct API-key endpoints that aren't first-class # providers (e.g. ``provider: openai`` → custom + api.openai.com/v1). # Applied to both explicit args and config-derived values. When the user @@ -6631,6 +7208,7 @@ def _build_call_kwargs( extra_body: Optional[dict] = None, reasoning_config: Optional[dict] = None, base_url: Optional[str] = None, + task: Optional[str] = None, ) -> dict: """Build kwargs for .chat.completions.create() with model/provider adjustments.""" kwargs: Dict[str, Any] = { @@ -6685,11 +7263,38 @@ def _build_call_kwargs( _provider_norm in {"nvidia", "nvidia-nim", "nim", "build-nvidia", "nemotron"} or base_url_host_matches(_effective_base, "integrate.api.nvidia.com") ) + _is_moa = bool(task) and str(task) == "moa_reference" + # Gemini's native generateContent maps max_tokens → maxOutputTokens and, + # when it is omitted, applies a fixed 65,535-token ceiling rather than + # "the model's full budget" (see gemini_native_adapter.build_gemini_request). + # So an explicit cap is both safe and the ONLY way to honor it here — + # dropping max_tokens silently makes MoA's reference_max_tokens a no-op + # for gemini advisors (they run effectively uncapped). + _is_gemini_native = _provider_norm in { + "gemini", "google", "google-gemini", "google-ai-studio", + } + if not _is_gemini_native and _effective_base: + try: + from agent.gemini_native_adapter import is_native_gemini_base_url + _is_gemini_native = is_native_gemini_base_url(_effective_base) + except Exception: + pass + _nous_on_messages = False + if _provider_norm in {"nous", "nous-portal", "nousresearch"}: + from hermes_cli.providers import nous_api_mode + + _nous_on_messages = nous_api_mode(model) == "anthropic_messages" if ( _is_anthropic_compat_endpoint(provider, _effective_base) + or _nous_on_messages or _is_nvidia_nim + or _is_moa + or _is_gemini_native ): - kwargs["max_tokens"] = max_tokens + # Use auxiliary_max_tokens_param() so models that require + # max_completion_tokens (GPT-5 family, Copilot) get the right + # parameter name instead of a hardcoded max_tokens that 400s. + kwargs.update(auxiliary_max_tokens_param(max_tokens, model=model)) if tools: # Defensive dedup: providers like Google Vertex, Azure, and Bedrock @@ -6776,21 +7381,43 @@ def _build_call_kwargs( else: effort = reasoning_config.get("effort") or "medium" merged_extra["reasoning"] = {"enabled": True, "effort": effort} - if provider == "nous" and "tags" not in merged_extra: - merged_extra["tags"] = _nous_portal_tags() + # Portal product tags + sticky session_id. The provider profile usually + # supplies both; this fallback covers profile-load failures and alias + # spellings the profile lookup might miss. session_id keeps aux + # compression/title/vision calls on the same upstream instance as the + # main turn (cache warmth) — tags alone are not enough on /v1/messages. + _provider_for_portal = str(provider or "").strip().lower() + if _provider_for_portal in {"nous", "nous-portal", "nousresearch"}: + if "tags" not in merged_extra: + merged_extra["tags"] = _nous_portal_tags() + if "session_id" not in merged_extra: + try: + from agent.portal_tags import get_conversation_context + + sticky_key = get_conversation_context() + except Exception: + sticky_key = None + if sticky_key: + merged_extra["session_id"] = sticky_key if merged_extra: kwargs["extra_body"] = merged_extra - # Native Anthropic Messages adapters do not consume ``extra_body``. Carry - # the normalized Hermes reasoning config through a private kwarg so the - # adapter can pass it into build_anthropic_kwargs(), where provider-aware - # thinking/output_config projection lives. Do not expose this private kwarg - # to ordinary OpenAI-compatible SDK clients, which would reject it. + # Anthropic Messages adapters translate Hermes reasoning into native + # ``thinking`` via a private kwarg (and strip OpenAI-shaped + # ``extra_body.reasoning``). Do not expose this private kwarg to ordinary + # OpenAI-compatible SDK clients, which would reject it. Portal Claude is + # dual-wire — include it when the catalog id selects /v1/messages. if reasoning_config and isinstance(reasoning_config, dict): provider_norm = str(provider or "").strip().lower() effective_base = base_url or "" + _nous_on_messages = False + if provider_norm in {"nous", "nous-portal", "nousresearch"}: + from hermes_cli.providers import nous_api_mode + + _nous_on_messages = nous_api_mode(model) == "anthropic_messages" if ( provider_norm == "anthropic" + or _nous_on_messages or _endpoint_speaks_anthropic_messages(effective_base) or _is_anthropic_compat_endpoint(provider_norm, effective_base) ): @@ -6836,6 +7463,7 @@ def _validate_llm_response( except (AttributeError, TypeError, IndexError) as exc: recovered = _recover_aux_response_message(response) if recovered is not None: + _complete_relay_auxiliary_call() return recovered response_type = type(response).__name__ response_preview = str(response)[:120] @@ -6845,9 +7473,34 @@ def _validate_llm_response( f"Expected object with .choices[0].message — check provider " f"adapter or custom endpoint compatibility." ) from exc + _complete_relay_auxiliary_call() return response +def _complete_relay_auxiliary_call(*, outcome: str = "success") -> None: + """Close one auxiliary logical call after acceptance or terminal failure.""" + context = _RELAY_AUX_CALL_CONTEXT.get() + if context is None: + return + from agent import relay_llm + + relay_llm.complete_logical_call( + str(context.get("request_id") or ""), + outcome=outcome, + ) + + +def _fail_relay_auxiliary_call() -> None: + """Close a terminally failed call without replacing its original error.""" + try: + _complete_relay_auxiliary_call(outcome="failed") + except Exception: + logger.warning( + "Relay auxiliary failure finalization failed", + exc_info=True, + ) + + def _recover_aux_response_message(response: Any) -> Optional[Any]: """Synthesize chat-completions shape from Responses-style text fields. @@ -6906,6 +7559,347 @@ def _obj_get(obj: Any, key: str, default: Any = None) -> Any: return value +# ── Streamed aggregation for progress-hooked auxiliary calls ───────────── +# When a forward-progress hook is installed (aux_progress_hook — today only +# by context compression), the primary chat.completions attempt is upgraded +# to a streamed request that is aggregated back into a complete response. +# Two effects, both deliberate: +# 1. The configured ``timeout`` becomes an INTER-CHUNK idle timeout instead +# of a total budget (httpx applies the read timeout per stream read), so +# a slow-but-generating summary model is never killed mid-generation +# while tokens are moving — only a genuinely silent connection dies. +# 2. Every arriving chunk ticks the progress hook, letting outer watchdogs +# (gateway session hygiene) extend their deadlines on liveness instead +# of guessing with a fixed wall clock. +# A total ceiling still bounds the pathological 1-token-per-idle-window +# stream; see _aux_stream_total_ceiling(). + +_AUX_STREAM_CEILING_FLOOR_SECONDS = 600.0 +_AUX_STREAM_CEILING_MULTIPLIER = 4.0 + + +def _aux_stream_total_ceiling(effective_timeout: Optional[float]) -> float: + """Absolute wall-clock bound for a progress-hooked streamed aux call. + + Generous by design — the idle timeout is the real guard; this only stops + a degenerate stream that trickles one token per idle window forever. + """ + try: + timeout = float(effective_timeout) if effective_timeout is not None else 0.0 + except (TypeError, ValueError): + timeout = 0.0 + return max(_AUX_STREAM_CEILING_FLOOR_SECONDS, + _AUX_STREAM_CEILING_MULTIPLIER * timeout) + + +def _client_streams_internally(client: Any) -> bool: + """Wire adapters that consume a stream inside .create() already tick the + progress hook themselves (Codex per SSE event, Anthropic per stream + event); Bedrock's Converse shim cannot stream at all. None of them + accept chat-completions ``stream=True`` semantics from us.""" + return isinstance(client, ( + CodexAuxiliaryClient, + AnthropicAuxiliaryClient, + BedrockAuxiliaryClient, + )) + + +def _is_streaming_rejected_error(exc: Exception) -> bool: + """Provider explicitly refused a streamed chat.completions request.""" + err = str(exc).lower() + if "stream_options" in err: + return True + return "stream" in err and ( + "not supported" in err + or "unsupported" in err + or "not allowed" in err + or "disabled" in err + ) + + +def _provider_requires_stream(provider: str, base_url: Optional[str]) -> bool: + """Detect providers that only accept streaming (non-stream = HTTP 400). + + Some OpenAI-compatible endpoints reject non-streaming chat requests + outright — e.g. Tencent Copilot returns + ``{"code": 11101, "msg": "Non-stream chat request is currently not + supported"}``. The main conversation loop already streams, so interactive + chat works; auxiliary tasks (title generation, compression, web extract) + used the non-streaming path and failed on every call. When this returns + True the auxiliary client sends ``stream=True`` and aggregates the chunks + itself (see :func:`_aggregate_chat_stream`). Credit @kudi88 (PR #60686). + + Beyond the known-host list, users can mark ANY custom endpoint as + stream-only via ``auxiliary.stream_only_base_urls`` in config.yaml + (list of substrings matched against the endpoint URL). + """ + _url = str(base_url or "").lower() + if not _url: + return False + # Tencent Copilot — "Non-stream chat request is currently not supported" + if base_url_host_matches(_url, "copilot.tencent.com"): + return True + try: + from hermes_cli.config import load_config + aux_cfg = (load_config() or {}).get("auxiliary", {}) + markers = aux_cfg.get("stream_only_base_urls") or [] + if isinstance(markers, (list, tuple)): + for marker in markers: + if isinstance(marker, str) and marker.strip() and marker.strip().lower() in _url: + return True + except Exception: + # Config read is best-effort; never break an aux call over it. + pass + return False + + +def _create_with_progress( + client: Any, + kwargs: Dict[str, Any], + task: Optional[str] = None, + *, + force_stream: bool = False, +) -> Any: + """chat.completions.create() that streams when a progress hook is active + or the provider only accepts streamed requests. + + Behavior is byte-for-byte identical to a plain ``create(**kwargs)`` when + neither trigger applies (every existing caller/task) or when the client's + wire adapter streams internally. With a hook + a chunk-capable client, + the request is sent with ``stream=True`` and aggregated, ticking the hook + per chunk — so the configured ``timeout`` acts per stream read (idle) + rather than as a total budget, and outer liveness watchdogs see tokens + moving. ``force_stream=True`` (stream-only providers such as Tencent + Copilot — credit @kudi88, PR #60686) takes the same streamed path even + without a hook. Providers that reject the streamed request fall back to + the plain non-streaming call — except under ``force_stream``, where a + stream-only provider rejects the plain call by definition, so the + original error is surfaced to the normal recovery chains instead. + """ + _notify_aux_progress() # request dispatched counts as progress + if (not _aux_progress_active() and not force_stream) or _client_streams_internally(client): + return client.chat.completions.create(**kwargs) + + total_ceiling = _aux_stream_total_ceiling(kwargs.get("timeout")) + stream_kwargs = dict(kwargs) + stream_kwargs["stream"] = True + stream_kwargs["stream_options"] = {"include_usage": True} + try: + chunks = client.chat.completions.create(**stream_kwargs) + except Exception as exc: + # Genuine provider failures (auth, credit, rate limit, network) are + # not streaming's fault — surface them unchanged so the existing + # recovery chains (credential refresh, pool rotation, provider + # fallback) see the same error they would on a plain call. + if ( + force_stream + or _is_transient_transport_error(exc) + or _is_auth_error(exc) + or _is_payment_error(exc) + or _is_rate_limit_error(exc) + ): + raise + # Anything else may be a streaming-specific rejection (explicit + # "stream not supported", stream_options 400, or an idiosyncratic + # 4xx). Retry non-streaming once; if the request itself is bad the + # plain call reproduces the real error for the normal except-chains. + logger.debug( + "Auxiliary %s: streamed request failed (%s); retrying " + "non-streaming", task or "call", exc, + ) + return client.chat.completions.create(**kwargs) + + # Some shims (MoA virtual provider under quiet mode, defensive adapters) + # return a complete response even when stream=True was requested. + if hasattr(chunks, "choices"): + _notify_aux_progress() + return chunks + return _aggregate_chat_stream( + chunks, model=str(kwargs.get("model") or ""), total_ceiling=total_ceiling, + ) + + +def _aggregate_chat_stream( + chunks: Any, + *, + model: str = "", + total_ceiling: Optional[float] = None, +) -> Any: + """Consume a chat.completions chunk stream into a complete response. + + Ticks the thread-local aux progress hook on every chunk. Raises + TimeoutError when *total_ceiling* seconds elapse before the stream + finishes — phrased with "timed out" so existing timeout classification + (``_is_timeout_error``) treats it exactly like a request timeout. + Accumulation is shared with the async mirror via + :class:`_ChatStreamAccumulator`. + """ + acc = _ChatStreamAccumulator(model=model, total_ceiling=total_ceiling) + try: + for chunk in chunks: + acc.feed(chunk) + finally: + close_fn = getattr(chunks, "close", None) + if callable(close_fn): + try: + close_fn() + except Exception: + pass + return acc.finish() + + +class _ChatStreamAccumulator: + """Shared per-chunk accumulation for sync and async stream aggregation. + + Mirrors :func:`_aggregate_chat_stream`'s chunk handling so the async + consumer below cannot drift from the sync one (same content/reasoning/ + tool-call delta reassembly, same "timed out" ceiling phrasing). + """ + + def __init__(self, model: str = "", total_ceiling: Optional[float] = None): + self._started = time.monotonic() + self._total_ceiling = total_ceiling + self.content_parts: List[str] = [] + self.reasoning_parts: List[str] = [] + self.tool_calls_acc: Dict[int, Dict[str, Any]] = {} + self.finish_reason = None + self.usage = None + self.resp_id = "" + self.resp_model = model or "" + + def feed(self, chunk: Any) -> None: + _notify_aux_progress() + if ( + self._total_ceiling is not None + and (time.monotonic() - self._started) >= self._total_ceiling + ): + raise TimeoutError( + f"Auxiliary streamed call timed out after {self._total_ceiling:.0f}s " + "total ceiling (stream still open but over budget)" + ) + self.resp_id = getattr(chunk, "id", None) or self.resp_id + self.resp_model = getattr(chunk, "model", None) or self.resp_model + chunk_usage = getattr(chunk, "usage", None) + if chunk_usage: + self.usage = chunk_usage + choices = getattr(chunk, "choices", None) or [] + if not choices: + return + choice = choices[0] + self.finish_reason = getattr(choice, "finish_reason", None) or self.finish_reason + delta = getattr(choice, "delta", None) + if delta is None: + return + piece = getattr(delta, "content", None) + if piece: + self.content_parts.append(piece) + reasoning_piece = ( + getattr(delta, "reasoning", None) + or getattr(delta, "reasoning_content", None) + ) + if reasoning_piece and isinstance(reasoning_piece, str): + self.reasoning_parts.append(reasoning_piece) + for tc in (getattr(delta, "tool_calls", None) or []): + idx = getattr(tc, "index", 0) or 0 + acc = self.tool_calls_acc.setdefault( + idx, {"id": "", "name": "", "arguments": []} + ) + if getattr(tc, "id", None): + acc["id"] = tc.id + fn = getattr(tc, "function", None) + if fn is not None: + if getattr(fn, "name", None): + acc["name"] = fn.name + if getattr(fn, "arguments", None): + acc["arguments"].append(fn.arguments) + + def finish(self) -> Any: + tool_calls = None + if self.tool_calls_acc: + tool_calls = [ + SimpleNamespace( + id=acc["id"], + type="function", + function=SimpleNamespace( + name=acc["name"], + arguments="".join(acc["arguments"]), + ), + ) + for _idx, acc in sorted(self.tool_calls_acc.items()) + ] + message = SimpleNamespace( + role="assistant", + content="".join(self.content_parts), + tool_calls=tool_calls, + reasoning="".join(self.reasoning_parts) or None, + ) + choice = SimpleNamespace( + index=0, + message=message, + finish_reason=self.finish_reason or "stop", + ) + return SimpleNamespace( + id=self.resp_id, + model=self.resp_model, + object="chat.completion", + choices=[choice], + usage=self.usage, + ) + + +async def _aggregate_chat_stream_async( + chunks: Any, + *, + model: str = "", + total_ceiling: Optional[float] = None, +) -> Any: + """Async mirror of :func:`_aggregate_chat_stream` (``async for`` consumer). + + The AsyncOpenAI stream contract is an async iterator — consuming it with + the sync helper raises. Same accumulation and ceiling semantics via + :class:`_ChatStreamAccumulator`. + """ + acc = _ChatStreamAccumulator(model=model, total_ceiling=total_ceiling) + try: + async for chunk in chunks: + acc.feed(chunk) + finally: + close_fn = getattr(chunks, "close", None) or getattr(chunks, "aclose", None) + if callable(close_fn): + try: + result = close_fn() + if inspect.isawaitable(result): + await result + except Exception: + pass + return acc.finish() + + +async def _acreate_with_stream( + client: Any, + kwargs: Dict[str, Any], + task: Optional[str] = None, +) -> Any: + """Async chat.completions.create() for stream-only providers. + + Sends ``stream=True`` and aggregates the async chunk stream into a + complete response (credit @kudi88, PR #60686 — async contract fixed to + ``async for`` and tool-call deltas preserved per sweeper review). + """ + total_ceiling = _aux_stream_total_ceiling(kwargs.get("timeout")) + stream_kwargs = dict(kwargs) + stream_kwargs["stream"] = True + stream_kwargs["stream_options"] = {"include_usage": True} + chunks = await client.chat.completions.create(**stream_kwargs) + # Defensive: shims may hand back a complete response despite stream=True. + if hasattr(chunks, "choices"): + return chunks + return await _aggregate_chat_stream_async( + chunks, model=str(kwargs.get("model") or ""), total_ceiling=total_ceiling, + ) + + +@_relay_auxiliary_call def call_llm( task: str = None, *, @@ -6921,6 +7915,7 @@ def call_llm( timeout: float = None, extra_body: dict = None, reasoning_config: Optional[dict] = None, + extra_headers: Optional[Dict[str, str]] = None, api_mode: str = None, stream: bool = False, stream_options: dict = None, @@ -6946,6 +7941,9 @@ def call_llm( extra_body: Additional request body fields. reasoning_config: Optional Hermes reasoning config for direct model calls such as MoA reference/aggregator slots. + extra_headers: Additional per-request HTTP headers. These override + client-level defaults for providers that gate capabilities on + request attribution (for example Copilot's ``x-initiator``). stream: When True, return the raw SDK streaming iterator instead of a validated complete response. The caller is responsible for consuming chunks (and for any fallback). Used by the MoA aggregator so its @@ -7042,6 +8040,11 @@ def call_llm( f"Run: hermes setup") effective_timeout = _effective_aux_timeout(task, timeout) + _set_relay_auxiliary_route( + resolved_provider, + final_model, + resolved_api_mode, + ) # Log what we're about to do — makes auxiliary operations visible _base_info = str(getattr(client, "base_url", resolved_base_url) or "") @@ -7058,7 +8061,9 @@ def call_llm( temperature=temperature, max_tokens=max_tokens, tools=tools, timeout=effective_timeout, extra_body=effective_extra_body, reasoning_config=reasoning_config, - base_url=_base_info or resolved_base_url) + base_url=_base_info or resolved_base_url, task=task) + if extra_headers: + kwargs["extra_headers"] = dict(extra_headers) # Convert image blocks for Anthropic-compatible endpoints (e.g. MiniMax) _client_base = str(getattr(client, "base_url", "") or "") @@ -7077,7 +8082,12 @@ def call_llm( kwargs["stream"] = True if stream_options: kwargs["stream_options"] = stream_options - return client.chat.completions.create(**kwargs) + return _relay_sync_stream( + client, + kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + ) # Handle unsupported temperature, max_tokens vs max_completion_tokens retry, # then payment fallback. @@ -7100,7 +8110,21 @@ def call_llm( # for the transient retry every auxiliary task shares. (PR #16587) try: return _validate_llm_response( - client.chat.completions.create(**kwargs), task, + _relay_sync_completion( + client, + kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + create=lambda request: _create_with_progress( + client, + request, + task, + force_stream=_provider_requires_stream( + resolved_provider, _base_info or resolved_base_url, + ), + ), + ), + task, provider=resolved_provider, base_url=_base_info) except Exception as transient_err: if not _is_transient_transport_error(transient_err): @@ -7133,7 +8157,22 @@ def call_llm( time.sleep(_backoff) try: return _validate_llm_response( - client.chat.completions.create(**kwargs), task) + _relay_sync_completion( + client, + kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + create=lambda request: _create_with_progress( + client, + request, + task, + force_stream=_provider_requires_stream( + resolved_provider, + _base_info or resolved_base_url, + ), + ), + ), + task) except Exception as retry_transient: if not _is_transient_transport_error(retry_transient): raise @@ -7150,7 +8189,12 @@ def call_llm( ) try: return _validate_llm_response( - client.chat.completions.create(**retry_kwargs), task) + _relay_sync_completion( + client, + retry_kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + ), task) except Exception as retry_err: retry_err_str = str(retry_err) # If retry still fails, fall through to the max_tokens / @@ -7188,7 +8232,12 @@ def call_llm( kwargs.pop("max_completion_tokens", None) try: return _validate_llm_response( - client.chat.completions.create(**kwargs), task) + _relay_sync_completion( + client, + kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + ), task) except Exception as retry_err: # If the max_tokens retry also hits a payment or connection # error, fall through to the fallback chain below. @@ -7218,7 +8267,12 @@ def call_llm( kwargs["model"] = healed_model try: return _validate_llm_response( - client.chat.completions.create(**kwargs), task) + _relay_sync_completion( + client, + kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + ), task) except Exception as retry_err: first_err = retry_err @@ -7251,7 +8305,12 @@ def call_llm( kwargs["model"] = refreshed_model try: return _validate_llm_response( - refreshed_client.chat.completions.create(**kwargs), task) + _relay_sync_completion( + refreshed_client, + kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + ), task) except Exception as retry_err: if not ( _is_auth_error(retry_err) @@ -7279,7 +8338,12 @@ def call_llm( if refreshed_model and refreshed_model != kwargs.get("model"): kwargs["model"] = refreshed_model return _validate_llm_response( - refreshed_client.chat.completions.create(**kwargs), task) + _relay_sync_completion( + refreshed_client, + kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + ), task) # ── Auth refresh retry ─────────────────────────────────────── auth_refresh_provider = _auth_refresh_provider_for_route( @@ -7312,6 +8376,7 @@ def call_llm( effective_timeout=effective_timeout, effective_extra_body=effective_extra_body, reasoning_config=reasoning_config, + extra_headers=extra_headers, ) # ── Same-provider credential-pool recovery ───────────────────── @@ -7328,7 +8393,12 @@ def call_llm( if _is_rate_limit_error(first_err) and not _is_payment_error(first_err): try: return _validate_llm_response( - client.chat.completions.create(**kwargs), task) + _relay_sync_completion( + client, + kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + ), task) except Exception as retry_err: if not (_is_auth_error(retry_err) or _is_payment_error(retry_err) or _is_rate_limit_error(retry_err)): raise @@ -7355,6 +8425,7 @@ def call_llm( effective_timeout=effective_timeout, effective_extra_body=effective_extra_body, reasoning_config=reasoning_config, + extra_headers=extra_headers, ) except Exception as retry2_err: # The rotated key also hit a quota/auth wall. Mark it @@ -7448,6 +8519,15 @@ def call_llm( logger.info("Auxiliary %s: %s on %s (%s), trying fallback", task or "call", reason, resolved_provider, first_err) + # Narrow the configured-chain skip to the exact model that + # failed ONLY for model-specific failures. Auth (401) and + # payment (402) errors are provider-wide — the credentials or + # account behind every model on that provider are the same — so + # a sibling model can't recover; keep skipping the whole + # provider so the main-agent-model safety net is still reached. + _chain_failed_model = ( + None if reason in ("auth error", "payment error") else final_model + ) # Fallback order (#26882, #26803): # 1. User-configured fallback_chain (per-task) if set # 2. For auto: top-level main fallback_providers/fallback_model @@ -7456,7 +8536,8 @@ def call_llm( fb_client, fb_model, fb_label = (None, None, "") if is_auto: fb_client, fb_model, fb_label = _try_configured_fallback_chain( - task, resolved_provider or "auto", reason=reason) + task, resolved_provider or "auto", reason=reason, + failed_model=_chain_failed_model) if fb_client is None: fb_client, fb_model, fb_label = _try_main_fallback_chain( task, resolved_provider or "auto", reason=reason) @@ -7465,10 +8546,12 @@ def call_llm( resolved_provider, task, reason=reason) else: fb_client, fb_model, fb_label = _try_configured_fallback_chain( - task, resolved_provider or "auto", reason=reason) + task, resolved_provider or "auto", reason=reason, + failed_model=_chain_failed_model) if fb_client is None: fb_client, fb_model, fb_label = _try_main_agent_model_fallback( - resolved_provider, task, reason=reason) + resolved_provider, task, reason=reason, + failed_model=_chain_failed_model) if fb_client is not None: fb_resp = _call_fallback_candidate_sync( @@ -7573,6 +8656,7 @@ def extract_content_or_reasoning(response) -> str: return "" +@_relay_auxiliary_call_async async def async_call_llm( task: str = None, *, @@ -7664,6 +8748,11 @@ async def async_call_llm( f"Run: hermes setup") effective_timeout = _effective_aux_timeout(task, timeout) + _set_relay_auxiliary_route( + resolved_provider, + final_model, + resolved_api_mode, + ) # Pass the client's actual base_url (not just resolved_base_url) so # endpoint-specific temperature overrides can distinguish @@ -7674,7 +8763,7 @@ async def async_call_llm( temperature=temperature, max_tokens=max_tokens, tools=tools, timeout=effective_timeout, extra_body=effective_extra_body, reasoning_config=reasoning_config, - base_url=_client_base or resolved_base_url) + base_url=_client_base or resolved_base_url, task=task) # Convert image blocks for Anthropic-compatible endpoints (e.g. MiniMax) if _is_anthropic_compat_endpoint(resolved_provider, _client_base): @@ -7684,9 +8773,32 @@ async def async_call_llm( # Retry ONCE on the same provider for a transient transport blip # before the except-chain escalates to fallback — see call_llm() # for the rationale. (PR #16587) + _force_stream_async = ( + _provider_requires_stream( + resolved_provider, _client_base or resolved_base_url, + ) + and not isinstance(client, ( + AsyncCodexAuxiliaryClient, + AsyncAnthropicAuxiliaryClient, + AsyncBedrockAuxiliaryClient, + )) + ) + + async def _acreate(_kwargs: Dict[str, Any]) -> Any: + if _force_stream_async: + return await _acreate_with_stream(client, _kwargs, task) + return await client.chat.completions.create(**_kwargs) + try: return _validate_llm_response( - await client.chat.completions.create(**kwargs), task, + await _relay_async_completion( + client, + kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + create=_acreate, + ), + task, provider=resolved_provider, base_url=_client_base) except Exception as transient_err: if not _is_transient_transport_error(transient_err): @@ -7707,7 +8819,14 @@ async def async_call_llm( task or "call", transient_err, ) return _validate_llm_response( - await client.chat.completions.create(**kwargs), task) + await _relay_async_completion( + client, + kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + create=_acreate, + ), + task) except Exception as first_err: if "temperature" in kwargs and _is_unsupported_temperature_error(first_err): retry_kwargs = dict(kwargs) @@ -7718,7 +8837,12 @@ async def async_call_llm( ) try: return _validate_llm_response( - await client.chat.completions.create(**retry_kwargs), task) + await _relay_async_completion( + client, + retry_kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + ), task) except Exception as retry_err: retry_err_str = str(retry_err) if not ( @@ -7752,7 +8876,12 @@ async def async_call_llm( kwargs.pop("max_completion_tokens", None) try: return _validate_llm_response( - await client.chat.completions.create(**kwargs), task) + await _relay_async_completion( + client, + kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + ), task) except Exception as retry_err: # If the max_tokens retry also hits a payment or connection # error, fall through to the fallback chain below. @@ -7781,7 +8910,12 @@ async def async_call_llm( kwargs["model"] = healed_model try: return _validate_llm_response( - await client.chat.completions.create(**kwargs), task) + await _relay_async_completion( + client, + kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + ), task) except Exception as retry_err: first_err = retry_err @@ -7813,7 +8947,12 @@ async def async_call_llm( kwargs["model"] = refreshed_model try: return _validate_llm_response( - await refreshed_client.chat.completions.create(**kwargs), task) + await _relay_async_completion( + refreshed_client, + kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + ), task) except Exception as retry_err: if not ( _is_auth_error(retry_err) @@ -7840,7 +8979,12 @@ async def async_call_llm( if refreshed_model and refreshed_model != kwargs.get("model"): kwargs["model"] = refreshed_model return _validate_llm_response( - await refreshed_client.chat.completions.create(**kwargs), task) + await _relay_async_completion( + refreshed_client, + kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + ), task) # ── Auth refresh retry (mirrors sync call_llm) ─────────────── auth_refresh_provider = _auth_refresh_provider_for_route( @@ -7884,7 +9028,12 @@ async def async_call_llm( if _is_rate_limit_error(first_err) and not _is_payment_error(first_err): try: return _validate_llm_response( - await client.chat.completions.create(**kwargs), task) + await _relay_async_completion( + client, + kwargs, + provider=resolved_provider, + api_mode=resolved_api_mode, + ), task) except Exception as retry_err: if not (_is_auth_error(retry_err) or _is_payment_error(retry_err) or _is_rate_limit_error(retry_err)): raise @@ -7966,6 +9115,15 @@ async def async_call_llm( logger.info("Auxiliary %s (async): %s on %s (%s), trying fallback", task or "call", reason, resolved_provider, first_err) + # Narrow the configured-chain skip to the exact model that + # failed ONLY for model-specific failures. Auth (401) and + # payment (402) errors are provider-wide — the credentials or + # account behind every model on that provider are the same — so + # a sibling model can't recover; keep skipping the whole + # provider so the main-agent-model safety net is still reached. + _chain_failed_model = ( + None if reason in ("auth error", "payment error") else final_model + ) # Fallback order (#26882, #26803): # 1. User-configured fallback_chain (per-task) if set # 2. For auto: top-level main fallback_providers/fallback_model @@ -7974,7 +9132,8 @@ async def async_call_llm( fb_client, fb_model, fb_label = (None, None, "") if is_auto: fb_client, fb_model, fb_label = _try_configured_fallback_chain( - task, resolved_provider or "auto", reason=reason) + task, resolved_provider or "auto", reason=reason, + failed_model=_chain_failed_model) if fb_client is None: fb_client, fb_model, fb_label = _try_main_fallback_chain( task, resolved_provider or "auto", reason=reason) @@ -7983,10 +9142,12 @@ async def async_call_llm( resolved_provider, task, reason=reason) else: fb_client, fb_model, fb_label = _try_configured_fallback_chain( - task, resolved_provider or "auto", reason=reason) + task, resolved_provider or "auto", reason=reason, + failed_model=_chain_failed_model) if fb_client is None: fb_client, fb_model, fb_label = _try_main_agent_model_fallback( - resolved_provider, task, reason=reason) + resolved_provider, task, reason=reason, + failed_model=_chain_failed_model) if fb_client is not None: # Convert sync fallback client to async diff --git a/agent/backend_identity.py b/agent/backend_identity.py new file mode 100644 index 000000000000..7a7e9efb6bfe --- /dev/null +++ b/agent/backend_identity.py @@ -0,0 +1,204 @@ +"""Single owner for backend identity and failure-scoped skip decisions. + +Every fallback / dedup / skip / quarantine decision in Hermes ultimately asks +one question: **"is this candidate the same backend as the one that failed, +along the axis that failure invalidated?"** Before this module, that +question was re-implemented inline at six call sites across four subsystems, +each comparing whatever string was locally convenient (provider label, +provider+model, base_url+model, ...). Each incident fixed one site while the +others kept the bug: #22548 (same-shim aliases), #70893 (xai-oauth vs xai — +same host, distinct credential), #59561 (aux chain skipped sibling models), +#72468 (aux main-model safety net, same bug three weeks later), #62984 / +#54250 / #57584 (dedup ignoring base_url strands multi-endpoint pools). + +The root insight: "provider" conflates three independent identity axes, and +each failure class invalidates a different one: + +* **credential surface** — auth 401 / payment 402 kill everything sharing the + credential (every model, every host reached with that key/token). +* **endpoint** — DNS failure / connection refused kill everything behind the + URL, regardless of model or credential. +* **model deployment** — timeout / overload / rate limit / model-incompatible + kill ONE model's deployment. A sibling model behind the same URL is an + independent deployment (real incident: aux ``glm-5.2`` hung and timed out + while main ``macaron-v1-venti`` on the identical endpoint was serving + 448K-token turns). + +Call sites should build :class:`BackendIdentity` values, classify the failure +with :func:`classify_failure_scope`, and ask :func:`should_skip_candidate`. +Do not re-implement any comparison inline — extend THIS module instead. +""" + +from __future__ import annotations + +import logging +from dataclasses import dataclass +from enum import Enum +from typing import Optional + +logger = logging.getLogger(__name__) + + +class FailureScope(Enum): + """Which identity axis a failure invalidates.""" + + #: Timeout, overload/429, connection blip, model-incompatible, invalid + #: response: evidence against ONE model deployment only. + MODEL = "model" + #: Auth 401 / payment 402: evidence against the shared credential — + #: every model reached with it is equally dead. + CREDENTIAL = "credential" + #: DNS / connection-refused / unreachable host: evidence against the + #: endpoint — every model behind the URL is equally dead. + ENDPOINT = "endpoint" + + +#: Reason strings already used by auxiliary_client's except-chain, mapped to +#: scopes. Unknown reasons default to MODEL — the least-invalidating scope — +#: so an unrecognized failure never over-skips viable candidates. +_REASON_SCOPES = { + "auth error": FailureScope.CREDENTIAL, + "payment error": FailureScope.CREDENTIAL, + "rate limit": FailureScope.MODEL, + "model incompatible with route": FailureScope.MODEL, + "invalid provider response": FailureScope.MODEL, + "connection error": FailureScope.MODEL, + "timeout": FailureScope.MODEL, +} + + +def classify_failure_scope(reason: Optional[str]) -> FailureScope: + """Map a human-readable failure reason to the identity axis it kills.""" + return _REASON_SCOPES.get((reason or "").strip().lower(), FailureScope.MODEL) + + +def _norm_provider(value: Optional[str]) -> str: + return (value or "").strip().lower() + + +def _norm_model(value: Optional[str]) -> str: + return (value or "").strip().lower() + + +def _norm_base_url(value: Optional[str]) -> str: + return (value or "").strip().rstrip("/").lower() + + +@dataclass(frozen=True) +class BackendIdentity: + """Normalized identity of one (provider, model, endpoint) deployment. + + Empty fields mean "unknown" — comparisons treat an unknown axis as + non-distinguishing (it can neither prove sameness nor difference on its + own; the remaining axes decide). + """ + + provider: str = "" + model: str = "" + base_url: str = "" + + @classmethod + def build( + cls, + provider: Optional[str] = None, + model: Optional[str] = None, + base_url: Optional[str] = None, + ) -> "BackendIdentity": + return cls( + provider=_norm_provider(provider), + model=_norm_model(model), + base_url=_norm_base_url(base_url), + ) + + +def _both_first_class(a: BackendIdentity, b: BackendIdentity) -> bool: + """True when both providers are distinct registered first-class providers. + + Two different registry providers have distinct credential surfaces even + when they share an inference host (xai-oauth vs xai, openai-codex vs + openai-api) — #70893. Custom/shim aliases are NOT in the registry, so + two aliases pointing at one URL still count as the same backend (#22548). + """ + if not a.provider or not b.provider or a.provider == b.provider: + return False + try: + from hermes_cli.auth import PROVIDER_REGISTRY + + return a.provider in PROVIDER_REGISTRY and b.provider in PROVIDER_REGISTRY + except Exception: + return False + + +def same_credential_surface(a: BackendIdentity, b: BackendIdentity) -> bool: + """Do two identities share the credential a 401/402 just invalidated? + + Conservative on purpose: an unprovable axis must answer "different" + (try the candidate — worst case one wasted RTT) rather than "same" + (skip — worst case stranded failover). Two distinct custom labels at + one URL may carry different per-entry api_keys, so a shared URL alone + never proves a shared credential; it is only used as a weak signal + when a provider label is missing entirely. + """ + if a.provider and b.provider: + # Same label = same configured credential. Different labels = + # different credential config (first-class registry providers + # explicitly so — #70893; custom entries can each carry their own + # api_key, so sameness is unprovable and we must not skip). + return a.provider == b.provider + # Provider unknown on a side: same explicit URL is the best signal left. + return bool(a.base_url and a.base_url == b.base_url) + + +def same_endpoint(a: BackendIdentity, b: BackendIdentity) -> bool: + """Do two identities sit behind the endpoint that just went unreachable?""" + if a.base_url and b.base_url: + return a.base_url == b.base_url + # An unknown base_url inherits the provider default → same provider + # label implies the same default endpoint. + return bool(a.provider and a.provider == b.provider) + + +def same_deployment(a: BackendIdentity, b: BackendIdentity) -> bool: + """Are these the exact same model deployment (the thing a timeout kills)? + + Provider+model must match; the base_url axis distinguishes only when BOTH + sides carry an explicit URL (#62984: same provider+model on two different + explicit URLs is two deployments — a pool). A side with an unknown URL + inherits the provider default and cannot prove difference. + """ + if not (a.provider and b.provider and a.provider == b.provider): + # Same-host different-label shims: same URL + same model IS the same + # deployment even when the alias labels differ (#22548) — unless both + # labels are first-class registry providers (#70893). + if ( + a.base_url + and a.base_url == b.base_url + and a.model + and a.model == b.model + and not _both_first_class(a, b) + ): + return True + return False + if not (a.model and b.model and a.model == b.model): + return False + if a.base_url and b.base_url and a.base_url != b.base_url: + return False # distinct explicit endpoints — a pool, not a dup + return True + + +def should_skip_candidate( + candidate: BackendIdentity, + failed: BackendIdentity, + scope: FailureScope = FailureScope.MODEL, +) -> bool: + """THE skip predicate: would trying ``candidate`` just repeat the failure? + + True when the candidate is the same backend as ``failed`` along the axis + ``scope`` says the failure invalidated. Every fallback/dedup/skip site + must call this instead of comparing labels inline. + """ + if scope is FailureScope.CREDENTIAL: + return same_credential_surface(candidate, failed) + if scope is FailureScope.ENDPOINT: + return same_endpoint(candidate, failed) + return same_deployment(candidate, failed) diff --git a/agent/background_review.py b/agent/background_review.py index c2ea87bd94e2..a0dbd4a99e28 100644 --- a/agent/background_review.py +++ b/agent/background_review.py @@ -209,7 +209,10 @@ _SKILL_REVIEW_PROMPT = ( "conversation for skills the user loaded via /skill-name or you " "read via skill_view. If any of them covers the territory of the " "new learning, PATCH that one first. It is the skill that was in " - "play, so it's the right one to extend.\n" + "play, so it's the right one to extend — but only if it is " + "curator-managed. Bundled, hub, pinned, and user-owned skills are " + "off-limits to you no matter how relevant (see Protected skills " + "below); for those, fall through to the next option.\n" " 2. UPDATE AN EXISTING UMBRELLA (via skills_list + skill_view). " "If no loaded skill fits but an existing class-level skill does, " "patch it. Add a subsection, a pitfall, or broaden a trigger.\n" @@ -251,10 +254,18 @@ _SKILL_REVIEW_PROMPT = ( "Protected skills (DO NOT edit these):\n" " • Bundled skills (shipped with Hermes, e.g. 'hermes-agent').\n" " • Hub-installed skills (installed via 'hermes skills install').\n" - "Pinned skills (marked via 'hermes curator pin') CAN be improved — " - "pin only blocks deletion/archive/consolidation by the curator, not " - "content updates. Patch them when a pitfall or missing step turns up, " - "same as any other agent-created skill.\n" + " • Skills in skills.external_dirs (externally owned).\n" + " • PINNED skills (marked via 'hermes curator pin'). You are an " + "autonomous no-user-present actor, so pin blocks your writes too — " + "content updates included. Only the user, in a foreground session, " + "can change a pinned skill.\n" + " • USER-OWNED skills — anything not curator-managed. A skill the " + "user hand-wrote, installed by URL, or asked a foreground agent to " + "create is theirs, not yours; your writes to it WILL be refused. " + "This includes skills that were loaded or consulted this session: " + "being in play does not make one yours to edit. If such a skill is " + "wrong or outdated, say so in your reply and recommend " + "'hermes curator adopt ' — do not try to patch it.\n" "If the only skills that need updating are protected, say\n" "'Nothing to save.' and stop.\n\n" "Do NOT capture (these become persistent self-imposed constraints " @@ -309,7 +320,9 @@ _COMBINED_REVIEW_PROMPT = ( " 1. UPDATE A CURRENTLY-LOADED SKILL. Check what skills were " "loaded via /skill-name or skill_view in the conversation. If one " "of them covers the learning, PATCH it first. It was in play; " - "it's the right place.\n" + "it's the right place — provided it is curator-managed. Protected " + "and user-owned skills are off-limits however relevant; fall " + "through when one of those is the best fit.\n" " 2. UPDATE AN EXISTING UMBRELLA (skills_list + skill_view to " "find the right one). Patch it.\n" " 3. ADD A SUPPORT FILE under an existing umbrella via " @@ -337,10 +350,15 @@ _COMBINED_REVIEW_PROMPT = ( "Protected skills (DO NOT edit these):\n" " • Bundled skills (shipped with Hermes, e.g. 'hermes-agent').\n" " • Hub-installed skills (installed via 'hermes skills install').\n" - "Pinned skills (marked via 'hermes curator pin') CAN be improved — " - "pin only blocks deletion/archive/consolidation by the curator, not " - "content updates. Patch them when a pitfall or missing step turns up, " - "same as any other agent-created skill.\n" + " • Skills in skills.external_dirs (externally owned).\n" + " • PINNED skills (marked via 'hermes curator pin'). Pin blocks " + "autonomous writes entirely — content updates included — because no " + "user is present to consent. Only a foreground session can change one.\n" + " • USER-OWNED skills — anything not curator-managed (hand-written, " + "URL-installed, or created by a foreground agent at the user's " + "request). Your writes to these WILL be refused, including to skills " + "loaded or consulted this session. If one is wrong, say so in your " + "reply and recommend 'hermes curator adopt ' instead.\n" "If the only skills that need updating are protected, say\n" "'Nothing to save.' and stop.\n\n" "Do NOT capture as skills (these become persistent self-imposed " diff --git a/agent/bedrock_adapter.py b/agent/bedrock_adapter.py index c8cff3f76e13..c399081619ff 100644 --- a/agent/bedrock_adapter.py +++ b/agent/bedrock_adapter.py @@ -433,6 +433,29 @@ def _model_supports_tool_use(model_id: str) -> bool: return not any(pattern in model_lower for pattern in _NON_TOOL_CALLING_PATTERNS) +# --------------------------------------------------------------------------- +# Prompt-cache capability detection (Converse API cachePoint) +# --------------------------------------------------------------------------- +# Claude on Bedrock already gets prompt caching through the AnthropicBedrock +# SDK path (see is_anthropic_bedrock_model / runtime_provider.py's dual-path +# routing) — it never reaches build_converse_kwargs unless bearer-token auth +# forces the Converse path (#28156). This allowlist covers the Converse API +# itself: sending an unsupported model a cachePoint block raises a +# ValidationException, so — like _model_supports_tool_use but inverted — +# unknown models default to NOT receiving cache markers until confirmed. +# Ref: https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-caching.html +_CACHE_POINT_PATTERNS = [ + "anthropic.claude", # bearer-token fallback path + "amazon.nova", +] + + +def _model_supports_prompt_cache(model_id: str) -> bool: + """Return True if the model accepts a Converse API cachePoint block.""" + model_lower = model_id.lower() + return any(pattern in model_lower for pattern in _CACHE_POINT_PATTERNS) + + def is_anthropic_bedrock_model(model_id: str) -> bool: """Return True if the model is an Anthropic Claude model on Bedrock. @@ -764,14 +787,22 @@ def normalize_converse_response(response: Dict) -> SimpleNamespace: reasoning_content="\n\n".join(reasoning_parts) if reasoning_parts else None, ) - # Build usage stats + # Build usage stats. Converse's inputTokens excludes cache read/write + # tokens (unlike OpenAI's prompt_tokens, which includes them) — restore + # the OpenAI-style "total includes cache" convention here so downstream + # normalize_usage() can subtract them back out consistently, and surface + # the Anthropic-named fields it already falls back to for cache reads. usage_data = response.get("usage", {}) + input_tokens = usage_data.get("inputTokens", 0) + cache_read_tokens = usage_data.get("cacheReadInputTokens", 0) + cache_write_tokens = usage_data.get("cacheWriteInputTokens", 0) + output_tokens = usage_data.get("outputTokens", 0) usage = SimpleNamespace( - prompt_tokens=usage_data.get("inputTokens", 0), - completion_tokens=usage_data.get("outputTokens", 0), - total_tokens=( - usage_data.get("inputTokens", 0) + usage_data.get("outputTokens", 0) - ), + prompt_tokens=input_tokens + cache_read_tokens + cache_write_tokens, + completion_tokens=output_tokens, + total_tokens=input_tokens + cache_read_tokens + cache_write_tokens + output_tokens, + cache_read_input_tokens=cache_read_tokens, + cache_creation_input_tokens=cache_write_tokens, ) finish_reason = _converse_stop_reason_to_openai(stop_reason) @@ -936,6 +967,8 @@ def stream_converse_with_callbacks( usage_data = { "inputTokens": meta_usage.get("inputTokens", 0), "outputTokens": meta_usage.get("outputTokens", 0), + "cacheReadInputTokens": meta_usage.get("cacheReadInputTokens", 0), + "cacheWriteInputTokens": meta_usage.get("cacheWriteInputTokens", 0), } # Flush remaining text @@ -949,12 +982,16 @@ def stream_converse_with_callbacks( reasoning_content="\n\n".join(reasoning_parts) if reasoning_parts else None, ) + input_tokens = usage_data.get("inputTokens", 0) + cache_read_tokens = usage_data.get("cacheReadInputTokens", 0) + cache_write_tokens = usage_data.get("cacheWriteInputTokens", 0) + output_tokens = usage_data.get("outputTokens", 0) usage = SimpleNamespace( - prompt_tokens=usage_data.get("inputTokens", 0), - completion_tokens=usage_data.get("outputTokens", 0), - total_tokens=( - usage_data.get("inputTokens", 0) + usage_data.get("outputTokens", 0) - ), + prompt_tokens=input_tokens + cache_read_tokens + cache_write_tokens, + completion_tokens=output_tokens, + total_tokens=input_tokens + cache_read_tokens + cache_write_tokens + output_tokens, + cache_read_input_tokens=cache_read_tokens, + cache_creation_input_tokens=cache_write_tokens, ) finish_reason = _converse_stop_reason_to_openai(stop_reason) @@ -993,6 +1030,7 @@ def build_converse_kwargs( Converts OpenAI-format inputs to Converse API parameters. """ system_prompt, converse_messages = convert_messages_to_converse(messages) + cache_enabled = _model_supports_prompt_cache(model) kwargs: Dict[str, Any] = { "modelId": model, @@ -1003,6 +1041,8 @@ def build_converse_kwargs( } if system_prompt: + if cache_enabled: + system_prompt = system_prompt + [{"cachePoint": {"type": "default"}}] kwargs["system"] = system_prompt from agent.anthropic_adapter import _forbids_sampling_params @@ -1026,6 +1066,8 @@ def build_converse_kwargs( # Strip tools for known non-tool-calling models and warn the user. # Ref: PR #7920 feedback from @ptlally, pattern from PR #4346. if _model_supports_tool_use(model): + if cache_enabled: + converse_tools = converse_tools + [{"cachePoint": {"type": "default"}}] kwargs["toolConfig"] = {"tools": converse_tools} else: logger.warning( @@ -1033,6 +1075,14 @@ def build_converse_kwargs( "The agent will operate in text-only mode.", model ) + if cache_enabled and len(converse_messages) >= 2: + # Checkpoint everything up to (not including) the newest turn, so the + # marker survives unchanged across requests as only the tail grows — + # mirroring the Anthropic system_and_3 strategy in prompt_caching.py. + content = converse_messages[-2].get("content") + if isinstance(content, list) and content: + content.append({"cachePoint": {"type": "default"}}) + if guardrail_config: kwargs["guardrailConfig"] = guardrail_config diff --git a/agent/billing_usage.py b/agent/billing_usage.py index 2ac762bc2b31..c3ab6203e30c 100644 --- a/agent/billing_usage.py +++ b/agent/billing_usage.py @@ -34,7 +34,7 @@ from __future__ import annotations import logging import math import os -from dataclasses import dataclass, field +from dataclasses import dataclass from typing import Any, Optional logger = logging.getLogger(__name__) diff --git a/agent/billing_view.py b/agent/billing_view.py index a535aee1f142..01a804e65f09 100644 --- a/agent/billing_view.py +++ b/agent/billing_view.py @@ -17,7 +17,7 @@ from __future__ import annotations import logging import os import uuid -from dataclasses import dataclass, field +from dataclasses import dataclass from decimal import Decimal, InvalidOperation from typing import Any, Optional @@ -107,6 +107,22 @@ class CardInfo: return f"{self.masked} — {label}" if label else self.masked +@dataclass(frozen=True) +class PaymentMethodInfo: + """The payment method on file. `kind` is "card", "link", or "unknown" + — anything else is normalised to "unknown" at parse time, so consumers + only ever see fields that belong to the kind they are looking at.""" + + kind: str + brand: Optional[str] = None + last4: Optional[str] = None + wallet: Optional[str] = None + email: Optional[str] = None + resolved_via: Optional[str] = None + #: What the server called it, when we did not recognise the kind. + raw_kind: Optional[str] = None + + @dataclass(frozen=True) class MonthlyCap: limit_usd: Optional[Decimal] = None @@ -150,6 +166,7 @@ class BillingState: min_usd: Optional[Decimal] = None max_usd: Optional[Decimal] = None card: Optional[CardInfo] = None + payment_method: Optional[PaymentMethodInfo] = None monthly_cap: Optional[MonthlyCap] = None auto_reload: Optional[AutoReload] = None portal_url: Optional[str] = None @@ -201,6 +218,41 @@ def _parse_card(raw: Any) -> Optional[CardInfo]: return CardInfo(brand=brand, last4=last4, resolved_via=resolved_via) +def _parse_payment_method(raw: Any) -> Optional[PaymentMethodInfo]: + if not isinstance(raw, dict): + return None + kind = raw.get("kind") + if not isinstance(kind, str): + return None + + def _optional_string(key: str) -> Optional[str]: + value = raw.get(key) + return value if isinstance(value, str) else None + + resolved_via = _optional_string("resolvedVia") + brand = _optional_string("brand") + last4 = _optional_string("last4") + # Settle the kind here, the way _parse_card settles a card, so nothing + # downstream has to re-check which fields this kind is allowed to have. + if kind == "card" and brand and last4: + return PaymentMethodInfo( + kind="card", + brand=brand, + last4=last4, + wallet=_optional_string("wallet"), + resolved_via=resolved_via, + ) + if kind == "link": + return PaymentMethodInfo( + kind="link", + email=_optional_string("email"), + resolved_via=resolved_via, + ) + return PaymentMethodInfo( + kind="unknown", raw_kind=kind, resolved_via=resolved_via + ) + + def _parse_monthly_cap(raw: Any) -> Optional[MonthlyCap]: if not isinstance(raw, dict): return None @@ -274,6 +326,7 @@ def billing_state_from_payload( min_usd=parse_money(bounds.get("minUsd")), max_usd=parse_money(bounds.get("maxUsd")), card=_parse_card(payload.get("card")), + payment_method=_parse_payment_method(payload.get("paymentMethod")), monthly_cap=_parse_monthly_cap(payload.get("monthlyCap")), auto_reload=_parse_auto_reload(payload.get("autoReload")), portal_url=portal_url, diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py index b2e5c8653a48..1c49a59e2a3c 100644 --- a/agent/chat_completion_helpers.py +++ b/agent/chat_completion_helpers.py @@ -15,6 +15,7 @@ sites unchanged. Symbols that tests patch on ``run_agent`` (e.g. from __future__ import annotations +import contextvars import json import logging import math @@ -57,6 +58,12 @@ _OPENROUTER_PROVIDER_SORT_VALUES = {"throughput", "latency", "price"} _FALLBACK_EXHAUSTED_COOLDOWN_S = 5.0 +def _context_thread_target(callback): + """Bind a no-argument thread target to the caller's ContextVars.""" + context = contextvars.copy_context() + return lambda: context.run(callback) + + def _ra(): """Lazy ``run_agent`` reference. @@ -188,6 +195,31 @@ def _provider_preferences_for_agent(agent) -> Dict[str, Any]: return preferences +def _merge_nous_portal_messages_extra_body(agent, anthropic_kwargs: dict) -> dict: + """Merge Portal ``tags`` / ``session_id`` onto an Anthropic Messages kwargs dict. + + The Nous provider profile is only consulted by the OpenAI-wire transport; + anthropic_messages callers must merge it themselves. Passes ``session_id`` + only — not ``provider_preferences`` (those become a top-level ``provider`` + routing object on the OpenAI wire). Never blocks a turn on tagging. + """ + if getattr(agent, "provider", None) not in {"nous", "nous-portal", "nousresearch"}: + return anthropic_kwargs + try: + from providers import get_provider_profile + + nous_profile = get_provider_profile("nous") + if nous_profile is not None: + anthropic_kwargs.setdefault("extra_body", {}).update( + nous_profile.build_extra_body( + session_id=getattr(agent, "session_id", None) + ) + ) + except Exception as exc: # noqa: BLE001 — never block a turn on tagging + logger.debug("Nous Portal extra_body merge failed: %s", exc) + return anthropic_kwargs + + def _env_float(name: str, default: float) -> float: try: return float(os.getenv(name, str(default))) @@ -195,6 +227,53 @@ def _env_float(name: str, default: float) -> float: return default +def _estimate_chunk_bytes(chunk: Any) -> int: + """Cheap per-chunk size estimate for the stream diagnostic counters. + + The previous implementation used ``len(repr(chunk))`` — a full recursive + repr of a pydantic model on EVERY streaming chunk (5.5-8.8 µs each, + ~20-30 ms of pure CPU on a 3,000-chunk response, in the hottest loop in + the agent). The counter only feeds a retry-diagnostic log line, so an + estimate based on the delta payload lengths is plenty (2.1-2.4 µs, ~3x + cheaper, and independent of model/pydantic field count). Chat Completions + chunks are sized from their delta content/reasoning/tool-argument strings + plus a small framing constant; anything shape-unknown (Anthropic events, + stub providers) falls back to a flat constant so `bytes` stays monotonic + and roughly proportional to traffic. + """ + size = 40 # SSE/JSON framing floor per chunk + try: + choices = getattr(chunk, "choices", None) + if choices: + delta = getattr(choices[0], "delta", None) + if delta is not None: + for attr in ("content", "reasoning_content", "reasoning"): + v = getattr(delta, attr, None) + if isinstance(v, str): + size += len(v) + tool_calls = getattr(delta, "tool_calls", None) + if tool_calls: + for tc in tool_calls: + fn = getattr(tc, "function", None) + if fn is not None: + args = getattr(fn, "arguments", None) + if isinstance(args, str): + size += len(args) + name = getattr(fn, "name", None) + if isinstance(name, str): + size += len(name) + else: + # Non-chat-completions shapes (Anthropic events etc.): try the + # common text fields, else keep the framing floor. + for attr in ("text", "partial_json"): + v = getattr(getattr(chunk, "delta", None), attr, None) + if isinstance(v, str): + size += len(v) + except Exception: + pass + return size + + def _codex_wait_notice_recovery( *, stale_timeout: float, @@ -433,26 +512,56 @@ def _dispatch_nonstreaming_api_request(agent, api_kwargs: dict, *, make_client): def should_use_direct_api_call(agent) -> bool: - """Whether a cron OpenAI-wire request should skip the interrupt worker. + """Whether an OpenAI-wire request should skip the interrupt worker. - Issue #62151 is specific to OpenRouter's chat-completions path inside the - gateway cron thread stack. Keep native/Codex/Bedrock/MoA transports on their - established workers: their cancellation and client ownership differ, and - the report provides no evidence that those paths share the pre-HTTP wedge. + Two nested-pool contexts wedge before the socket opens when the request + is pushed onto yet another daemon worker thread: + + - Gateway cron turns (#62151): gateway asyncio loop → cron thread → + interrupt worker. Fixed by running inline. + - Delegated children (#60203): gateway loop → async-delegation executor + (module-lifetime daemon pool) → per-child timeout executor → interrupt + worker. Same fingerprint after multi-day gateway uptime — children hang + at their FIRST API call with zero stale-detector output (the worker + never reaches dispatch), all providers, restart cures it. The cron fix + originally excluded delegation "for lack of evidence"; #60203 is that + evidence. + + Running inline drops the deepest thread layer (whose only job is + interactive-interrupt responsiveness). Interrupts still work: the inline + path registers ``agent._active_request_abort``, which ``interrupt()`` + invokes cross-thread to shut the active sockets — the same mechanism the + async-delegation stall monitor (#72227) relies on. + + Keep native/Codex/Bedrock/MoA transports on their established workers: + their cancellation and client ownership differ. """ - return ( - getattr(agent, "platform", None) == "cron" - and getattr(agent, "api_mode", None) == "chat_completions" - and getattr(agent, "provider", None) != "moa" - ) + if getattr(agent, "api_mode", None) != "chat_completions": + return False + if getattr(agent, "provider", None) == "moa": + return False + if getattr(agent, "platform", None) == "cron": + return True + # Delegated child (delegate_task sync or background) — detected via the + # execution ContextVar set by _run_single_child, with the agent's own + # platform stamp as a fallback for callers that bypass the runner. + try: + from agent.delegation_context import is_delegated_child_context + + if is_delegated_child_context(): + return True + except Exception: + pass + return getattr(agent, "platform", None) == "subagent" def direct_api_call(agent, api_kwargs: dict): """Run a non-streaming LLM call inline on the conversation thread. - Used when ``should_use_direct_api_call`` is True. Skips the interrupt worker - (whose only job is interactive-interrupt responsiveness, which this context - does not have) so the nested-pool deadlock (#62151) cannot occur. Because the + Used when ``should_use_direct_api_call`` is True (cron turns and + delegated children). Skips the interrupt worker (whose only job is + interactive-interrupt responsiveness, which these contexts do not have) + so the nested-pool deadlock (#62151, #60203) cannot occur. Because the request runs in-flight normally, the per-request OpenAI client's own httpx timeout (provider ``request_timeout_seconds`` / ``HERMES_API_TIMEOUT``) bounds a genuinely hung provider — the same bound interactive calls already rely on. @@ -463,11 +572,17 @@ def direct_api_call(agent, api_kwargs: dict): request_client_lock = threading.Lock() def _abort_active_request(reason: str) -> None: - """Abort the inline request from cron's watchdog/interrupt thread.""" + """Abort the inline request from a watchdog/interrupt thread.""" + # Abort while still holding the holder lock: the instant it is + # released, the inline finally may pop + cache the client for reuse + # and the NEXT call check it out — a late abort would then poison + # the slot and shut down an innocent in-flight request's sockets + # (same atomicity contract as _close_request_client_once in the + # interruptible variants; the abort itself never blocks). with request_client_lock: request_client = request_client_holder["client"] - if request_client is not None: - agent._abort_request_openai_client(request_client, reason=reason) + if request_client is not None: + agent._abort_request_openai_client(request_client, reason=reason) def _make_client(reason: str, kind: str = "openai"): # direct_api_call only runs for OpenAI-wire chat_completions cron @@ -480,6 +595,10 @@ def direct_api_call(agent, api_kwargs: dict): agent._active_request_abort = _abort_active_request return client + # Only a clean return may report the reuse reason (request_complete): + # after an error or interrupt the wire client is really closed so the + # retry builds a fresh pool (see _REQUEST_CLIENT_REUSE_REASONS). + succeeded = False try: response = _dispatch_nonstreaming_api_request( agent, api_kwargs, make_client=_make_client @@ -492,6 +611,7 @@ def direct_api_call(agent, api_kwargs: dict): if getattr(agent, "_interrupt_requested", False): raise InterruptedError("Agent interrupted during API call") _reset_stale_streak(agent) + succeeded = True return response finally: if getattr(agent, "_active_request_abort", None) is _abort_active_request: @@ -500,7 +620,10 @@ def direct_api_call(agent, api_kwargs: dict): request_client = request_client_holder["client"] request_client_holder["client"] = None if request_client is not None: - agent._close_request_openai_client(request_client, reason="request_complete") + agent._close_request_openai_client( + request_client, + reason="request_complete" if succeeded else "request_error_cleanup", + ) def interruptible_api_call(agent, api_kwargs: dict): @@ -578,20 +701,28 @@ def interruptible_api_call(agent, api_kwargs: dict): and owner_tid is not None and owner_tid != threading.get_ident() ) - if not stranger_thread: - # Owning thread (or no recorded owner) → pop and fully close. - request_client_holder["client"] = None - request_client_holder["owner_tid"] = None + if stranger_thread: + # Abort while still holding the holder lock: the instant it + # is released, the worker's finally may pop + cache the client + # for reuse and the NEXT call check it out — an abort landing + # after that would poison the slot and shut down an innocent + # in-flight request's sockets. The abort itself never blocks + # (socket shutdown + slot poison), so holding the lock across + # it only delays the racing pop, never the data path. + if request_client_kind.get("value", "openai") == "anthropic_messages": + agent._abort_request_anthropic_client( + request_client, reason=reason + ) + else: + agent._abort_request_openai_client(request_client, reason=reason) + return + # Owning thread (or no recorded owner) → pop and fully close. + request_client_holder["client"] = None + request_client_holder["owner_tid"] = None if request_client is None: return - kind = request_client_kind.get("value", "openai") - if kind == "anthropic_messages": - if stranger_thread: - agent._abort_request_anthropic_client(request_client, reason=reason) - else: - agent._close_request_anthropic_client(request_client, reason=reason) - elif stranger_thread: - agent._abort_request_openai_client(request_client, reason=reason) + if request_client_kind.get("value", "openai") == "anthropic_messages": + agent._close_request_anthropic_client(request_client, reason=reason) else: agent._close_request_openai_client(request_client, reason=reason) @@ -628,7 +759,15 @@ def interruptible_api_call(agent, api_kwargs: dict): return result["error"] = e finally: - _close_request_client_once("request_complete") + # Reuse reason only on a clean response; any other outcome — + # error, or the cancel-swallow return above (which leaves both + # result slots None) — really closes so the next attempt builds + # a fresh pool (see _REQUEST_CLIENT_REUSE_REASONS). + _close_request_client_once( + "request_complete" + if result["response"] is not None + else "request_error_cleanup" + ) # ── Stale-call timeout (mirrors streaming stale detector) ──────── # Non-streaming calls return nothing until the full response is @@ -755,7 +894,7 @@ def interruptible_api_call(agent, api_kwargs: dict): _call_start = time.time() agent._touch_activity("waiting for non-streaming API response") - t = threading.Thread(target=_call, daemon=True) + t = threading.Thread(target=_context_thread_target(_call), daemon=True) t.start() _poll_count = 0 while t.is_alive(): @@ -993,7 +1132,7 @@ def build_api_kwargs(agent, api_messages: list) -> dict: ephemeral_out = getattr(agent, "_ephemeral_max_output_tokens", None) if ephemeral_out is not None: agent._ephemeral_max_output_tokens = None # consume immediately - return _transport.build_kwargs( + anthropic_kwargs = _transport.build_kwargs( model=agent.model, messages=anthropic_messages, tools=tools_for_api, @@ -1006,6 +1145,12 @@ def build_api_kwargs(agent, api_messages: list) -> dict: fast_mode=(agent.request_overrides or {}).get("speed") == "fast", drop_context_1m_beta=bool(getattr(agent, "_oauth_1m_beta_disabled", False)), ) + # Nous Portal reads ``tags`` and ``session_id`` as top-level body fields + # on its Messages route the same way it does on /chat/completions, but + # the profile hook that produces them is only consulted by the + # OpenAI-wire transport. Merge them here so Messages traffic keeps + # product attribution and sticky routing. + return _merge_nous_portal_messages_extra_body(agent, anthropic_kwargs) # AWS Bedrock native Converse API — bypasses the OpenAI client entirely. # The adapter handles message/tool conversion and boto3 calls directly. @@ -1076,6 +1221,7 @@ def build_api_kwargs(agent, api_messages: list) -> dict: tools=tools_for_api, reasoning_config=agent.reasoning_config, session_id=getattr(agent, "session_id", None), + base_url=agent.base_url, max_tokens=agent.max_tokens, timeout=agent._resolved_api_call_timeout(), request_overrides=agent.request_overrides, @@ -1311,6 +1457,17 @@ def build_assistant_message(agent, assistant_message, finish_reason: str) -> dic from agent.redact import redact_sensitive_text _san_content = redact_sensitive_text(_san_content) + # NOTE (empty-content class fix): textless assistant turns are NOT padded + # here. The single owner for "never send a turn strict wire validation + # rejects as empty" is ``repair_empty_non_final_messages`` in + # agent_runtime_helpers, which runs inside ``sanitize_api_messages`` — the + # unconditional pre-send chokepoint for both the main loop and the summary + # path. Padding at write time was tried (a single-space pad, later a + # placeholder) and rejected: it forked the concept across three sites, + # broke codex commentary turns (content:'' is a designed state there), and + # a DB-side pad can't survive ``_rows_to_conversation``'s whitespace strip + # anyway. Repair belongs at the send boundary, once. + msg = { "role": "assistant", "content": _san_content, @@ -1598,29 +1755,28 @@ def try_activate_fallback(agent, reason: "FailoverReason | None" = None) -> bool ) return agent._try_activate_fallback(reason) - # Skip entries that resolve to the current (provider, model) — falling - # back to the same backend that just failed loops the failure. Compare - # base_url too so two distinct custom_providers entries pointing at the - # same shim/proxy URL also dedup. See issue #22548. - current_provider = (getattr(agent, "provider", "") or "").strip().lower() - current_model = (getattr(agent, "model", "") or "").strip() - current_base_url = str(getattr(agent, "base_url", "") or "").rstrip("/").lower() - fb_base_url_for_dedup = (fb.get("base_url") or "").strip().rstrip("/").lower() - if fb_provider == current_provider and fb_model == current_model: + # Skip entries that resolve to the same backend that just failed — + # falling back to it loops the failure. Identity semantics (which axes + # distinguish two backends, shim aliases, first-class credential + # surfaces, multi-endpoint pools) are owned by agent.backend_identity — + # see #22548, #70893, #62984. Do not re-implement comparisons here. + from agent.backend_identity import BackendIdentity, should_skip_candidate + + current_ident = BackendIdentity.build( + provider=getattr(agent, "provider", ""), + model=getattr(agent, "model", ""), + base_url=str(getattr(agent, "base_url", "") or ""), + ) + fb_ident = BackendIdentity.build( + provider=fb_provider, + model=fb_model, + base_url=(fb.get("base_url") or ""), + ) + if should_skip_candidate(fb_ident, current_ident): logger.warning( - "Fallback skip: chain entry %s/%s matches current provider/model", - fb_provider, fb_model, - ) - return agent._try_activate_fallback(reason) - if ( - fb_base_url_for_dedup - and current_base_url - and fb_base_url_for_dedup == current_base_url - and fb_model == current_model - ): - logger.warning( - "Fallback skip: chain entry base_url %s matches current backend", - fb_base_url_for_dedup, + "Fallback skip: chain entry %s/%s resolves to the same backend " + "as the current one (%s)", + fb_provider, fb_model, current_ident.base_url or current_ident.provider, ) return agent._try_activate_fallback(reason) @@ -1671,6 +1827,14 @@ def try_activate_fallback(agent, reason: "FailoverReason | None" = None) -> bool _fb_is_azure = agent._is_azure_openai_url(fb_base_url) if fb_provider == "openai-codex": fb_api_mode = "codex_responses" + elif fb_provider in {"nous", "nous-portal", "nousresearch"}: + # Portal is dual-wire: anthropic/* must land on /v1/messages. + # resolve_provider_client still returns an OpenAI client for + # Nous; the anthropic_messages branch below rebuilds the native + # client from that credential + base_url. + from hermes_cli.providers import nous_api_mode + + fb_api_mode = nous_api_mode(fb_model) elif ( fb_provider == "anthropic" or fb_base_url.rstrip("/").lower().endswith("/anthropic") @@ -1712,6 +1876,7 @@ def try_activate_fallback(agent, reason: "FailoverReason | None" = None) -> bool agent._config_context_length = None agent.model = fb_model agent.provider = fb_provider + agent.requested_provider = fb_provider agent.base_url = fb_base_url agent.api_mode = fb_api_mode if hasattr(agent, "_transport_cache"): @@ -1738,6 +1903,7 @@ def try_activate_fallback(agent, reason: "FailoverReason | None" = None) -> bool fb_provider, fb_model, _pool_provider, ) agent._credential_pool = None + agent._credential_pool_entry_id = None if getattr(agent, "_credential_pool", None) is None: try: from agent.credential_pool import load_pool @@ -1800,6 +1966,9 @@ def try_activate_fallback(agent, reason: "FailoverReason | None" = None) -> bool # not only after a later credential-rotation rebuild. agent._replace_primary_openai_client(reason="fallback_timeout_apply") + from agent.agent_runtime_helpers import sync_credential_pool_entry_id + sync_credential_pool_entry_id(agent) + # Re-evaluate prompt caching for the new provider/model agent._use_prompt_caching, agent._use_native_cache_layout = ( agent._anthropic_prompt_cache_policy( @@ -1904,6 +2073,28 @@ def handle_max_iterations(agent, messages: list, api_call_count: int) -> str: """Request a summary when max iterations are reached. Returns the final response text.""" print(f"⚠️ Reached maximum iterations ({agent.max_iterations}). Requesting summary...") + summary_api_request_id = f"iteration-summary:{uuid.uuid4()}" + summary_call_outcome = "failed" + + def _managed_summary_call(request, callback, *, retry_count: int): + from agent import relay_llm + + return relay_llm.execute_current( + request, + callback, + name=str(getattr(agent, "provider", "") or "provider"), + model_name=str(getattr(agent, "model", "") or ""), + metadata={ + "api_mode": str( + getattr(agent, "api_mode", "") or "chat_completions" + ), + "api_request_id": summary_api_request_id, + "call_role": "iteration_summary", + "retry_count": retry_count, + }, + defer_logical_completion=True, + ) + summary_request = ( "You've reached the maximum number of tool-calling iterations allowed. " "Please provide a final response summarizing what you've found and accomplished so far, " @@ -1945,7 +2136,17 @@ def handle_max_iterations(agent, messages: list, api_call_count: int) -> str: for internal_key in [k for k in api_msg if isinstance(k, str) and k.startswith("_")]: api_msg.pop(internal_key, None) if _needs_sanitize: - agent._sanitize_tool_calls_for_strict_api(api_msg, model=agent.model) + # In MoA mode, agent.model is the virtual preset name, + # not the actual aggregator model. Resolve the real + # aggregator model so Gemini preserves thought_signature. + _sanitize_model = agent.model + if agent.provider == "moa": + _moa_client = getattr(agent, "client", None) + if _moa_client is not None: + _agg_slot = getattr(_moa_client, "last_aggregator_slot", None) + if _agg_slot and _agg_slot.get("model"): + _sanitize_model = _agg_slot["model"] + agent._sanitize_tool_calls_for_strict_api(api_msg, model=_sanitize_model) api_messages.append(api_msg) effective_system = agent._cached_system_prompt or "" @@ -2079,15 +2280,33 @@ def handle_max_iterations(agent, messages: list, api_call_count: int) -> str: if agent.api_mode == "anthropic_messages": _tsum = agent._get_transport() - _ant_kw = _tsum.build_kwargs(model=agent.model, messages=api_messages, tools=None, - max_tokens=agent.max_tokens, reasoning_config=agent.reasoning_config, - is_oauth=agent._is_anthropic_oauth, - preserve_dots=agent._anthropic_preserve_dots()) - summary_response = agent._anthropic_messages_create(_ant_kw) + _ant_kw = _tsum.build_kwargs( + model=agent.model, + messages=api_messages, + tools=None, + max_tokens=agent.max_tokens, + reasoning_config=agent.reasoning_config, + is_oauth=agent._is_anthropic_oauth, + preserve_dots=agent._anthropic_preserve_dots(), + base_url=getattr(agent, "_anthropic_base_url", None), + ) + _ant_kw = _merge_nous_portal_messages_extra_body(agent, _ant_kw) + summary_response = _managed_summary_call( + _ant_kw, + agent._anthropic_messages_create, + retry_count=0, + ) _summary_result = _tsum.normalize_response(summary_response, strip_tool_prefix=agent._is_anthropic_oauth) final_response = (_summary_result.content or "").strip() else: - summary_response = agent._ensure_primary_openai_client(reason="iteration_limit_summary").chat.completions.create(**summary_kwargs) + summary_client = agent._ensure_primary_openai_client( + reason="iteration_limit_summary" + ) + summary_response = _managed_summary_call( + summary_kwargs, + lambda request: summary_client.chat.completions.create(**request), + retry_count=0, + ) _summary_result = agent._get_transport().normalize_response(summary_response) final_response = (_summary_result.content or "").strip() @@ -2095,6 +2314,7 @@ def handle_max_iterations(agent, messages: list, api_call_count: int) -> str: if "" in final_response: final_response = re.sub(r'.*?\s*', '', final_response, flags=re.DOTALL).strip() if final_response: + summary_call_outcome = "success" messages.append({"role": "assistant", "content": final_response}) else: final_response = "I reached the iteration limit and couldn't generate a summary." @@ -2109,11 +2329,22 @@ def handle_max_iterations(agent, messages: list, api_call_count: int) -> str: final_response = (_cnr_retry.content or "").strip() elif agent.api_mode == "anthropic_messages": _tretry = agent._get_transport() - _ant_kw2 = _tretry.build_kwargs(model=agent.model, messages=api_messages, tools=None, - is_oauth=agent._is_anthropic_oauth, - max_tokens=agent.max_tokens, reasoning_config=agent.reasoning_config, - preserve_dots=agent._anthropic_preserve_dots()) - retry_response = agent._anthropic_messages_create(_ant_kw2) + _ant_kw2 = _tretry.build_kwargs( + model=agent.model, + messages=api_messages, + tools=None, + is_oauth=agent._is_anthropic_oauth, + max_tokens=agent.max_tokens, + reasoning_config=agent.reasoning_config, + preserve_dots=agent._anthropic_preserve_dots(), + base_url=getattr(agent, "_anthropic_base_url", None), + ) + _ant_kw2 = _merge_nous_portal_messages_extra_body(agent, _ant_kw2) + retry_response = _managed_summary_call( + _ant_kw2, + agent._anthropic_messages_create, + retry_count=1, + ) _retry_result = _tretry.normalize_response(retry_response, strip_tool_prefix=agent._is_anthropic_oauth) final_response = (_retry_result.content or "").strip() else: @@ -2130,7 +2361,14 @@ def handle_max_iterations(agent, messages: list, api_call_count: int) -> str: if summary_extra_body: summary_kwargs["extra_body"] = summary_extra_body - summary_response = agent._ensure_primary_openai_client(reason="iteration_limit_summary_retry").chat.completions.create(**summary_kwargs) + summary_client = agent._ensure_primary_openai_client( + reason="iteration_limit_summary_retry" + ) + summary_response = _managed_summary_call( + summary_kwargs, + lambda request: summary_client.chat.completions.create(**request), + retry_count=1, + ) _retry_result = agent._get_transport().normalize_response(summary_response) final_response = (_retry_result.content or "").strip() @@ -2138,6 +2376,7 @@ def handle_max_iterations(agent, messages: list, api_call_count: int) -> str: if "" in final_response: final_response = re.sub(r'.*?\s*', '', final_response, flags=re.DOTALL).strip() if final_response: + summary_call_outcome = "success" messages.append({"role": "assistant", "content": final_response}) else: final_response = "I reached the iteration limit and couldn't generate a summary." @@ -2147,6 +2386,13 @@ def handle_max_iterations(agent, messages: list, api_call_count: int) -> str: except Exception as e: logger.warning(f"Failed to get summary response: {e}") final_response = f"I reached the maximum iterations ({agent.max_iterations}) but couldn't summarize. Error: {str(e)}" + finally: + from agent import relay_llm + + relay_llm.complete_logical_call( + summary_api_request_id, + outcome=summary_call_outcome, + ) return final_response @@ -2305,7 +2551,9 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= pass def _bedrock_call(): + stream = None try: + from agent import relay_llm from agent.bedrock_adapter import ( _get_bedrock_runtime_client, invalidate_runtime_client, @@ -2314,44 +2562,40 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= normalize_converse_response, stream_converse_with_callbacks, ) - region = api_kwargs.pop("__bedrock_region__", "us-east-1") - api_kwargs.pop("__bedrock_converse__", None) - client = _get_bedrock_runtime_client(region) - try: - raw_response = client.converse_stream(**api_kwargs) - except Exception as _bedrock_exc: - # IAM policies scoped to bedrock:InvokeModel only (no - # InvokeModelWithResponseStream) reject converse_stream() - # with AccessDeniedException. That denial is permanent for - # the session — fall back to the non-streaming converse() - # inline (it maps to bedrock:InvokeModel) and disable - # streaming for subsequent calls so we don't re-fail every - # turn. - if is_streaming_access_denied_error(_bedrock_exc): - agent._disable_streaming = True - agent._safe_print( - "\n⚠ AWS IAM denied bedrock:InvokeModelWithResponseStream — " - "falling back to non-streaming InvokeModel.\n" - " Grant that action to restore streaming output.\n" - ) - logger.info( - "bedrock: converse_stream denied by IAM (%s) — " - "using non-streaming converse() for this session.", - type(_bedrock_exc).__name__, - ) - result["response"] = normalize_converse_response( - client.converse(**api_kwargs) - ) - return - # Evict the cached client on stale-connection failures - # so the outer retry loop builds a fresh client/pool. - if is_stale_connection_error(_bedrock_exc): - invalidate_runtime_client(region) - raise + intercepted_events = [] + writer_token = {"value": None} - # Claim the delta sink for this bedrock stream (#65991) so a - # superseded attempt's callbacks are fenced by the sink guard. - claim_stream_writer(agent) + def _open_bedrock_stream(next_api_kwargs: dict[str, Any]): + final_kwargs = dict(next_api_kwargs) + region = final_kwargs.pop("__bedrock_region__", "us-east-1") + final_kwargs.pop("__bedrock_converse__", None) + client = _get_bedrock_runtime_client(region) + try: + raw_response = client.converse_stream(**final_kwargs) + except Exception as _bedrock_exc: + # InvokeModel-only policies cannot open a stream. Keep + # the fallback inside the same managed Relay attempt so + # the real provider request and terminal response still + # share one lifecycle boundary. + if is_streaming_access_denied_error(_bedrock_exc): + agent._disable_streaming = True + agent._safe_print( + "\n⚠ AWS IAM denied bedrock:InvokeModelWithResponseStream — " + "falling back to non-streaming InvokeModel.\n" + " Grant that action to restore streaming output.\n" + ) + logger.info( + "bedrock: converse_stream denied by IAM (%s) — " + "using non-streaming converse() for this session.", + type(_bedrock_exc).__name__, + ) + return normalize_converse_response( + client.converse(**final_kwargs) + ) + if is_stale_connection_error(_bedrock_exc): + invalidate_runtime_client(region) + raise + return raw_response.get("stream", []) def _on_text(text): _fire_first() @@ -2366,18 +2610,65 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= _fire_first() agent._fire_reasoning_delta(text) - result["response"] = stream_converse_with_callbacks( - raw_response, + def _finalize_bedrock_stream(): + return stream_converse_with_callbacks( + {"stream": list(intercepted_events)} + ) + + def _bedrock_stream_created(_stream: Any) -> None: + writer_token["value"] = claim_stream_writer(agent) + + def _accept_bedrock_event(_event: Any) -> bool: + token = writer_token["value"] + return token is None or stream_writer_is_current(agent, token) + + stream = relay_llm.stream( + dict(api_kwargs), + _open_bedrock_stream, + session_id=str(getattr(agent, "session_id", "") or ""), + name=str(getattr(agent, "provider", "") or "bedrock"), + model_name=str(getattr(agent, "model", "") or ""), + finalizer=_finalize_bedrock_stream, + on_stream_created=_bedrock_stream_created, + on_chunk=intercepted_events.append, + chunk_adapter=lambda chunk: chunk, + accept_chunk=_accept_bedrock_event, + completed_response_predicate=lambda response: bool( + getattr(response, "choices", None) + ), + metadata={ + "api_mode": "custom", + "api_request_id": getattr( + agent, "_current_api_request_id", None + ), + "call_role": ( + "delegated" + if getattr(agent, "is_subagent", False) + else "fallback" + if int(getattr(agent, "_fallback_index", 0) or 0) > 0 + else "primary" + ), + }, + defer_logical_completion=True, + ) + streamed_response = stream_converse_with_callbacks( + {"stream": stream}, on_text_delta=_on_text if agent._has_stream_consumers() else None, on_tool_start=_on_tool, on_reasoning_delta=_on_reasoning if agent.reasoning_callback or agent.stream_delta_callback else None, on_interrupt_check=lambda: agent._interrupt_requested, on_event=lambda: _bedrock_last_event.__setitem__("t", time.time()), ) + result["response"] = stream.final_response or streamed_response except Exception as e: result["error"] = e + finally: + if stream is not None: + stream.close() - t = threading.Thread(target=_bedrock_call, daemon=True) + t = threading.Thread( + target=_context_thread_target(_bedrock_call), daemon=True + ) t.start() while t.is_alive(): t.join(timeout=0.3) @@ -2462,7 +2753,11 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= request_client_holder = {"client": None, "diag": None, "owner_tid": None} # Transport kind of the registered request client — see the non-streaming # variant. Routes _close_request_client_once to anthropic vs openai abort/ - # close helpers (#67142). + # close helpers (#67142). ``kind="stream"`` registers a per-request + # *stream handle* instead of a client — used under the MoA facade, whose + # singleton client has no per-request sockets to abort + # (_abort_request_openai_client is a no-op on it), so interrupts must + # close the stream object itself (#57354). request_client_kind = {"value": "openai"} request_client_lock = threading.Lock() # Request-local cancellation flag — see interruptible_api_call for the full @@ -2482,6 +2777,44 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= request_client_holder["owner_tid"] = threading.get_ident() return client + def _stream_close_callable(stream): + close = getattr(stream, "close", None) + if callable(close): + return close + response = getattr(stream, "response", None) + close = getattr(response, "close", None) + if callable(close): + return close + return None + + def _set_request_stream_handle(stream): + # Register the per-request *stream* under kind="stream" so an + # interrupt closes the stream handle itself. Under the MoA facade the + # registered "client" is the shared facade singleton whose + # per-request abort helpers are no-ops, leaving the underlying HTTP + # stream open until the provider drained it (#57354). + if _stream_close_callable(stream) is None: + return stream + with request_client_lock: + request_client_holder["client"] = stream + request_client_kind["value"] = "stream" + request_client_holder["owner_tid"] = threading.get_ident() + return stream + + def _close_request_stream_handle(stream, reason: str) -> None: + close = _stream_close_callable(stream) + if close is None: + return + try: + close() + logger.info("Streaming response handle closed (%s)", reason) + except Exception as exc: + logger.debug( + "Streaming response handle close failed (%s): %s", + reason, + exc, + ) + def _close_request_client_once(reason: str) -> None: # See #29507 explanation in the non-streaming variant above. A # stranger thread (the interrupt-check / stale-stream detector loop) @@ -2489,30 +2822,45 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= # so the worker thread retains ownership of the FD release. with request_client_lock: request_client = request_client_holder.get("client") + request_kind = request_client_kind.get("value", "openai") owner_tid = request_client_holder.get("owner_tid") + # A registered stream handle (kind="stream", MoA facade path) is + # safe to close from any thread — closing IS the abort — so the + # stranger-thread ownership carve-out only applies to real + # per-request clients (#57354). stranger_thread = ( - request_client is not None + request_kind != "stream" + and request_client is not None and owner_tid is not None and owner_tid != threading.get_ident() ) - if not stranger_thread: - request_client_holder["client"] = None - request_client_holder["owner_tid"] = None + if stranger_thread: + # Abort under the holder lock — see the non-streaming variant + # for why the holder read and the abort must be atomic (a late + # abort would otherwise hit the NEXT request's checkout). + if request_client_kind.get("value", "openai") == "anthropic_messages": + agent._abort_request_anthropic_client( + request_client, reason=reason + ) + else: + agent._abort_request_openai_client(request_client, reason=reason) + return + request_client_holder["client"] = None + request_client_holder["owner_tid"] = None if request_client is None: return - kind = request_client_kind.get("value", "openai") - if kind == "anthropic_messages": - if stranger_thread: - agent._abort_request_anthropic_client(request_client, reason=reason) - else: - agent._close_request_anthropic_client(request_client, reason=reason) - elif stranger_thread: - agent._abort_request_openai_client(request_client, reason=reason) + # Stranger threads returned under the lock above, so only the owner + # (or an any-thread-safe stream handle) reaches the close dispatch. + if request_kind == "stream": + _close_request_stream_handle(request_client, reason) + elif request_kind == "anthropic_messages": + agent._close_request_anthropic_client(request_client, reason=reason) else: agent._close_request_openai_client(request_client, reason=reason) first_delta_fired = {"done": False} deltas_were_sent = {"yes": False} # Track if any deltas were fired (for fallback) + provider_tool_in_flight = {"yes": False} # Wall-clock timestamp of the last real streaming chunk. The outer # poll loop uses this to detect stale connections that keep receiving # SSE keep-alive pings but no actual data. @@ -2532,11 +2880,29 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= "discarded_chunks": 0, "discarded_bytes": 0, } + managed_stream_holder = {"stream": None} + + def _set_managed_stream(stream: Any) -> Any: + managed_stream_holder["stream"] = stream + return stream + + def _close_managed_stream() -> None: + stream = managed_stream_holder.pop("stream", None) + if stream is None: + return + close = getattr(stream, "close", None) + if callable(close): + try: + close() + except Exception: + logger.debug("Managed provider stream cleanup failed", exc_info=True) def _start_stream_attempt() -> int: with stream_attempt_lock: stream_attempt_state["current"] += 1 - return int(stream_attempt_state["current"]) + attempt_id = int(stream_attempt_state["current"]) + provider_tool_in_flight["yes"] = False + return attempt_id def _cancel_current_stream_attempt(reason: str) -> None: with stream_attempt_lock: @@ -2646,102 +3012,6 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= # Cap connect/pool at 60s even when provider timeout is higher. # connect/pool cover TCP handshake, not model inference. _conn_cap = min(_base_timeout, 60.0) if _provider_timeout_cfg is not None else 30.0 - stream_kwargs = { - **api_kwargs, - "stream": True, - "timeout": _httpx.Timeout( - connect=_conn_cap, - read=_stream_read_timeout, - write=_base_timeout, - pool=_conn_cap, - ), - } - # OpenAI's `stream_options={"include_usage": True}` drives usage - # accounting on OpenAI-compatible endpoints (incl. the Gemini OpenAI - # compat shim and aggregators like OpenRouter). Google's *native* - # Gemini REST endpoint rejects the keyword outright - # (`Completions.create() got an unexpected keyword argument - # 'stream_options'`), so omit it only for that endpoint. - if not is_native_gemini_base_url(agent.base_url): - stream_kwargs["stream_options"] = {"include_usage": True} - request_client = _set_request_client( - agent._create_request_openai_client( - reason="chat_completion_stream_request", - api_kwargs=stream_kwargs, - ) - ) - # Reset stale-stream timer so the detector measures from this - # attempt's start, not a previous attempt's last chunk. - last_chunk_time["t"] = time.time() - agent._touch_activity("waiting for provider response (streaming)") - # Initialize per-attempt stream diagnostics so the retry block can - # reach for them after the stream dies. Lives on - # ``request_client_holder["diag"]`` for closure access. - _diag = agent._stream_diag_init() - request_client_holder["diag"] = _diag - stream = request_client.chat.completions.create(**stream_kwargs) - # Claim the delta sink for THIS attempt (#65991). If a prior attempt's - # stream is somehow still alive (a stale-stream reconnect whose socket - # abort raced), this claim supersedes it so its late chunks are fenced - # out of the turn instead of interleaving with ours. - _writer_token = claim_stream_writer(agent) - - # Some OpenAI-compatible adapters (for example copilot-acp, and the MoA - # openai-codex aggregator) accept stream=True but still return a - # completed response object rather than an iterator of chunks. Treat - # that as "streaming unsupported" for the rest of this session instead - # of crashing on ``for chunk in stream`` with ``'types.SimpleNamespace' - # object is not iterable`` (#11732, #55933). - # - # Discriminate on the mere PRESENCE of a ``choices`` attribute, not on - # it being a non-empty list: an adapter may hand back a completed - # response whose ``choices`` is ``None`` or empty (an error / - # content-filter / terminal frame), and every such shape is still a - # whole response — not a token stream — that would crash iteration just - # the same. A genuine provider stream (SDK ``Stream`` object, - # generator) exposes no ``choices`` attribute, so it is left untouched. - if hasattr(stream, "choices"): - logger.info( - "Streaming request returned a final response object instead of " - "an iterator; switching %s/%s to non-streaming for this session.", - agent.provider or "unknown", - agent.model or "unknown", - ) - agent._disable_streaming = True - # An empty/None ``choices`` carries no message to surface; return the - # completed object as-is so the outer loop's normal invalid-response - # validation (conversation_loop.py) handles it via the retry path, - # never ``for chunk in stream``. - choices = stream.choices - first_choice = choices[0] if isinstance(choices, (list, tuple)) and choices else None - message = getattr(first_choice, "message", None) - if message is not None: - reasoning_text = ( - getattr(message, "reasoning_content", None) - or getattr(message, "reasoning", None) - ) - if isinstance(reasoning_text, str) and reasoning_text: - _fire_first_delta() - agent._fire_reasoning_delta(reasoning_text) - content = getattr(message, "content", None) - if isinstance(content, str) and content: - _fire_first_delta() - agent._fire_stream_delta(content) - return stream - - # Capture rate limit headers from the initial HTTP response. - # The OpenAI SDK Stream object exposes the underlying httpx - # response via .response before any chunks are consumed. - agent._capture_rate_limits(getattr(stream, "response", None)) - agent._capture_credits(getattr(stream, "response", None)) - # Snapshot diagnostic headers (cf-ray, x-openrouter-provider, etc.) - # so they survive even when the stream dies before any chunk - # arrives. Best-effort; never raises. - agent._stream_diag_capture_response(_diag, getattr(stream, "response", None)) - - # Log OpenRouter response cache status when present. - agent._check_openrouter_cache_status(getattr(stream, "response", None)) - content_parts: list = [] tool_calls_acc: dict = {} tool_gen_notified: set = set() @@ -2756,19 +3026,125 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= role = "assistant" reasoning_parts: list = [] usage_obj = None - for chunk in stream: - # Stop the moment a newer attempt has claimed the delta sink - # (#65991): this attempt has been superseded, so it must neither - # fire deltas (incl. the tool-suppressed raw-callback path below) - # nor keep consuming a stream that would interleave into the turn. - if not stream_writer_is_current(agent, _writer_token): + _diag = agent._stream_diag_init() + request_client_holder["diag"] = _diag + _writer_token = {"value": None} + attempt_request_client = {"value": None} + + def _open_stream(next_api_kwargs: dict[str, Any]): + stream_kwargs = { + **next_api_kwargs, + "stream": True, + "timeout": _httpx.Timeout( + connect=_conn_cap, + read=_stream_read_timeout, + write=_base_timeout, + pool=_conn_cap, + ), + } + # Native Gemini rejects OpenAI's usage-streaming extension. + if not is_native_gemini_base_url(agent.base_url): + stream_kwargs["stream_options"] = {"include_usage": True} + request_client = _set_request_client( + agent._create_request_openai_client( + reason="chat_completion_stream_request", + api_kwargs=stream_kwargs, + ) + ) + attempt_request_client["value"] = request_client + last_chunk_time["t"] = time.time() + agent._touch_activity("waiting for provider response (streaming)") + return request_client.chat.completions.create(**stream_kwargs) + + def _stream_created(raw_stream: Any) -> None: + response = getattr(raw_stream, "response", None) + agent._capture_rate_limits(response) + agent._capture_credits(response) + agent._stream_diag_capture_response(_diag, response) + agent._check_openrouter_cache_status(response) + _writer_token["value"] = claim_stream_writer(agent) + + def _accept_stream_chunk(_chunk: Any) -> bool: + # A stale-attempt fence can win while Relay is handing an + # already-received tool-call chunk back to Hermes. Preserve only + # the fact that a tool call was in flight so retry policy does not + # misclassify the attempt as a partial text response. The chunk + # itself is still rejected below and never reaches callbacks. + try: + choices = getattr(_chunk, "choices", None) + delta = getattr(choices[0], "delta", None) if choices else None + if getattr(delta, "tool_calls", None): + provider_tool_in_flight["yes"] = True + except Exception: + pass + if not _stream_attempt_is_active(stream_attempt_id): + return False + token = _writer_token["value"] + if token is not None and not stream_writer_is_current(agent, token): logger.warning( "Streaming attempt superseded by a newer stream; stopping " "consumption to preserve the single-writer invariant " "(model=%s).", api_kwargs.get("model", "unknown"), ) - break + return False + # Record provider activity before Relay processes the chunk. This + # prevents the stale watchdog from cancelling a live stream while + # an interceptor or codec is still handling an already-received + # event. + last_chunk_time["t"] = time.time() + return True + + def _relay_final_response() -> dict[str, Any]: + tool_calls = [tool_calls_acc[index] for index in sorted(tool_calls_acc)] + return { + "model": model_name, + "choices": [ + { + "message": { + "role": role, + "content": "".join(content_parts) or None, + "reasoning_content": "".join(reasoning_parts) or None, + "tool_calls": tool_calls or None, + }, + "finish_reason": finish_reason or "stop", + } + ], + "usage": usage_obj, + } + + from agent import relay_llm + + stream = _set_managed_stream( + relay_llm.stream( + api_kwargs, + _open_stream, + session_id=str(getattr(agent, "session_id", "") or ""), + name=str(getattr(agent, "provider", "") or "provider"), + model_name=str(getattr(agent, "model", "") or ""), + finalizer=_relay_final_response, + on_stream_created=_stream_created, + accept_chunk=_accept_stream_chunk, + completed_response_predicate=lambda value: hasattr(value, "choices"), + metadata={ + "api_mode": "chat_completions", + "api_request_id": getattr(agent, "_current_api_request_id", None), + "call_role": ( + "delegated" + if getattr(agent, "is_subagent", False) + else "fallback" + if int(getattr(agent, "_fallback_index", 0) or 0) > 0 + else "primary" + ), + }, + defer_logical_completion=True, + ) + ) + if agent.provider == "moa": + # Hermes interrupts the managed stream; Relay retains sole + # ownership of closing the underlying provider stream. + _set_request_stream_handle(stream) + for chunk in stream: last_chunk_time["t"] = time.time() agent._touch_activity("receiving stream response") @@ -2779,18 +3155,39 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= _diag["chunks"] = int(_diag.get("chunks", 0)) + 1 if _diag.get("first_chunk_at") is None: _diag["first_chunk_at"] = last_chunk_time["t"] - # Approximate byte size from the chunk's repr — exact wire - # bytes aren't exposed by the SDK, but len(repr(chunk)) is - # a stable proxy for "how much content arrived" that - # survives stub provider differences. + # Approximate byte size from the chunk's delta payload — + # exact wire bytes aren't exposed by the SDK. A full + # repr() per chunk was 5.5-8.8 µs of pure CPU on the + # hottest loop in the agent; the delta-length estimate + # is ~3x cheaper and stays proportional to traffic. try: - _diag["bytes"] = int(_diag.get("bytes", 0)) + len(repr(chunk)) + _diag["bytes"] = int(_diag.get("bytes", 0)) + _estimate_chunk_bytes(chunk) except Exception: pass except Exception: pass if agent._interrupt_requested: + # Abandoning a half-read SSE response leaves its connection + # permanently checked out of the httpx pool — and the partial + # response built below makes the worker's finally report a + # reuse-reason close, which would cache the client together + # with the leaked connection (each interrupt leaking one more + # until the pool exhausts). Close the stream here, on the + # owning thread, so the connection is released first. + try: + stream.close() + except Exception: + # Connection may still be checked out — poison the slot so + # the finally's close really closes the pool instead of + # caching it (owner-thread abort: shutdown is safe, and the + # FD release still happens in the finally below). + request_client = attempt_request_client["value"] + if request_client is not None: + agent._abort_request_openai_client( + request_client, + reason="interrupt_stream_close_failed", + ) break if not _stream_attempt_is_active(stream_attempt_id): @@ -2922,11 +3319,46 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= if hasattr(chunk, "usage") and chunk.usage: usage_obj = chunk.usage + _close_managed_stream() + if _stream_attempt_was_cancelled(stream_attempt_id): raise _httpx.RemoteProtocolError( f"stream attempt {stream_attempt_id} was superseded" ) + # Some OpenAI-compatible adapters accept ``stream=True`` but return a + # completed response. Relay records that attempt while Hermes preserves + # its existing switch-to-non-streaming behavior for later calls. + if stream.final_response is not None: + final_response = stream.final_response + logger.info( + "Streaming request returned a final response object instead of " + "an iterator; switching %s/%s to non-streaming for this session.", + agent.provider or "unknown", + agent.model or "unknown", + ) + agent._disable_streaming = True + choices = final_response.choices + first_choice = ( + choices[0] + if isinstance(choices, (list, tuple)) and choices + else None + ) + message = getattr(first_choice, "message", None) + if message is not None: + reasoning_text = ( + getattr(message, "reasoning_content", None) + or getattr(message, "reasoning", None) + ) + if isinstance(reasoning_text, str) and reasoning_text: + _fire_first_delta() + agent._fire_reasoning_delta(reasoning_text) + content = getattr(message, "content", None) + if isinstance(content, str) and content: + _fire_first_delta() + agent._fire_stream_delta(content) + return final_response + # Build mock response matching non-streaming shape full_content = "".join(content_parts) or None mock_tool_calls = None @@ -3088,72 +3520,95 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= # fabricated "successful" empty turn. saw_stream_event = False - # Reset stale-stream timer for this attempt last_chunk_time["t"] = time.time() - # Per-attempt diagnostic dict for the retry block to consume. _diag = agent._stream_diag_init() request_client_holder["diag"] = _diag - # Defensive: strip Responses-only kwargs (instructions, input, ...) - # that can leak in under an api_mode-flip race. The Anthropic SDK - # raises a non-retryable TypeError on them, killing the turn. See - # #31673 / sanitize_anthropic_kwargs(). + _writer_token = {"value": None} + _stream_context = {"manager": None, "stream": None} + base_final_message = None + + from agent import relay_llm from agent.anthropic_adapter import sanitize_anthropic_kwargs - sanitize_anthropic_kwargs( - api_kwargs, log_prefix=getattr(agent, "log_prefix", "") - ) - # Use the Anthropic SDK's streaming context manager - with request_client.messages.stream(**api_kwargs) as stream: + + accumulator = relay_llm.AnthropicStreamAccumulator() + + def _open_anthropic_stream(next_api_kwargs: dict[str, Any]): + final_kwargs = dict(next_api_kwargs) + sanitize_anthropic_kwargs( + final_kwargs, + log_prefix=getattr(agent, "log_prefix", ""), + ) + manager = request_client.messages.stream(**final_kwargs) + _stream_context["manager"] = manager + return manager.__enter__() + + def _anthropic_stream_created(raw_stream: Any) -> None: + _stream_context["stream"] = raw_stream # The Anthropic SDK exposes the raw httpx response on - # ``stream.response``. Snapshot diagnostic headers - # immediately so they survive a stream that dies before the - # first event. + # ``stream.response``. Snapshot diagnostics immediately so they + # survive a stream that dies before the first event. try: agent._stream_diag_capture_response( - _diag, getattr(stream, "response", None) + _diag, + getattr(raw_stream, "response", None), ) except Exception: pass - # Claim the delta sink for THIS attempt (#65991) — parity with the - # chat_completions path so a superseded anthropic stream is fenced. - _writer_token = claim_stream_writer(agent) + _writer_token["value"] = claim_stream_writer(agent) + + def _accept_anthropic_event(_event: Any) -> bool: + token = _writer_token["value"] + if token is None or stream_writer_is_current(agent, token): + return True + logger.warning( + "Anthropic streaming attempt superseded by a newer stream; " + "stopping consumption to preserve the single-writer " + "invariant (model=%s).", + api_kwargs.get("model", "unknown"), + ) + return False + + stream = _set_managed_stream( + relay_llm.stream( + api_kwargs, + _open_anthropic_stream, + session_id=str(getattr(agent, "session_id", "") or ""), + name=str(getattr(agent, "provider", "") or "anthropic"), + model_name=str(getattr(agent, "model", "") or ""), + finalizer=accumulator.finalize, + on_stream_created=_anthropic_stream_created, + on_chunk=accumulator.observe, + accept_chunk=_accept_anthropic_event, + metadata={ + "api_mode": "anthropic_messages", + "api_request_id": getattr(agent, "_current_api_request_id", None), + "call_role": ( + "delegated" + if getattr(agent, "is_subagent", False) + else "fallback" + if int(getattr(agent, "_fallback_index", 0) or 0) > 0 + else "primary" + ), + }, + defer_logical_completion=True, + ) + ) + try: for event in stream: - # Bail the instant a newer attempt supersedes this one so a - # stale stream can't interleave tokens into the turn. - if not stream_writer_is_current(agent, _writer_token): - logger.warning( - "Anthropic streaming attempt superseded by a newer " - "stream; stopping consumption to preserve the " - "single-writer invariant (model=%s).", - api_kwargs.get("model", "unknown"), - ) - break saw_stream_event = True - # Update stale-stream timer on every event so the - # outer poll loop knows data is flowing. Without - # this, the detector kills healthy long-running - # Opus streams after 180 s even when events are - # actively arriving (the chat_completions path - # already does this at the top of its chunk loop). last_chunk_time["t"] = time.time() agent._touch_activity("receiving stream response") - - # Update per-attempt diagnostic counters (best-effort). try: _diag["chunks"] = int(_diag.get("chunks", 0)) + 1 if _diag.get("first_chunk_at") is None: _diag["first_chunk_at"] = last_chunk_time["t"] - try: - _diag["bytes"] = int(_diag.get("bytes", 0)) + len(repr(event)) - except Exception: - pass + _diag["bytes"] = int(_diag.get("bytes", 0)) + _estimate_chunk_bytes(event) except Exception: pass - if agent._interrupt_requested: break event_type = getattr(event, "type", None) - if event_type == "content_block_start": block = getattr(event, "content_block", None) if block and getattr(block, "type", None) == "tool_use": @@ -3162,7 +3617,6 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= if tool_name: _fire_first_delta() agent._fire_tool_gen_started(tool_name) - elif event_type == "content_block_delta": delta = getattr(event, "delta", None) if delta: @@ -3178,48 +3632,49 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= if thinking_text: _fire_first_delta() agent._fire_reasoning_delta(thinking_text) - - # Return the native Anthropic Message for downstream processing. - # If the stream was interrupted (the event loop broke out above on - # agent._interrupt_requested), do NOT call get_final_message() — on - # a partially-consumed stream the SDK may hang draining remaining - # events or return a Message with incomplete tool_use blocks (partial - # JSON in `input`). The outer poll loop raises InterruptedError, so - # this return value is discarded anyway. - if agent._interrupt_requested: - return None - # Zero-event guard (parity with the chat_completions zero-chunk - # guard above). Real SDK: an eventless stream has no - # message_start, so get_final_message() raises AssertionError - # (final-message snapshot is None) — normalize that to - # EmptyStreamError so it gets the transient retry budget - # instead of surfacing raw. + if not agent._interrupt_requested: + raw_stream = _stream_context["stream"] + if raw_stream is not None: + try: + base_final_message = raw_stream.get_final_message() + except AssertionError: + if not saw_stream_event: + raise EmptyStreamError( + "Provider returned an empty stream with no events " + "(possible upstream error or malformed event stream)." + ) from None + raise + finally: try: - _final_message = stream.get_final_message() - except AssertionError: - if not saw_stream_event: - raise EmptyStreamError( - "Provider returned an empty stream with no events " - "(possible upstream error or malformed event stream)." - ) from None - raise - # Shim variants of the same failure: an OpenAI-compat adapter - # may fabricate a contentless Message with no stop_reason, or - # return None where the SDK assert would have fired (e.g. - # ``python -O``). A real completed response always carries a - # stop_reason, so this cannot fire on legitimate turns. - if not saw_stream_event and ( - _final_message is None - or ( - not getattr(_final_message, "content", None) - and getattr(_final_message, "stop_reason", None) is None - ) - ): - raise EmptyStreamError( - "Provider returned an empty stream with no stop_reason " - "(possible upstream error or malformed event stream)." - ) - return _final_message + _close_managed_stream() + finally: + manager = _stream_context["manager"] + if manager is not None: + manager.__exit__(None, None, None) + + if agent._interrupt_requested: + return None + if ( + base_final_message is not None + and not getattr(base_final_message, "content", None) + and getattr(base_final_message, "stop_reason", None) is None + ): + raise EmptyStreamError( + "Provider returned an empty stream with no stop_reason " + "(possible upstream error or malformed event stream)." + ) + if base_final_message is not None and not stream.output_modified: + return base_final_message + final_message = accumulator.response(base_final_message) + if ( + not getattr(final_message, "content", None) + and getattr(final_message, "stop_reason", None) is None + ): + raise EmptyStreamError( + "Provider returned an empty stream with no stop_reason " + "(possible upstream error or malformed event stream)." + ) + return final_message def _call(): import httpx as _httpx @@ -3254,6 +3709,7 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= result["response"] = _call_chat_completions(stream_attempt_id) return # success except Exception as e: + _close_managed_stream() # If the main poll loop force-closed this request because # of an interrupt, the resulting transport error is the # expected consequence of our own close — NOT a transient @@ -3293,7 +3749,7 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= if deltas_were_sent["yes"]: _partial_tool_in_flight = bool( result.get("partial_tool_names") - ) + ) or provider_tool_in_flight["yes"] _is_sse_conn_err_preview = False if not _is_timeout and not _is_conn_err: from openai import APIError as _APIError @@ -3379,13 +3835,9 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= # already worker-owned-closed by _close_request_client_once # above; the next attempt builds a fresh one. The shared # _anthropic_client is never closed from inside a request. - if agent.api_mode != "anthropic_messages": - try: - agent._replace_primary_openai_client( - reason="stream_mid_tool_retry_pool_cleanup" - ) - except Exception: - pass + # #70773: same FD-recycle corruption vector for OpenAI. + # The shared client will be replaced lazily by + # _ensure_primary_openai_client on the next attempt. continue # SSE error events from proxies (e.g. OpenRouter sends @@ -3444,13 +3896,9 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= # above; next attempt builds fresh), so the shared # _anthropic_client is never closed from inside a # request — only the OpenAI-wire primary is refreshed. - if agent.api_mode != "anthropic_messages": - try: - agent._replace_primary_openai_client( - reason="stream_retry_pool_cleanup" - ) - except Exception: - pass + # #70773: same FD-recycle corruption vector for OpenAI. + # The shared client will be replaced lazily by + # _ensure_primary_openai_client on the next attempt. continue # Retries exhausted. Log the final failure with # full diagnostic detail (chain, headers, @@ -3550,7 +3998,15 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= result["error"] = e return finally: - _close_request_client_once("stream_request_complete") + _close_managed_stream() + # Reuse reason only on a clean stream; any other outcome (error, + # cancel-swallow) really closes so the next attempt builds a + # fresh pool (see _REQUEST_CLIENT_REUSE_REASONS). + _close_request_client_once( + "stream_request_complete" + if result["response"] is not None + else "stream_error_cleanup" + ) # Provider-configured stale timeout takes priority over env default. _cfg_stale = get_provider_stale_timeout(agent.provider, agent.model) @@ -3572,9 +4028,9 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= # env var ``HERMES_LOCAL_STREAM_STALE_TIMEOUT`` overrides for escape-hatch. _local_default = 900.0 try: - from hermes_cli.config import load_config + from hermes_cli.config import load_config_readonly - _cfg = load_config() + _cfg = load_config_readonly() # read-only consumer — no deepcopy _agent_cfg = _cfg.get("agent") if isinstance(_cfg, dict) else None if isinstance(_agent_cfg, dict): _v = _agent_cfg.get("local_stream_stale_timeout") @@ -3612,7 +4068,7 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= if _reasoning_floor is not None: _stream_stale_timeout = max(_stream_stale_timeout, _reasoning_floor) - t = threading.Thread(target=_call, daemon=True) + t = threading.Thread(target=_context_thread_target(_call), daemon=True) t.start() _last_heartbeat = time.time() _HEARTBEAT_INTERVAL = 30.0 # seconds between gateway activity touches @@ -3693,10 +4149,15 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= # FD-recycle corruption vector. Nothing further is needed. pass else: - try: - agent._replace_primary_openai_client(reason="stale_stream_pool_cleanup") - except Exception: - pass + # #70773: same FD-recycle corruption vector as #67142. + # The shared OpenAI client's connection pool must NOT be + # closed from this watchdog/poll thread — worker threads + # from previous stale-killed attempts may still be + # unwinding their SSL BIOs. The request-local client is + # already closed above via _close_request_client_once. + # The shared client will be replaced lazily by + # _ensure_primary_openai_client on the next request. + pass # Reset the timer so we don't kill repeatedly while # the inner thread processes the closure. last_chunk_time["t"] = time.time() @@ -3779,6 +4240,17 @@ def interruptible_streaming_api_call(agent, api_kwargs: dict, *, on_first_delta= result["error"], ) _stub_finish_reason = FINISH_REASON_LENGTH + # NOTE (empty-content class fix): the stub is deliberately allowed + # to carry empty content here. The conversation loop's truncation + # path detects an EMPTY partial-stream stub (PARTIAL_STREAM_STUB_ID + # + no content) and skips appending it to history entirely — only + # the continuation nudge is sent. Substituting placeholder text at + # this site was tried and reverted: it defeats that guard (the stub + # no longer looks empty), gets appended to history, and the + # placeholder leaks into the stitched final response via + # truncated_response_parts. Transcripts that already carry a + # persisted empty turn are healed at the send boundary by + # ``repair_empty_non_final_messages`` (the single owner). _stub_msg = SimpleNamespace( role="assistant", content=_partial_text, tool_calls=None, reasoning_content=None, diff --git a/agent/codex_responses_adapter.py b/agent/codex_responses_adapter.py index bce372ebb5da..23708eca9729 100644 --- a/agent/codex_responses_adapter.py +++ b/agent/codex_responses_adapter.py @@ -18,6 +18,7 @@ import uuid from types import SimpleNamespace from typing import Any, Dict, List, Optional +from agent.message_sanitization import deterministic_call_id from agent.prompt_builder import DEFAULT_AGENT_IDENTITY logger = logging.getLogger(__name__) @@ -182,12 +183,34 @@ def _summarize_user_message_for_log(content: Any, *, sep: str = " ") -> str: def _deterministic_call_id(fn_name: str, arguments: str, index: int = 0) -> str: """Generate a deterministic call_id from tool call content. - Used as a fallback when the API doesn't provide a call_id. + Thin wrapper over the single policy owner + ``agent.message_sanitization.deterministic_call_id`` (audit F4) — kept + as a module-level name because run_agent and tests import it from here. Deterministic IDs prevent cache invalidation — random UUIDs would make every API call's prefix unique, breaking OpenAI's prompt cache. """ - seed = f"{fn_name}:{arguments}:{index}" - digest = hashlib.sha256(seed.encode("utf-8", errors="replace")).hexdigest()[:12] + return deterministic_call_id(fn_name, arguments, index) + + +def _clamp_responses_call_id(call_id: str) -> str: + """Keep a ``call_id`` within the Responses API's 64-char limit (#73492). + + The codex app-server namespaces MCP tool call ids as + ``codex_mcp_____``; with an ``exec-`` + component the built-in ``hermes-tools`` server already overflows 64 chars, + and the Responses API rejects the whole payload with a non-retryable HTTP + 400 that then replays every turn — permanently bricking the session. + + Sibling defect to #10788 (which clamped ``input[*].id``), applied here to + ``call_id``. The surrogate is a pure, deterministic function of the + original, so the ``function_call`` and its matching ``function_call_output`` + — which carry the same original id — map to the same surrogate and stay + paired without correlating the two items. Short ids pass through unchanged, + preserving prompt-cache prefixes. + """ + if len(call_id) <= _MAX_RESPONSES_ITEM_ID_LENGTH: + return call_id + digest = hashlib.sha256(call_id.encode("utf-8", errors="replace")).hexdigest()[:32] return f"call_{digest}" @@ -546,7 +569,7 @@ def _chat_messages_to_responses_input( items.append({ "type": "function_call", - "call_id": call_id, + "call_id": _clamp_responses_call_id(call_id), "name": fn_name, "arguments": arguments, }) @@ -589,7 +612,7 @@ def _chat_messages_to_responses_input( items.append({ "type": "function_call_output", - "call_id": call_id, + "call_id": _clamp_responses_call_id(call_id), "output": output_value, }) @@ -912,7 +935,8 @@ def _preflight_codex_api_kwargs( allowed_keys = { "model", "instructions", "input", "tools", "store", "reasoning", "include", "max_output_tokens", "temperature", - "tool_choice", "parallel_tool_calls", "prompt_cache_key", "service_tier", + "tool_choice", "parallel_tool_calls", "prompt_cache_key", + "prompt_cache_retention", "service_tier", "extra_headers", "extra_body", "timeout", } normalized: Dict[str, Any] = { @@ -950,8 +974,13 @@ def _preflight_codex_api_kwargs( if isinstance(temperature, (int, float)): normalized["temperature"] = float(temperature) - # Pass through tool_choice, parallel_tool_calls, prompt_cache_key - for passthrough_key in ("tool_choice", "parallel_tool_calls", "prompt_cache_key"): + # Pass through cache routing/retention and tool-dispatch hints. + for passthrough_key in ( + "tool_choice", + "parallel_tool_calls", + "prompt_cache_key", + "prompt_cache_retention", + ): val = api_kwargs.get(passthrough_key) if val is not None: normalized[passthrough_key] = val diff --git a/agent/codex_runtime.py b/agent/codex_runtime.py index 59f9bac25a26..7b8bed6137bb 100644 --- a/agent/codex_runtime.py +++ b/agent/codex_runtime.py @@ -18,7 +18,6 @@ from __future__ import annotations import json import logging -import os import time from types import SimpleNamespace from typing import Any, Callable, Dict, List @@ -74,7 +73,10 @@ def _record_codex_app_server_usage(agent, turn) -> dict[str, Any]: try: if not agent._session_db_created: agent._ensure_db_session() - agent._session_db.update_token_counts( + # Enqueued for the SessionDB background writer — keeps the + # per-call accounting write off the turn thread (see + # conversation_loop's queue_token_counts call). + agent._session_db.queue_token_counts( agent.session_id, model=agent.model, billing_provider=agent.provider, @@ -154,7 +156,8 @@ def _record_codex_app_server_usage(agent, turn) -> dict[str, Any]: try: if not agent._session_db_created: agent._ensure_db_session() - agent._session_db.update_token_counts( + # Enqueued for the SessionDB background writer (see above). + agent._session_db.queue_token_counts( agent.session_id, input_tokens=canonical_usage.input_tokens, output_tokens=canonical_usage.output_tokens, @@ -778,12 +781,27 @@ def run_codex_app_server_turn( # the already-flushed user turn). See gateway/run.py agent_persisted. if getattr(agent, "_session_db", None) is not None: try: - agent._flush_messages_to_session_db(messages) + _codex_flush_ok = agent._flush_messages_to_session_db(messages) except Exception: - logger.debug( + _codex_flush_ok = False + logger.warning( "codex app-server projected-message flush failed", exc_info=True, ) + if _codex_flush_ok is False: + # Unlike the chat-completions loop (which fails closed BEFORE + # projection — see conversation_loop session_persistence_failed), + # codex output has already streamed to the user by the time this + # flush runs, so there is nothing left to withhold. We cannot + # flip agent_persisted=False either: the gateway fallback write + # would re-INSERT the already-flushed user turn (#860/#42039). + # Surface the durability gap loudly instead of a silent debug. + logger.warning( + "codex app-server turn was delivered but could NOT be " + "persisted to the session DB (session=%s) — this turn " + "will be missing after restart/resume", + getattr(agent, "session_id", None), + ) # Counter ticks for the agent-improvement loop. @@ -1221,6 +1239,8 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_delta """ import httpx as _httpx + from agent import relay_llm + active_client = client or agent._ensure_primary_openai_client(reason="codex_stream_direct") max_stream_retries = 1 # Accumulate streamed text so callers / compat shims can read it. @@ -1245,48 +1265,88 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_delta if agent._interrupt_requested: raise InterruptedError("Agent interrupted before Codex stream retry") - stream_kwargs = dict(api_kwargs) - stream_kwargs["stream"] = True + intercepted_events = [] + writer_token = {"value": None} + + def _open_codex_stream(next_api_kwargs: dict[str, Any]): + stream_kwargs = dict(next_api_kwargs) + stream_kwargs["stream"] = True + return active_client.responses.create(**stream_kwargs) + + def _codex_stream_created(_raw_stream: Any) -> None: + # Claim the delta sink for THIS physical attempt. A newer attempt + # supersedes this token and fences late deltas out of the turn. + writer_token["value"] = claim_stream_writer(agent) + + def _accept_codex_chunk(_chunk: Any) -> bool: + token = writer_token["value"] + if token is None or stream_writer_is_current(agent, token): + return True + logger.warning( + "Codex streaming attempt superseded by a newer stream; " + "stopping consumption to preserve the single-writer " + "invariant (model=%s).", + api_kwargs.get("model", "unknown"), + ) + return False + + def _finalize_codex_stream() -> Any: + return _consume_codex_event_stream( + list(intercepted_events), + model=api_kwargs.get("model"), + ) try: - event_stream = active_client.responses.create(**stream_kwargs) - except (_httpx.RemoteProtocolError, _httpx.ReadTimeout, _httpx.ConnectError, ConnectionError) as exc: + event_stream = relay_llm.stream( + dict(api_kwargs), + _open_codex_stream, + session_id=str(getattr(agent, "session_id", "") or ""), + name=str(getattr(agent, "provider", "") or "codex"), + model_name=str(api_kwargs.get("model") or ""), + finalizer=_finalize_codex_stream, + on_stream_created=_codex_stream_created, + on_chunk=intercepted_events.append, + chunk_adapter=lambda chunk: chunk, + accept_chunk=_accept_codex_chunk, + completed_response_predicate=lambda response: bool( + hasattr(response, "output") and not hasattr(response, "__iter__") + ), + metadata={ + "api_mode": "codex_responses", + "api_request_id": getattr(agent, "_current_api_request_id", None), + "call_role": ( + "delegated" + if getattr(agent, "is_subagent", False) + else "fallback" + if int(getattr(agent, "_fallback_index", 0) or 0) > 0 + else "primary" + ), + "retry_count": attempt, + }, + defer_logical_completion=True, + ) + except ( + _httpx.RemoteProtocolError, + _httpx.ReadTimeout, + _httpx.ConnectError, + ConnectionError, + ) as exc: if attempt < max_stream_retries: logger.debug( - "Codex Responses stream connect failed (attempt %s/%s); retrying. %s error=%s", - attempt + 1, max_stream_retries + 1, - agent._client_log_context(), exc, + "Codex Responses stream connect failed (attempt %s/%s); " + "retrying. %s error=%s", + attempt + 1, + max_stream_retries + 1, + agent._client_log_context(), + exc, ) continue raise - # Claim the delta sink for THIS attempt (#65991) — parity with the - # chat_completions/anthropic/bedrock paths. If a prior attempt's - # stream is somehow still alive, this claim supersedes it so its - # late deltas are fenced out of the turn; conversely, a newer - # attempt supersedes us and the interrupt_check below stops our - # consumption immediately. - _writer_token = claim_stream_writer(agent) - - def _interrupt_or_superseded(_tok=_writer_token) -> bool: - if agent._interrupt_requested: - return True - if not stream_writer_is_current(agent, _tok): - logger.warning( - "Codex streaming attempt superseded by a newer stream; " - "stopping consumption to preserve the single-writer " - "invariant (model=%s).", - api_kwargs.get("model", "unknown"), - ) - return True - return False + def _interrupt_or_superseded() -> bool: + return bool(agent._interrupt_requested) try: - # Compatibility: some mocks/providers return a concrete response - # instead of an iterable. Pass it straight through. - if hasattr(event_stream, "output") and not hasattr(event_stream, "__iter__"): - return event_stream - try: final = _consume_codex_event_stream( event_stream, @@ -1305,6 +1365,12 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_delta on_event=_on_event, interrupt_check=_interrupt_or_superseded, ) + # The terminal SSE frame is contractually last. Request the + # end-of-stream marker so Relay can run its response finalizer + # and close the physical attempt scope before Hermes returns. + if not agent._interrupt_requested: + for _ignored in event_stream: + pass except (_httpx.RemoteProtocolError, _httpx.ReadTimeout, _httpx.ConnectError, ConnectionError) as exc: if attempt < max_stream_retries: logger.debug( @@ -1315,6 +1381,10 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_delta ) continue raise + except RuntimeError: + if event_stream.final_response is not None: + return event_stream.final_response + raise if final.status in {"incomplete", "failed"}: logger.warning( @@ -1332,7 +1402,20 @@ def run_codex_stream(agent, api_kwargs: dict, client: Any = None, on_first_delta try: close_fn() except Exception: - pass + # A failed close can leave this response's connection + # checked out of the httpx pool while the caller's finally + # reports a reuse-reason close (e.g. interrupt_check broke + # the event loop with collected output) — caching the + # client with the leaked connection. Poison the slot so + # that close really closes the pool (owner-thread abort; + # mirrors the chat-streaming interrupt-break handling). + # ``client is None`` means the shared primary client, + # which is never reuse-cached and must not have its + # sockets force-shut here. + if client is not None: + agent._abort_request_openai_client( + active_client, reason="codex_stream_close_failed" + ) def run_codex_create_stream_fallback(agent, api_kwargs: dict, client: Any = None): diff --git a/agent/coding_context.py b/agent/coding_context.py index 4a0cb8410308..fabbdb48e079 100644 --- a/agent/coding_context.py +++ b/agent/coding_context.py @@ -520,30 +520,46 @@ class RuntimeMode: return None return [self.profile.toolset, *_enabled_mcp_servers(config)] - def system_blocks(self) -> list[str]: - """Stable system-prompt blocks for this posture (brief + workspace). + def system_prompt_parts(self) -> tuple[list[str], list[str], list[str]]: + """Return prefix, workspace, and trailing posture blocks separately. The operating brief carries a model-family edit-format nudge appended to it (one cached string, not a separate block) so the model is steered toward the `patch` mode it handles best — see ``_edit_format_line``. + + The three lists preserve the historical flat prompt order: the brief, + the live workspace snapshot, then configured operator instructions. + Prompt assembly can therefore put a cache boundary before the snapshot + without changing the persisted system-prompt bytes. """ if not self.is_coding: - return [] - blocks: list[str] = [] + return [], [], [] + prefix: list[str] = [] + workspace_parts: list[str] = [] + trailing: list[str] = [] if self.profile.guidance: brief = self.profile.guidance edit_line = _edit_format_line(self.model) if edit_line: brief = f"{brief}\n{edit_line}" - blocks.append(brief) + prefix.append(brief) workspace = build_coding_workspace_block(self.cwd) if workspace: - blocks.append(workspace) + workspace_parts.append(workspace) # Operator instructions ride their own block so the brief (block 0) stays # byte-stable and cache-keyed independently of user config. if self.instructions: - blocks.append(f"Operator instructions (from config):\n{self.instructions}") - return blocks + trailing.append(f"Operator instructions (from config):\n{self.instructions}") + return prefix, workspace_parts, trailing + + def system_blocks(self) -> list[str]: + """Return posture blocks in their historical display order. + + ``system_prompt_parts`` is the cache-aware API. This compatibility + helper retains the public flat list for callers outside prompt assembly. + """ + prefix, workspace, trailing = self.system_prompt_parts() + return [*prefix, *workspace, *trailing] def compact_skill_categories(self) -> frozenset[str]: """Skill categories to demote to names-only in the prompt's skill index. @@ -644,6 +660,19 @@ def coding_system_blocks( ).system_blocks() +def coding_system_prompt_parts( + *, + platform: Optional[str] = None, + cwd: Optional[str | Path] = None, + config: Optional[dict[str, Any]] = None, + model: Optional[str] = None, +) -> tuple[list[str], list[str], list[str]]: + """Return coding prefix, workspace snapshot, and trailing guidance.""" + return resolve_runtime_mode( + platform=platform, cwd=cwd, config=config, model=model + ).system_prompt_parts() + + def coding_compact_skill_categories( *, platform: Optional[str] = None, diff --git a/agent/context_breakdown.py b/agent/context_breakdown.py index 0e2eb772f2ff..4527c5dca220 100644 --- a/agent/context_breakdown.py +++ b/agent/context_breakdown.py @@ -154,3 +154,207 @@ def compute_session_context_breakdown( "estimated_total": estimated_total, "model": getattr(agent, "model", "") or "", } + + +# ── /context rendering (CLI + gateway) ────────────────────────────────────── +# +# Pure text renderers over the payload above. The CLI shows a glyph block-grid +# plus a category table; the gateway uses the same table without the grid +# (proportional monospace is not guaranteed on messaging platforms). + +_CATEGORY_GLYPHS = { + "system_prompt": "■", + "tool_definitions": "▣", + "rules": "▩", + "skills": "▤", + "mcp": "▥", + "subagent_definitions": "▦", + "memory": "▧", + "conversation": "▨", +} +_FREE_GLYPH = "·" +_GRID_COLUMNS = 20 +_GRID_ROWS = 5 # 100 cells → 1 cell per percent of the context window + +# Human-readable tables cap the expanded listings; nothing is dropped from +# the underlying data. +_DETAILS_TABLE_LIMIT = 15 + + +def _bytes_to_tokens(size: Optional[int]) -> Optional[int]: + if size is None: + return None + return (int(size) + 3) // 4 + + +def compute_context_details(agent: Any) -> Dict[str, Any]: + """Expanded per-skill / per-toolset cost listing for ``/context all``. + + Reuses the ``hermes prompt-size`` attribution mechanism (PR #66656): + per-skill index-line bytes parsed from the live ```` + block, and per-toolset schema bytes attributed via the tool registry's + canonical tool→toolset map. Byte figures are converted to the same + chars/4 token heuristic the categories above use. + """ + from hermes_cli.prompt_size import ( + _compute_skills_breakdown, + _compute_toolsets_breakdown, + ) + from agent.system_prompt import build_system_prompt_parts + + parts = build_system_prompt_parts(agent) + stable = parts.get("stable", "") or "" + skills_match = _SKILLS_BLOCK_RE.search(stable) + skills_block = skills_match.group(0) if skills_match else "" + + skills: List[Dict[str, Any]] = [] + if skills_block: + for entry in _compute_skills_breakdown(skills_block): + skills.append({ + "name": entry.get("name", ""), + "index_tokens": _bytes_to_tokens(entry.get("index_line_bytes")) or 0, + "skill_md_tokens": _bytes_to_tokens(entry.get("skill_md_bytes")), + }) + + toolsets: List[Dict[str, Any]] = [] + tools = list(getattr(agent, "tools", None) or []) + if tools: + for group in _compute_toolsets_breakdown(tools): + toolsets.append({ + "toolset": group.get("toolset", ""), + "tool_count": int(group.get("tool_count", 0) or 0), + "schema_tokens": _bytes_to_tokens(group.get("json_bytes")) or 0, + }) + + return {"skills": skills, "toolsets": toolsets} + + +def render_context_grid(payload: Dict[str, Any]) -> List[str]: + """Render the payload as a Claude Code-style glyph block grid. + + 100 cells (5×20), each one percent of the model context window. Categories + fill in declaration order; the remainder renders as free space. + """ + context_max = int(payload.get("context_max") or 0) + categories = payload.get("categories") or [] + total_cells = _GRID_COLUMNS * _GRID_ROWS + + cells: List[str] = [] + if context_max > 0: + for cat in categories: + tokens = int(cat.get("tokens") or 0) + n = round(tokens / context_max * total_cells) + if tokens > 0 and n == 0: + n = 1 # never render a nonzero category as invisible + glyph = _CATEGORY_GLYPHS.get(str(cat.get("id") or ""), "▪") + cells.extend([glyph] * n) + cells = cells[:total_cells] + cells.extend([_FREE_GLYPH] * (total_cells - len(cells))) + + return [ + " ".join(cells[row * _GRID_COLUMNS:(row + 1) * _GRID_COLUMNS]) + for row in range(_GRID_ROWS) + ] + + +def render_context_category_lines(payload: Dict[str, Any]) -> List[str]: + """Render the 'Estimated usage by category' table as plain-text lines.""" + categories = payload.get("categories") or [] + context_max = int(payload.get("context_max") or 0) + estimated_total = int(payload.get("estimated_total") or 0) + denom = context_max or estimated_total + + lines = ["Estimated usage by category"] + if not categories: + lines.append(" (no data yet — send a message first)") + return lines + + width = max(len(str(cat.get("label") or "")) for cat in categories) + width = max(width, len("Free space")) + for cat in categories: + tokens = int(cat.get("tokens") or 0) + glyph = _CATEGORY_GLYPHS.get(str(cat.get("id") or ""), "▪") + pct = tokens / denom * 100 if denom else 0.0 + label = str(cat.get("label") or cat.get("id") or "") + lines.append(f"{glyph} {label:<{width}} {tokens:>9,} tokens {pct:>5.1f}%") + if context_max > 0: + free = max(0, context_max - estimated_total) + pct = free / context_max * 100 + lines.append(f"{_FREE_GLYPH} {'Free space':<{width}} {free:>9,} tokens {pct:>5.1f}%") + return lines + + +def render_context_details_lines(details: Dict[str, Any]) -> List[str]: + """Render the expanded ``/context all`` per-skill / per-toolset tables.""" + lines: List[str] = [] + + toolsets = details.get("toolsets") or [] + if toolsets: + lines.append("Toolsets by schema cost (largest first)") + for group in toolsets[:_DETAILS_TABLE_LIMIT]: + lines.append( + f" {group['toolset']:<24} {group['tool_count']:>3} tools" + f" {group['schema_tokens']:>8,} tokens" + ) + remaining = len(toolsets) - _DETAILS_TABLE_LIMIT + if remaining > 0: + lines.append(f" … and {remaining} more") + + skills = details.get("skills") or [] + if skills: + if lines: + lines.append("") + lines.append("Skills by cost (index = always-on; SKILL.md = cost when loaded)") + for entry in skills[:_DETAILS_TABLE_LIMIT]: + name = str(entry.get("name") or "") + if len(name) > 28: + name = name[:27] + "…" + md = entry.get("skill_md_tokens") + md_str = f"{md:>8,}" if md is not None else f"{'n/a':>8}" + lines.append( + f" {name:<28} index {entry['index_tokens']:>6,}" + f" SKILL.md {md_str} tokens" + ) + remaining = len(skills) - _DETAILS_TABLE_LIMIT + if remaining > 0: + lines.append(f" … and {remaining} more") + + return lines + + +def render_context_breakdown_lines( + payload: Dict[str, Any], + *, + details: Optional[Dict[str, Any]] = None, + grid: bool = True, +) -> List[str]: + """Render the full /context view as plain-text lines. + + ``grid=True`` (CLI) prepends the glyph block grid; the gateway passes + ``grid=False`` and keeps its own gauge. ``details`` (from + :func:`compute_context_details`) appends the expanded listings. + """ + lines: List[str] = [] + if grid: + lines.extend(render_context_grid(payload)) + lines.append("") + lines.extend(render_context_category_lines(payload)) + + context_max = int(payload.get("context_max") or 0) + context_used = int(payload.get("context_used") or 0) + if context_max > 0: + pct = int(payload.get("context_percent") or 0) + lines.append("") + lines.append( + f"Context window: {context_used:,} / {context_max:,} tokens ({pct}%)" + ) + + if details is not None: + detail_lines = render_context_details_lines(details) + if detail_lines: + lines.append("") + lines.extend(detail_lines) + else: + lines.append("") + lines.append("Use /context all for per-skill and per-toolset costs.") + return lines diff --git a/agent/context_compressor.py b/agent/context_compressor.py index 9eaee872e353..4837925ce624 100644 --- a/agent/context_compressor.py +++ b/agent/context_compressor.py @@ -90,9 +90,6 @@ def _is_summary_access_or_quota_error(exc: Exception) -> bool: HISTORICAL_TASK_HEADING = "## Historical Task Snapshot" -HISTORICAL_IN_PROGRESS_HEADING = "## Historical In-Progress State" -HISTORICAL_PENDING_ASKS_HEADING = "## Historical Pending User Asks" -HISTORICAL_REMAINING_WORK_HEADING = "## Historical Remaining Work" SUMMARY_PREFIX = ( @@ -107,9 +104,7 @@ SUMMARY_PREFIX = ( "Topic overlap with the summary does NOT mean you should resume its " "task: even on similar topics, the latest user message WINS. Treat ONLY " "the latest message as the active task and discard stale items from " - f"'{HISTORICAL_TASK_HEADING}' / '{HISTORICAL_IN_PROGRESS_HEADING}' / " - f"'{HISTORICAL_PENDING_ASKS_HEADING}' / " - f"'{HISTORICAL_REMAINING_WORK_HEADING}' entirely — do not 'wrap up' or " + f"'{HISTORICAL_TASK_HEADING}' entirely — do not 'wrap up' or " "'finish' work described there unless the latest message explicitly " "asks for it. " "Reverse signals in the latest message (e.g. 'stop', 'undo', 'roll " @@ -219,8 +214,45 @@ _MERGED_SUMMARY_DELIMITER = "[END OF PRIOR CONTEXT — COMPACTION SUMMARY BELOW] # stale directive it carried (e.g. "resume exactly from Active Task") survives # embedded in the body and keeps hijacking replies. Keep newest-first; entries # are matched literally. Add a frozen copy here whenever SUMMARY_PREFIX changes. +# NEVER mutate or reorder an existing entry — each one is the exact wire text a +# shipped build persisted, so editing it silently un-normalizes every summary +# written by that build generation; prepend only. tests/agent/ +# test_summary_prefix_semantics.py byte-pins every entry to enforce this. _HISTORICAL_SUMMARY_PREFIXES = ( - # Jul 2026 (#65848 class): identical to the current prefix except it + # Pre-#69619: identical to the current prefix except the stale-item + # discard clause named all four historical headings (the three + # section headers removed by #69619 were still in the template). + # Summaries persisted by builds immediately before #69619 carry this + # exact text and must remain detectable/strippable on resume. + "[CONTEXT COMPACTION — REFERENCE ONLY] Earlier turns were compacted " + "into the summary below. This is a handoff from a previous context " + "window — treat it as background reference, NOT as active instructions. " + "Do NOT answer questions or fulfill requests mentioned in this summary; " + "they were already addressed. " + "Respond ONLY to the latest user message that appears AFTER this " + "summary — that message is the single source of truth for what to do " + "right now. " + "Topic overlap with the summary does NOT mean you should resume its " + "task: even on similar topics, the latest user message WINS. Treat ONLY " + "the latest message as the active task and discard stale items from " + "'## Historical Task Snapshot' / '## Historical In-Progress State' / " + "'## Historical Pending User Asks' / " + "'## Historical Remaining Work' entirely — do not 'wrap up' or " + "'finish' work described there unless the latest message explicitly " + "asks for it. " + "Reverse signals in the latest message (e.g. 'stop', 'undo', 'roll " + "back', 'just verify', 'don't do that anymore', 'never mind', a new " + "topic) must immediately end any in-flight work described in the " + "summary; do not re-surface it in later turns. " + "IMPORTANT: Your persistent memory (MEMORY.md, USER.md) in the system " + "prompt is ALWAYS authoritative and active — never ignore or deprioritize " + "memory content due to this compaction note. " + "None of the above restricts HOW you work: your tools remain fully " + "active — keep calling them normally for the active task (edit files, " + "run commands, search) instead of merely narrating what you would do. " + "The current session state (files, config, etc.) may reflect work " + "described here — avoid repeating it:", + # Jul 2026 (#65848 class): identical to the pre-#69619 prefix except it # lacked the explicit "tools remain fully active" clause — the strong # REFERENCE ONLY framing bled into general tool-use suppression # (observed: 7 consecutive narration-only turns immediately after a @@ -236,9 +268,9 @@ _HISTORICAL_SUMMARY_PREFIXES = ( "Topic overlap with the summary does NOT mean you should resume its " "task: even on similar topics, the latest user message WINS. Treat ONLY " "the latest message as the active task and discard stale items from " - f"'{HISTORICAL_TASK_HEADING}' / '{HISTORICAL_IN_PROGRESS_HEADING}' / " - f"'{HISTORICAL_PENDING_ASKS_HEADING}' / " - f"'{HISTORICAL_REMAINING_WORK_HEADING}' entirely — do not 'wrap up' or " + "'## Historical Task Snapshot' / '## Historical In-Progress State' / " + "'## Historical Pending User Asks' / " + "'## Historical Remaining Work' entirely — do not 'wrap up' or " "'finish' work described there unless the latest message explicitly " "asks for it. " "Reverse signals in the latest message (e.g. 'stop', 'undo', 'roll " @@ -303,9 +335,238 @@ _SUMMARY_RATIO = 0.20 # itself a context-pressure source and slows every compaction. _SUMMARY_TOKENS_CEILING = 10_000 +# Aggregate cap on the serialized turn block fed to the summarizer prompt +# (chars). Per-message truncation (_CONTENT_MAX / _TOOL_ARGS_MAX) alone is +# not enough: a compression window with hundreds of already-truncated turns +# can still produce a multi-hundred-KB prompt that blows past slow auxiliary +# backends' context limits or timeouts (Codex Responses fallback paths +# especially). 160K chars ≈ 40K tokens — comfortably inside every supported +# aux model's window while leaving room for the template + previous summary. +# Applied AFTER per-message truncation, with head+tail retention and an +# explicit omitted-middle marker (see _bound_summary_input). This is a +# prompt-side bound only — NEVER add a max_tokens wire cap on the summary +# call (see the no-wire-cap contract test in +# test_compression_small_ctx_threshold_floor.py). +_SUMMARY_INPUT_MAX_CHARS = 160_000 + # Placeholder used when pruning old tool results _PRUNED_TOOL_PLACEHOLDER = "[Old tool output cleared to save context space]" +# Ghost-skill defense (#32106): when compaction reduces an old ``skill_view`` +# result to a 1-line metadata summary, the model still believes the skill is +# loaded even though its instructions are gone. The marker below is the ONE +# canonical prune signal — ``_skill_pruned_marker()`` builds it and every +# presence check matches against the same string, so the emit side and the +# check side can never drift apart (the original PR #44166 emitted +# ``[SKILL_PRUNED:`` but presence-checked ``[SKILL_PRUNED]``, making +# re-injection fire even when the marker had survived). +SKILL_PRUNED_MARKER_PREFIX = "[SKILL_PRUNED:" +# skill_view results at or below this size stay verbatim in pruned +# summaries — small skills are cheap to keep and their loss is unlikely to +# ghost the model. Shared by the emit site and the summarizer-input scan. +_SKILL_VIEW_PRUNE_MIN_CHARS = 5000 +# Cap for the deterministic marker re-injection list — keeps a very long +# session from growing an unbounded "## Pruned Skills" block in every +# iterative summary update. Newest-referenced skills win. +_MAX_PRUNED_SKILL_MARKERS = 20 + + +def _skill_pruned_marker(skill_name: str) -> str: + """Return the canonical prune marker for *skill_name*. + + Used verbatim by BOTH the emit sites (tool-result summarization, + summary re-injection) and the survival check in + ``_reinject_pruned_skill_markers`` — one string, no drift. + """ + return ( + f"{SKILL_PRUNED_MARKER_PREFIX} content lost in compression; " + f"reload with skill_view(name='{skill_name}')]" + ) + + +# Matches the canonical marker and captures the skill name. Anchored on the +# shared prefix constant so a wording change to the marker body updates the +# emit helper and this extractor together. +_SKILL_PRUNED_MARKER_RE = re.compile( + re.escape(SKILL_PRUNED_MARKER_PREFIX) + + r"[^\]]*?reload with skill_view\(name='([^']+)'\)" +) + + +def _extract_pruned_skill_names(text: str) -> list[str]: + """Return skill names referenced by prune markers in *text*, in order.""" + names: list[str] = [] + for match in _SKILL_PRUNED_MARKER_RE.finditer(text or ""): + name = match.group(1) + if name not in names: + names.append(name) + return names + + +def _collect_ghosted_skill_names(turns: List[Dict[str, Any]]) -> list[str]: + """Skill names whose instructions are about to be lost in compaction. + + Covers BOTH shapes a compacted middle window can carry: + + - a ``skill_view`` result already demoted by Phase-1 pruning — the + canonical ``[SKILL_PRUNED: ...]`` marker is in the row content; + - a RAW ``skill_view`` body that was never demoted (it sat inside the + protected tail of an earlier prune, then aged into the compression + window). The summarizer will paraphrase the instructions away, which + is exactly the ghost-skill failure — so it needs a marker too. + """ + names: list[str] = [] + + def _add(name: str) -> None: + if name and name not in names: + names.append(name) + + call_id_to_skill: dict[str, str] = {} + for idx, skill in _skill_view_call_sites(turns): + msg = turns[idx] + for tc in msg.get("tool_calls") or []: + tc_fn = tc.get("function", {}) if isinstance(tc, dict) else getattr(tc, "function", None) + tc_name = tc_fn.get("name", "") if isinstance(tc_fn, dict) else getattr(tc_fn, "name", "") + if tc_name != "skill_view": + continue + cid = tc.get("id", "") if isinstance(tc, dict) else (getattr(tc, "id", "") or "") + if cid: + call_id_to_skill[cid] = skill + for msg in turns: + content = msg.get("content") + text = content if isinstance(content, str) else _content_text_for_contains(content) + for name in _extract_pruned_skill_names(text): + _add(name) + if ( + msg.get("role") == "tool" + and isinstance(content, str) + and len(content) > _SKILL_VIEW_PRUNE_MIN_CHARS + ): + skill = call_id_to_skill.get(str(msg.get("tool_call_id") or "")) + if skill: + _add(skill) + return names + + +_PRUNED_SKILLS_SECTION_HEADING = "## Pruned Skills" + + +def _reinject_pruned_skill_markers(summary: str, skill_names: list[str]) -> str: + """Deterministically restore prune markers the summarizer dropped. + + ``skill_names`` was extracted from the summarizer INPUT before the LLM + call. For every skill whose canonical marker (``_skill_pruned_marker``) + is absent from the model's output, append it under a ``## Pruned + Skills`` section. Presence is checked against the SAME canonical string + the emit sites produce — a paraphrased or renamed marker counts as + dropped and is restored (the original PR checked the literal + ``[SKILL_PRUNED]``, which never matches the emitted ``[SKILL_PRUNED:`` + form, so it duplicated markers that HAD survived). + + The appended block is plain body text: it never carries a handoff + prefix, the merged-summary delimiter, or a start-of-content scaffolding + marker, so ``classify_summary_content`` / todo-snapshot flag handling + are unaffected. The block is routed through ``_redact_compaction_text`` + like every other compaction-boundary text. + """ + if not skill_names: + return summary + missing = [ + name for name in skill_names + if _skill_pruned_marker(name) not in summary + ] + if not missing: + return summary + lines = [_skill_pruned_marker(name) for name in missing] + block = ( + "\n\n" + _PRUNED_SKILLS_SECTION_HEADING + "\n" + + "\n".join(lines) + + "\n(The listed skills' instructions were pruned during context " + "compression. Reload with the skill_view call in each marker before " + "relying on that skill; one reload per skill is enough — ignore any " + "older markers for the same skill.)" + ) + return summary + _redact_compaction_text(block) + + +# A skill_view call within this many trailing messages counts as "just +# loaded": its full instruction body must survive the Phase-1 prune even when +# the token-budget boundary would otherwise demote it (#32106). Distinct from +# the protected-tail boundary, which is token-based and can land immediately +# after a bulky just-loaded skill body. +_SKILL_PRUNE_RECENT_WINDOW = 10 + + +def _skill_view_call_sites( + messages: List[Dict[str, Any]], +) -> list[tuple[int, str]]: + """Yield ``(message_index, skill_name)`` for every skill_view tool call.""" + sites: list[tuple[int, str]] = [] + for i, msg in enumerate(messages): + if msg.get("role") != "assistant": + continue + for tc in msg.get("tool_calls") or []: + if isinstance(tc, dict): + fn = tc.get("function", {}) + name = fn.get("name", "") if isinstance(fn, dict) else "" + args_str = fn.get("arguments", "") if isinstance(fn, dict) else "" + else: + fn = getattr(tc, "function", None) + name = getattr(fn, "name", "") if fn else "" + args_str = getattr(fn, "arguments", "") if fn else "" + if name != "skill_view" or not isinstance(args_str, str) or not args_str: + continue + try: + args = json.loads(args_str) + except (json.JSONDecodeError, TypeError): + continue + if isinstance(args, dict): + skill = args.get("name", "") + if isinstance(skill, str) and skill: + sites.append((i, skill)) + return sites + + +def _collect_protected_skill_names( + messages: List[Dict[str, Any]], prune_boundary: int, +) -> set[str]: + """Skill names whose skill_view bodies must survive Phase-1 demotion. + + A skill is protected (lower-cased set) when any of these hold: + + - its most recent ``skill_view`` call sits within the last + ``_SKILL_PRUNE_RECENT_WINDOW`` messages (just loaded / just reloaded); + - its most recent ``skill_view`` call sits inside the protected tail + (at or after *prune_boundary*); + - its name is mentioned in a user message inside the protected tail + (the user is actively steering work that depends on it). + + Protection applies to the ordinary Phase-1/2 prune only. The Pass-4 + pressure demotion deliberately ignores it: when the protected region + itself exceeds the soft budget, exempting skill bodies would recreate + the #61932 dead-end shape. + """ + total = len(messages) + if not total: + return set() + recent_start = max(0, total - _SKILL_PRUNE_RECENT_WINDOW) + tail_start = max(0, prune_boundary) + tail_user_texts: list[str] = [] + for msg in messages[tail_start:]: + if msg.get("role") != "user": + continue + content = msg.get("content") + if isinstance(content, str) and content: + tail_user_texts.append(content.lower()) + protected: set[str] = set() + for idx, skill in _skill_view_call_sites(messages): + key = skill.lower() + if idx >= recent_start or idx >= tail_start: + protected.add(key) + elif any(key in text for text in tail_user_texts): + protected.add(key) + return protected + # Chars per token rough estimate _CHARS_PER_TOKEN = 4 # Flat token cost per attached image part. Real cost varies by provider and @@ -335,6 +596,11 @@ _ACTIVE_TASK_MAX_CHARS = 1400 # high for small/light tails, but using all 20 as a hard floor here would bring # back the old large-tool-output case where nothing can be compacted. _MAX_TAIL_MESSAGE_FLOOR = 8 +# Under context pressure (protected-tail tool bodies alone exceed the soft +# tail budget), demote large completed tool/file outputs even inside the +# protected region — but always keep this many trailing messages verbatim so +# the active user ask / latest tool pair remain readable. Issue #61932. +_PRESSURE_KEEP_RECENT_MESSAGES = 3 # Models with context windows below this get their compression threshold # floored at ``_SMALL_CTX_THRESHOLD_PERCENT`` (raise-only — an explicitly @@ -872,7 +1138,19 @@ def _summarize_tool_result_unguarded(tool_name: str, tool_args: str, tool_conten code_preview += "..." return f"[execute_code] `{code_preview}` ({line_count} lines output)" - if tool_name in {"skill_view", "skills_list", "skill_manage"}: + if tool_name == "skill_view": + name = args.get("name", "?") + if content_len > _SKILL_VIEW_PRUNE_MIN_CHARS: + # Ghost-skill defense (#32106): a metadata-only summary makes the + # model believe the skill is still loaded. The canonical marker + # tells it the instructions are gone AND how to get them back. + return ( + f"[skill_view] name={name} ({content_len:,} chars) " + + _skill_pruned_marker(str(name)) + ) + return f"[skill_view] name={name} ({content_len:,} chars)" + + if tool_name in {"skills_list", "skill_manage"}: name = args.get("name", "?") return f"[{tool_name}] name={name} ({content_len:,} chars)" @@ -967,6 +1245,7 @@ class ContextCompressor(ContextEngine): self._last_aux_model_failure_model = None self._last_compression_savings_pct = 100.0 self._ineffective_compression_count = 0 + self._anti_thrash_recovery_deadline = 0.0 self._fallback_compression_streak = 0 self._verify_compaction_cleared_threshold = False self._last_compression_made_progress = False @@ -1075,6 +1354,125 @@ class ContextCompressor(ContextEngine): previous = telemetry.get("aux_call_duration_ms") or 0 telemetry["aux_call_duration_ms"] = previous + max(0, int(duration_ms)) + def _emit_init_summary_once(self) -> None: + """Emit the informative startup line once, on first resolution. + + Deferred out of ``__init__`` (#32221): the line reports resolved token + budgets, so emitting it there would force the synchronous + ``get_model_context_length()`` probe during construction. Reads via + the properties below are safe here because + ``_resolved_context_length`` is already set. + """ + if not getattr(self, "_log_init_summary", False): + return + self._log_init_summary = False + logger.info( + "Context compressor initialized: model=%s context_length=%d " + "threshold=%d (%.0f%%) target_ratio=%.0f%% tail_budget=%d " + "provider=%s base_url=%s", + self.model, self._resolved_context_length, self.threshold_tokens, + self.threshold_percent * 100, self.summary_target_ratio * 100, + self.tail_token_budget, + self.provider or "none", self.base_url or "none", + ) + + def _resolve_context_length(self) -> int: + """Resolve and cache the model's context length on first access.""" + if self._resolved_context_length is None: + self._resolved_context_length = get_model_context_length( + self.model, + base_url=self.base_url, + api_key=self.api_key, + config_context_length=self._config_context_length, + provider=self.provider, + ) + # Small-context threshold floor: models under 512K trigger at + # >=75% so compaction doesn't fire with half the window still + # free. Raise-only; must run AFTER context_length is resolved + # and BEFORE threshold_tokens is derived (deferred here from + # __init__ along with the resolution itself, #32221). + # _base_threshold_percent already has the per-model override + # applied, so the floor stacks on top of it. + self.threshold_percent = self._effective_threshold_percent( + self._resolved_context_length, self._base_threshold_percent, + ) + self._emit_init_summary_once() + return self._resolved_context_length + + @property + def context_length(self) -> int: + return self._resolve_context_length() + + @context_length.setter + def context_length(self, value: int) -> None: + # No-op guard: repeated assignment of the SAME window (e.g. the codex + # app-server usage callback re-reports the window on every response) + # must not invalidate the derived budgets — that would wipe runtime + # corrections applied directly to threshold_tokens/tail_token_budget + # (see conversation_compression's aux-context threshold sync), which + # persisted on main's eager-init behavior. + if value == getattr(self, "_resolved_context_length", None): + return + self._resolved_context_length = value + # Re-apply the small-context floor (raise-only) for the genuinely new + # window so the invalidated budgets below recompute coherently — + # percent and tokens must derive from the same window. Skipped on + # bare test instances built via object.__new__ that never ran + # __init__ (no _base_threshold_percent). + _base = getattr(self, "_base_threshold_percent", None) + if _base is not None: + self.threshold_percent = self._effective_threshold_percent( + value, _base, + ) + self._threshold_tokens = None + self._tail_token_budget = None + self._max_summary_tokens = None + self._emit_init_summary_once() + + @property + def threshold_tokens(self) -> int: + if self._threshold_tokens is None: + # Resolve the window FIRST (may apply the small-context floor to + # threshold_percent as a side effect) so the percent read below + # is the floored value regardless of argument evaluation order. + _ctx = self.context_length + # Floor: never compress below MINIMUM_CONTEXT_LENGTH tokens even + # if the percentage would suggest a lower value (#14690 handles + # the degenerate small-window case inside the helper). + self._threshold_tokens = self._compute_threshold_tokens( + _ctx, self.threshold_percent, self.max_tokens, + ) + # Apply absolute token cap (compression.threshold_tokens) — + # takes the lower of the ratio-based threshold and the cap. + self._apply_threshold_tokens_cap() + return self._threshold_tokens + + @threshold_tokens.setter + def threshold_tokens(self, value: int) -> None: + self._threshold_tokens = value + + @property + def tail_token_budget(self) -> int: + if self._tail_token_budget is None: + self._tail_token_budget = int(self.threshold_tokens * self.summary_target_ratio) + return self._tail_token_budget + + @tail_token_budget.setter + def tail_token_budget(self, value: int) -> None: + self._tail_token_budget = value + + @property + def max_summary_tokens(self) -> int: + if self._max_summary_tokens is None: + self._max_summary_tokens = min( + int(self.context_length * 0.05), _SUMMARY_TOKENS_CEILING, + ) + return self._max_summary_tokens + + @max_summary_tokens.setter + def max_summary_tokens(self, value: int) -> None: + self._max_summary_tokens = value + def on_session_end(self, session_id: str, messages: List[Dict[str, Any]]) -> None: """Clear all per-session compaction state at a real session boundary. @@ -1104,6 +1502,7 @@ class ContextCompressor(ContextEngine): self._last_aux_model_failure_model = None self._last_compression_savings_pct = 100.0 self._ineffective_compression_count = 0 + self._anti_thrash_recovery_deadline = 0.0 self._fallback_compression_streak = 0 self._verify_compaction_cleared_threshold = False self._last_compression_made_progress = False @@ -1129,8 +1528,11 @@ class ContextCompressor(ContextEngine): self._last_summary_error = None self._consecutive_timeout_failures = 0 self._fallback_compression_streak = 0 + self._ineffective_compression_count = 0 + self._anti_thrash_recovery_deadline = 0.0 self.get_active_compression_failure_cooldown() self._load_fallback_compression_streak() + self._load_ineffective_compression_count() def on_session_start(self, session_id: str, **kwargs) -> None: """Bind session-scoped compression state for a new or resumed session.""" @@ -1139,6 +1541,7 @@ class ContextCompressor(ContextEngine): old_session_id = kwargs.get("old_session_id") session_db = kwargs.get("session_db", getattr(self, "_session_db", None)) previous_fallback_streak = self._fallback_compression_streak + previous_ineffective_count = self._ineffective_compression_count if boundary_reason == "compression" and old_session_id: getter = getattr(session_db, "get_compression_fallback_streak", None) if callable(getter): @@ -1153,12 +1556,37 @@ class ContextCompressor(ContextEngine): "compression parent fallback streak lookup failed (non-sqlite): %s", exc, ) + count_getter = getattr( + session_db, "get_compression_ineffective_count", None, + ) + if callable(count_getter): + try: + stored_count = count_getter(old_session_id) + if isinstance(stored_count, (int, float, str)): + previous_ineffective_count = max(0, int(stored_count)) + except (TypeError, ValueError, sqlite3.Error) as exc: + logger.debug( + "compression parent ineffective count lookup failed: %s", exc, + ) + except Exception as exc: + logger.debug( + "compression parent ineffective count lookup failed (non-sqlite): %s", + exc, + ) self.bind_session_state(session_db, session_id) if boundary_reason == "compression": # Rotation creates a fresh child row before this callback. Preserve # the logical conversation's streak until boundary bookkeeping # persists the updated value onto the child row. self._fallback_compression_streak = previous_fallback_streak + # Same for the anti-thrash strike counter — but unlike the streak, + # no later boundary bookkeeping writes it, so persist the carried + # value onto the (fresh) child row now. Otherwise a restart between + # rotation and the next real-usage verdict would silently disarm + # an armed guard (#54923). + if self._ineffective_compression_count != previous_ineffective_count: + self._ineffective_compression_count = previous_ineffective_count + self._persist_ineffective_compression_count() def _load_fallback_compression_streak(self) -> None: session_db = getattr(self, "_session_db", None) @@ -1192,6 +1620,59 @@ class ContextCompressor(ContextEngine): except Exception as exc: logger.debug("compression fallback streak persist failed (non-sqlite): %s", exc) + def _load_ineffective_compression_count(self) -> None: + """Load the durable anti-thrash strike count for the bound session. + + A fresh compressor on a resumed session starts with + ``compression_count == 0`` and, historically, an in-memory-only + ineffective counter — so a guard armed (1 strike) or tripped + (2 strikes) before a process restart silently disarmed, and a + near-threshold session could re-compact once per restart forever + (#54923). The counter now round-trips through the session row like + the failure cooldown and the fallback streak. + """ + session_db = getattr(self, "_session_db", None) + session_id = getattr(self, "_session_id", "") + getter = getattr(session_db, "get_compression_ineffective_count", None) + if not session_id or not callable(getter): + return + try: + stored_count = getter(session_id) + self._ineffective_compression_count = max( + 0, + int(stored_count) + if isinstance(stored_count, (int, float, str)) + else 0, + ) + except (TypeError, ValueError, sqlite3.Error) as exc: + logger.debug("compression ineffective count lookup failed: %s", exc) + except Exception as exc: + logger.debug("compression ineffective count lookup failed (non-sqlite): %s", exc) + + def _persist_ineffective_compression_count(self) -> None: + session_db = getattr(self, "_session_db", None) + session_id = getattr(self, "_session_id", "") + setter = getattr(session_db, "set_compression_ineffective_count", None) + if not session_id or not callable(setter): + return + try: + setter(session_id, self._ineffective_compression_count) + except sqlite3.Error as exc: + logger.debug("compression ineffective count persist failed: %s", exc) + except Exception as exc: + logger.debug("compression ineffective count persist failed (non-sqlite): %s", exc) + + def _record_ineffective_compression_verdict(self, count: int) -> None: + """Set the anti-thrash strike counter, keeping the durable copy in sync. + + Persists only on change so the reset issued by every ordinary fitting + response (already-zero -> zero) never costs a DB write. + """ + if count == self._ineffective_compression_count: + return + self._ineffective_compression_count = count + self._persist_ineffective_compression_count() + def record_completed_compaction(self, *, used_fallback: bool = False) -> None: """Record one completed boundary and its summary quality.""" self._verify_compaction_cleared_threshold = True @@ -1400,7 +1881,10 @@ class ContextCompressor(ContextEngine): self.last_rough_tokens_when_real_prompt_fit = 0 self.last_compression_rough_tokens = 0 self.awaiting_real_usage_after_compression = False - self._ineffective_compression_count = 0 + # Strikes were judged against the PREVIOUS threshold; a recomputed + # trigger invalidates them. Keep the durable copy in sync so a + # restart doesn't resurrect strikes this recalibration just voided. + self._record_ineffective_compression_verdict(0) if runtime_changed: self._fallback_compression_streak = 0 self._persist_fallback_compression_streak() @@ -1417,6 +1901,15 @@ class ContextCompressor(ContextEngine): # rationale as the gpt-5.5/Codex 85% autoraise. _MIN_CTX_TRIGGER_RATIO = 0.85 + # Anti-thrash recovery window (#14694): once the ineffective/fallback + # breaker trips, automatic compaction stays blocked for this long, then + # ONE probe attempt is allowed (counters drop to 1 strike, so another + # ineffective pass re-trips immediately). Long enough that a genuinely + # incompressible session isn't compacting in a loop; short enough that a + # session which has since grown real compressible material recovers well + # before it rides into the provider's hard context limit. + _ANTI_THRASH_RECOVERY_SECONDS = 300.0 + @staticmethod def _coerce_max_tokens(value: Any) -> int | None: """Normalize a max_tokens value to a positive int or None. @@ -1540,6 +2033,10 @@ class ContextCompressor(ContextEngine): max_tokens: int | None = None, model_thresholds: dict[str, float] | None = None, threshold_tokens_cap: Any = None, + proactive_prune_tokens: int = 0, + proactive_prune_min_result_chars: int = 8000, + proactive_prune_min_reclaim_tokens: int = 4096, + min_tail_user_messages: int = 1, ): self.model = model self.base_url = base_url @@ -1569,6 +2066,32 @@ class ContextCompressor(ContextEngine): ) self.protect_first_n = protect_first_n self.protect_last_n = protect_last_n + # Proactive tool-result pruning (cost-oriented; runs INDEPENDENTLY of the + # full-compression trigger, via prune_tool_results_only()). 0 = disabled. + self.proactive_prune_tokens = int(proactive_prune_tokens or 0) + # Floor the summarize threshold at 200 chars (matching + # _prune_old_tool_results' dedup floor). Below ~200 a generated summary + # can be longer than the floor it replaces, so Pass 2 would re-summarize + # its own output every turn (corrupting it and never converging); a + # negative value would strip every non-tail tool result outright. A + # configured 0 keeps the 8000 default via `or`. Keep the floor well above + # typical summary length (default 8000) to stay idempotent. + self.proactive_prune_min_result_chars = max( + 200, int(proactive_prune_min_result_chars or 8000) + ) + # Minimum estimated token reclaim before a proactive prune COMMITS. + # Every commit rewrites messages the provider has already seen, which + # invalidates the prompt-cache prefix from the earliest rewritten + # message forward. Without this gate a busy tool loop would re-fire + # the prune nearly every iteration (each new tool pair ages an old one + # out of the protected tail), breaking the cache per turn. Requiring a + # meaningful batch of reclaimable tokens makes fires episodic and + # amortized — the same way full compression is the one sanctioned + # cache break. 0 disables the gate (commit any non-zero prune). + self.proactive_prune_min_reclaim_tokens = max( + 0, int(proactive_prune_min_reclaim_tokens or 0) + ) + self.min_tail_user_messages = min_tail_user_messages self.summary_target_ratio = max(0.10, min(summary_target_ratio, 0.80)) self.quiet_mode = quiet_mode # Output-token reservation: the provider carves max_tokens out of the @@ -1584,56 +2107,30 @@ class ContextCompressor(ContextEngine): # deterministic "summary unavailable" handoff and drop the middle window. self.abort_on_summary_failure = abort_on_summary_failure - self.context_length = get_model_context_length( - model, base_url=base_url, api_key=api_key, - config_context_length=config_context_length, - provider=provider, - ) - # Small-context threshold floor: models under 512K trigger at >=75% - # so compaction doesn't fire with half the window still free (the - # incompressible floor makes 50%-triggered compaction thrash on - # 128K-262K models). Raise-only; must run AFTER context_length is - # resolved and BEFORE threshold_tokens is derived. The pre-floor - # value is kept so update_model() can re-derive for a new window - # (switching small -> large must drop back to the configured value). - # Note: _base_threshold_percent already has the per-model override - # applied, so the floor stacks on top of any model-specific threshold. + # Defer context-length resolution to first access (#32221): + # get_model_context_length() can issue a synchronous /models HTTP + # probe, which must not block AIAgent construction. The small-context + # threshold floor and the absolute threshold cap both need the + # resolved window, so they are applied on first resolution (see + # _resolve_context_length / the threshold_tokens property) instead + # of here. update_model() re-derives the floor for a new window from + # _config_threshold_percent (the raw config value snapshotted above), + # so switching small -> large correctly drops back to the configured + # value. + self._config_context_length = config_context_length self._configured_threshold_percent = self.threshold_percent - self.threshold_percent = self._effective_threshold_percent( - self.context_length, self._base_threshold_percent, - ) - threshold_percent = self.threshold_percent - # Floor: never compress below MINIMUM_CONTEXT_LENGTH tokens even if - # the percentage would suggest a lower value. This prevents premature - # compression on large-context models at 50% while keeping the % sane - # for models right at the minimum. _compute_threshold_tokens also - # guards the degenerate case where the floor would equal/exceed the - # window (small models), so auto-compression can still fire (#14690). - self.threshold_tokens = self._compute_threshold_tokens( - self.context_length, threshold_percent, self.max_tokens, - ) - # Apply absolute token cap (compression.threshold_tokens) — takes - # the lower of the ratio-based threshold and the cap. - self._apply_threshold_tokens_cap() + self._resolved_context_length: int | None = None + self._threshold_tokens: int | None = None + self._tail_token_budget: int | None = None + self._max_summary_tokens: int | None = None self.compression_count = 0 - # Derive token budgets: ratio is relative to the threshold, not total context - target_tokens = int(self.threshold_tokens * self.summary_target_ratio) - self.tail_token_budget = target_tokens - self.max_summary_tokens = min( - int(self.context_length * 0.05), _SUMMARY_TOKENS_CEILING, - ) - - if not quiet_mode: - logger.info( - "Context compressor initialized: model=%s context_length=%d " - "threshold=%d (%.0f%%) target_ratio=%.0f%% tail_budget=%d " - "provider=%s base_url=%s", - model, self.context_length, self.threshold_tokens, - threshold_percent * 100, self.summary_target_ratio * 100, - self.tail_token_budget, - provider or "none", base_url or "none", - ) + # The "initialized" log reports resolved token budgets, which would + # force the deferred get_model_context_length() probe to run inside + # __init__ and re-introduce the exact synchronous blocking this change + # removes (#32221). Emit it on first context-length resolution instead + # so construction stays non-blocking on every path (not just quiet). + self._log_init_summary = not quiet_mode self._context_probed = False # True after a step-down from context error self.last_prompt_tokens = 0 @@ -1656,6 +2153,12 @@ class ContextCompressor(ContextEngine): # Anti-thrashing: track whether last compression was effective self._last_compression_savings_pct: float = 100.0 self._ineffective_compression_count: int = 0 + # Monotonic deadline after which a tripped anti-thrash guard grants + # one probation probe (#14694). 0.0 = clock not armed. Armed lazily on + # the first blocked evaluation; deliberately NOT durable, so a process + # restart with a persisted tripped counter (#69872) waits a full fresh + # window before probing (#54923: restart must never disarm a guard). + self._anti_thrash_recovery_deadline: float = 0.0 # Consecutive completed deterministic-fallback boundaries. Unlike the # real-usage effectiveness counter, ordinary fitting responses must not # reset this breaker; only a healthy completed summary does. @@ -1724,7 +2227,7 @@ class ContextCompressor(ContextEngine): # when this response was not immediately after compaction. The # independent fallback streak is boundary-scoped and survives # ordinary fitting responses during context regrowth. - self._ineffective_compression_count = 0 + self._record_ineffective_compression_verdict(0) else: self.last_rough_tokens_when_real_prompt_fit = 0 @@ -1746,7 +2249,9 @@ class ContextCompressor(ContextEngine): # per compaction. if self._verify_compaction_cleared_threshold: if self.last_prompt_tokens >= self.threshold_tokens: - self._ineffective_compression_count += 1 + self._record_ineffective_compression_verdict( + self._ineffective_compression_count + 1, + ) if not self.quiet_mode: logger.warning( "Compaction did not clear the threshold: %d real " @@ -1758,13 +2263,23 @@ class ContextCompressor(ContextEngine): self._ineffective_compression_count, ) else: - self._ineffective_compression_count = 0 + self._record_ineffective_compression_verdict(0) # Consume the pending-verification flag once real usage arrives, whether # or not prompt_tokens was reported, so a usage-less response can't leave # it armed for a later, unrelated reading. self._verify_compaction_cleared_threshold = False self.awaiting_real_usage_after_compression = False + def snapshot_preflight_display_tokens(self) -> int: + """Capture the display token count before a speculative preflight seed.""" + return self.last_prompt_tokens + + def rollback_interrupted_preflight_display_tokens(self, snapshot: int) -> None: + """Restore a speculative display seed without touching compaction state.""" + if self.awaiting_real_usage_after_compression and self.last_prompt_tokens == -1: + return + self.last_prompt_tokens = snapshot + def should_defer_preflight_to_real_usage(self, rough_tokens: int) -> bool: """Return True when a high rough preflight estimate is known-noisy. @@ -1810,23 +2325,83 @@ class ContextCompressor(ContextEngine): def should_compress(self, prompt_tokens: int = None) -> bool: """Check if context exceeds the compression threshold. + Returns ``True`` when compression should run now. For the caller-facing + *reason* (e.g. why compression is skipped while still over threshold), + see :meth:`should_compress_info`, which returns a ``(bool, reason)`` + tuple without changing the decision logic here. + + Includes anti-thrashing protection: if the last two compressions + each saved less than 10%, skip compression to avoid infinite loops + where each pass removes only 1-2 messages. + """ + decision, _reason = self.should_compress_info(prompt_tokens) + return decision + + def should_compress_info( + self, prompt_tokens: int = None + ) -> "tuple[bool, str | None]": + """Check if context exceeds the compression threshold. + + Returns a ``(should_compress, reason)`` tuple instead of a bare bool so + callers can tell *why* compression is skipped when it is skipped while + the context is already over threshold. ``reason`` is ``None`` unless + compression is needed but blocked: + + * ``"cooldown:"`` — the summary LLM is recovering from a + recent 429/transient failure; compression is deferred to avoid the + freeze loop described in #11529. + * ``"ineffective"`` — anti-thrashing has backed off because the last + two compressions each saved <10%. + + When ``reason`` is non-``None`` the session is over its compression + threshold yet cannot shrink — callers should surface a warning so the + user knows the model may silently stop answering (the context keeps + growing until it hits the hard provider limit). Without this signal an + over-threshold session fails opaquely. + Includes anti-thrashing protection: if the last two compressions each saved less than 10%, skip compression to avoid infinite loops where each pass removes only 1-2 messages. """ tokens = prompt_tokens if prompt_tokens is not None else self.last_prompt_tokens if tokens < self.threshold_tokens: - return False - return not self._automatic_compression_blocked() + return False, None + if self._automatic_compression_blocked(): + return False, self._compression_block_reason() or "blocked" + return True, None + + def _compression_block_reason(self) -> "str | None": + """Return a human-readable reason for the current automatic-compaction + block, derived from the same in-memory state that + :meth:`_automatic_compression_blocked_locally` evaluates. + + * ``"cooldown:"`` — the summary LLM is recovering from a + recent 429/transient failure; compression is deferred to avoid the + freeze loop described in #11529. + * ``"ineffective"`` — anti-thrashing has backed off (the last two + compressions each saved <10%, or the fallback streak tripped). + * ``None`` — no block active. + """ + _cooldown_remaining = self._summary_failure_cooldown_until - time.monotonic() + if _cooldown_remaining > 0: + return f"cooldown:{_cooldown_remaining:.0f}" + if ( + self._ineffective_compression_count >= 2 + or self._fallback_compression_streak >= 2 + ): + return "ineffective" + return None def _refresh_durable_guards(self) -> None: - """Re-read durable cooldown + fallback-streak state from the DB. + """Re-read durable cooldown + breaker state from the DB. Cheap, best-effort, and only called when a gate is about to say "blocked": another agent on the same session may have cleared the - durable rows (successful boundary, forced retry) after this - compressor was bound, and a fallback streak has no timer — without - a re-read the stale in-memory snapshot blocks forever. + durable rows (successful boundary, forced retry, a real usage + reading that dipped below the threshold) after this compressor was + bound, and neither the fallback streak nor the ineffective-strike + counter has a timer — without a re-read the stale in-memory + snapshot blocks forever. """ try: self.get_active_compression_failure_cooldown(refresh=True) @@ -1836,26 +2411,22 @@ class ContextCompressor(ContextEngine): self._load_fallback_compression_streak() except Exception as exc: logger.debug("compression fallback-streak refresh failed: %s", exc) + try: + self._load_ineffective_compression_count() + except Exception as exc: + logger.debug("compression ineffective-count refresh failed: %s", exc) def _automatic_compression_blocked(self) -> bool: """Return whether automatic compaction is in cooldown or tripped.""" if not self._automatic_compression_blocked_locally(): return False # Blocked on the in-memory snapshot. Durable guard rows may have - # been cleared by another agent since bind_session_state(); refresh - # and re-evaluate so a stale local block cannot outlive the durable - # state that justified it. The unblocked hot path above never pays - # for the DB reads. - if ( - self._summary_failure_cooldown_until <= time.monotonic() - and self._fallback_compression_streak < 2 - ): - # Blocked solely by the in-memory ineffective-compression - # counter, which is not durable — there is nothing in the DB - # that could unblock it, so skip the refresh (otherwise this - # branch would re-read the DB on every gate check for the rest - # of the session). - return True + # been cleared by another agent since bind_session_state() — a + # successful boundary, a forced retry, or a real usage reading + # below the threshold (which zeroes the durable ineffective + # counter) — so refresh and re-evaluate before letting a stale + # local block outlive the durable state that justified it. The + # unblocked hot path above never pays for the DB reads. self._refresh_durable_guards() return self._automatic_compression_blocked_locally() @@ -1878,21 +2449,66 @@ class ContextCompressor(ContextEngine): _cooldown_remaining, ) return True - # Anti-thrashing: back off if recent compressions were ineffective + # Anti-thrashing: back off if recent compressions were ineffective. + # The back-off must not be permanent (#14694): the tripped state was + # judged against the transcript as it existed THEN (e.g. a middle + # region too small to matter), but the conversation keeps growing and + # can accumulate plenty of compressible material later. Without a + # recovery path the session never auto-compacts again and rides into + # the provider's hard context limit. Recovery is a probation probe: + # after _ANTI_THRASH_RECOVERY_SECONDS of continuous block, allow ONE + # attempt by dropping the tripped counter(s) to 1 strike (persisted, + # so sibling agents on the same session row unblock too). If the probe + # is ineffective again the very next verdict re-trips the guard, so + # the worst case in the truly-incompressible state is one compaction + # attempt per recovery window — bounded, not thrash. + # + # The clock is armed lazily on the first BLOCKED evaluation rather + # than persisted at trip time: a fresh process that loads a durable + # tripped counter (#69872) therefore starts a full window blocked, + # preserving the restart-must-not-disarm contract (#54923). if ( self._ineffective_compression_count >= 2 or self._fallback_compression_streak >= 2 ): + _now = time.monotonic() + if self._anti_thrash_recovery_deadline <= 0.0: + self._anti_thrash_recovery_deadline = ( + _now + self._ANTI_THRASH_RECOVERY_SECONDS + ) + elif _now >= self._anti_thrash_recovery_deadline: + self._anti_thrash_recovery_deadline = 0.0 + if self._ineffective_compression_count >= 2: + self._record_ineffective_compression_verdict(1) + if self._fallback_compression_streak >= 2: + self._fallback_compression_streak = 1 + self._persist_fallback_compression_streak() + if not self.quiet_mode: + logger.info( + "Anti-thrashing recovery: %.0fs elapsed since the " + "guard tripped — allowing one compaction probe " + "(ineffective=%d fallback=%d).", + self._ANTI_THRASH_RECOVERY_SECONDS, + self._ineffective_compression_count, + self._fallback_compression_streak, + ) + return False if not self.quiet_mode: logger.warning( "Compression skipped — repeated compaction attempts did not " "restore healthy context. ineffective=%d fallback=%d. " - "Consider /new to start fresh, or /compress for " - "focused compression.", + "Auto-compaction will retry once in %.0fs. Consider /new " + "to start fresh, or /compress for focused " + "compression.", self._ineffective_compression_count, self._fallback_compression_streak, + max(0.0, self._anti_thrash_recovery_deadline - _now), ) return True + # Guard not tripped (counters were cleared by an effective compaction + # or a fitting real-usage reading) — disarm any pending recovery clock + # so a LATER trip starts its own full window. + self._anti_thrash_recovery_deadline = 0.0 return False # ------------------------------------------------------------------ @@ -1902,6 +2518,7 @@ class ContextCompressor(ContextEngine): def _prune_old_tool_results( self, messages: List[Dict[str, Any]], protect_tail_count: int, protect_tail_tokens: int | None = None, + min_prune_chars: int = 200, ) -> tuple[List[Dict[str, Any]], int]: """Replace old tool result contents with informative 1-line summaries. @@ -1918,7 +2535,14 @@ class ContextCompressor(ContextEngine): fall within ``protect_tail_tokens`` (when provided) OR the last ``protect_tail_count`` messages (backward-compatible default). When both are given, the token budget takes priority and the message - count acts as a hard minimum floor. + count acts as a hard minimum floor — capped at + ``_MAX_TAIL_MESSAGE_FLOOR`` so a default ``protect_last_n=20`` cannot + freeze a whole run of bulky tool outputs against pruning. + + When the protected region itself still exceeds the soft tail budget + (``protect_tail_tokens * 1.5``), a pressure pass demotes large + completed tool/file outputs *inside* that region while keeping a + short recent floor verbatim (issue #61932). Returns (pruned_messages, pruned_count). """ @@ -1946,10 +2570,17 @@ class ContextCompressor(ContextEngine): # Determine the prune boundary if protect_tail_tokens is not None and protect_tail_tokens > 0: - # Token-budget approach: walk backward accumulating tokens + # Token-budget approach: walk backward accumulating tokens. + # Cap the message-count floor the same way tail-cut does so a + # default protect_last_n=20 cannot lock a bulky recent tool run + # outside the compressible / prunable window (#61932). accumulated = 0 boundary = len(result) - min_protect = min(protect_tail_count, len(result)) + min_protect = min( + protect_tail_count, + len(result), + _MAX_TAIL_MESSAGE_FLOOR, + ) for i in range(len(result) - 1, -1, -1): msg = result[i] msg_tokens = _estimate_msg_budget_tokens(msg) @@ -1997,54 +2628,72 @@ class ContextCompressor(ContextEngine): else: content_hashes[h] = (i, msg.get("tool_call_id", "?")) - # Pass 2: Replace old tool results with informative summaries - for i in range(prune_boundary): - msg = result[i] + # Ghost-skill defense (#32106): skills just loaded (or actively + # referenced in the protected tail) keep their full skill_view + # bodies through the ordinary prune passes. Without this, a skill + # loaded moments before a compaction can be demoted to metadata + # while the model still believes its instructions are in context. + protected_skills = _collect_protected_skill_names(result, prune_boundary) + + def _demote_tool_result_at(idx: int, *, spare_protected_skills: bool = True) -> bool: + """Replace a bulky tool result at ``idx`` with a 1-line summary. + + Returns True when the message was modified. + """ + nonlocal pruned + msg = result[idx] if msg.get("role") != "tool": - continue + return False content = msg.get("content", "") - # Multimodal content (base64 screenshots etc.): strip the image - # payload — keep a lightweight text placeholder in its place. - # Without this, an old computer_use screenshot (~1MB base64 + - # ~1500 real tokens) survives every compression pass forever. if isinstance(content, list): stripped = _strip_image_parts_from_parts(content) if stripped is not None: - result[i] = {**msg, "content": stripped} + result[idx] = {**msg, "content": stripped} pruned += 1 - continue + return True + return False if isinstance(content, dict) and content.get("_multimodal"): summary = content.get("text_summary") or "[screenshot removed to save context]" - result[i] = {**msg, "content": f"[screenshot removed] {summary[:200]}"} + result[idx] = {**msg, "content": f"[screenshot removed] {summary[:200]}"} pruned += 1 - continue + return True if not isinstance(content, str): - continue + return False if not content or content == _PRUNED_TOOL_PLACEHOLDER: - continue - # Skip already-deduplicated or previously-summarized results + return False if content.startswith("[Duplicate tool output"): - continue - # Only prune if the content is substantial (>200 chars) - if len(content) > 200: - call_id = msg.get("tool_call_id", "") - tool_name, tool_args = call_id_to_tool.get(call_id, ("unknown", "")) - summary = _summarize_tool_result(tool_name, tool_args, content) - result[i] = {**msg, "content": summary} - pruned += 1 + return False + # Already replaced by a prior prune/pressure pass (1-line summary). + if content.startswith("[") and " chars)" in content and len(content) < 400: + return False + if content.startswith("[screenshot removed"): + return False + # Only prune if the content is substantial (default >200 chars; the + # proactive path raises this floor via min_prune_chars). + if len(content) <= min_prune_chars: + return False + call_id = msg.get("tool_call_id", "") + tool_name, tool_args = call_id_to_tool.get(call_id, ("unknown", "")) + if spare_protected_skills and tool_name == "skill_view" and protected_skills: + # Just-loaded / actively-referenced skills survive verbatim + # (#32106). Pass-4 pressure demotion overrides this. + try: + _args = json.loads(tool_args) if tool_args else {} + except (json.JSONDecodeError, TypeError): + _args = {} + _skill = _args.get("name", "") if isinstance(_args, dict) else "" + if isinstance(_skill, str) and _skill.lower() in protected_skills: + return False + summary = _summarize_tool_result(tool_name, tool_args, content) + result[idx] = {**msg, "content": summary} + pruned += 1 + return True - # Pass 3: Truncate large tool_call arguments in assistant messages - # outside the protected tail. write_file with 50KB content, for - # example, survives pruning entirely without this. - # - # The shrinking is done inside the parsed JSON structure so the - # result remains valid JSON — otherwise downstream providers 400 - # on every subsequent turn until the broken call falls out of - # the window. See ``_truncate_tool_call_args_json`` docstring. - for i in range(prune_boundary): - msg = result[i] + def _truncate_tool_call_args_at(idx: int) -> bool: + """Shrink large tool_call argument payloads at ``idx``.""" + msg = result[idx] if msg.get("role") != "assistant" or not msg.get("tool_calls"): - continue + return False new_tcs = [] modified = False for tc in msg["tool_calls"]: @@ -2057,10 +2706,170 @@ class ContextCompressor(ContextEngine): modified = True new_tcs.append(tc) if modified: - result[i] = {**msg, "tool_calls": new_tcs} + result[idx] = {**msg, "tool_calls": new_tcs} + return modified + + # Pass 2: Replace old tool results with informative summaries + for i in range(max(0, prune_boundary)): + _demote_tool_result_at(i) + + # Pass 3: Truncate large tool_call arguments in assistant messages + # outside the protected tail. write_file with 50KB content, for + # example, survives pruning entirely without this. + # + # The shrinking is done inside the parsed JSON structure so the + # result remains valid JSON — otherwise downstream providers 400 + # on every subsequent turn until the broken call falls out of + # the window. See ``_truncate_tool_call_args_json`` docstring. + for i in range(max(0, prune_boundary)): + _truncate_tool_call_args_at(i) + + # Pass 4 (issue #61932): protected-tail pressure demotion. + # After multiple in-place compactions the transcript can be short + # enough that nearly every remaining message sits inside the + # protected floor, yet those messages are huge completed tool / + # file outputs. Summarizing the (empty) middle does nothing and + # preflight ends in "Cannot compress further". Demote bulky tool + # bodies *inside* the protected region until the protected tail + # fits the soft budget, always keeping a short recent floor + # verbatim so the active ask stays readable. + if protect_tail_tokens is not None and protect_tail_tokens > 0 and result: + soft_ceiling = int(protect_tail_tokens * 1.5) + keep_recent = min(_PRESSURE_KEEP_RECENT_MESSAGES, len(result)) + demote_end = len(result) - keep_recent + + def _protected_region_tokens() -> int: + start = max(0, prune_boundary) + return sum( + _estimate_msg_budget_tokens(result[i]) + for i in range(start, len(result)) + ) + + if demote_end > prune_boundary and _protected_region_tokens() > soft_ceiling: + pressure_hits = 0 + for i in range(max(0, prune_boundary), demote_end): + # Pressure passes override the just-loaded-skill guard: + # when the protected region itself blows the soft budget, + # sparing skill bodies would recreate the #61932 dead-end. + if _demote_tool_result_at(i, spare_protected_skills=False): + pressure_hits += 1 + if _truncate_tool_call_args_at(i): + pressure_hits += 1 + if _protected_region_tokens() <= soft_ceiling: + break + # If the short recent floor itself is still dominated by a + # stack of huge tool bodies, demote every protected tool + # result except the single most recent one. The active + # user message (usually the last row) stays untouched. + if _protected_region_tokens() > soft_ceiling: + last_tool_idx = None + for i in range(len(result) - 1, -1, -1): + if result[i].get("role") == "tool": + last_tool_idx = i + break + for i in range(max(0, prune_boundary), len(result)): + if last_tool_idx is not None and i == last_tool_idx: + continue + if result[i].get("role") == "tool": + if _demote_tool_result_at(i, spare_protected_skills=False): + pressure_hits += 1 + elif result[i].get("role") == "assistant": + if _truncate_tool_call_args_at(i): + pressure_hits += 1 + # Absolute last resort: even the newest tool body can + # be larger than the soft budget alone (one 200KB file + # read). Summarize it so compression can still reclaim + # enough headroom to continue the session. + if ( + last_tool_idx is not None + and last_tool_idx >= prune_boundary + and _protected_region_tokens() > soft_ceiling + ): + if _demote_tool_result_at( + last_tool_idx, spare_protected_skills=False + ): + pressure_hits += 1 + if pressure_hits and not self.quiet_mode: + logger.info( + "Pre-compression pressure demotion: reclaimed protected-tail " + "tool output (%d change(s); protected region now ~%s tokens, " + "soft ceiling %s)", + pressure_hits, + f"{_protected_region_tokens():,}", + f"{soft_ceiling:,}", + ) return result, pruned + def prune_tool_results_only( + self, messages: List[Dict[str, Any]], current_tokens: int | None = None, + ) -> tuple[List[Dict[str, Any]], int]: + """Deterministic, no-LLM tool-result prune for the cost-oriented path. + + Runs the Phase-1 prune (``_prune_old_tool_results``) WITHOUT the + compression summary phase, gated on ``proactive_prune_tokens`` rather + than the (much higher) full-compression threshold. On large-window + models ``should_compress()`` (≈50% of the window) rarely fires, so old + tool outputs otherwise ride in history and are re-sent verbatim on every + subsequent turn; this reclaims them early with no quality-risky LLM + summarization. + + Protects the recent tail by message COUNT (``protect_last_n``), never by + ``tail_token_budget`` — the latter is derived from the 50% compression + threshold (≈100K tokens on a 1M window) and would protect the entire + session, pruning nothing. + + ``_prune_old_tool_results`` runs all three deterministic passes: + (1) dedup byte-identical tool results — keeps the newest full copy and + back-references older exact duplicates ANYWHERE in the list (including + the protected tail), so no unique content is ever lost; (2) summarize + non-tail tool results larger than ``min_prune_chars``; (3) truncate + oversized tool_call arguments on non-tail assistant messages. Only + pass (2)'s floor is raised by ``proactive_prune_min_result_chars``; + passes (1) and (3) keep their own fixed floors. The recent-tail + protection applies to passes (2) and (3); pass (1) is tail-agnostic by + design because dedup is lossless. + + PROMPT-CACHE CONTRACT: a committed prune rewrites message bodies the + provider has already seen, invalidating the cached prefix from the + earliest rewritten message forward — exactly like a compression + boundary. To keep that break episodic rather than per-turn, the prune + only COMMITS when the estimated reclaim meets + ``proactive_prune_min_reclaim_tokens`` (measured on the actual pruned + output, not guessed up front). Below the gate the INPUT list object is + returned unchanged — the standard no-op caller contract (callers gate + bookkeeping on ``result is not input``). + + Returns ``(messages, 0)`` — the input object — when disabled, below + the trigger, or when the reclaim gate rejects the commit. + """ + if self.proactive_prune_tokens <= 0: + return messages, 0 + if current_tokens is not None and current_tokens < self.proactive_prune_tokens: + return messages, 0 + # Nothing to reclaim until there are messages outside the protected tail. + if len(messages) <= self.protect_last_n + self._protect_head_size(messages) + 1: + return messages, 0 + pruned_msgs, pruned_count = self._prune_old_tool_results( + messages, + protect_tail_count=self.protect_last_n, + protect_tail_tokens=None, + min_prune_chars=self.proactive_prune_min_result_chars, + ) + if not pruned_count: + # Standard no-op contract: hand back the INPUT object so callers + # can gate bookkeeping on `result is not input`. + return messages, 0 + # Measured-savings gate (prompt-cache hysteresis): only commit when + # the prune reclaims a meaningful batch of tokens. Estimated on the + # real before/after messages so dedup + arg truncation count too. + if self.proactive_prune_min_reclaim_tokens > 0: + before = sum(_estimate_msg_budget_tokens(m) for m in messages) + after = sum(_estimate_msg_budget_tokens(m) for m in pruned_msgs) + if (before - after) < self.proactive_prune_min_reclaim_tokens: + return messages, 0 + return pruned_msgs, pruned_count + # ------------------------------------------------------------------ # Summarization # ------------------------------------------------------------------ @@ -2084,6 +2893,10 @@ class ContextCompressor(ContextEngine): _CONTENT_TAIL = 1500 # chars kept from the end _TOOL_ARGS_MAX = 1500 # tool call argument chars _TOOL_ARGS_HEAD = 1200 # kept from the start of tool args + # Aggregate cap over the whole serialized block, applied AFTER the + # per-message limits above. Alias of the module-level constant (which + # carries the full rationale) so subclasses/tests can override per-class. + _SUMMARY_INPUT_MAX_CHARS = _SUMMARY_INPUT_MAX_CHARS def _serialize_for_summary(self, turns: List[Dict[str, Any]]) -> str: """Serialize conversation turns into labeled text for the summarizer. @@ -2343,12 +3156,6 @@ Recovered from a deterministic fallback because the LLM context summarizer was u ## Active State Unknown from deterministic fallback. Inspect current repository/session state if needed. -{HISTORICAL_IN_PROGRESS_HEADING} -Unknown from deterministic fallback — the latest user ask is recorded once under -"{HISTORICAL_TASK_HEADING}" above as historical context only. Do NOT treat it as an -unfulfilled instruction to re-answer; verify current state and continue from the -protected recent messages after this summary. - ## Blocked {_bullets(blockers, limit=5)} @@ -2358,27 +3165,62 @@ None recoverable from deterministic fallback. ## Resolved Questions None recoverable from deterministic fallback. -{HISTORICAL_PENDING_ASKS_HEADING} -None recoverable from deterministic fallback. (The latest user ask is preserved once -under "{HISTORICAL_TASK_HEADING}" as historical context — it is NOT necessarily -outstanding.) - ## Relevant Files {_bullets(relevant_files, limit=12)} -{HISTORICAL_REMAINING_WORK_HEADING} -Continue from the most recent unfulfilled user ask and protected tail messages. Verify state with tools before making claims. - ## Last Dropped Turns {_bullets(last_dropped_turns, limit=8)} ## Critical Context Summary generation was unavailable, so this is a best-effort deterministic fallback for {len(turns_to_summarize)} compacted message(s).{reason_text}""" + # Ghost-skill defense (#32106): the fallback's per-turn truncation + # (``_FALLBACK_TURN_MAX_CHARS``) routinely cuts [SKILL_PRUNED: ...] + # markers out of the compacted turns. Re-derive the ghosted skills + # from the raw turn contents and re-inject deterministically, + # exactly like the LLM-summary path. + _pruned_names = _collect_ghosted_skill_names(turns_to_summarize) + del _pruned_names[_MAX_PRUNED_SKILL_MARKERS:] summary = self._with_summary_prefix(_redact_compaction_text(body.strip())) if len(summary) > _FALLBACK_SUMMARY_MAX_CHARS: summary = summary[: _FALLBACK_SUMMARY_MAX_CHARS - 42].rstrip() + "\n...[fallback summary truncated]" + # Re-inject AFTER the size cap: the markers live at the end of the + # body, exactly where the truncation above cuts. + summary = _reinject_pruned_skill_markers(summary, _pruned_names) return summary + @classmethod + def _bound_summary_input(cls, content: str) -> str: + """Cap total summarizer input while preserving beginning and recent tail. + + Per-message truncation alone is not enough for very long sessions: a + compression window with hundreds of messages can still produce a huge + single prompt that slow auxiliary backends time out on. Keep both edges + because the beginning often has task setup and the tail has the most + recent state; explicitly mark the omitted middle so the summarizer knows + context was intentionally compressed before it saw the prompt. + """ + if len(content) <= cls._SUMMARY_INPUT_MAX_CHARS: + return content + + marker_template = ( + "\n\n...[summary input truncated: omitted " + "{omitted:,} chars from the middle to keep compression prompt bounded]...\n\n" + ) + # Estimate once, then rebuild with the exact omitted span after the + # head/tail split is known. The second marker can differ by a few chars + # if the comma-formatted number changes width, so recompute once. + marker = marker_template.format(omitted=len(content)) + remaining = max(cls._SUMMARY_INPUT_MAX_CHARS - len(marker), 0) + head_chars = int(remaining * 0.45) + tail_chars = remaining - head_chars + omitted = max(len(content) - head_chars - tail_chars, 0) + marker = marker_template.format(omitted=omitted) + remaining = max(cls._SUMMARY_INPUT_MAX_CHARS - len(marker), 0) + head_chars = int(remaining * 0.45) + tail_chars = remaining - head_chars + tail = content[-tail_chars:].lstrip() if tail_chars else "" + return content[:head_chars].rstrip() + marker + tail + def _fallback_to_main_for_compression(self, e: Exception, reason: str) -> None: """Switch from a separate ``summary_model`` back to the main model. @@ -2452,6 +3294,23 @@ Summary generation was unavailable, so this is a best-effort deterministic fallb summary_budget = self._compute_summary_budget(turns_to_summarize) content_to_summarize = self._serialize_for_summary(turns_to_summarize) + # P2 ghost-skill defense (#32106): [SKILL_PRUNED: ...] markers entering + # the summarizer are prompt INPUT only — LLMs routinely paraphrase them + # into vague prose ("some skills were loaded"), which erases the reload + # instruction. Collect the ghosted skills deterministically BEFORE the + # call (both already-pruned marker rows AND raw skill_view bodies whose + # instructions are about to be summarized away); + # ``_reinject_pruned_skill_markers`` restores any marker the model + # dropped AFTER the call. Markers already carried by the previous + # summary must survive iterative rewrites the same way. Collection + # walks the turn LIST, so the serialized input bound below cannot + # hide a marker in its omitted middle. + _pruned_skill_names = _collect_ghosted_skill_names(turns_to_summarize) + for _name in _extract_pruned_skill_names(self._previous_summary or ""): + if _name not in _pruned_skill_names: + _pruned_skill_names.append(_name) + del _pruned_skill_names[_MAX_PRUNED_SKILL_MARKERS:] + content_to_summarize = self._bound_summary_input(content_to_summarize) _sanitized_memory_context = sanitize_memory_context(memory_context) _serialized_memory_context = json.dumps( _sanitized_memory_context, @@ -2619,9 +3478,6 @@ Be specific with file paths, commands, line numbers, and results.] - Any running processes or servers - Environment details that matter] -{HISTORICAL_IN_PROGRESS_HEADING} -[Work currently underway — what was being done when compaction fired] - ## Blocked [Any blockers, errors, or issues not yet resolved. Include exact error messages.] @@ -2631,30 +3487,39 @@ Be specific with file paths, commands, line numbers, and results.] ## Resolved Questions {_resolved_questions_instructions} -{HISTORICAL_PENDING_ASKS_HEADING} -{_pending_asks_instructions} - ## Relevant Files [Files read, modified, or created — with brief note on each] -{HISTORICAL_REMAINING_WORK_HEADING} -[What remains to be done — framed as STALE context for reference only. The agent must NOT resume this work unless the latest user message explicitly asks for it.] - ## Critical Context [Any specific values, error messages, configuration details, or data that would be lost without explicit preservation. NEVER include API keys, tokens, passwords, or credentials — write [REDACTED] instead.] +{_PRUNED_SKILLS_SECTION_HEADING} +[If any [SKILL_PRUNED: ...reload with skill_view(...)] markers appear in the input, +repeat each one verbatim here — copy the exact text, do NOT paraphrase, summarize, +or describe them. These markers tell the agent which skills must be reloaded before +use. If none appear, omit this section entirely.] + Target ~{summary_budget} tokens. Be CONCRETE — include file paths, command outputs, error messages, line numbers, and specific values. Avoid vague descriptions like "made some changes" — say exactly what changed. {_temporal_anchoring_rule} Write only the summary body. Do not include any preamble or prefix.""" if self._previous_summary: - # Iterative update: preserve existing info, add new progress + # Iterative update: preserve existing info, add new progress. + # Bound the previous-summary block with the same aggregate cap as + # the serialized new turns: a normal summary is far below the cap + # (the output side is held to a ~10K-token ceiling), but a + # pathological handoff rehydrated from a persisted session can be + # arbitrarily large — the iterative prompt (previous summary + + # new turns) must stay bounded too. + _bounded_previous_summary = self._bound_summary_input( + self._previous_summary + ) prompt = f"""{_summarizer_preamble} You are updating a context compaction summary. A previous compaction produced the summary below. New conversation turns have occurred since then and need to be incorporated. PREVIOUS SUMMARY: -{self._previous_summary} +{_bounded_previous_summary} NEW TURNS TO INCORPORATE: {content_to_summarize}{_memory_section} @@ -2785,6 +3650,9 @@ This compaction should PRIORITISE preserving all information related to the focu # Redact the summary output as well — the summarizer LLM may # ignore prompt instructions and echo back secrets verbatim. summary = _redact_compaction_text(content.strip()) + # P2 ghost-skill defense (#32106): deterministically restore any + # [SKILL_PRUNED: ...] marker the summarizer paraphrased away. + summary = _reinject_pruned_skill_markers(summary, _pruned_skill_names) summary = self._ground_historical_task_snapshot(summary, turns_to_summarize) self._validate_summary_user_provenance(summary, has_user_turn) # Store for iterative updates on next compaction @@ -3845,6 +4713,69 @@ This compaction should PRIORITISE preserving all information related to the focu return max(pair_end, head_end + 1) return adjusted + def _ensure_last_n_user_messages_in_tail( + self, + messages: List[Dict[str, Any]], + cut_idx: int, + head_end: int, + n: int, + ) -> int: + """Guarantee the last N actionable user messages are in the protected tail. + + Generalizes ``_ensure_last_user_message_in_tail`` to preserve an + arbitrary number of recent user messages. This prevents the token- + budget-based tail cut from consuming recent conversation turns + when large tool outputs fill the budget. + + When *n* <= 1, delegates directly to the existing single-message + method for byte-identical regression safety. + + If the conversation has fewer than *n* user messages, the earliest + available user message is used without error. + + Only REAL actionable user turns count toward N — the collector uses + the same ``_is_actionable_user_turn`` / + ``_is_synthetic_compression_user_turn`` pair as + ``_find_last_user_message_idx``, so blank platform echoes, compaction + handoffs, continuation markers, and todo-snapshot rows never consume + a slot (#69291 bug class). + + A user message is already a clean boundary — there is no + tool_call/result group that spans across it, so + ``_align_boundary_backward`` is intentionally NOT called. + Calling it can pull the cut past the user message into the + preceding assistant(tool_calls)→tool group and split it (#22566). + """ + if n <= 1: + return self._ensure_last_user_message_in_tail(messages, cut_idx, head_end) + + # Collect real user message indices walking backward from end. + # Mirror _find_last_user_message_idx's filters: compaction handoffs, + # blank platform echoes, and synthetic continuation/todo rows are + # continuity artifacts, not real user turns. + user_indices = [] + for i in range(len(messages) - 1, head_end - 1, -1): + msg = messages[i] + if ( + self._is_actionable_user_turn(msg) + and not self._is_synthetic_compression_user_turn(msg) + ): + user_indices.append(i) + + if len(user_indices) == 0: + return cut_idx + + if len(user_indices) < n: + target_idx = user_indices[-1] + else: + target_idx = user_indices[n - 1] + + if target_idx >= cut_idx: + return cut_idx + + cut_idx = target_idx + return max(cut_idx, head_end + 1) + def _find_turn_pair_end( self, messages: List[Dict[str, Any]], @@ -3974,6 +4905,26 @@ This compaction should PRIORITISE preserving all information related to the focu # monotonic — the tail can only grow, never shrink. cut_idx = self._ensure_last_assistant_message_in_tail(messages, cut_idx, head_end) + # Extend to the last N actionable user messages when configured + # (compression.min_tail_user_messages > 1). This prevents the + # token-budget tail from consuming recent turns when large tool + # outputs fill the budget. The anchor only walks ``cut_idx`` + # backward (monotonic — the tail can only grow, never shrink), and + # a user message is a clean boundary, so the forward re-alignment + # below remains a no-op for the anchored index. Gated at the call + # site so the default (1) path is byte-identical to the historical + # single-anchor pipeline — the single-user anchor already ran above, + # and re-invoking it here could re-trigger the causal-coupling + # forward push (#22523) after the assistant anchor adjusted the cut. + # getattr-guarded: bare ``ContextCompressor.__new__`` test doubles + # (and plugin engines) skip __init__, so the attribute may be absent + # (see the compression-path test-double pitfall). + _min_tail_users = getattr(self, "min_tail_user_messages", 1) + if isinstance(_min_tail_users, int) and not isinstance(_min_tail_users, bool) and _min_tail_users > 1: + cut_idx = self._ensure_last_n_user_messages_in_tail( + messages, cut_idx, head_end, _min_tail_users, + ) + # The floor guarantees forward progress — compression must always claim # at least one message or the caller's compress_start >= compress_end # guard turns the pass into a no-op that re-runs forever (the same loop @@ -4083,7 +5034,9 @@ This compaction should PRIORITISE preserving all information related to the focu # threshold because of the incompressible floor (system prompt + # tool schemas), every subsequent turn re-fires a compaction that # returns here unchanged, and the CLI appears frozen. - self._ineffective_compression_count += 1 + self._record_ineffective_compression_verdict( + self._ineffective_compression_count + 1, + ) self._last_compression_savings_pct = 0.0 telemetry["failure_class"] = "insufficient_messages" if not self.quiet_mode: @@ -4151,7 +5104,9 @@ This compaction should PRIORITISE preserving all information related to the focu # an ineffective compression the anti-thrashing guard in # should_compress() never fires and every subsequent turn # re-triggers a no-op compression loop. (#40803) - self._ineffective_compression_count += 1 + self._record_ineffective_compression_verdict( + self._ineffective_compression_count + 1, + ) self._last_compression_savings_pct = 0.0 if not self.quiet_mode: logger.warning( @@ -4271,6 +5226,39 @@ This compaction should PRIORITISE preserving all information related to the focu ) telemetry["chunk_count"] = 1 if turns_to_summarize else 0 + if not turns_to_summarize: + # The newest handoff summary consumed the entire compressible + # window (every window row was a standalone handoff that strips + # to None, and nothing follows it before compress_end) — there + # is nothing new to summarize. Skip the summary call entirely: + # without this guard the empty window still reached + # _generate_summary, wasting an aux LLM call that aborts + # noisily on empty input (#59496). Mirrors the sibling + # "no compressable window" guard above (#40803): record an + # ineffective strike through the durable write-through helper + # so the anti-thrash breaker in should_compress() can stop the + # loop — this shape cannot shrink, so every subsequent turn + # would otherwise re-fire the same no-op. The rehydrated + # _previous_summary is deliberately KEPT (not rolled back as + # the summary-abort path does for #57835): it came from a + # handoff genuinely present in this transcript, which is + # returned unchanged. + telemetry["failure_class"] = "empty_post_handoff_window" + self._record_ineffective_compression_verdict( + self._ineffective_compression_count + 1, + ) + self._last_compression_savings_pct = 0.0 + if not self.quiet_mode: + logger.warning( + "Compression skipped: latest context summary leaves no " + "new turns to summarize in window %d-%d. " + "ineffective_compression_count=%d", + compress_start, + compress_end, + self._ineffective_compression_count, + ) + return messages + if not self.quiet_mode: logger.info( "Context compression triggered (%d tokens >= %d threshold)", diff --git a/agent/context_engine.py b/agent/context_engine.py index eafbb5ddc2d8..b772125c0cbe 100644 --- a/agent/context_engine.py +++ b/agent/context_engine.py @@ -53,6 +53,39 @@ def sanitize_memory_context(memory_context: str) -> str: ) +def automatic_compaction_status_message( + engine: Any, + *, + phase: str, + default_message: str, + **context: Any, +) -> str | None: + """Resolve host-visible status for an automatic compaction event. + + Engines can suppress routine automatic status with + ``emit_automatic_compaction_status = False`` or customize it by defining + ``get_automatic_compaction_status_message(...)``. Empty strings and + ``None`` mean "do not emit a lifecycle status". + """ + if not getattr(engine, "emit_automatic_compaction_status", True): + return None + + formatter = getattr(engine, "get_automatic_compaction_status_message", None) + if callable(formatter): + message = formatter( + phase=phase, + default_message=default_message, + **context, + ) + else: + message = default_message + + if message is None: + return None + message = str(message).strip() + return message or None + + class ContextEngine(ABC): """Base class all context engines must implement.""" @@ -89,6 +122,12 @@ class ContextEngine(ABC): protect_first_n: int = 3 protect_last_n: int = 6 + # User-visible lifecycle status for automatic host-triggered compaction. + # Alternative engines that treat compaction as routine background + # maintenance can set this false to keep successful automatic passes silent; + # warnings, errors, and explicit manual commands should still surface. + emit_automatic_compaction_status: bool = True + # -- Core interface ---------------------------------------------------- @abstractmethod @@ -107,6 +146,19 @@ class ContextEngine(ABC): def should_compress(self, prompt_tokens: int = None) -> bool: """Return True if compaction should fire this turn.""" + def should_compress_info(self, prompt_tokens: int = None) -> "tuple[bool, str | None]": + """Return ``(should_compress, reason)``. + + The base implementation is backward-compatible: engines that only + implement ``should_compress`` get ``(should_compress(prompt_tokens), + None)``. Concrete engines with richer block reasons (e.g. a + summary-LLM cooldown or an anti-thrashing guard) override this to + surface a human-readable reason so callers can warn the user instead + of silently skipping compression. Added for the silent-overflow + warning fix (#62625) so plugin engines don't raise AttributeError. + """ + return self.should_compress(prompt_tokens), None + @abstractmethod def compress( self, @@ -137,6 +189,144 @@ class ContextEngine(ABC): host filters unsupported optional arguments by signature. """ + # -- Optional: proactive tool-result prune ----------------------------- + + def prune_tool_results_only( + self, + messages: List[Dict[str, Any]], + current_tokens: int | None = None, + ) -> tuple[List[Dict[str, Any]], int]: + """Deterministically trim old tool-result payloads without an LLM call. + + Runs on a low, cost-oriented trigger independent of ``should_compress`` + so large-window engines can reclaim re-sent tool output long before full + compaction would fire. Returns ``(messages, n_pruned)``. + + Default is a safe no-op: the list is returned unchanged with ``0`` + pruned. Engines that don't implement a cheap prune — and any engine that + predates this hook — inherit this default, so the agent loop's + post-tool-call prune path never raises ``AttributeError`` on them. The + built-in ContextCompressor overrides this with the real implementation. + """ + return messages, 0 + + # -- Optional: per-turn context selection (distinct from compression) -- + + def select_context( + self, + request_messages: List[Dict[str, Any]], + *, + conversation_messages: List[Dict[str, Any]] = None, + incoming_message: Dict[str, Any] = None, + budget_tokens: int = 0, + ) -> List[Dict[str, Any]]: + """Optionally choose/replace the context for THIS request, pre-generation. + + Called every turn after the request message list is assembled and + before it is dispatched to the provider — independent of + ``should_compress()``. This lets an engine *select* which context + enters the prompt (retrieval, topic routing, role/branch switching) + rather than *shrink* context that is already there. The two verbs are + orthogonal: + + - ``compress()`` : context is too long -> make it shorter. + - ``select_context()``: this turn belongs to a different context + -> use that one instead. + + Without this hook, engines that need per-turn access to the message + list have to force ``should_compress()`` to return ``True`` so that + ``compress()`` is invoked every turn purely as a callback — which + conflates selection with compression and degrades behaviour when the + engine's backend is unavailable. ``select_context()`` removes the need + for that workaround. + + The returned list is request-only: it replaces the messages sent to + the provider for this single call and MUST NOT be treated as persisted + transcript state. The conversation history in the session DB is left + untouched, so nothing leaks across turns. Return ``None`` to leave the + request unchanged. + + Unlike the ``pre_llm_call`` plugin hook (which appends to the user + message and intentionally never rewrites the list, to preserve the + cache prefix), ``select_context()`` may *replace* the message list. + + Ordering / cache contract: the host runs this hook **before** prompt + cache-control and **before** every request sanitizer (orphaned-tool + cleanup, thinking-only/role normalization, whitespace/JSON + normalization). So (a) whatever the hook returns still passes through + the same validation as any request — a malformed replacement cannot + reach the provider — and (b) prompt-cache stability (an AGENTS.md + invariant) is preserved: the default no-op leaves the request + byte-identical, so cache behaviour is unchanged for the built-in + compressor and any non-implementing engine. An engine that *does* + replace the list changes its own cache prefix by definition; that is + the engine's concern, and cache-control breakpoints are re-derived on + the selected list. The hook is evaluated per provider request (so it + re-runs on retries within a turn), consistent with "select the context + for THIS request". + + Args: + request_messages: The assembled request message list (system + prompt + history + any ephemeral prefill), in OpenAI format. + conversation_messages: The unmodified persisted conversation + history, for reference only (do not mutate). + incoming_message: The current turn's user message, if available. + budget_tokens: The active model's context length, or 0 if unknown. + + Default returns ``None`` (no-op) — zero impact on the built-in + compressor or any existing engine. + """ + return None + + def on_turn_complete( + self, + messages: List[Dict[str, Any]], + usage: Dict[str, Any] = None, + **kwargs: Any, + ) -> None: + """Observe a finished user turn (post-turn ingestion / observation). + + Called from the standard turn-finalization path once the assistant/tool + loop completes, with the finalized in-memory transcript snapshot. This + is the complement to ``select_context()``: selection happens *before* + the request, while observation happens *after* the turn. It lets an + engine ingest, index, summarize, or update routing / topic / session + state from what actually happened — so the next ``select_context()`` + can act on it. + + Coverage: this fires from the normal finalization seam. Some abnormal + early-return paths in the loop (e.g. a content-policy block or a + provider terminal failure) persist and return without routing through + finalization, and therefore do not currently emit this hook. Treat it + as a best-effort post-turn observation for completed turns, not a + guaranteed callback for every possible early exit; unifying all + terminal paths behind one finalization seam is a separate follow-up. + + Together the two hooks remove the need to abuse ``should_compress()`` / + ``compress()`` as a generic per-turn callback just to observe history, + and they cover the case where a turn finishes and there may be no next + request from which to infer the previous turn. + + ``messages`` is a shallow copy and should be treated as read-only: + return values are ignored and this hook must not rely on transcript + mutation for persistence. ``kwargs`` may include ``turn_id``, + ``task_id``, ``api_call_count``, ``interrupted``, ``failed``, and + ``turn_exit_reason``. + + ``usage`` carries the completed turn's canonical token usage (the same + dict shape passed to ``update_from_response`` — ``prompt_tokens`` / + ``completion_tokens`` / ``total_tokens`` plus the canonical + ``input_tokens`` / ``output_tokens`` / ``cache_read_tokens`` / + ``cache_write_tokens`` / ``reasoning_tokens`` buckets) so an engine can + weigh how large/expensive the selected context actually was when + deciding the next ``select_context()``. It is ``None`` on finalized + turns that never reached a provider response (e.g. interrupt); engines + must treat it as optional. + + Default is a no-op. + """ + return None + # -- Optional: pre-flight check ---------------------------------------- def should_compress_preflight(self, messages: List[Dict[str, Any]]) -> bool: @@ -156,6 +346,27 @@ class ContextEngine(ABC): """ return False + def get_automatic_compaction_status_message( + self, + *, + phase: str, + default_message: str, + **context: Any, + ) -> str | None: + """Return user-visible status for automatic host-triggered compaction. + + Return ``None`` to suppress successful automatic lifecycle status for + this compaction event. ``phase`` identifies the host call site (for + example ``"preflight"`` or ``"compress"``). ``context`` contains + best-effort fields such as ``approx_tokens`` and ``threshold_tokens``. + + This hook does not control warning/error messages or explicit manual + commands such as ``/compress``. + """ + if not self.emit_automatic_compaction_status: + return None + return default_message + # -- Optional: manual /compress preflight ------------------------------ def has_content_to_compress(self, messages: List[Dict[str, Any]]) -> bool: diff --git a/agent/context_references.py b/agent/context_references.py index eea16ae52b44..ab370a5a5924 100644 --- a/agent/context_references.py +++ b/agent/context_references.py @@ -19,6 +19,7 @@ REFERENCE_PATTERN = re.compile( rf"(?diff|staged)\b|(?Pfile|folder|git|url):(?P{_QUOTED_REFERENCE_VALUE}(?::\d+(?:-\d+)?)?|\S+))" ) TRAILING_PUNCTUATION = ",.;!?" +_NEEDS_QUOTING = re.compile(r"""[\s()\[\]{}<>"'`]""") _SENSITIVE_HOME_DIRS = (".ssh", ".aws", ".gnupg", ".kube", ".docker", ".azure", ".config/gh") _SENSITIVE_HERMES_DIRS = (Path("skills") / ".hub",) _SENSITIVE_HOME_FILES = ( @@ -60,6 +61,21 @@ class ContextReferenceResult: blocked: bool = False +def format_reference_value(value: str) -> str: + """Quote a reference value so ``REFERENCE_PATTERN`` reads it back whole. + + The unquoted alternative in the pattern is ``\\S+``, so a path containing a + space parses as a truncated ref with the tail left behind as loose text. + Mirrors ``formatRefValue`` in the desktop's directive-text.tsx. + """ + if not _NEEDS_QUOTING.search(value): + return value + for quote in ("`", '"', "'"): + if quote not in value: + return f"{quote}{value}{quote}" + return value + + def parse_context_references(message: str) -> list[ContextReference]: refs: list[ContextReference] = [] if not message: @@ -197,8 +213,12 @@ async def preprocess_context_references_async( f"@ context injection warning: {injected_tokens} tokens exceeds the 25% soft limit ({soft_limit})." ) - stripped = _remove_reference_tokens(message, refs) - final = stripped + # Leave the `@file:`/`@folder:` tokens where the user typed them. The token + # IS the reference, not scaffolding around it: clients render each one as an + # inline chip, so stripping them left a sentence with a hole in it ("review + # and ship") and made the desktop re-derive the refs from the attached block + # to show them as a detached list above the prose. + final = message if warnings: final = f"{final}\n\n--- Context Warnings ---\n" + "\n".join(f"- {warning}" for warning in warnings) if blocks: @@ -308,7 +328,7 @@ def _expand_git_reference( ["git", *args], cwd=cwd, capture_output=True, - text=True, + text=True, encoding='utf-8', errors='replace', timeout=30, stdin=subprocess.DEVNULL, **_popen_kwargs, @@ -457,19 +477,6 @@ def _parse_file_reference_value(value: str) -> tuple[str, int | None, int | None return _strip_reference_wrappers(value), None, None -def _remove_reference_tokens(message: str, refs: list[ContextReference]) -> str: - pieces: list[str] = [] - cursor = 0 - for ref in refs: - pieces.append(message[cursor:ref.start]) - cursor = ref.end - pieces.append(message[cursor:]) - text = "".join(pieces) - text = re.sub(r"\s{2,}", " ", text) - text = re.sub(r"\s+([,.;:!?])", r"\1", text) - return text.strip() - - def _is_binary_file(path: Path) -> bool: mime, _ = mimetypes.guess_type(path.name) if mime and not mime.startswith("text/") and not any( @@ -534,7 +541,7 @@ def _rg_files(path: Path, cwd: Path, limit: int) -> list[Path] | None: ["rg", "--files", str(path.relative_to(cwd))], cwd=cwd, capture_output=True, - text=True, + text=True, encoding='utf-8', errors='replace', timeout=10, stdin=subprocess.DEVNULL, **_popen_kwargs, diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py index 04206a407211..8308b618da76 100644 --- a/agent/conversation_compression.py +++ b/agent/conversation_compression.py @@ -40,9 +40,12 @@ import uuid import threading from datetime import datetime from pathlib import Path -from typing import Any, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple -from agent.context_engine import sanitize_memory_context +from agent.context_engine import ( + automatic_compaction_status_message, + sanitize_memory_context, +) from agent.model_metadata import estimate_request_tokens_rough logger = logging.getLogger(__name__) @@ -106,6 +109,22 @@ COMPRESSION_RETRY_CONTEXT_REDUCED_STATUS_TEMPLATE = ( "🗜️ Context reduced to {new_ctx:,} tokens (was {old_ctx:,}), retrying..." ) +# FAILURE-CLASS notice — a deliberate carve-out from routine-compression +# silence (#16775 class): the context is over the compression threshold but +# compression is blocked (summary-LLM cooldown / anti-thrash breaker), so the +# session will keep growing until the hard provider token limit kills it. +# This MUST stay visible on chat gateways. Do NOT add it to +# ROUTINE_COMPRESSION_STATUS_SAMPLES or the gateway noise regex +# (_TELEGRAM_NOISY_STATUS_RE); it is pinned un-swallowed in +# tests/gateway/test_telegram_noise_filter.py::VISIBLE_COMPRESSION_MESSAGES. +CONTEXT_OVERFLOW_BLOCKED_WARNING_TEMPLATE = ( + "⚠ Context is over the compression threshold " + "(~{tokens:,} tokens >= {threshold:,}) " + "but compression is currently blocked ({reason}). " + "The model may stop responding. Run /new to start a fresh " + "session or /compress to retry immediately." +) + # Sample-formatted instances of every routine compression status line, for # behavioral tests that iterate the ACTUAL emitted wording (formatted from the # same constants the emission sites use) through the gateway noise filter. @@ -188,6 +207,83 @@ def _cached_prompt_reflects_builtin_memory(agent: Any, cached_prompt: str) -> bo return True +class CompressionCommitFence: + """Fence timeout cancellation against post-summary session mutation. + + Compression itself is synchronous and may be running in an executor thread. + A caller can stop waiting for the summary, but it cannot kill that thread. + This fence makes the commit boundary deterministic: cancellation either wins + before session mutation starts, or waits until an already-started commit is + fully complete before the caller proceeds. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + self._cancelled = False + self._commit_started = False + # Forward-progress telemetry: the compression worker touches this + # whenever the streamed summary call produces a token (see + # ContextCompressor._call_summary_llm). Waiters use it to distinguish + # a SLOW-but-alive summary model from a HUNG one, so slow models are + # not killed by a fixed wall-clock deadline while tokens are moving. + self._last_progress = time.monotonic() + + def touch_progress(self) -> None: + """Record forward progress (e.g. a streamed summary token arriving). + + Called from the compression worker thread; read by async waiters via + :meth:`seconds_since_progress`. A bare float store is atomic in + CPython, so no lock is needed. + """ + self._last_progress = time.monotonic() + + def seconds_since_progress(self) -> float: + """Seconds since the worker last reported forward progress.""" + return max(0.0, time.monotonic() - self._last_progress) + + def cancel_before_commit(self) -> bool: + """Cancel a pending commit, or wait for an active commit to finish. + + Returns ``True`` when cancellation won before the commit boundary. + Returns ``False`` when the worker had already entered the boundary; in + that case acquiring this lock waits until all session mutation finishes. + """ + with self._lock: + if self._commit_started: + return False + self._cancelled = True + return True + + def try_cancel_before_commit(self) -> Optional[bool]: + """Non-blocking form of :meth:`cancel_before_commit`. + + Returns ``None`` while an active commit owns the fence, allowing an + async caller to yield instead of blocking its event loop. + """ + if not self._lock.acquire(blocking=False): + return None + try: + if self._commit_started: + return False + self._cancelled = True + return True + finally: + self._lock.release() + + def begin_commit(self) -> bool: + """Enter the commit boundary unless cancellation already won.""" + self._lock.acquire() + if self._cancelled: + self._lock.release() + return False + self._commit_started = True + return True + + def finish_commit(self) -> None: + """Leave a commit boundary entered by :meth:`begin_commit`.""" + self._lock.release() + + def _lock_api_is_absent_on_session_db(lock_db: Any) -> bool: """Whether the live in-memory SessionDB class structurally predates locks. @@ -216,6 +312,7 @@ def _refresh_persisted_compression_guards(compressor: Any) -> None: method_calls = ( ("get_active_compression_failure_cooldown", {"refresh": True}), ("_load_fallback_compression_streak", {}), + ("_load_ineffective_compression_count", {}), ) for method_name, kwargs in method_calls: method = getattr(type(compressor), method_name, None) @@ -277,6 +374,143 @@ def _emit_compression_attempt_telemetry( logger.debug("failed to emit compression attempt telemetry: %s", exc) +def compression_skipped_due_to_lock(agent: Any) -> bool: + """Type-pinned read of the #69870 lock-skip signal. + + ``agent._compression_skipped_due_to_lock`` is set by ``compress_context`` + when a compression pass no-ops because another path holds the per-session + compression lock (holder string when the holder was confirmed, ``True`` + otherwise) and cleared to ``None`` at the entry of every call. + + The read MUST be type-pinned (``is True or isinstance(x, str)``), never + bare truthiness: MagicMock test-double agents auto-create truthy + attributes, and a bare ``if getattr(agent, ...)`` would hijack every + mocked agent in sibling suites into the lock-skip branch (the + #69870 × #69840 type-ahead incident). + """ + _sig = getattr(agent, "_compression_skipped_due_to_lock", None) + return _sig is True or isinstance(_sig, str) + + +def _adopt_live_compression_child( + agent: Any, + session_db: Any, + parent_session_id: str, +) -> Optional[List[Dict[str, Any]]]: + """Move a stale compression contender onto the unique durable child. + + Resolve and load first, then mutate the live agent. This ordering keeps the + stale contender fail-closed when lineage is ambiguous or the compacted + handoff cannot be read. + """ + finder = getattr(type(session_db), "find_live_compression_child", None) + loader = getattr(type(session_db), "get_messages_as_conversation", None) + if not callable(finder) or not callable(loader): + return None + child = finder(session_db, parent_session_id) + if not child or not child.get("id"): + return None + child_session_id = str(child["id"]) + recovered = loader(session_db, child_session_id) + if not isinstance(recovered, list) or not recovered: + return None + # Revalidate after loading: the child may have rotated or a competing + # continuation may have appeared between the two DB reads. + confirmed = finder(session_db, parent_session_id) + if not confirmed or str(confirmed.get("id") or "") != child_session_id: + return None + + agent.session_id = child_session_id + try: + from gateway.session_context import set_current_session_id + + set_current_session_id(child_session_id) + except Exception: + os.environ["HERMES_SESSION_ID"] = child_session_id + try: + from hermes_logging import set_session_context + + set_session_context(child_session_id) + except Exception: + pass + + agent._session_db_created = True + if child.get("system_prompt"): + agent._cached_system_prompt = child["system_prompt"] + agent._last_flushed_db_idx = len(recovered) + agent._flushed_db_message_session_id = child_session_id + agent._flushed_db_message_ids = { + id(message) for message in recovered if isinstance(message, dict) + } + + on_session_start = getattr(agent.context_compressor, "on_session_start", None) + if callable(on_session_start): + try: + on_session_start( + child_session_id, + boundary_reason="compression", + old_session_id=parent_session_id, + session_db=session_db, + platform=getattr(agent, "platform", None) or "cli", + conversation_id=getattr(agent, "_gateway_session_key", None), + ) + except Exception as exc: + logger.debug("context engine compression-child adoption failed: %s", exc) + else: + bind_state = getattr(agent.context_compressor, "bind_session_state", None) + if callable(bind_state): + try: + bind_state(session_db=session_db, session_id=child_session_id) + except Exception: + pass + try: + if agent._memory_manager: + agent._memory_manager.on_session_switch( + child_session_id, + parent_session_id=parent_session_id, + reset=False, + reason="compression", + ) + except Exception as exc: + logger.debug("memory manager compression-child adoption failed: %s", exc) + + return recovered + + +def recover_rotated_compression_session( + agent: Any, +) -> Optional[List[Dict[str, Any]]]: + """Recover a stale live agent before a new turn writes to its old parent.""" + session_db = getattr(agent, "_session_db", None) + session_id = getattr(agent, "session_id", None) or "" + if session_db is None or not session_id: + return None + try: + if not _session_was_rotated_by_compression(session_db, session_id): + return None + # Rotation publication holds the parent compression lease until the + # child handoff is durable. A concurrent turn waits briefly rather than + # observing the intentional parent-ended/child-empty intermediate state. + holder_getter = getattr(session_db, "get_compression_lock_holder", None) + for attempt in range(21): + recovered = _adopt_live_compression_child(agent, session_db, session_id) + if recovered is not None: + return recovered + holder = holder_getter(session_id) if callable(holder_getter) else None + if not holder or attempt == 20: + return None + time.sleep(0.05) + return None + except Exception as exc: + logger.warning( + "compression session recovery failed for session=%s (%s: %s)", + session_id, + type(exc).__name__, + exc, + ) + return None + + def _compression_lock_holder(agent: Any) -> str: """Build a unique holder id for the lock: pid:tid:agent-instance:uuid. @@ -437,7 +671,17 @@ class _CompressionLockLeaseRefresher: # by the TTL the acquirer set — the lock can never be held past its TTL # by a stuck refresher. consecutive_failures = 0 - while not self._stop.wait(self._refresh_interval_seconds): + # First refresh happens immediately, not one interval late. Everything + # between try_acquire() and start() (the rotation-ownership lookup, the + # durable-breaker re-read, thread startup) is charged against the very + # first lease, so on a short TTL under load the lock could already be + # expired — and reclaimable by a competing path — before tick #1. + first = True + while first or not self._stop.wait(self._refresh_interval_seconds): + if first: + first = False + if self._stop.is_set(): + break try: refreshed = self._db.refresh_compression_lock( self._session_id, @@ -730,7 +974,11 @@ def replay_compression_warning(agent: Any) -> None: pass -def conversation_history_after_compression(agent: Any, messages: list) -> Optional[list]: +def conversation_history_after_compression( + agent: Any, + messages: list, + previous_history: Optional[list] = None, +) -> Optional[list]: """Return the correct flush baseline after a compression boundary. Legacy compression rotates to a fresh child session. That child has not @@ -747,7 +995,19 @@ def conversation_history_after_compression(agent: Any, messages: list) -> Option A shallow copy is intentional: it captures the current compacted dict identities as history while allowing later same-turn appends to remain new. + + An aborted or no-op attempt after an earlier in-place compaction must retain + the pre-attempt baseline. Treating all current messages as persisted would + drop any later, unflushed turns on restart; clearing the baseline would + append the already-persisted compacted rows a second time. """ + if bool(getattr(agent, "_last_compression_attempt_recorded", False)): + attempt_in_place = getattr(agent, "_last_compression_attempt_in_place", None) + if attempt_in_place is True: + return list(messages) + if attempt_in_place is False: + return None + return previous_history if bool(getattr(agent, "_last_compaction_in_place", False)): return list(messages) return None @@ -780,6 +1040,7 @@ _SYNTHETIC_USER_FLAGS = ( "_empty_recovery_synthetic", "_verification_stop_synthetic", "_pre_verify_synthetic", + "_dropped_toolcall_nudge", ) @@ -806,6 +1067,37 @@ def _is_real_user_message(message: Any) -> bool: return not ContextCompressor._is_synthetic_compression_user_turn(message) +def _strip_stale_todo_snapshot(content: Any) -> Any: + """Remove a previously merged todo-snapshot block from message content. + + Snapshot merges (see the injection site in ``compress_context``) always + append the block at the end of the trailing user turn, so a surviving + header marks stale todo state from an earlier compaction boundary. + Stripping before re-injection keeps repeated boundaries from + accumulating outdated snapshots (#26981). + """ + from tools.todo_tool import TODO_INJECTION_HEADER + + if isinstance(content, str): + idx = content.find(TODO_INJECTION_HEADER) + if idx == -1: + return content + return content[:idx].rstrip() + if isinstance(content, list): + return [ + part + for part in content + if not ( + isinstance(part, dict) + and part.get("type") == "text" + and str(part.get("text") or "") + .lstrip() + .startswith(TODO_INJECTION_HEADER) + ) + ] + return content + + def _merge_anchor_into_user_message(target: dict, anchor: dict) -> None: """Fold the human anchor into an existing user-role scaffolding turn. @@ -975,6 +1267,7 @@ def compress_context( focus_topic: Optional[str] = None, force: bool = False, defer_context_engine_notification: bool = False, + commit_fence: Optional[CompressionCommitFence] = None, ) -> Tuple[list, str]: """Compress conversation context and split the session in SQLite. @@ -994,6 +1287,9 @@ def compress_context( callers use the default ``False``. defer_context_engine_notification: Delay the existing context-engine hook until a manual host commits its outer history transaction. + commit_fence: Optional cooperative fence for executor callers that + may time out. It prevents a late worker from mutating session state + after its caller has moved on. Returns: ``(compressed_messages, new_system_prompt)`` tuple. When @@ -1008,6 +1304,21 @@ def compress_context( ): raise RuntimeError("a compression notification is already pending") + # ``conversation_history_after_compression()`` needs the latest attempt's + # outcome, while ``_last_compaction_in_place`` remains the run-level signal + # read by gateway callers. ``None`` means this attempt aborted or made no + # boundary, so the previous flush baseline remains authoritative. + agent._last_compression_attempt_recorded = True + agent._last_compression_attempt_in_place = None + # Clear the lock-skip signal at the VERY TOP, before the codex route and + # the breaker gates below can early-return (per-attempt state rule, + # #58630/#69853). A stale ``True``/holder value from a prior lock-skip + # must never make a later breaker/codex no-op look like lock contention + # to the automatic-path consumers (compression_deferred, #49874) — the + # second clear before lock acquisition below stays for the same reason + # it was added in #69870 and is simply idempotent now. + agent._compression_skipped_due_to_lock = None + _attempt_started_at = time.monotonic() _attempt_id = uuid.uuid4().hex _trigger_source = "manual" if force else "auto" @@ -1030,14 +1341,26 @@ def compress_context( # the app server does not expose its native summary prompt, so there is no # truthful injection point for ``on_pre_compress()`` return text here. if getattr(agent, "api_mode", None) == "codex_app_server": - return _compress_context_via_codex_app_server( - agent, - messages, - system_message, - approx_tokens=approx_tokens, - task_id=task_id, - force=force, - ) + _codex_fence_entered = False + if commit_fence is not None: + _codex_fence_entered = commit_fence.begin_commit() + if not _codex_fence_entered: + existing_prompt = getattr(agent, "_cached_system_prompt", None) + if not existing_prompt: + existing_prompt = agent._build_system_prompt(system_message) + return messages, existing_prompt + try: + return _compress_context_via_codex_app_server( + agent, + messages, + system_message, + approx_tokens=approx_tokens, + task_id=task_id, + force=force, + ) + finally: + if _codex_fence_entered: + commit_fence.finish_commit() # Every automatic entrypoint must honor compressor-owned cooldown and # breaker state. Gateway hygiene constructs a fresh AIAgent, so the @@ -1078,8 +1401,11 @@ def compress_context( # parent_session_id child, no # `name #N` renumber, no contextvar/env/logging re-sync, no memory/context- # engine session-switch. The conversation keeps one durable id for life, - # eliminating the session-rotation bug cluster. Default False during rollout. - in_place = bool(getattr(agent, "compression_in_place", False)) + # eliminating the session-rotation bug cluster. Default True (2107b86024). + # Default True matches DEFAULT_CONFIG / #38763. A missing attribute must + # NOT fall back to rotation mode — that re-enables the pre-lease drift + # path and can wedge busy sessions that never set the flag. + in_place = bool(getattr(agent, "compression_in_place", True)) # Set True once the in-place DB write actually completes (the DB block can # raise and skip it). Surfaced to the gateway via agent._last_compaction_in_place. compacted_in_place = False @@ -1089,7 +1415,20 @@ def compress_context( f"{approx_tokens:,}" if approx_tokens else "unknown", agent.model, focus_topic, ) - agent._emit_status(COMPACTION_STATUS) + _compaction_status = COMPACTION_STATUS + if not force: + _compaction_status = automatic_compaction_status_message( + agent.context_compressor, + phase="compress", + default_message=_compaction_status, + approx_tokens=approx_tokens, + message_count=_pre_msg_count, + model=agent.model, + focus_topic=focus_topic, + ) + _compaction_status_emitted = bool(_compaction_status) + if _compaction_status: + agent._emit_status(_compaction_status) _compaction_done_emitted = False def _complete_compaction_lifecycle() -> None: @@ -1097,7 +1436,11 @@ def compress_context( if _compaction_done_emitted: return _compaction_done_emitted = True - _emit_compaction_done(agent) + # A suppressed start (quiet context engine) opened no visible + # compaction phase — emit no terminal edge either. Failure warnings + # go through agent._emit_warning and are never suppressed here. + if _compaction_status_emitted: + _emit_compaction_done(agent) # ── Compression lock ──────────────────────────────────────────────── # Atomic, state.db-backed lock per session_id. Without this, two @@ -1134,6 +1477,12 @@ def compress_context( _try_acquire_lock = None _lock_lookup_error: Optional[Exception] = None _legacy_session_db_without_lock_api = False + # Clear any stale lock-skip signal from a prior call so this call's + # outcome alone determines what callers see. Without this an + # auto-compress lock-skip followed by a successful manual /compress + # would falsely report "Compression already in progress" and discard + # the compression results. + agent._compression_skipped_due_to_lock = None if _lock_db is not None: try: _legacy_session_db_without_lock_api = _lock_api_is_absent_on_session_db( @@ -1221,6 +1570,11 @@ def compress_context( _lock_sid, existing, ) _lock_holder = None # don't release a lock we don't own + # Signal to callers that this no-op is due to a concurrent lock, + # not a genuine "nothing to compress" or aux-model failure. + # Manual /compress callers can surface a clear status message + # instead of the misleading "No changes from compression" text. + agent._compression_skipped_due_to_lock = existing or True # Surface to the user once — quiet for downstream auto-compress loops if getattr(agent, "_last_compression_lock_warning_sid", None) != _lock_sid: agent._last_compression_lock_warning_sid = _lock_sid @@ -1258,6 +1612,8 @@ def compress_context( if _lock_released: return _lock_released = True + if getattr(agent, "_active_compression_lock_holder", None) == _lock_holder: + agent._active_compression_lock_holder = None if _lock_refresher is not None: try: _lock_refresher.stop() @@ -1269,6 +1625,9 @@ def compress_context( except Exception as _rel_err: logger.debug("compression lock release failed: %s", _rel_err) + if _lock_holder is not None: + agent._active_compression_lock_holder = _lock_holder + # A delayed contender can acquire the parent lock after the winning path # has released it and completed rotation. The lock serializes work but does # not by itself prove that this stale agent still owns a live parent. @@ -1291,15 +1650,25 @@ def compress_context( _existing_sp = agent._build_system_prompt(system_message) return messages, _existing_sp if _parent_already_rotated: - logger.info( - "compression skipped: session=%s was already rotated by " - "another compression path", - _lock_sid, + recovered_messages = _adopt_live_compression_child( + agent, _lock_db, _lock_sid ) _release_lock() _existing_sp = getattr(agent, "_cached_system_prompt", None) if not _existing_sp: _existing_sp = agent._build_system_prompt(system_message) + if recovered_messages is not None: + logger.warning( + "compression recovery: stale session=%s adopted live child=%s", + _lock_sid, + agent.session_id, + ) + return recovered_messages, _existing_sp + logger.warning( + "compression skipped: session=%s was already rotated by " + "another compression path, but no unique live child could be adopted", + _lock_sid, + ) return messages, _existing_sp # The agent may have been constructed before another path completed an @@ -1333,6 +1702,47 @@ def compress_context( ) _lock_refresher.start() + # The caller's history snapshot predates lease acquisition. Reload the + # durable parent after the lease is live; MORE durable rows than the + # snapshot carries means a frontend/background writer committed a turn + # in that window, so publishing from this snapshot would omit it. + # Deliberately a LENGTH check, not content equality: in-memory + # mutation of past turns is legal (multimodal compression, retry + # history replacement, think-tag stripping), and a content-equality + # abort would permanently wedge compression on such sessions — the + # #14694 failure shape. + # Rotation-only: in-place compaction (archive_and_compact) is + # non-destructive — pre-compaction rows are soft-archived (active=0, + # compacted=1), stay searchable and recoverable, so snapshot/durable + # drift cannot lose data there and must not abort compaction. + # + # When durable DID grow, ADOPT it and continue rather than aborting. + # Aborting returned the stale snapshot unchanged, so busy sessions + # (memory review / shared session_id writers) stayed permanently + # behind the DB: every /compress and auto-compress saw + # "changed before lease acquisition", surfaced as the misleading + # "No changes from compression", and never reclaimed tokens. + if not in_place and _lock_db is not None and _lock_sid: + durable_loader = getattr( + type(_lock_db), "get_messages_as_conversation", None + ) + if callable(durable_loader): + durable_parent = durable_loader(_lock_db, _lock_sid) + if isinstance(durable_parent, list) and len(durable_parent) > len(messages): + logger.info( + "compression: session=%s grew before lease " + "(%d → %d msgs); adopting durable snapshot", + _lock_sid, + len(messages), + len(durable_parent), + ) + messages = durable_parent + _pre_msg_count = len(messages) + # Token estimate was for the stale snapshot; clear it so + # the compressor re-derives from the adopted transcript + # instead of under-counting the newly visible rows. + approx_tokens = 0 + # Notify external memory provider before compression discards context. # The provider's on_pre_compress() may return a string of insights it # wants surfaced inside the compression summary; capture and forward it @@ -1373,7 +1783,29 @@ def compress_context( messages_before_compression = copy.deepcopy(messages) _activity_heartbeat = _CompressionActivityHeartbeat(agent).start() - compressed = compress_fn(messages, **compress_kwargs) + # Publish forward progress to the commit fence while the summary LLM + # call streams. Async hosts (gateway session hygiene) poll + # ``commit_fence.seconds_since_progress()`` to extend their deadline + # while tokens are moving — so a SLOW summary model is only killed + # when it is actually silent, not merely thorough. The hook is + # thread-local and the compress call is synchronous on this thread, + # so it cannot leak into unrelated auxiliary calls. + # + # Fenceless callers (CLI /compress, in-loop auto-compress) install a + # no-op hook: nobody polls their progress, but an ACTIVE hook is what + # switches the summary call onto the streamed path — giving every + # compression path the same two guarantees: the configured timeout + # acts on inactivity (slow models finish), and a byte-trickling + # provider that keeps the connection alive forever is cut off at the + # streamed total ceiling (see _aux_stream_total_ceiling) instead of + # outliving the SDK's inactivity timeout indefinitely. + from agent.auxiliary_client import aux_progress_hook + _progress_hook = ( + commit_fence.touch_progress if commit_fence is not None + else (lambda: None) + ) + with aux_progress_hook(_progress_hook): + compressed = compress_fn(messages, **compress_kwargs) except BaseException as _compress_exc: # ANY exception after lock acquisition — memory hook, capability # inspection, engine lookup, or compress() — must release the lock so @@ -1394,6 +1826,7 @@ def compress_context( if _activity_heartbeat is not None: _activity_heartbeat.stop("context compression completed") + _commit_fence_entered = False try: # Capture boundary quality before session-rotation callbacks run. Built-in # and plugin lifecycle hooks may reset per-session compressor fields while @@ -1481,6 +1914,28 @@ def compress_context( _release_lock() return messages, _existing_sp + if commit_fence is not None: + _commit_fence_entered = commit_fence.begin_commit() + if not _commit_fence_entered: + logger.info( + "Compression commit cancelled before session mutation " + "(session=%s).", + agent.session_id or "none", + ) + agent._last_compaction_in_place = False + _existing_sp = getattr(agent, "_cached_system_prompt", None) + if not _existing_sp: + _existing_sp = agent._build_system_prompt(system_message) + _emit_compression_attempt_telemetry( + agent, + started_at=_attempt_started_at, + commit_status="aborted", + split_status="aborted", + failure_class="commit_fence_cancelled", + ) + _release_lock() + return messages, _existing_sp + summary_error = getattr(agent.context_compressor, "_last_summary_error", None) if summary_error: if getattr(agent, "_last_compression_summary_warning", None) != summary_error: @@ -1509,11 +1964,54 @@ def compress_context( todo_snapshot = agent._todo_store.format_for_injection() if todo_snapshot: - compressed.append({ - "role": "user", - "content": todo_snapshot, - "_todo_snapshot_synthetic": True, - }) + # Fold the snapshot into a trailing REAL user message so + # compression never introduces a synthetic user/user pair. Any + # snapshot merged at an earlier boundary is stripped first so + # repeated compactions refresh rather than accumulate todo state + # (#26981). Scaffolding tails (continuation marker, summary + # handoff, a bare stale snapshot row) must never absorb the + # snapshot: merging would upgrade them to "real user" evidence + # and break zero-user provenance (#69292), so those keep the + # flagged standalone append and the real-user preservation pass + # continues to see todo scaffolding, not human intent. + from agent.context_compressor import _append_text_to_content + + merged = False + _tail = ( + compressed[-1] + if compressed and isinstance(compressed[-1], dict) + else None + ) + if _tail is not None and _tail.get("role") == "user": + _stripped = _strip_stale_todo_snapshot(_tail.get("content")) + _probe = { + key: value for key, value in _tail.items() if key != "content" + } + _probe["content"] = _stripped + if _is_real_user_message(_probe): + _snapshot_text = ( + f"\n\n{todo_snapshot}" + if isinstance(_stripped, str) and _stripped + else todo_snapshot + ) + _tail["content"] = _append_text_to_content( + _stripped, _snapshot_text + ) + merged = True + elif _stripped != _tail.get("content") and not _message_text( + {"role": "user", "content": _stripped} + ).strip(): + # The tail was nothing but an earlier snapshot row — + # refresh it in place instead of stacking a duplicate. + _tail["content"] = todo_snapshot + _tail["_todo_snapshot_synthetic"] = True + merged = True + if not merged: + compressed.append({ + "role": "user", + "content": todo_snapshot, + "_todo_snapshot_synthetic": True, + }) _ensure_compressed_has_user_turn(messages, compressed) cached_system_prompt = agent._cached_system_prompt @@ -1535,6 +2033,20 @@ def compress_context( ): new_system_prompt = cached_system_prompt agent._cached_system_prompt = cached_system_prompt + # _invalidate_system_prompt() above also cleared the + # cross-session-stable prefix marker boundary. The kept prompt + # is byte-identical, so reconstruct the stable tier and reuse + # it ONLY when the kept prompt still literally starts with it + # (same startswith gate as the restore path); otherwise the + # request layer falls back to the legacy single-breakpoint + # layout with the prompt bytes untouched. + from agent.system_prompt import reconstruct_static_prefix + + reconstruct_static_prefix( + agent, + system_message=system_message, + log_label="compression keep-prompt", + ) else: new_system_prompt = agent._build_system_prompt(system_message) agent._cached_system_prompt = new_system_prompt @@ -1611,81 +2123,54 @@ def compress_context( ) except Exception: pass # best-effort — don't block compression on a flush error - # Propagate title to the new session with auto-numbering + # Publish parent closure + child row + compacted handoff in + # one transaction. No reader can observe a missing/empty child. + # The rotation child must stay on the parent's profile — + # mirror _ensure_db_session's stamp ("default" persists as + # NULL). publish_compression_child additionally COALESCEs + # from the parent row, covering app-global remote sessions + # whose thread lacks the HERMES_HOME context. + try: + from hermes_cli.profiles import get_active_profile_name + + _profile_for_child = get_active_profile_name() + if _profile_for_child == "default": + _profile_for_child = None + except Exception: + _profile_for_child = None old_title = agent._session_db.get_session_title(agent.session_id) - agent._session_db.end_session(agent.session_id, "compression") old_session_id = agent.session_id - agent.session_id = f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:6]}" - # Ordering contract: the agent thread updates the contextvar here; - # the gateway propagates to SessionEntry after run_in_executor returns. + new_session_id = ( + f"{datetime.now().strftime('%Y%m%d_%H%M%S')}_" + f"{uuid.uuid4().hex[:6]}" + ) + agent._session_db.publish_compression_child( + parent_session_id=old_session_id, + child_session_id=new_session_id, + source=agent.platform + or os.environ.get("HERMES_SESSION_SOURCE", "cli"), + model=agent.model, + model_config=agent._session_init_model_config, + system_prompt=new_system_prompt, + messages=compressed, + cwd=getattr(agent, "working_directory", None), + profile_name=_profile_for_child, + compression_lock_holder=_lock_holder, + require_compression_lease=_lock_holder is not None, + ) + agent.session_id = new_session_id try: from gateway.session_context import set_current_session_id set_current_session_id(agent.session_id) except Exception: os.environ["HERMES_SESSION_ID"] = agent.session_id - # The gateway/tools session context (ContextVar + env) and the - # logging session context are SEPARATE mechanisms. The call above - # moves the former; the ``[session_id]`` tag on log lines comes - # from ``hermes_logging._session_context`` (set once per turn in - # conversation_loop.py). Without this, post-rotation log lines in - # the same turn keep the STALE old id while the message/DB/gateway - # state carry the new one — breaking log correlation exactly at the - # compaction boundary (see #34089). Guarded separately so a logging - # failure can never regress the routing update above. try: from hermes_logging import set_session_context set_session_context(agent.session_id) except Exception: pass - agent._session_db_created = False - try: - agent._session_db.create_session( - session_id=agent.session_id, - source=agent.platform or os.environ.get("HERMES_SESSION_SOURCE", "cli"), - model=agent.model, - model_config=agent._session_init_model_config, - parent_session_id=old_session_id, - ) - except Exception as _cs_err: - # The child row could not be created (e.g. FK constraint, - # contended write). Previously the outer handler simply - # warned and let the agent continue on the NEW id — which - # has no row in state.db, producing an orphan: the parent - # is ended, the child is never indexed, and every - # subsequent message is attributed to a session that - # doesn't exist (#33906/#33907). Roll the live id back to - # the parent so the conversation stays attached to a real, - # indexed session instead of a phantom. - logger.warning( - "Compression child session create failed (%s) — " - "rolling back to parent session %s to avoid an orphan.", - _cs_err, old_session_id, - ) - agent.session_id = old_session_id - try: - from gateway.session_context import set_current_session_id - set_current_session_id(agent.session_id) - except Exception: - os.environ["HERMES_SESSION_ID"] = agent.session_id - try: - from hermes_logging import set_session_context - set_session_context(agent.session_id) - except Exception: - pass - # Re-open the parent: it was ended above, but we're - # continuing on it, so it must not stay closed. - try: - agent._session_db.reopen_session(old_session_id) - except Exception: - pass - old_session_id = None # no rotation happened - # The parent row already exists in state.db, so mark the - # session as created — _ensure_db_session would otherwise - # retry a (harmless INSERT OR IGNORE) create next turn. - agent._session_db_created = True - raise agent._session_db_created = True split_status = "rotated_committed" # Carry a persistent /goal onto the continuation session. @@ -1705,18 +2190,14 @@ def compress_context( except (ValueError, Exception) as e: logger.debug("Could not propagate title on compression: %s", e) - # Shared post-write steps (both modes target agent.session_id, which - # in-place keeps and rotation has already reassigned to the new id): - # refresh the stored system prompt and reset the flush cursor so the - # next turn re-bases its append diff. - agent._session_db.update_system_prompt(agent.session_id, new_system_prompt) + # In-place mode still updates/replaces the current row here. + # Rotation already published prompt + compacted handoff atomically. if in_place: + agent._session_db.update_system_prompt( + agent.session_id, new_system_prompt + ) agent._last_flushed_db_idx = 0 else: - # A headless turn can be killed before its finalizer. Persist - # the rotated child's compacted handoff at the boundary so - # the new session is immediately resumable. - agent._session_db.replace_messages(agent.session_id, compressed) agent._last_flushed_db_idx = len(compressed) agent._flushed_db_message_session_id = agent.session_id agent._flushed_db_message_ids = { @@ -1726,7 +2207,22 @@ def compress_context( } _session_commit_succeeded = True except Exception as e: - split_status = "aborted" if locals().get("old_session_id") is None and not in_place else "failed_not_indexed" + if ( + not in_place + and locals().get("old_session_id") + and agent.session_id == old_session_id + ): + # Atomic publication failed (including lease loss): keep the + # parent live and discard the stale compacted snapshot. + old_session_id = None + messages[:] = copy.deepcopy(messages_before_compression) + compressed = messages + _compression_made_progress = False + split_status = ( + "aborted" + if locals().get("old_session_id") is None and not in_place + else "failed_not_indexed" + ) # If the rotation rolled back to the parent (orphan-avoidance # above), agent.session_id is the still-indexed parent and # old_session_id was cleared — so this is recovery, not an @@ -1823,6 +2319,7 @@ def compress_context( # via a rotation-independent flag. The gateway uses this — NOT an # id-change diff — to re-baseline transcript handling (history_offset=0 + # rewrite on the same id) when compaction happened in place. See #38763. + agent._last_compression_attempt_in_place = compacted_in_place agent._last_compaction_in_place = compacted_in_place # Keep the post-compression rough estimate for diagnostics, but do not @@ -1888,7 +2385,11 @@ def compress_context( # file dedup) ran. A concurrent path that wakes up the moment we # release will see the NEW session_id in state.db / SessionEntry and # acquire on that — no race against our just-finished work. - _release_lock() + try: + _release_lock() + finally: + if _commit_fence_entered: + commit_fence.finish_commit() def _compress_context_via_codex_app_server( @@ -2220,16 +2721,28 @@ def try_shrink_image_parts_in_messages( media_type = "image/jpeg" return f"data:{media_type};base64,{data}" - def _write_data_url_to_source(source: dict, data_url: str) -> None: + def _write_data_url_to_source(source: dict, data_url: str) -> dict: + """Return a NEW source dict carrying the re-encoded payload. + + Copy-on-write: content parts on the per-call ``api_messages`` list may + be shared references into the persistent conversation history (the + per-message copy is shallow, and cache decoration only deep-copies the + marked messages). Mutating the existing dict would rewrite the stored + transcript with the degraded image — so the caller replaces the part, + never edits it in place. + """ header, _, data = data_url.partition(",") media_type = "image/jpeg" if header.startswith("data:"): candidate = header[len("data:"):].split(";", 1)[0].strip() if candidate.startswith("image/"): media_type = candidate - source["type"] = "base64" - source["media_type"] = media_type - source["data"] = data + return { + **source, + "type": "base64", + "media_type": media_type, + "data": data, + } for msg in api_messages: if not isinstance(msg, dict): @@ -2237,7 +2750,13 @@ def try_shrink_image_parts_in_messages( content = msg.get("content") if not isinstance(content, list): continue - for part in content: + # Copy-on-write per message: never mutate part/source dicts in place — + # they can alias the stored conversation history (see + # _write_data_url_to_source). Build a replacement content list on the + # first shrunken part and reassign msg["content"] (a top-level write on + # the per-call message copy, which never reaches history). + new_content: list | None = None + for part_idx, part in enumerate(content): if not isinstance(part, dict): continue ptype = part.get("type") @@ -2246,7 +2765,12 @@ def try_shrink_image_parts_in_messages( url = _source_to_data_url(source) resized, unshrinkable = _shrink_data_url(url or "") if resized and isinstance(source, dict): - _write_data_url_to_source(source, resized) + if new_content is None: + new_content = list(content) + new_content[part_idx] = { + **part, + "source": _write_data_url_to_source(source, resized), + } changed_count += 1 elif unshrinkable: unshrinkable_oversized += 1 @@ -2260,17 +2784,26 @@ def try_shrink_image_parts_in_messages( url = image_value.get("url", "") resized, unshrinkable = _shrink_data_url(url) if resized: - image_value["url"] = resized + if new_content is None: + new_content = list(content) + new_content[part_idx] = { + **part, + "image_url": {**image_value, "url": resized}, + } changed_count += 1 elif unshrinkable: unshrinkable_oversized += 1 elif isinstance(image_value, str): resized, unshrinkable = _shrink_data_url(image_value) if resized: - part["image_url"] = resized + if new_content is None: + new_content = list(content) + new_content[part_idx] = {**part, "image_url": resized} changed_count += 1 elif unshrinkable: unshrinkable_oversized += 1 + if new_content is not None: + msg["content"] = new_content if changed_count: logger.info( diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py index e8034d32652b..5d96b8e65127 100644 --- a/agent/conversation_loop.py +++ b/agent/conversation_loop.py @@ -22,9 +22,7 @@ import os import random import re import ssl -import threading import time -import uuid from typing import Any, Dict, List, Optional from agent.codex_responses_adapter import _summarize_user_message_for_log @@ -34,11 +32,12 @@ from agent.conversation_compression import ( COMPRESSION_RETRY_TOKENS_STATUS_TEMPLATE, COMPRESSION_RETRY_TOO_LARGE_STATUS_TEMPLATE, PRE_API_COMPRESSION_STATUS_TEMPLATE, + compression_skipped_due_to_lock, conversation_history_after_compression, ) +from agent.context_engine import automatic_compaction_status_message from agent.display import KawaiiSpinner from agent.error_classifier import FailoverReason, classify_api_error -from agent.iteration_budget import IterationBudget from agent.turn_context import ( _compression_warrants_another_preflight_pass, build_turn_context, @@ -46,6 +45,7 @@ from agent.turn_context import ( reanchor_current_turn_user_idx, ) from agent.turn_retry_state import TurnRetryState +from agent.runtime_cwd import resolve_agent_cwd from agent.message_sanitization import ( close_interrupted_tool_sequence, _repair_tool_call_arguments, @@ -69,7 +69,10 @@ from agent.model_metadata import ( save_context_length, ) from agent.process_bootstrap import _install_safe_stdio -from agent.prompt_caching import apply_anthropic_cache_control +from agent.prompt_caching import ( + apply_anthropic_cache_control, + strip_anthropic_cache_control, +) from agent.retry_utils import ( adaptive_rate_limit_backoff, is_zai_coding_overload_error, @@ -115,22 +118,44 @@ def _apply_active_turn_redirect(agent: Any, messages: List[Dict[str, Any]], text Incomplete provider reasoning blocks are not valid replay items (Anthropic signs them; Responses reasoning items require their following output). - Preserve only what Hermes actually displayed, demoted to ordinary text, - then add the correction as a real user message. This keeps role alternation + Preserve only the *visible* response text, demoted to ordinary text, then + add the correction as a real user message. This keeps role alternation valid and leaves every previously cached message byte-for-byte unchanged. + + INVARIANT — raw chain-of-thought must never be serialized into replayable + message content. Streamed reasoning is display-only state: it may be shown + live, but it does not re-enter the transcript as assistant (or user) text. + An assistant turn whose content inlines its own chain-of-thought reads to + Anthropic's output classifier as reasoning-injection/prefill jailbreak, + and because the poisoned checkpoint is persisted and replayed on every + subsequent call, the session dies permanently with deterministic + "Provider returned an empty response" storms that no retry, nudge, or + empty-recovery branch can escape (July 2026: four sessions bricked this + way; every reasoning-free checkpoint that week was untouched — same + mechanism as the ~/.hermes/prefill.json incident, 20/20 blocked with + assistant-exposed CoT vs 0/20 without). The interrupted reasoning was + incomplete by definition; the model regenerates it on the retried turn. + If a future path needs to preserve interrupted thinking, carry it in a + provider-gated reasoning *field*, never in content. + INVARIANT — the scaffolding is provider-replay text, not transcript text. + ``[This response was interrupted by a user correction.]`` and its + ``Visible response before the interruption:`` header exist so the MODEL + understands its own reply was cut off. They are not prose the user wrote + or the agent said. Persisting them into ``content`` painted the raw + machinery as an assistant bubble on every reload (and merged it into the + preceding tool-call bubble), which is what made a steered transcript + unreadable. Carry the scaffolded form in the ``api_content`` sidecar -- + the exact bytes replayed to the provider -- and keep ``content`` clean. + When nothing was on screen there is no clean form at all, so the row is + marked ``display_kind="hidden"``: still replayed to the model, dropped by + every transcript surface (desktop, TUI, CLI resume), exactly like the + compaction-reference rows. """ - reasoning = str( - getattr(agent, "_current_streamed_reasoning_text", "") or "" - ).strip() visible = agent._strip_think_blocks( getattr(agent, "_current_streamed_assistant_text", "") or "" ).strip() checkpoint_parts = ["[This response was interrupted by a user correction.]"] - if reasoning: - checkpoint_parts.extend( - ["Reasoning shown before the interruption:", reasoning] - ) if visible: checkpoint_parts.extend( ["Visible response before the interruption:", visible] @@ -147,13 +172,25 @@ def _apply_active_turn_redirect(agent: Any, messages: List[Dict[str, Any]], text f"{checkpoint}\n\n" f"{text}" ) - messages.append({"role": "user", "content": correction}) + # Transcript shows the user's own words; the provider replays the + # scaffolded form so it still sees the interrupted context. + messages.append( + {"role": "user", "content": text, "api_content": correction} + ) else: - messages.append({"role": "assistant", "content": checkpoint}) + entry: Dict[str, Any] = { + "role": "assistant", + "content": visible or checkpoint, + "api_content": checkpoint, + } + if not visible: + # Nothing reached the screen — this row carries no assistant prose + # at all, only the cut-off notice for the model. + entry["display_kind"] = "hidden" + messages.append(entry) messages.append({"role": "user", "content": text}) agent._current_streamed_assistant_text = "" - agent._current_streamed_reasoning_text = "" agent._stream_needs_break = True @@ -434,6 +471,20 @@ def _restore_or_build_system_prompt(agent, system_message, conversation_history) # Continuing session — reuse the exact system prompt from the # previous turn so the Anthropic cache prefix matches. agent._cached_system_prompt = stored_prompt + # Reconstruct the cross-session-stable prefix for the early cache + # breakpoint. The static prefix is not persisted (only the full + # prompt is), so gateway surfaces that build a fresh AIAgent per + # turn would otherwise lose the two-block system layout after the + # first turn — flip-flopping the wire shape mid-conversation and + # silently degrading to the legacy single-breakpoint layout. + # + # ``reconstruct_static_prefix`` gates on ``_use_prompt_caching`` (so + # non-Anthropic routes skip the rebuild), applies the startswith + # safety gate (stored prompt bytes are never rewritten), and + # fails open to the legacy cache layout. + from agent.system_prompt import reconstruct_static_prefix + + reconstruct_static_prefix(agent, system_message=system_message) return if stored_prompt: stored_state = "stale_runtime" @@ -466,7 +517,7 @@ def _restore_or_build_system_prompt(agent, system_message, conversation_history) # session is created (not on continuation). Plugins can use this # to initialise session-scoped state (e.g. warm a memory cache). try: - from hermes_cli.plugins import invoke_hook as _invoke_hook + from hermes_cli.lifecycle import invoke_hook as _invoke_hook _invoke_hook( "on_session_start", session_id=agent.session_id, @@ -506,9 +557,17 @@ def _restore_or_build_system_prompt(agent, system_message, conversation_history) def _stored_prompt_matches_runtime(agent, prompt: str) -> bool: - """Return False when the persisted Model/Provider lines are stale.""" + """Return False when the persisted runtime-identity lines are stale.""" def line_value(label: str) -> str: + """Last matching line wins. + + Safe ONLY for fields emitted in the volatile tier at the very END of + the prompt (Model / Provider / Platform). User-supplied project + context (AGENTS.md / CLAUDE.md / .cursorrules) is embedded in the + middle context tier, so a last-match scan lets project prose shadow + any field emitted EARLIER — see ``host_info_value``. + """ prefix = f"{label}:" value = "" for line in prompt.splitlines(): @@ -516,6 +575,32 @@ def _stored_prompt_matches_runtime(agent, prompt: str) -> bool: value = line[len(prefix):].strip() return value + def host_info_value(label: str) -> str: + """Read a field from the prompt's own host-info block. + + The host-info block (``build_environment_hints``) sits in the STABLE + tier, ahead of the embedded project context files. A bare scan of the + whole prompt would therefore match a user's ``AGENTS.md`` that merely + contains a line starting with the same label, comparing runtime state + against project prose. That mismatch never clears, so the check would + reject the stored prompt on EVERY turn — rebuilding the system prompt + each message and destroying the prefix cache for the whole session, + which is far worse than the staleness this function guards against. + + Anchor on the ``User home directory:`` line that immediately precedes + the working-directory line in that block, and take the FIRST such + occurrence, so only Hermes' own emitted block can satisfy the read. + """ + prefix = f"{label}:" + lines = prompt.splitlines() + for idx, line in enumerate(lines): + if not line.startswith("User home directory:"): + continue + for candidate in lines[idx + 1: idx + 4]: + if candidate.startswith(prefix): + return candidate[len(prefix):].strip() + return "" + stored_model = line_value("Model") current_model = str(getattr(agent, "model", "") or "").strip() if stored_model and current_model and stored_model != current_model: @@ -526,6 +611,24 @@ def _stored_prompt_matches_runtime(agent, prompt: str) -> bool: if stored_provider and current_provider and stored_provider != current_provider: return False + # Detect cwd drift: if the stored prompt was built in a different working + # directory, reuse would silently inject a stale path into the prefix cache. + # Compare against resolve_agent_cwd() — the SAME resolver used to build the + # prompt — so gateway/TUI sessions that set TERMINAL_CWD are not falsely + # rejected (they would always differ from the launch dir's os.getcwd()). + stored_cwd = host_info_value("Current working directory") + if stored_cwd: + if stored_cwd != str(resolve_agent_cwd()): + return False + + # Detect runtime-surface drift: the stored prompt records which platform it + # was built for (e.g. "desktop" vs "cli"). Reusing a desktop-built prompt on + # a terminal session (or vice versa) would inject the wrong runtime hints. + stored_platform = line_value("Platform") + current_platform = str(getattr(agent, "platform", "") or "").strip() + if stored_platform and current_platform and stored_platform != current_platform: + return False + return True @@ -639,6 +742,90 @@ def _content_policy_blocked_result( } +def _compression_deferred_result( + agent, + messages: List[Dict], + api_call_count: int, +) -> Dict[str, Any]: + """Build the soft turn result for a lock-contended compression defer. + + Another path (a sibling turn, a background review fork, a manual + ``/compress``) holds this session's compression lock, so every + compression pass this turn no-oped and the request still does not fit. + This is a TEMPORARY condition — the lock winner is actively shrinking + the same session — so the turn must end as a soft defer + (``compression_deferred``), never as ``compression_exhausted``: the + gateway auto-resets (wipes) the session on exhaustion (#9893/#35809), + which would destroy a session that the concurrent compressor is about + to make healthy again. + + ``failed`` stays False so the gateway persists the user turn (transient + branch) and retry-next-message semantics apply. + """ + holder = getattr(agent, "_compression_skipped_due_to_lock", None) + logger.info( + "turn deferred: compression lock held by another path " + "(session=%s holder=%s) — not counting as compression exhaustion", + agent.session_id or "none", + holder if isinstance(holder, str) else "unconfirmed", + ) + try: + agent._flush_status_buffer() + except Exception: + pass + _final = ( + "Context compression is already running for this session. " + "Please retry in a moment — your next message will be processed " + "once the concurrent compression finishes." + ) + return { + "final_response": _final, + "messages": messages, + "completed": False, + "api_calls": api_call_count, + "error": _final, + "partial": True, + "failed": False, + "compression_deferred": True, + "session_id": agent.session_id, + } + + +def _rewrite_system_content_blocks(system_message: dict, effective: str) -> bool: + """Rewrite a cache-decorated system message in place, keeping its blocks. + + ``apply_anthropic_cache_control`` runs once per call block, *before* the + retry loop, and splits the system prompt into ``[static prefix, volatile + tail]`` text blocks carrying the cache_control breakpoints. Assigning a bare + string over that list drops both breakpoints, so the failover retry ships + the whole system prompt uncached and re-bills it in full. + + ``rewrite_prompt_model_identity`` only touches the LAST ``Model:`` / + ``Provider:`` lines, and those live in the volatile tail — so the static + prefix stays byte-identical and its cache entry keeps matching. Returns + False when the shape is not one we can safely patch, so the caller falls + back to the plain-string assignment. + """ + content = system_message.get("content") + if not isinstance(content, list) or not content: + return False + if not all( + isinstance(part, dict) and part.get("type") == "text" for part in content + ): + return False + if len(content) == 1: + content[0]["text"] = effective + return True + if len(content) == 2: + head = content[0].get("text") or "" + if head and effective.startswith(head): + tail = effective[len(head):] + if tail: + content[1]["text"] = tail + return True + return False + + def _sync_failover_system_message(agent, api_messages, active_system_prompt): """Refresh the in-flight system message after a provider failover. @@ -661,10 +848,239 @@ def _sync_failover_system_message(agent, api_messages, active_system_prompt): effective = sp if agent.ephemeral_system_prompt: effective = (effective + "\n\n" + agent.ephemeral_system_prompt).strip() - api_messages[0]["content"] = effective + if not _rewrite_system_content_blocks(api_messages[0], effective): + api_messages[0]["content"] = effective return sp +def _ensure_cached_system_prompt_static(agent, system_message=None) -> None: + """Rebuild ``_cached_system_prompt_static`` when caching becomes active. + + Sessions restored under a cache-off primary skip the static-prefix rebuild + (gated on ``_use_prompt_caching`` at restore time). A later failover to a + cache-on provider would otherwise redecorate with ``static_system_prefix= + None`` and silently fall back to the legacy system-plus-3 layout (#72626). + + Thin wrapper over :func:`agent.system_prompt.reconstruct_static_prefix`, + which memoizes failed rebuilds so this stays cheap on the retry-loop hot + path (it runs at the top of every attempt). + """ + from agent.system_prompt import reconstruct_static_prefix + + reconstruct_static_prefix( + agent, system_message=system_message, log_label="failover redecoration" + ) + + +def _peel_moa_guidance( + messages: List[Dict[str, Any]], + guidance: Any, +) -> List[Dict[str, Any]]: + """Remove MoA reference guidance previously attached by ``_attach_reference_guidance``. + + Thin wrapper over :func:`agent.moa_loop.peel_reference_guidance` (kept + adjacent to the attach so the forward/inverse shapes evolve together). + Lazy import mirrors the module's other moa_loop touchpoints. + """ + from agent.moa_loop import peel_reference_guidance + + return peel_reference_guidance(messages, guidance) + + +def _redecorate_prompt_cache_for_provider( + agent, + api_messages: List[Dict[str, Any]], + *, + system_message=None, + moa_prepared: Optional[Dict[str, Any]] = None, +) -> tuple[List[Dict[str, Any]], Optional[Dict[str, Any]]]: + """Strip and re-apply cache_control for the *current* provider policy. + + Decoration runs once per call block before the retry loop for the primary + provider. ``try_activate_fallback`` refreshes ``_use_prompt_caching`` / + ``_use_native_cache_layout`` but the nine failover ``continue`` paths reused + the old ``api_messages`` (#72626). Mirror ``_reapply_reasoning_echo_for_provider`` + by reshaping at the top of each retry attempt. + + The source list is the mutated in-flight request (image shrink / ASCII / + reasoning_details recoveries already applied) — never a pristine + pre-decoration snapshot. MoA guidance is peeled, the base is redecorated, + then ``rebase_prepared_request`` re-attaches guidance outside the cached + span. + """ + messages: List[Dict[str, Any]] = [ + dict(m) if isinstance(m, dict) else m for m in (api_messages or []) + ] + prepared = moa_prepared + guidance = prepared.get("guidance") if isinstance(prepared, dict) else None + if guidance: + messages = _peel_moa_guidance(messages, guidance) + + strip_anthropic_cache_control(messages) + + # Direct attribute access matches the call-block decoration site — the + # flags are unconditionally initialized on AIAgent, and a getattr + # default here would mask a real init bug as silent cache-off. + if agent._use_prompt_caching: + _ensure_cached_system_prompt_static(agent, system_message=system_message) + static = getattr(agent, "_cached_system_prompt_static", None) + messages = apply_anthropic_cache_control( + messages, + cache_ttl=agent._cache_ttl, + native_anthropic=agent._use_native_cache_layout, + static_system_prefix=static if isinstance(static, str) else None, + ) + + if ( + prepared is not None + and getattr(agent, "provider", None) == "moa" + ): + # No `and guidance` here: guidance=None is a real prepared shape + # (all-references-failed / silent degraded policy builds the + # prepared request without attaching guidance), and the MoA facade + # sends prepared["messages"] — not api_kwargs["messages"] — so the + # rebase must refresh the prepared object even when there is no + # guidance to re-attach. rebase_prepared_request handles falsy + # guidance by copying the messages and skipping the attach. + completions = getattr(getattr(agent.client, "chat", None), "completions", None) + rebase = getattr(completions, "rebase_prepared_request", None) + if callable(rebase): + prepared = rebase(prepared, messages) + messages = prepared["messages"] + + return messages, prepared + + +def _apply_context_engine_selection( + agent: Any, + api_messages: List[Dict[str, Any]], + conversation_messages: List[Dict[str, Any]], + incoming_message: Optional[Dict[str, Any]], + *, + logger: Any, +) -> List[Dict[str, Any]]: + """Run the optional per-turn ``ContextEngine.select_context()`` hook. + + Returns the (possibly replaced) request message list. The hook is for + context *selection / routing* (retrieval, topic routing, role switching), + which is distinct from compression and fires every turn independent of + ``should_compress()``. + + Fail-open by design: a missing hook, any exception, or an invalid return + value yields the unmodified ``api_messages``. The result is request-only — + persisted conversation history is never mutated here. + """ + engine = getattr(agent, "context_compressor", None) + if engine is None or not hasattr(engine, "select_context"): + return api_messages + + # Skip the no-op base implementation so non-implementing engines — + # including the built-in ContextCompressor — pay nothing per request: + # no history copies below, no call. ``hasattr`` alone is not enough, + # because the ABC defines a default ``select_context`` that every engine + # inherits. Mirrors the base-method short-circuit in + # ``_notify_context_engine_turn_complete``. Lazy import avoids any import + # cycle with agent.context_engine. + try: + from agent.context_engine import ContextEngine as _CE + if getattr(engine.select_context, "__func__", None) is _CE.select_context: + return api_messages + except Exception: + pass + + session_label = getattr(agent, "session_id", None) or "-" + # Pass shallow copies of the reference-only inputs so an engine that + # mutates them in place cannot alter persisted transcript state. Only + # ``request_messages`` (the per-call request list) is meant to be acted on, + # and it may be replaced wholesale via the return value — never mutated in + # place either. ``conversation_messages`` / ``incoming_message`` are + # read-only context; copying enforces the request-only contract rather than + # merely documenting it. + _conv_copy = [dict(m) if isinstance(m, dict) else m for m in conversation_messages] \ + if conversation_messages is not None else None + _incoming_copy = dict(incoming_message) if isinstance(incoming_message, dict) else incoming_message + try: + selected = engine.select_context( + api_messages, + conversation_messages=_conv_copy, + incoming_message=_incoming_copy, + budget_tokens=getattr(engine, "context_length", 0) or 0, + ) + except Exception: + logger.warning( + "Context engine select_context hook failed; using unmodified " + "request messages (session=%s)", + session_label, + exc_info=True, + ) + return api_messages + + if selected is None: + return api_messages + # Require a NON-EMPTY list of dicts. An empty list must fall open to the + # original request: ``all([])`` is ``True``, so without the emptiness check + # a ``[]`` returned by a buggy/failing engine would replace a valid request + # with an empty message list that the downstream sanitizers cannot restore, + # reaching the provider as an invalid request instead of failing open. + if isinstance(selected, list) and selected and all(isinstance(m, dict) for m in selected): + return selected + + logger.warning( + "Context engine select_context returned an invalid value " + "(not a non-empty list of dicts); ignoring (session=%s)", + session_label, + ) + return api_messages + + +def _notify_context_engine_turn_complete( + agent: Any, + messages: List[Dict[str, Any]], + *, + usage: Optional[Dict[str, Any]] = None, + logger: Any, + **meta: Any, +) -> None: + """Notify the active context engine that a user turn has finished. + + Calls the optional ``ContextEngine.on_turn_complete()`` observation hook + once per turn, after the assistant/tool loop has produced the finalized + transcript. The complement to ``select_context()`` (pre-request selection): + this lets an engine ingest / index / summarize the completed turn. + + Fail-open: a missing or no-op hook, or any exception, is swallowed. + ``messages`` is passed as a shallow copy so the engine cannot mutate the + persisted transcript. + """ + engine = getattr(agent, "context_compressor", None) + hook = getattr(engine, "on_turn_complete", None) + if engine is None or not callable(hook): + return + + # Skip the no-op base implementation so non-implementing engines (incl. + # the built-in compressor) pay nothing per turn. Lazy import avoids any + # import cycle with agent.context_engine. + try: + from agent.context_engine import ContextEngine as _CE + if getattr(hook, "__func__", None) is _CE.on_turn_complete: + return + except Exception: + pass + + try: + hook( + [dict(m) if isinstance(m, dict) else m for m in messages], + usage=usage, + **meta, + ) + except Exception: + logger.warning( + "Context engine on_turn_complete hook failed (session=%s)", + getattr(agent, "session_id", None) or "-", + exc_info=True, + ) + + def run_conversation( agent, user_message: Any, @@ -674,6 +1090,8 @@ def run_conversation( stream_callback: Optional[callable] = None, persist_user_message: Optional[Any] = None, persist_user_timestamp: Optional[float] = None, + persist_user_display_kind: Optional[str] = None, + persist_user_display_metadata: Optional[Dict[str, Any]] = None, moa_config: Optional[dict[str, Any]] = None, ) -> Dict[str, Any]: """ @@ -692,6 +1110,13 @@ def run_conversation( synthetic prefixes. persist_user_timestamp: Optional platform event timestamp to store as metadata on that persisted user message. + persist_user_display_kind: Optional presentation type for a + synthesized user turn (``auto_continue``, ``model_switch``, …). + Display-only: transcript surfaces render the row as a timeline + event instead of a user bubble, while the model still receives + the message unchanged. + persist_user_display_metadata: Optional payload for that event + (e.g. a delegation's task count). or queuing follow-up prefetch work. Returns: @@ -710,6 +1135,13 @@ def run_conversation( except Exception: pass + # The gateway caches agents across user turns. Compression state is + # per-turn: carrying a prior in-place boundary forward would make a later + # uncompressed result look like a compacted transcript to gateway writers. + agent._last_compaction_in_place = False + agent._last_compression_attempt_recorded = False + agent._last_compression_attempt_in_place = None + # ── Per-turn setup (the prologue) ── # All once-per-turn setup — stdio guarding, retry-counter resets, user # message sanitization, todo/nudge hydration, system-prompt restore-or- @@ -727,6 +1159,8 @@ def run_conversation( stream_callback, persist_user_message, persist_user_timestamp, + persist_user_display_kind=persist_user_display_kind, + persist_user_display_metadata=persist_user_display_metadata, restore_or_build_system_prompt=_restore_or_build_system_prompt, install_safe_stdio=_install_safe_stdio, sanitize_surrogates=_sanitize_surrogates, @@ -753,6 +1187,9 @@ def run_conversation( # Commentary deduplication spans all provider continuations and tool calls # within one user turn, but must not suppress the same phrase next turn. agent._delivered_interim_texts = set() + # A configured SessionDB append failure halts only the affected turn. A + # cached gateway agent must recover on the next message if storage did. + agent._incremental_persistence_failed = False # Main conversation loop counters (pure locals consumed by the loop below). api_call_count = 0 @@ -797,6 +1234,13 @@ def run_conversation( # over instead of spinning. Reset here so each turn starts fresh. See #26080. agent._auth_pool_refresh_counts = {} + # Reset the per-turn usage holder forwarded to the context engine's + # on_turn_complete() observation hook. Set after each successful provider + # response (see below); left as None on turns that never reach a response + # (early failure / interrupt) so the hook receives None rather than a + # stale prior turn's usage. + agent._last_turn_usage = None + # Optional opt-in runtime: if api_mode == codex_app_server, hand the # turn to the codex app-server subprocess (terminal/file ops/patching # all run inside Codex). Default Hermes path is bypassed entirely. @@ -939,10 +1383,23 @@ def run_conversation( # However, providers like Moonshot AI require a separate 'reasoning_content' field # on assistant messages with tool_calls. We handle both cases here. request_logger = getattr(agent, "logger", None) or logging.getLogger(__name__) + # Per-agent validation cursor: skips re-json.loads-ing tool_call + # arguments on history messages already validated in a previous + # iteration. Identity-keyed (strong refs) — compression/undo/repair + # rewriting the list breaks the prefix match and forces a re-scan + # from the divergence point. See sanitize_tool_call_arguments. + _sanitize_cursor = getattr(agent, "_sanitize_args_cursor", None) + if _sanitize_cursor is None: + _sanitize_cursor = {} + try: + agent._sanitize_args_cursor = _sanitize_cursor + except Exception: + pass repaired_tool_calls = agent._sanitize_tool_call_arguments( messages, logger=request_logger, session_id=agent.session_id, + cursor=_sanitize_cursor, ) if repaired_tool_calls > 0: request_logger.info( @@ -981,6 +1438,13 @@ def run_conversation( # outgoing copy. _api_content = api_msg.pop("api_content", None) + # Display-only timeline metadata. Never a provider field — strip + # from every outgoing copy so strict OpenAI-compatible backends + # don't reject the request after a model switch or resumed typed + # event row enters the live history. + api_msg.pop("display_kind", None) + api_msg.pop("display_metadata", None) + # Inject ephemeral context into the current turn's user message. # Sources: memory manager prefetch + plugin pre_llm_call hooks # with target="user_message" (the default). Both are @@ -1038,7 +1502,28 @@ def run_conversation( # Uses new dicts so the internal messages list retains the fields # for Codex Responses compatibility. if agent._should_sanitize_tool_calls(): - agent._sanitize_tool_calls_for_strict_api(api_msg, model=agent.model) + # In MoA mode, agent.model is the virtual preset name + # (e.g. "closed"), not the actual aggregator model. Use + # the resolved aggregator model so Gemini aggregators + # correctly preserve thought_signature (extra_content). + _sanitize_model = agent.model + if agent.provider == "moa": + if moa_config: + _agg = moa_config.get("aggregator") or {} + if _agg.get("model"): + _sanitize_model = _agg["model"] + if _sanitize_model == agent.model: + # Virtual-provider mode: no moa_config is threaded + # through run_conversation — the facade resolves the + # preset internally. Ask the facade for the resolved + # aggregator slot from the previous create() instead + # (set before any history replay that could carry + # thought_signature). + _moa_client = getattr(agent, "client", None) + _agg_slot = getattr(_moa_client, "last_aggregator_slot", None) + if _agg_slot and _agg_slot.get("model"): + _sanitize_model = _agg_slot["model"] + agent._sanitize_tool_calls_for_strict_api(api_msg, model=_sanitize_model) # Keep 'reasoning_details' - OpenRouter uses this for multi-turn reasoning context # The signature field helps maintain reasoning continuity api_messages.append(api_msg) @@ -1055,9 +1540,9 @@ def run_conversation( # # Hermes invariant: the system prompt is built ONCE per session # (cached on ``_cached_system_prompt``) and replayed verbatim on - # every turn. We send it as a single content string so the - # bytes are byte-stable across turns and upstream prompt caches - # stay warm. + # every turn. ``apply_anthropic_cache_control`` may split its stable + # prefix into content blocks on the wire, but the stored string and + # its byte-stability remain unchanged. effective_system = active_system_prompt or "" if agent.ephemeral_system_prompt: effective_system = (effective_system + "\n\n" + agent.ephemeral_system_prompt).strip() @@ -1084,7 +1569,18 @@ def run_conversation( aggregator=moa_config.get("aggregator") or {}, temperature=_preset_temperature(moa_config, "reference_temperature"), aggregator_temperature=_preset_temperature(moa_config, "aggregator_temperature"), - max_tokens=moa_config.get("reference_max_tokens"), + reference_max_tokens=moa_config.get("reference_max_tokens"), + # None = no per-preset override; inherit + # auxiliary.moa_reference.timeout via call_llm. + reference_timeout=( + float(moa_config["reference_timeout"]) + if moa_config.get("reference_timeout") + else None + ), + degraded_reference_policy=str( + moa_config.get("degraded_reference_policy") or "loud" + ), + agent=agent, ) if _moa_context: for _msg in reversed(api_messages): @@ -1111,18 +1607,25 @@ def run_conversation( for idx, pfm in enumerate(agent.prefill_messages): api_messages.insert(sys_offset + idx, pfm.copy()) - # Apply Anthropic prompt caching for Claude models on native - # Anthropic, OpenRouter, and third-party Anthropic-compatible - # gateways. Auto-detected: if ``_use_prompt_caching`` is set, - # inject cache_control breakpoints (system + last 3 messages) - # to reduce input token costs by ~75% on multi-turn - # conversations. - if agent._use_prompt_caching: - api_messages = apply_anthropic_cache_control( - api_messages, - cache_ttl=agent._cache_ttl, - native_anthropic=agent._use_native_cache_layout, - ) + # Per-turn context selection hook (additive, no-op by default). + # Lets a context engine select/replace which context enters the + # prompt for THIS call only — retrieval, topic routing, role/branch + # switching — distinct from compression and independent of + # should_compress(). Request-only: persisted history is untouched, so + # caching/sanitization below operate on whatever the engine selected. + # Fail-open (see _apply_context_engine_selection). + _sel_incoming = ( + messages[current_turn_user_idx] + if 0 <= current_turn_user_idx < len(messages) + else None + ) + api_messages = _apply_context_engine_selection( + agent, + api_messages, + messages, + _sel_incoming, + logger=request_logger, + ) # Safety net: strip orphaned tool results / add stubs for missing # results before sending to the API. Runs unconditionally — not @@ -1182,6 +1685,48 @@ def run_conversation( # the OpenAI SDK. Sanitizing here prevents the 3-retry cycle. _sanitize_messages_surrogates(api_messages) + # NOTE (empty-content class fix): no send-time pad loop here. The + # single owner for "never send a turn strict wire validation rejects + # as empty" is ``repair_empty_non_final_messages``, which runs inside + # ``_sanitize_api_messages`` above — the unconditional pre-send + # chokepoint shared with the summary path. Its placeholder is + # non-whitespace, so it survives the whitespace-normalization pass + # regardless of ordering (a single-space pad here previously had to + # be sequenced after normalization to survive, forking the concept). + + # Apply Anthropic prompt caching for Claude models on native + # Anthropic, OpenRouter, and third-party Anthropic-compatible + # gateways. Auto-detected: if ``_use_prompt_caching`` is set, inject + # cache_control breakpoints for the static system prefix, full system + # prompt, and last two messages (or the legacy system-and-3 layout + # when no static prefix is available). + # + # Runs LAST, after every message mutation above. Marking earlier + # defeats the prefix stability the mutations exist to create: + # ``_apply_cache_marker`` rewrites ``content`` from a plain string + # into a ``[{"type": "text", ...}]`` block, so the marked messages + # no longer match the ``isinstance(content, str)`` test in the + # whitespace-normalization pass and silently keep their raw + # leading/trailing whitespace. A tool result ending in "\n" is + # therefore sent unstripped while it sits in the last-3 window and + # stripped once it rolls out of it — the same message, different + # bytes on consecutive turns, which breaks the prefix match at + # exactly the point the breakpoints were meant to protect. Marking + # last also keeps breakpoints off messages that the orphan sweep or + # the thinking-only drop is about to remove or merge away. + if agent._use_prompt_caching: + _static_system_prefix = getattr(agent, "_cached_system_prompt_static", None) + api_messages = apply_anthropic_cache_control( + api_messages, + cache_ttl=agent._cache_ttl, + native_anthropic=agent._use_native_cache_layout, + static_system_prefix=( + _static_system_prefix + if isinstance(_static_system_prefix, str) + else None + ), + ) + # Build a persistent-MoA request before measuring compression pressure. # MoA reference output is injected into the aggregator prompt, but it # is deliberately ephemeral and therefore absent from ``messages``. @@ -1300,6 +1845,15 @@ def run_conversation( if _moa_prepared_request is not None: pending_moa_prepared_request = _moa_prepared_request compression_attempts += 1 + # Compression is actually running (block cleared / was never + # blocked) — reset the blocked-overflow warning dedup so a future + # blocked-over-threshold turn can warn again. Mirrors the + # turn-context preflight reset (silent-overflow fix #62625). + # getattr guard: test doubles built via object.__new__ lack the + # method (gateway test-double pitfall) — treat absence as no-op. + _clear_warn = getattr(agent, "_clear_context_overflow_warn", None) + if callable(_clear_warn): + _clear_warn() logger.info( "Pre-API compression: ~%s request tokens >= %s threshold " "(context=%s, attempt=%s/%s)", @@ -1310,42 +1864,98 @@ def run_conversation( compression_attempts, max_compression_attempts, ) - agent._emit_status( - PRE_API_COMPRESSION_STATUS_TEMPLATE.format( + _pre_api_status = automatic_compaction_status_message( + _compressor, + phase="pre_api", + default_message=PRE_API_COMPRESSION_STATUS_TEMPLATE.format( tokens=request_pressure_tokens - ) + ), + approx_tokens=request_pressure_tokens, + threshold_tokens=int( + getattr(_compressor, "threshold_tokens", 0) or 0 + ), + context_length=int( + getattr(_compressor, "context_length", 0) or 0 + ), + model=agent.model, + attempt=compression_attempts, + max_attempts=max_compression_attempts, ) + if _pre_api_status: + agent._emit_status(_pre_api_status) _last_preflight_pressure = request_pressure_tokens + _pre_api_input = messages messages, active_system_prompt = agent._compress_context( messages, system_message, approx_tokens=request_pressure_tokens, task_id=effective_task_id, ) - # Reset retry/empty-response state so the compacted request - # gets a fresh chance instead of inheriting stale recovery - # counters from the pre-compaction history. - agent._empty_content_retries = 0 - agent._thinking_prefill_retries = 0 - agent._last_content_with_tools = None - agent._last_content_tools_all_housekeeping = False - agent._mute_post_response = False - # Re-baseline the flush cursor for the compaction mode that just - # ran. Legacy session-rotation returns None (the child session has - # not seen the compacted transcript, so the next flush writes it - # whole); in-place compaction returns list(messages) because the - # compacted rows are already persisted under the same session id — - # leaving None there would re-append them, doubling the active - # context and retriggering compression. Mirrors the post-response - # and preflight compaction sites; see - # conversation_history_after_compression(). - conversation_history = conversation_history_after_compression( - agent, messages - ) - api_call_count -= 1 - agent._api_call_count = api_call_count - agent.iteration_budget.refund() - continue + if messages is _pre_api_input and compression_skipped_due_to_lock(agent): + # #69870 lock-skip: another path holds this session's + # compression lock, so this pass no-oped. That is a temporary + # DEFER, not evidence about compressibility — refund the + # attempt (it must not burn the shared overflow-recovery + # budget toward compression_exhausted → gateway auto-reset, + # #9893/#35809) and leave the insufficient-progress blocker + # unarmed. Proceed with the current request: if it truly does + # not fit, the provider's 413/overflow handler returns the + # soft compression_deferred result with that stronger signal. + compression_attempts -= 1 + _last_preflight_pressure = None + if pending_moa_prepared_request is _moa_prepared_request: + pending_moa_prepared_request = None + else: + # Reset retry/empty-response state so the compacted request + # gets a fresh chance instead of inheriting stale recovery + # counters from the pre-compaction history. + agent._empty_content_retries = 0 + agent._thinking_prefill_retries = 0 + agent._last_content_with_tools = None + agent._last_content_tools_all_housekeeping = False + agent._mute_post_response = False + # Re-baseline the flush cursor for the compaction mode that just + # ran. Legacy session-rotation returns None (the child session has + # not seen the compacted transcript, so the next flush writes it + # whole); in-place compaction returns list(messages) because the + # compacted rows are already persisted under the same session id — + # leaving None there would re-append them, doubling the active + # context and retriggering compression. Mirrors the post-response + # and preflight compaction sites; see + # conversation_history_after_compression(). + conversation_history = conversation_history_after_compression( + agent, messages, conversation_history + ) + api_call_count -= 1 + agent._api_call_count = api_call_count + agent.iteration_budget.refund() + continue + elif ( + agent.compression_enabled + and len(messages) > 1 + and compression_attempts < max_compression_attempts + and not _defer_preflight(request_pressure_tokens) + and _compression_cooldown + ): + # Blocked by the summary-LLM cooldown. Surface a deduped warning + # (only when actually over threshold — should_compress_info + # returns a None reason below threshold) so the user isn't left + # with a silently growing context. Mirrors the turn-context + # preflight and the loop-compaction guards (silent-overflow fix + # #62625). + _block_reason = None + try: + _block_reason = _compressor.should_compress_info( + request_pressure_tokens + )[1] + except Exception: + _block_reason = None + if _block_reason: + agent._warn_context_overflow_blocked( + _block_reason, + request_pressure_tokens, + int(getattr(_compressor, "threshold_tokens", 0) or 0), + ) # Thinking spinner for quiet mode (animated during API call) thinking_spinner = None @@ -1447,6 +2057,18 @@ def run_conversation( # unless the active provider needs it) so the fallback request # isn't sent with stale, primary-shaped reasoning fields. agent._reapply_reasoning_echo_for_provider(api_messages) + # Same story for prompt-cache decoration (#72626): try_activate_ + # fallback refreshes the policy flags, but the decorated list + # still carries the primary's breakpoints (or none). Strip and + # re-render for the current provider before building kwargs. + api_messages, _moa_prepared_request = ( + _redecorate_prompt_cache_for_provider( + agent, + api_messages, + system_message=system_message, + moa_prepared=_moa_prepared_request, + ) + ) api_kwargs = agent._build_api_kwargs(api_messages) if agent._force_ascii_payload: _sanitize_structure_non_ascii(api_kwargs) @@ -1488,7 +2110,7 @@ def run_conversation( _llm_middleware_trace = [] try: - from hermes_cli.plugins import ( + from hermes_cli.lifecycle import ( has_hook, invoke_hook as _invoke_hook, ) @@ -1529,6 +2151,7 @@ def run_conversation( base_url=agent.base_url, api_mode=agent.api_mode, api_call_count=api_call_count, + retry_count=retry_count, request_messages=list(request_messages) if isinstance(request_messages, list) else [], @@ -1618,7 +2241,28 @@ def run_conversation( return agent._interruptible_streaming_api_call( next_api_kwargs, on_first_delta=_stop_spinner ) - return agent._interruptible_api_call(next_api_kwargs) + from agent import relay_llm + + return relay_llm.execute( + next_api_kwargs, + agent._interruptible_api_call, + session_id=str(agent.session_id or ""), + name=str(agent.provider or "provider"), + model_name=str(agent.model or ""), + metadata={ + "api_mode": agent.api_mode, + "api_request_id": api_request_id, + "call_role": ( + "delegated" + if getattr(agent, "is_subagent", False) + else "fallback" + if int(getattr(agent, "_fallback_index", 0) or 0) > 0 + else "primary" + ), + "retry_count": retry_count, + }, + defer_logical_completion=True, + ) from hermes_cli.middleware import run_llm_execution_middleware @@ -1912,6 +2556,17 @@ def run_conversation( _backoff_touch_counter = 0 while time.time() < sleep_end: if agent._interrupt_requested: + # A redirect uses the interrupt machinery to cancel + # only the live request. Aborting the retry here + # with clear_interrupt() would DESTROY the pending + # correction and kill the turn with "Operation + # interrupted" — the exact mid-stream steer loss + # users hit when a redirect lands during provider + # backoff. Rebuild from the correction instead, + # mirroring the InterruptedError handler. + if agent.clear_interrupt(preserve_redirect=True): + _retry.restart_with_redirected_messages = True + break agent._vprint(f"{agent.log_prefix}⚡ Interrupt detected during retry wait, aborting.", force=True) _interrupt_text = f"Operation interrupted during retry ({_failure_hint}, attempt {retry_count}/{max_retries})." close_interrupted_tool_sequence(messages, _interrupt_text) @@ -1933,8 +2588,12 @@ def run_conversation( f"retry backoff ({retry_count}/{max_retries}), " f"{int(sleep_end - time.time())}s remaining" ) + if _retry.restart_with_redirected_messages: + break # rebuild this iteration from the correction continue # Retry the API call + agent._turn_received_provider_response = True + # Check finish_reason before proceeding if agent.api_mode == "codex_responses": status = getattr(response, "status", None) @@ -2236,10 +2895,27 @@ def run_conversation( ) if assistant_message is not None and not _trunc_has_tool_calls: length_continue_retries += 1 - interim_msg = agent._build_assistant_message(assistant_message, finish_reason) - messages.append(interim_msg) - if assistant_message.content: - truncated_response_parts.append(assistant_message.content) + # An EMPTY partial-stream stub (stream dropped + # mid tool-call before any text was delivered) + # must not be appended as an interim assistant + # message: it would serialize as + # {"role": "assistant", "content": ""}, and + # strict providers (Moonshot/Kimi via OpenRouter) + # reject empty assistant content with HTTP 400 + # ("message ... with role 'assistant' must not be + # empty") on the very next replay — permanently + # poisoning the session history. There is no + # partial text to continue from anyway, so only + # the continuation user-message is appended. + _is_empty_partial_stub = ( + getattr(response, "id", "") == PARTIAL_STREAM_STUB_ID + and not getattr(assistant_message, "content", None) + ) + if not _is_empty_partial_stub: + interim_msg = agent._build_assistant_message(assistant_message, finish_reason) + messages.append(interim_msg) + if assistant_message.content: + truncated_response_parts.append(assistant_message.content) if length_continue_retries < 4: _is_partial_stream_stub = ( @@ -2343,13 +3019,17 @@ def run_conversation( force=True, ) agent._cleanup_task_resources(effective_task_id) - agent._persist_session(messages, conversation_history) _final_response = ( "Stream repeatedly dropped mid tool-call (network); " "the tool was not executed" if _is_stub_stall else "Response truncated due to output length limit" ) + # Prior successful tool batches (or injected tool + # errors) can leave a tool-result tail; this path + # never reaches finalize_turn (#48879 class). + close_interrupted_tool_sequence(messages, _final_response) + agent._persist_session(messages, conversation_history) return { "final_response": _final_response, "messages": messages, @@ -2452,6 +3132,14 @@ def run_conversation( "reasoning_tokens": canonical_usage.reasoning_tokens, } agent.context_compressor.update_from_response(usage_dict) + + # Stash this response's canonical usage so the post-turn + # on_turn_complete() observation hook can forward it (the + # same dict shape passed to update_from_response). A turn + # may make several API calls; the engine's per-turn signal + # of interest is the cost/size of the latest assembled + # request, so we keep the most recent call's usage. + agent._last_turn_usage = dict(usage_dict) elif getattr( agent.context_compressor, "awaiting_real_usage_after_compression", @@ -2561,7 +3249,12 @@ def run_conversation( _cost_delta = (_cost_delta or 0.0) + float(_moa_ref_cost) except (TypeError, ValueError): # pragma: no cover pass - agent._session_db.update_token_counts( + # Enqueued, not written: the background writer + # applies the delta off the turn thread (a cold + # state.db UPDATE here stalled the tool loop for + # up to hundreds of ms per API call). Drained at + # turn finalize via _persist_session. + agent._session_db.queue_token_counts( agent.session_id, input_tokens=canonical_usage.input_tokens, output_tokens=canonical_usage.output_tokens, @@ -2627,6 +3320,12 @@ def run_conversation( clear_nous_rate_limit() except Exception: pass + from agent import relay_llm + + relay_llm.complete_logical_call( + api_request_id, + outcome="success", + ) agent._touch_activity(f"API call #{api_call_count} completed") break # Success, exit retry loop @@ -3122,7 +3821,7 @@ def run_conversation( agent._buffer_vprint("🔐 Vertex AI token refreshed after 401. Retrying request...") continue if ( - agent.api_mode == "chat_completions" + agent.api_mode in ("chat_completions", "anthropic_messages") and agent.provider == "nous" and status_code == 401 and not _retry.nous_auth_retry_attempted @@ -3394,6 +4093,12 @@ def run_conversation( # Check for interrupt before deciding to retry if agent._interrupt_requested: + # Preserve a pending redirect (mid-stream correction): the + # user is steering, not stopping. Rebuild the turn from the + # correction instead of aborting with a dead-end interrupt. + if agent.clear_interrupt(preserve_redirect=True): + _retry.restart_with_redirected_messages = True + break agent._vprint(f"{agent.log_prefix}⚡ Interrupt detected during error handling, aborting retries.", force=True) _interrupt_text = f"Operation interrupted: handling API error ({error_type}: {agent._clean_error_message(str(api_error))})." close_interrupted_tool_sequence(messages, _interrupt_text) @@ -3523,7 +4228,7 @@ def run_conversation( task_id=effective_task_id, ) conversation_history = conversation_history_after_compression( - agent, messages + agent, messages, conversation_history ) if len(messages) < original_len or old_ctx > _reduced_ctx: agent._buffer_status( @@ -3773,12 +4478,25 @@ def run_conversation( original_len = len(messages) original_tokens = estimate_messages_tokens_rough(messages) + _overflow_input = messages messages, active_system_prompt = agent._compress_context( messages, system_message, approx_tokens=approx_tokens, task_id=effective_task_id, ) + if messages is _overflow_input and compression_skipped_due_to_lock(agent): + # #69870 lock-skip: the provider proved the request + # does not fit, but this compression pass no-oped only + # because another path holds the session's compression + # lock. Temporary defer, not exhaustion — refund the + # attempt and end the turn softly so the gateway does + # NOT auto-reset the session (#9893/#35809). + compression_attempts -= 1 + agent._persist_session(messages, conversation_history) + return _compression_deferred_result( + agent, messages, api_call_count + ) conversation_history = conversation_history_after_compression( - agent, messages + agent, messages, conversation_history ) # Re-estimate tokens after compression. Same-message-count @@ -4014,12 +4732,25 @@ def run_conversation( original_len = len(messages) original_tokens = estimate_messages_tokens_rough(messages) + _overflow_input = messages messages, active_system_prompt = agent._compress_context( messages, system_message, approx_tokens=approx_tokens, task_id=effective_task_id, ) + if messages is _overflow_input and compression_skipped_due_to_lock(agent): + # #69870 lock-skip: the provider proved the request + # does not fit, but this compression pass no-oped only + # because another path holds the session's compression + # lock. Temporary defer, not exhaustion — refund the + # attempt and end the turn softly so the gateway does + # NOT auto-reset the session (#9893/#35809). + compression_attempts -= 1 + agent._persist_session(messages, conversation_history) + return _compression_deferred_result( + agent, messages, api_call_count + ) conversation_history = conversation_history_after_compression( - agent, messages + agent, messages, conversation_history ) # Re-estimate tokens after compression. Same-message-count @@ -4604,6 +5335,12 @@ def run_conversation( _backoff_touch_counter = 0 while time.time() < sleep_end: if agent._interrupt_requested: + # Same preserve-redirect rule as the retry-wait above: + # a steering correction must survive backoff, not die + # as "Operation interrupted". + if agent.clear_interrupt(preserve_redirect=True): + _retry.restart_with_redirected_messages = True + break agent._vprint(f"{agent.log_prefix}⚡ Interrupt detected during retry wait, aborting.", force=True) _interrupt_text = f"Operation interrupted: retrying API call after error (retry {retry_count}/{max_retries})." close_interrupted_tool_sequence(messages, _interrupt_text) @@ -4625,6 +5362,11 @@ def run_conversation( f"error retry backoff ({retry_count}/{max_retries}), " f"{int(sleep_end - time.time())}s remaining" ) + if _retry.restart_with_redirected_messages: + # Leave the retry loop — the check right below rebuilds this + # iteration from the correction instead of re-firing the + # stale request. + break if _retry.restart_with_redirected_messages: # The cancelled request produced no valid assistant item. Reuse the @@ -4728,7 +5470,7 @@ def run_conversation( assistant_message.content = str(raw) try: - from hermes_cli.plugins import ( + from hermes_cli.lifecycle import ( has_hook, invoke_hook as _invoke_hook, ) @@ -4970,6 +5712,14 @@ def run_conversation( args_preview = raw_args[:200] if isinstance(raw_args, str) else repr(raw_args)[:200] logging.debug("Tool call: %s with args: %s...", tc.function.name, args_preview) + # Uniquify duplicate tool-call ids BEFORE any downstream + # consumer (validation error paths, dispatch, history build, + # Responses item-id derivation). Models that reuse one id for + # different calls in a batch otherwise lose the later call's + # result: the pre-API sanitizer keeps only the first + # call/result pair per id. See _uniquify_tool_call_ids. + agent._uniquify_tool_call_ids(assistant_message.tool_calls) + # Validate tool call names - detect model hallucinations # Repair mismatched tool names before validating for tc in assistant_message.tool_calls: @@ -5022,8 +5772,13 @@ def run_conversation( agent._flush_status_buffer() agent._vprint(f"{agent.log_prefix}❌ Max retries (3) for invalid tool calls exceeded. Stopping as partial.", force=True) agent._invalid_tool_retries = 0 - agent._persist_session(messages, conversation_history) _final_response = f"Model generated invalid tool call: {invalid_preview}" + # Prior <3 retries (or an earlier successful tool batch) + # leave a tool-result tail. Closing it here matches + # interrupt aborts (#48879 / #52592) so the next user + # turn is not tool→user for strict providers. + close_interrupted_tool_sequence(messages, _final_response) + agent._persist_session(messages, conversation_history) return { "final_response": _final_response, "messages": messages, @@ -5103,14 +5858,18 @@ def run_conversation( ) agent._invalid_json_retries = 0 agent._cleanup_task_resources(effective_task_id) + _final_response = "Response truncated due to output length limit" + # Same tool-tail close as interrupt / invalid-tool + # exhaustion — this path never reaches finalize_turn. + close_interrupted_tool_sequence(messages, _final_response) agent._persist_session(messages, conversation_history) return { - "final_response": "Response truncated due to output length limit", + "final_response": _final_response, "messages": messages, "api_calls": api_call_count, "completed": False, "partial": True, - "error": "Response truncated due to output length limit", + "error": _final_response, } # Track retries for invalid JSON arguments @@ -5249,6 +6008,10 @@ def run_conversation( # flag so it can fire again if the model goes empty on # a LATER tool round. agent._post_tool_empty_retried = False + # A landed tool call means any earlier dropped-tool-call stall + # was recovered — refresh that budget too so it guards each + # stall independently rather than capping the whole run. + agent._dropped_toolcall_retries = 0 previous_msg = messages[-1] if messages else None current_interim_visible = agent._interim_assistant_visible_text(assistant_msg) @@ -5265,8 +6028,6 @@ def run_conversation( and previous_interim_visible == current_interim_visible ) messages.append(assistant_msg) - if not duplicate_previous_interim: - agent._emit_interim_assistant_message(assistant_msg) # Mixed batch: error-result the invalid calls and strip them # from the execution set. The assistant message above keeps @@ -5288,13 +6049,17 @@ def run_conversation( if tc.function.name in agent.valid_tool_names ] + _tool_turn_persisted = None try: # Persist the assistant tool-call turn before any tool # side effects run. If a destructive tool restarts or # terminates Hermes mid-turn, resume logic still sees the # exact tool-call block that already executed. - agent._flush_messages_to_session_db(messages, conversation_history) + _tool_turn_persisted = agent._flush_messages_to_session_db( + messages, conversation_history + ) except Exception as exc: + _tool_turn_persisted = False logger.warning( "Incremental tool-call persistence failed before execution " "(session=%s): %s", @@ -5302,6 +6067,22 @@ def run_conversation( exc, ) + if _tool_turn_persisted is False: + # The canonical append failed. Do not project the row or + # run side-effecting tools from state that exists only in + # this process. Breaking also avoids retrying the same + # unpersisted turn until the iteration budget is exhausted. + _turn_exit_reason = "session_persistence_failed" + final_response = "" + failed = True + break + + # A UI must never observe an assistant/tool-call row that is + # still only an ephemeral in-memory projection. Emit interim + # commentary only after the canonical SessionDB append above. + if not duplicate_previous_interim: + agent._emit_interim_assistant_message(assistant_msg) + # Close any open streaming display (response box, reasoning # box) before tool execution begins. Intermediate turns may # have streamed early content that opened the response box; @@ -5316,6 +6097,15 @@ def run_conversation( agent._execute_tool_calls(assistant_message, messages, effective_task_id, api_call_count) + if getattr(agent, "_incremental_persistence_failed", False): + # A tool result could not be made canonical. Do not send + # the in-memory result back to the model or project any + # later events from this turn. + _turn_exit_reason = "session_persistence_failed" + final_response = "" + failed = True + break + if agent._tool_guardrail_halt_decision is not None: decision = agent._tool_guardrail_halt_decision _turn_exit_reason = "guardrail_halt" @@ -5401,24 +6191,122 @@ def run_conversation( and _compressor.should_compress(_real_tokens) ): compression_attempts += 1 + # Compression is actually running (block cleared / was + # never blocked) — reset the blocked-overflow warning + # dedup so a future blocked-over-threshold turn can warn + # again (silent-overflow fix #62625). + # getattr guard: test doubles built via object.__new__ lack the + # method (gateway test-double pitfall) — treat absence as no-op. + _clear_warn = getattr(agent, "_clear_context_overflow_warn", None) + if callable(_clear_warn): + _clear_warn() agent._safe_print(" ⟳ compacting context…") + _post_tool_input = messages messages, active_system_prompt = agent._compress_context( messages, system_message, approx_tokens=agent.context_compressor.last_prompt_tokens, task_id=effective_task_id, ) - conversation_history = conversation_history_after_compression( - agent, messages - ) + if ( + messages is _post_tool_input + and compression_skipped_due_to_lock(agent) + ): + # #69870 lock-skip: this pass no-oped because another + # path holds the session's compression lock — a + # temporary defer, not evidence about compressibility. + # Refund the attempt so a lock-loser tool loop does not + # burn the shared per-turn budget toward + # compression_exhausted (#9893/#35809). + compression_attempts -= 1 + else: + conversation_history = conversation_history_after_compression( + agent, messages, conversation_history + ) + elif agent.compression_enabled: + # Over threshold but compression is blocked (summary-LLM + # cooldown or anti-thrashing). Surface a deduped warning so + # the user isn't left with a silently growing context that + # eventually hits the hard provider limit. Mirrors the + # turn-context preflight guard (silent-overflow fix #62625). + _block_reason = None + _info = getattr(_compressor, "should_compress_info", None) + if _info is not None: + try: + _block_reason = _info(_real_tokens)[1] + except Exception: + _block_reason = None + if _block_reason: + agent._warn_context_overflow_blocked( + _block_reason, + _real_tokens, + int(getattr(_compressor, "threshold_tokens", 0) or 0), + ) + # Proactive tool-result prune: reclaim re-sent history on + # large-window models long before should_compress() (≈50% of + # the window) would ever fire. Deterministic, no LLM call; + # protects the recent tail. No-op unless proactive_prune_tokens + # is configured and _real_tokens is above it — and even then + # the prune only commits when it reclaims at least + # proactive_prune_min_reclaim_tokens, so prompt-cache breaks + # stay episodic like compression's (the one sanctioned cache + # break) instead of firing every tool iteration. See + # ContextCompressor.prune_tool_results_only. + # getattr guard: plugin context engines predating the hook and + # minimal test doubles (SimpleNamespace compressors) lack the + # method — treat absence as a no-op. + _prune = getattr(_compressor, "prune_tool_results_only", None) + if callable(_prune): + try: + _pruned_msgs, _pruned_n = _prune( + messages, current_tokens=_real_tokens + ) + except Exception: + logger.debug( + "proactive tool-result prune failed; skipping", + exc_info=True, + ) + _pruned_msgs, _pruned_n = messages, 0 + # Standard no-op caller contract: only commit when the + # engine returned a NEW list object with a non-zero count. + if _pruned_n and _pruned_msgs is not messages: + # Do NOT rebuild conversation_history here. Unlike the + # compression branch, the prune neither rotates the session + # nor calls archive_and_compact(), so there is no new + # persistence baseline to establish. _prune_old_tool_results + # returns per-message copies that preserve the + # _DB_PERSISTED_MARKER, so the marker-based flush dedup (see + # _flush_messages_to_session_db) already prevents both + # duplicate writes and dropped rows. Calling + # conversation_history_after_compression (a compaction-only + # helper keyed on the _last_compaction_in_place flag) would be + # a no-op at best, and on a stale in-place flag could seed + # this turn's fresh, not-yet-persisted rows into history_ids + # and skip writing them. + messages = _pruned_msgs # Save session log incrementally (so progress is visible even if interrupted) agent._session_messages = messages + # Touch activity before continuing so the gateway's + # inactivity monitor never sees a stale timestamp + # between tool completion and the start of the next + # API call. Without this, a tool-call result (which + # takes ~0s to process) followed by slow post-tool + # processing (compression, persist) and a slow + # follow-up API call can exceed the gateway inactivity + # timeout (HERMES_AGENT_TIMEOUT, default 1800s) and the + # gateway kills the session before the next activity + # touch fires (#69559, #69131). + agent._touch_activity(f"tool results posted, continuing iteration #{api_call_count}") # Continue loop for next response continue else: - # No tool calls - this is the final response + # No tool calls - this is the final response. + # (Dropped tool-call recovery — finish_reason=="tool_calls" with + # an empty tool_calls array — is handled at the finalization + # chokepoint below, after final_msg is built, so it catches + # every path that reaches turn finalization, not just this one.) final_response = assistant_message.content or "" # Fix: unmute output when entering the no-tool-call branch @@ -5690,7 +6578,28 @@ def run_conversation( ". No fallback providers configured.") ) - final_response = "(empty)" + # Deliver a labeled reasoning excerpt instead of a bare + # "(empty)" when the model DID think but never produced + # visible text. This is delivery-only: the persisted + # assistant message above keeps the "(empty)" sentinel + # (its replay semantics prevent empty-response loops), + # and raw chain-of-thought is never promoted to a normal + # answer earlier in the ladder — prefill continuation, + # empty-content retries, and provider fallback all run + # first. Only at this terminal, where the alternative is + # returning nothing, is showing the model's own reasoning + # (clearly labeled as such) strictly more useful. + # Idea credit: PR #48795 (@ligl0325). + if reasoning_text: + final_response = ( + "⚠️ The model produced only internal reasoning and " + "no final answer, despite retries" + + (" and fallback" if agent._fallback_chain else "") + + ". Its last reasoning, which may contain the " + "answer:\n\n" + reasoning_preview + ) + else: + final_response = "(empty)" break # Reset retry counter/signature on successful content @@ -5750,6 +6659,64 @@ def run_conversation( final_msg = agent._build_assistant_message(assistant_message, finish_reason) + # ── Dropped tool-call recovery (copilot/Claude) ──────── + # Some providers (observed: claude-opus-4.8 / claude-sonnet-4.5 + # on GitHub Copilot, ~2026-07) return finish_reason="tool_calls" + # while the parsed tool_calls array is empty — the model + # signalled it wanted to act but the payload shipped no call. + # Reaching finalization with that mismatch means the turn is + # about to end with the task unstarted (the narration, which may + # be in content or only in the reasoning field, gets treated as + # the final answer). Re-prompt (bounded to 3 CONSECUTIVE stalls; + # the budget resets after any successful tool round) to make the + # model emit the call instead of exiting. finish_reason="stop" + # text finishes never enter this guard. + if ( + finish_reason == "tool_calls" + and not assistant_message.tool_calls + and getattr(agent, "_dropped_toolcall_retries", 0) < 3 + ): + agent._dropped_toolcall_retries = getattr(agent, "_dropped_toolcall_retries", 0) + 1 + logger.warning( + "finish_reason=tool_calls with empty tool_calls array " + "(narration only) — re-prompting to emit the call " + "(retry %d/3, model=%s provider=%s)", + agent._dropped_toolcall_retries, agent.model, agent.provider, + ) + agent._emit_status( + "↻ Model signaled a tool call but sent none — " + f"re-prompting ({agent._dropped_toolcall_retries}/3)" + ) + # Both halves of the re-prompt pair are ephemeral recovery + # scaffolding (mirrors the empty-response nudge pattern): + # the interim narration-only assistant turn exists solely to + # keep role alternation valid for the nudge, and the nudge + # exists solely to drive the retry. Flag both so the + # persistence layer never writes them to the durable + # transcript and the finalization pop below can strip an + # unanswered tail pair. A recovered (answered) pair stays + # buried mid-list in live memory but is skipped by the + # flush regardless of position. + final_msg["_dropped_toolcall_nudge"] = True + messages.append(final_msg) + messages.append({ + "role": "user", + "content": ( + "Your previous turn indicated a tool call but none was " + "included. Do not narrate a plan or restate intent — issue " + "the actual tool call now to continue the task." + ), + "_dropped_toolcall_nudge": True, + }) + agent._session_messages = messages + final_response = None + continue + + # Reached finalization without the dropped-tool-call mismatch — + # a genuine turn end. Clear the consecutive-stall budget so the + # next turn starts fresh. + agent._dropped_toolcall_retries = 0 + # Pop thinking-only prefill and empty-response retry # scaffolding before appending either a final response or a # verification-stop follow-up. These internal turns are only @@ -5762,6 +6729,7 @@ def run_conversation( messages[-1].get("_thinking_prefill") or messages[-1].get("_empty_recovery_synthetic") or messages[-1].get("_empty_terminal_sentinel") + or messages[-1].get("_dropped_toolcall_nudge") ) ): messages.pop() @@ -5835,7 +6803,8 @@ def run_conversation( _attempt = getattr(agent, "_pre_verify_nudges", 0) try: from agent.verify_hooks import max_verify_nudges - from hermes_cli.plugins import get_pre_verify_continue_message, has_hook + from hermes_cli.lifecycle import has_hook + from hermes_cli.plugins import get_pre_verify_continue_message if _edited and has_hook("pre_verify") and _attempt < max_verify_nudges(): # Posture is fixed for the session — resolve once + cache. diff --git a/agent/copilot_acp_client.py b/agent/copilot_acp_client.py index 5e095af3902b..9cbdcd349446 100644 --- a/agent/copilot_acp_client.py +++ b/agent/copilot_acp_client.py @@ -503,15 +503,20 @@ class CopilotACPClient: def _run_prompt(self, prompt_text: str, *, timeout_seconds: float) -> tuple[str, str]: try: + # Hide the console the CLI child would otherwise flash on Windows + # (#56747). Hide-only — stdio pipes stay intact for the ACP wire. + from hermes_cli._subprocess_compat import windows_hide_flags + proc = subprocess.Popen( [self._acp_command] + self._acp_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, - text=True, + text=True, encoding='utf-8', errors='replace', bufsize=1, cwd=self._acp_cwd, env=_build_subprocess_env(), + creationflags=windows_hide_flags(), ) except FileNotFoundError as exc: raise RuntimeError( @@ -703,7 +708,7 @@ class CopilotACPClient: if block_error: raise PermissionError(block_error) try: - content = path.read_text() + content = path.read_text(encoding="utf-8") except FileNotFoundError: content = "" line = params.get("line") @@ -731,7 +736,7 @@ class CopilotACPClient: if denied: raise PermissionError(denied) path.parent.mkdir(parents=True, exist_ok=True) - path.write_text(str(params.get("content") or "")) + path.write_text(str(params.get("content") or ""), encoding="utf-8") response = { "jsonrpc": "2.0", "id": message_id, diff --git a/agent/credential_pool.py b/agent/credential_pool.py index f8109a1aa458..08b0c0ea6b97 100644 --- a/agent/credential_pool.py +++ b/agent/credential_pool.py @@ -594,22 +594,64 @@ class CredentialPool: # Re-armed to None on every successful selection so a recover→re-exhaust # transition logs promptly instead of being swallowed by a stale window. self._last_no_entries_log_at: Optional[float] = None + # #70401: consecutive mark_exhausted_and_rotate() calls whose supplied + # credential identity matched no pool entry (OAuth wrappers whose + # runtime key rotates, entries pruned by another process, ...). These + # rotations mark nothing exhausted, so without a cap the pool can + # never converge to "no available entries" and the caller's 401 retry + # loop runs unbounded and non-interruptible. Reset whenever a real + # entry is identified or an escape path returns None. + self._unmatched_rotation_streak: int = 0 def has_credentials(self) -> bool: - return bool(self._entries) + with self._lock: + return bool(self._entries) def has_available(self) -> bool: """True if at least one entry is not currently in exhaustion cooldown.""" - return bool(self._available_entries()) + # ``_available_entries`` is not read-only: it prunes aged-out DEAD + # manual entries (rebinding ``self._entries``) and persists. It must + # run under ``self._lock`` like every other caller (``select`` etc.), + # otherwise a status probe here can race a concurrent ``select`` / + # rotation and tear ``self._entries`` or double-write auth.json. + with self._lock: + return bool(self._available_entries()) def entries(self) -> List[PooledCredential]: - return list(self._entries) + with self._lock: + return list(self._entries) - def current(self) -> Optional[PooledCredential]: + def _current_unlocked(self) -> Optional[PooledCredential]: if not self._current_id: return None return next((entry for entry in self._entries if entry.id == self._current_id), None) + def current(self) -> Optional[PooledCredential]: + with self._lock: + return self._current_unlocked() + + def entry_id_for_api_key(self, api_key_hint: Any = None) -> Optional[str]: + """Return the stable id for the runtime credential in use. + + Prefer the current selection when it still supplies ``api_key_hint``. + If the cursor was cleared, fall back to an unambiguous key match. + """ + with self._lock: + current = self._current_unlocked() + if current is not None and ( + api_key_hint is None + or current.runtime_api_key == api_key_hint + ): + return current.id + if api_key_hint is None: + return None + matches = [ + entry + for entry in self._entries + if entry.runtime_api_key == api_key_hint + ] + return matches[0].id if len(matches) == 1 else None + def _replace_entry(self, old: PooledCredential, new: PooledCredential) -> None: """Swap an entry in-place by id, preserving sort order.""" for idx, entry in enumerate(self._entries): @@ -652,6 +694,8 @@ class CredentialPool: entry: PooledCredential, status_code: Optional[int], error_context: Optional[Dict[str, Any]] = None, + *, + persist: bool = True, ) -> PooledCredential: normalized_error = _normalize_error_context(error_context) # Permanent OAuth failures (token_invalidated, token_revoked, etc.) @@ -675,7 +719,8 @@ class CredentialPool: last_error_reset_at=normalized_error.get("reset_at"), ) self._replace_entry(entry, updated) - self._persist() + if persist: + self._persist() return updated def _sync_anthropic_entry_from_credentials_file(self, entry: PooledCredential) -> PooledCredential: @@ -1547,7 +1592,13 @@ class CredentialPool: def select(self) -> Optional[PooledCredential]: with self._lock: - return self._select_unlocked() + entry = self._select_unlocked() + if entry is not None: + # A normal (non-recovery) selection starts a fresh episode — + # don't let a leftover unmatched-rotation streak from an old + # failure trip the #70401 bound early next time. + self._unmatched_rotation_streak = 0 + return entry def _available_entries(self, *, clear_expired: bool = False, refresh: bool = False) -> List[PooledCredential]: """Return entries not currently in exhaustion cooldown. @@ -1726,18 +1777,21 @@ class CredentialPool: self._entries = [replace(candidate, priority=idx) for idx, candidate in enumerate(rotated)] self._persist() self._current_id = entry.id - return self.current() or entry + return self._current_unlocked() or entry entry = available[0] self._current_id = entry.id return entry def peek(self) -> Optional[PooledCredential]: - current = self.current() - if current is not None: - return current - available = self._available_entries() - return available[0] if available else None + # Single lock acquisition for the whole read; call the unlocked + # helpers so we don't re-enter the non-reentrant ``self._lock``. + with self._lock: + current = self._current_unlocked() + if current is not None: + return current + available = self._available_entries() + return available[0] if available else None def mark_exhausted_and_rotate( self, @@ -1745,10 +1799,17 @@ class CredentialPool: status_code: Optional[int], error_context: Optional[Dict[str, Any]] = None, api_key_hint: Optional[str] = None, + credential_id: Optional[str] = None, ) -> Optional[PooledCredential]: with self._lock: entry = None - if api_key_hint: + identity_supplied = bool(credential_id or api_key_hint) + if credential_id: + entry = next( + (e for e in self._entries if e.id == credential_id), + None, + ) + if entry is None and api_key_hint: # Prefer the specific entry whose API key matches the one that # actually failed. When this pool was freshly loaded from disk # (another process already rotated), current() is None and @@ -1757,12 +1818,89 @@ class CredentialPool: (e for e in self._entries if e.runtime_api_key == api_key_hint), None, ) + if entry is None and identity_supplied: + # The failed credential is identifiable but matches no entry + # (rotated away, or a wrapper whose runtime key differs). + # Falling through to current()/_select_unlocked() would mark an + # innocent healthy key exhausted for the full cooldown TTL. + # + # #70401: this branch must still be BOUNDED. With OAuth-token + # auth the upstream 401's key hint never matches any entry's + # ``runtime_api_key``, so every retry lands here, nothing is + # ever marked exhausted, and the pool can never reach the + # "no available entries" state — the caller retries the same + # dead token forever (~6/sec, starving the event loop so chat + # interrupts are never processed). The single-entry case + # below already escapes; multi-entry pools could still + # ping-pong A→B→A indefinitely without marking anything. + # Cap consecutive no-mark rotations at one full lap of the + # available entries: past that, every candidate has been + # handed back at least once without recovery, so stop + # guessing and surface the error (no cooldown is written for + # anybody — healthy keys stay available for the next turn). + self._unmatched_rotation_streak += 1 + available_count = len(self._available_entries()) + if self._unmatched_rotation_streak > max(available_count, 1): + logger.warning( + "credential pool: failed credential identity matched no " + "%s entry for %d consecutive rotations (pool size %d) — " + "surfacing the error instead of rotating again", + self.provider, + self._unmatched_rotation_streak, + available_count, + ) + self._unmatched_rotation_streak = 0 + self._current_id = None + return None + logger.info( + "credential pool: failed credential identity matched no %s " + "entry; rotating without marking any credential exhausted", + self.provider, + ) + self._current_id = None + next_entry = self._select_unlocked() + if next_entry is not None and len(self._available_entries()) == 1: + # A single-entry pool cannot rotate. Returning its only + # entry reports a successful recovery without changing + # the credential, so the caller retries the same 401 + # indefinitely. Let fallback/error propagation proceed. + self._unmatched_rotation_streak = 0 + self._current_id = None + return None + return next_entry + # A real entry was identified — any prior unmatched-rotation + # streak is stale (this mark WILL advance pool state). + self._unmatched_rotation_streak = 0 if entry is None: - entry = self.current() or self._select_unlocked() + entry = self._current_unlocked() or self._select_unlocked() if entry is None: return None _label = entry.label or entry.id[:8] self._mark_exhausted(entry, status_code, error_context) + # A 402/429/401 is an API-key–level failure: the account is out of + # balance, rate-limited, or its key is rejected. The same key can + # back more than one pool entry (e.g. an explicit pool entry plus a + # ``model_config`` entry auto-seeded from ``model.api_key`` — both + # carry the identical ``runtime_api_key``). Marking only the first + # match leaves the sibling entries OK, so ``_select_unlocked()`` + # keeps handing back the same depleted key and rotation never + # converges — the caller ``continue``s forever until the client + # disconnects (a ~2.5min hang with no error surfaced to the user). + # Mark every entry sharing the failed key so the pool can reach the + # "no available entries" state and let the error propagate. + failed_runtime_key = getattr(entry, "runtime_api_key", None) + if identity_supplied and failed_runtime_key: + siblings_marked = False + for sibling in self._entries: + if sibling.id == entry.id: + continue + if sibling.runtime_api_key == failed_runtime_key: + self._mark_exhausted( + sibling, status_code, error_context, persist=False + ) + siblings_marked = True + if siblings_marked: + self._persist() # Re-read the updated entry to log the correct terminal state. updated_entry = next( (e for e in self._entries if e.id == entry.id), entry, @@ -1830,9 +1968,11 @@ class CredentialPool: return self._try_refresh_current_unlocked() def try_refresh_matching( - self, api_key_hint: Optional[str] = None + self, + api_key_hint: Optional[str] = None, + credential_id: Optional[str] = None, ) -> Optional[PooledCredential]: - """Force-refresh the entry that supplied ``api_key_hint``. + """Force-refresh the entry that supplied the failed request. Direct provider integrations may reload the pool after a request has already failed, so they cannot rely on ``current_id`` identifying the @@ -1842,24 +1982,36 @@ class CredentialPool: """ with self._lock: entry = None - if api_key_hint: + if credential_id: entry = next( ( candidate for candidate in self._entries - if candidate.runtime_api_key == api_key_hint + if candidate.id == credential_id ), None, ) - else: - entry = self.current() or self._select_unlocked(refresh=False) + if entry is None: + if api_key_hint: + entry = next( + ( + candidate + for candidate in self._entries + if candidate.runtime_api_key == api_key_hint + ), + None, + ) + else: + entry = self._current_unlocked() or self._select_unlocked( + refresh=False + ) if entry is None: return None self._current_id = entry.id return self._try_refresh_current_unlocked() def _try_refresh_current_unlocked(self) -> Optional[PooledCredential]: - entry = self.current() + entry = self._current_unlocked() if entry is None: return None refreshed = self._refresh_entry(entry, force=True) @@ -1868,76 +2020,80 @@ class CredentialPool: return refreshed def reset_statuses(self) -> int: - count = 0 - new_entries = [] - for entry in self._entries: - if entry.last_status or entry.last_status_at or entry.last_error_code: - new_entries.append( - replace( - entry, - last_status=None, - last_status_at=None, - last_error_code=None, - last_error_reason=None, - last_error_message=None, - last_error_reset_at=None, + with self._lock: + count = 0 + new_entries = [] + for entry in self._entries: + if entry.last_status or entry.last_status_at or entry.last_error_code: + new_entries.append( + replace( + entry, + last_status=None, + last_status_at=None, + last_error_code=None, + last_error_reason=None, + last_error_message=None, + last_error_reset_at=None, + ) ) - ) - count += 1 - else: - new_entries.append(entry) - if count: - self._entries = new_entries - self._persist() - return count + count += 1 + else: + new_entries.append(entry) + if count: + self._entries = new_entries + self._persist() + return count def remove_index(self, index: int) -> Optional[PooledCredential]: - if index < 1 or index > len(self._entries): - return None - removed = self._entries.pop(index - 1) - self._entries = [ - replace(entry, priority=new_priority) - for new_priority, entry in enumerate(self._entries) - ] - write_credential_pool( - self.provider, - [entry.to_dict() for entry in self._entries], - removed_ids=[removed.id], - ) - if self._current_id == removed.id: - self._current_id = None - return removed + with self._lock: + if index < 1 or index > len(self._entries): + return None + removed = self._entries.pop(index - 1) + self._entries = [ + replace(entry, priority=new_priority) + for new_priority, entry in enumerate(self._entries) + ] + write_credential_pool( + self.provider, + [entry.to_dict() for entry in self._entries], + removed_ids=[removed.id], + ) + if self._current_id == removed.id: + self._current_id = None + return removed def resolve_target(self, target: Any) -> Tuple[Optional[int], Optional[PooledCredential], Optional[str]]: raw = str(target or "").strip() if not raw: return None, None, "No credential target provided." - for idx, entry in enumerate(self._entries, start=1): - if entry.id == raw: - return idx, entry, None + with self._lock: + for idx, entry in enumerate(self._entries, start=1): + if entry.id == raw: + return idx, entry, None - label_matches = [ - (idx, entry) - for idx, entry in enumerate(self._entries, start=1) - if entry.label.strip().lower() == raw.lower() - ] - if len(label_matches) == 1: - return label_matches[0][0], label_matches[0][1], None - if len(label_matches) > 1: - return None, None, f'Ambiguous credential label "{raw}". Use the numeric index or entry id instead.' - if raw.isdigit(): - index = int(raw) - if 1 <= index <= len(self._entries): - return index, self._entries[index - 1], None - return None, None, f"No credential #{index}." - return None, None, f'No credential matching "{raw}".' + label_matches = [ + (idx, entry) + for idx, entry in enumerate(self._entries, start=1) + if entry.label.strip().lower() == raw.lower() + ] + if len(label_matches) == 1: + return label_matches[0][0], label_matches[0][1], None + if len(label_matches) > 1: + return None, None, f'Ambiguous credential label "{raw}". Use the numeric index or entry id instead.' + if raw.isdigit(): + index = int(raw) + if 1 <= index <= len(self._entries): + return index, self._entries[index - 1], None + return None, None, f"No credential #{index}." + return None, None, f'No credential matching "{raw}".' def add_entry(self, entry: PooledCredential) -> PooledCredential: - entry = replace(entry, priority=_next_priority(self._entries)) - self._entries.append(entry) - self._persist() - return entry + with self._lock: + entry = replace(entry, priority=_next_priority(self._entries)) + self._entries.append(entry) + self._persist() + return entry def _upsert_entry(entries: List[PooledCredential], provider: str, source: str, payload: Dict[str, Any]) -> bool: diff --git a/agent/credential_sources.py b/agent/credential_sources.py index 18f0823ba842..32cd5e01a80d 100644 --- a/agent/credential_sources.py +++ b/agent/credential_sources.py @@ -164,7 +164,7 @@ def _remove_env_source(provider: str, removed) -> RemovalResult: if env_path.exists(): env_in_dotenv = any( line.strip().startswith(f"{env_var}=") - for line in env_path.read_text(errors="replace").splitlines() + for line in env_path.read_text(errors="replace", encoding="utf-8").splitlines() ) except OSError: pass diff --git a/agent/credits_tracker.py b/agent/credits_tracker.py index f2186fb91a56..b47c3f274edf 100644 --- a/agent/credits_tracker.py +++ b/agent/credits_tracker.py @@ -170,6 +170,27 @@ CREDITS_USAGE_BANDS: tuple[tuple[float, str, int], ...] = ( ) CREDITS_USAGE_KEY = "credits.usage" # single key for the escalating usage notice +# Minimum subscription balance that counts as "grant not yet spent" for the +# grant_spent crossing gate (see evaluate_credits_notices). 1¢: portal-seeded +# states derive micros from float dollars and can carry sub-cent residue where +# the inference headers report exactly 0 — without this floor such a seed +# opens the gate and the first header re-creates the at-open nag. +GRANT_UNSPENT_MIN_MICROS = 10_000 + + +def new_credits_latch() -> dict: + """Fresh notice latch in the shape :func:`evaluate_credits_notices` expects. + + The policy owns this schema — every producer (agent build, lazy re-init, + tests) must build the latch through here so a new gate key lands everywhere + at once instead of drifting across hand-rolled literals.""" + return { + "active": set(), + "seen_below_90": False, + "usage_band": None, + "seen_grant_unspent": False, + } + # ── AgentNotice (out-of-band notice payload; driver-agnostic) ──────────────── @@ -250,7 +271,8 @@ def evaluate_credits_notices( ) -> tuple[list[AgentNotice], list[str]]: """Reconcile credits notices against the latch. Mutates ``latch`` IN PLACE. - latch = {"active": set[str], "seen_below_90": bool, "usage_band": Optional[int]}. + latch = {"active": set[str], "seen_below_90": bool, "usage_band": Optional[int], + "seen_grant_unspent": bool}. ``model_is_free``: True when the session's active model is a Nous free-tier model (see :func:`is_free_tier_model`). Suppresses the ``credits.depleted`` @@ -277,6 +299,18 @@ def evaluate_credits_notices( if uf is not None and uf < _lowest_band: latch["seen_below_90"] = True # gate opened: usage-band notices may now fire + # Grant-spent crossing gate: grant_spent may fire only after this session + # has OBSERVED the grant meaningfully unspent (≥1¢ left — see + # GRANT_UNSPENT_MIN_MICROS). Opening at grant-spent is a steady STATE, not + # an event — /usage carries it; only a live in-session crossing announces. + # Unlike seen_below_90, seeds must NOT prime this gate. + if ( + uf is not None + and uf < 1.0 + and state.subscription_micros >= GRANT_UNSPENT_MIN_MICROS + ): + latch["seen_grant_unspent"] = True + active = latch["active"] # ── Conditions ─────────────────────────────────────────────────────────── @@ -316,12 +350,21 @@ def evaluate_credits_notices( active.discard(CREDITS_USAGE_KEY) if target_band is not None: # Belt-and-suspenders: a producer could set subscription_limit_micros - # without subscription_limit_usd. Render "$? cap" rather than "$None cap". + # without subscription_limit_usd. Render "$?" rather than "$None". _cap_usd = state.subscription_limit_usd or "?" _level = current_band[1] # type: ignore[index] (current_band set when target_band set) + # Report absolute dollars used, not a bare "N% used": the percentage is + # only meaningful against a Nous subscription cap (no cap → never fires), + # so dollars are clearer and don't imply a universal %. Used = cap − + # remaining (micros, money-safe), clamped to [0, cap]. Re-emits on band + # change (50 → 75 → 90), not every turn — a snapshot, not a live ticker. + _lim = state.subscription_limit_micros or 0 + _used_micros = max(0, min(_lim, _lim - state.subscription_micros)) + _used_usd = f"{_used_micros / 1_000_000:.2f}" if _lim else "?" + _glyph = "⚠" if _level == "warn" else "•" to_show.append( AgentNotice( - text=f"{'⚠' if _level == 'warn' else '•'} Credits {target_band}% used · ${_cap_usd} cap", + text=f"{_glyph} You've used ${_used_usd} of your ${_cap_usd} cap", level=_level, kind=CREDITS_NOTICE_KIND, key=CREDITS_USAGE_KEY, @@ -332,7 +375,17 @@ def evaluate_credits_notices( latch["usage_band"] = target_band # ── grant_spent ────────────────────────────────────────────────────────── - if grant_cond and "credits.grant_spent" not in active: + # The crossing gate guards only the SHOW and is CONSUMED by it — one + # announcement per crossing. A header flicker (uf → None → back to 1.0) + # clears the sticky line via grant_cond but cannot re-announce; only a + # renewal that re-opens the gate (a fresh ≥1¢ observation) arms the next + # announcement. .get(): default closed for any hand-built latch missing + # the key, so a first observation can never fire this notice. + if ( + grant_cond + and "credits.grant_spent" not in active + and latch.get("seen_grant_unspent", False) + ): to_show.append( AgentNotice( text=f"• Grant spent · ${state.purchased_usd} top-up left", @@ -343,6 +396,7 @@ def evaluate_credits_notices( ) ) active.add("credits.grant_spent") + latch["seen_grant_unspent"] = False elif "credits.grant_spent" in active and not grant_cond: to_clear.append("credits.grant_spent") active.discard("credits.grant_spent") @@ -618,7 +672,8 @@ _DEV_FIXTURES: dict[str, dict] = { subscription_limit_micros=20_000_000, subscription_limit_usd="20.00", denominator_kind="subscription_cap", paid_access=True, ), - "grant_exhausted": dict( # used_fraction == 1.0 + purchased>0 → credits.grant_spent + "grant_exhausted": dict( # uf == 1.0 + purchased>0 → SILENT at open (crossing-gated); + # flip healthy → grant_exhausted via the fixture-file path to see credits.grant_spent remaining_micros=12_340_000, remaining_usd="12.34", subscription_micros=0, subscription_usd="0.00", subscription_limit_micros=20_000_000, subscription_limit_usd="20.00", @@ -732,6 +787,9 @@ def _hydrate_seed_state(agent, state) -> None: agent._credits_session_start_micros = state.remaining_micros _latch = getattr(agent, "_credits_latch", None) if isinstance(_latch, dict) and state.used_fraction is not None: + # Prime ONLY seen_below_90 (open-high band warnings are wanted at open). + # Never prime seen_grant_unspent here: a seed observing grant-spent is a + # steady state, and priming it would revive the every-session nag. _latch["seen_below_90"] = True emit = getattr(agent, "_emit_credits_notices", None) if callable(emit): diff --git a/agent/curator.py b/agent/curator.py index ada93248e246..21827bec4844 100644 --- a/agent/curator.py +++ b/agent/curator.py @@ -325,7 +325,7 @@ def apply_automatic_transitions(now: Optional[datetime] = None) -> Dict[str, int counts = {"marked_stale": 0, "archived": 0, "reactivated": 0, "checked": 0, "seeded": 0} - for row in _u.agent_created_report(): + for row in _u.curated_report(): counts["checked"] += 1 name = row["name"] if row.get("pinned"): @@ -422,7 +422,9 @@ CURATOR_REVIEW_PROMPT = ( "INSTRUCTIONS AND EXPERIENTIAL KNOWLEDGE. A collection of hundreds of " "narrow skills where each one captures one session's specific bug is " "a FAILURE of the library — not a feature. An agent searching skills " - "matches on descriptions, not on exact names; one broad umbrella " + "matches on descriptions, not on exact names (note: long descriptions " + "are truncated to 57 chars in the system prompt skill index — keep the " + "trigger class in that window). One broad umbrella " "skill with labeled subsections beats five narrow siblings for " "discoverability, not the other way around.\n\n" "The right target shape is CLASS-LEVEL skills with rich SKILL.md " @@ -900,7 +902,6 @@ def _reconcile_classification( Every removed skill is placed in exactly one bucket. """ heur_cons = {e["name"]: e for e in heuristic.get("consolidated", [])} - heur_pruned = {e["name"] for e in heuristic.get("pruned", [])} model_cons = {e["from"]: e for e in model_block.get("consolidations", [])} model_pruned = {e["name"]: e for e in model_block.get("prunings", [])} @@ -1470,15 +1471,16 @@ def _render_report_markdown(p: Dict[str, Any]) -> str: # --------------------------------------------------------------------------- def _render_candidate_list() -> str: - """Human/agent-readable list of agent-created skills with usage stats.""" - rows = skill_usage.agent_created_report() + """Human/agent-readable list of curator-managed skills with usage stats.""" + rows = skill_usage.curated_report() if not rows: - return "No agent-created skills to review." + return "No curator-managed skills to review." cron_referenced = _cron_referenced_skills() - lines = [f"Agent-created skills ({len(rows)}):\n"] + lines = [f"Curator-managed skills ({len(rows)}):\n"] for r in rows: lines.append( f"- {r['name']} " + f"provenance={r.get('provenance', 'agent')} " f"state={r['state']} " f"pinned={'yes' if r.get('pinned') else 'no'} " f"cron={'yes' if r['name'] in cron_referenced else 'no'} " @@ -1531,7 +1533,7 @@ def run_curator_review( if dry_run: # Count candidates without mutating state. try: - report = skill_usage.agent_created_report() + report = skill_usage.curated_report() counts = { "checked": len(report), "marked_stale": 0, @@ -1584,7 +1586,7 @@ def run_curator_review( nonlocal auto_summary # Snapshot skill state BEFORE the LLM pass so the report can diff. try: - before_report = skill_usage.agent_created_report() + before_report = skill_usage.curated_report() except Exception: before_report = [] before_names = {r.get("name") for r in before_report if isinstance(r, dict)} @@ -1610,7 +1612,7 @@ def run_curator_review( state2["last_run_duration_seconds"] = elapsed state2["last_run_summary"] = final_summary try: - after_report = skill_usage.agent_created_report() + after_report = skill_usage.curated_report() except Exception: after_report = [] try: @@ -1697,7 +1699,7 @@ def run_curator_review( try: rename_lines = _build_rename_summary( before_names=before_names, - after_report=skill_usage.agent_created_report(), + after_report=skill_usage.curated_report(), tool_calls=llm_meta.get("tool_calls", []) or [], model_final=llm_meta.get("final", "") or "", ) @@ -1715,7 +1717,7 @@ def run_curator_review( # reporting bug never breaks the curator itself. Report path is # recorded in state so `hermes curator status` can point at it. try: - after_report = skill_usage.agent_created_report() + after_report = skill_usage.curated_report() except Exception: after_report = [] try: diff --git a/agent/delegation_context.py b/agent/delegation_context.py new file mode 100644 index 000000000000..b80bbbe00fbf --- /dev/null +++ b/agent/delegation_context.py @@ -0,0 +1,85 @@ +"""Context-local state for delegate_task child execution. + +The parent Hermes process may itself be a Kanban dispatcher worker with +HERMES_KANBAN_* variables in process env. delegate_task children run inside the +same Python process, but they are not dispatcher-owned Kanban workers. This +module lets code paths that resolve tool schemas or spawn subprocesses fail +closed for delegated children without mutating global os.environ for the parent. +""" +from __future__ import annotations + +from contextlib import contextmanager +from contextvars import ContextVar +from typing import Iterator, Mapping, MutableMapping + +_DELEGATED_CHILD_CONTEXT: ContextVar[bool] = ContextVar( + "hermes_delegated_child_context", + default=False, +) + +DELEGATED_CHILD_ENV_MARKER = "HERMES_DELEGATED_CHILD_CONTEXT" + +KANBAN_ENV_KEYS: tuple[str, ...] = ( + "HERMES_KANBAN_TASK", + "HERMES_KANBAN_RUN_ID", + "HERMES_KANBAN_WORKSPACE", + "HERMES_KANBAN_WORKSPACES_ROOT", + "HERMES_KANBAN_CLAIM_LOCK", + "HERMES_KANBAN_BOARD", + "HERMES_KANBAN_DB", +) + + +@contextmanager +def delegated_child_context() -> Iterator[None]: + """Mark the current execution context as a delegate_task child.""" + token = _DELEGATED_CHILD_CONTEXT.set(True) + try: + yield + finally: + _DELEGATED_CHILD_CONTEXT.reset(token) + + +def is_delegated_child_context() -> bool: + """Return True while code is running for a delegate_task child.""" + return bool(_DELEGATED_CHILD_CONTEXT.get()) + + +def is_delegated_child_process_context() -> bool: + """Return True in this process or a subprocess spawned by a child.""" + import os + + return bool(_DELEGATED_CHILD_CONTEXT.get()) or bool( + os.environ.get(DELEGATED_CHILD_ENV_MARKER) + ) + + +def scrub_kanban_env(env: Mapping[str, str] | MutableMapping[str, str]) -> dict[str, str]: + """Return *env* with dispatcher-only Kanban variables removed.""" + cleaned = dict(env) + for key in KANBAN_ENV_KEYS: + cleaned.pop(key, None) + cleaned[DELEGATED_CHILD_ENV_MARKER] = "1" + return cleaned + + +def delegated_child_subprocess_env( + env: Mapping[str, str] | MutableMapping[str, str] | None = None, +) -> dict[str, str] | None: + """Return an env override only when delegated-child lineage must cross fork. + + Most subprocess call sites historically used ``env=None`` to inherit the + process environment. In a ``delegate_task`` child, inheriting as-is leaks + parent dispatcher ``HERMES_KANBAN_*`` vars while losing the ContextVar in + the new process. This helper preserves normal ``env=None`` semantics for + non-delegated calls, and only materializes a scrubbed env when the lineage + marker must be propagated across a child-process boundary. + """ + if not is_delegated_child_process_context(): + return None if env is None else dict(env) + + if env is None: + import os + + env = os.environ + return scrub_kanban_env(env) diff --git a/agent/error_classifier.py b/agent/error_classifier.py index 9d830cdc996f..27df08f58ea9 100644 --- a/agent/error_classifier.py +++ b/agent/error_classifier.py @@ -159,6 +159,14 @@ _RATE_LIMIT_PATTERNS = [ "throttlingexception", "too many concurrent requests", "servicequotaexceededexception", + # Generic throttle prefix — Bedrock (and some proxies) surface throttling + # as "Throttling error: Too many tokens, please wait before trying + # again." Without this entry the message falls through to the + # context-overflow list (which contains "too many tokens") and the retry + # loop compresses a healthy session instead of backing off. Matched + # BEFORE _CONTEXT_OVERFLOW_PATTERNS in the message-only path, so the + # throttle wins. (port of anomalyco/opencode#37848's exclusion guard) + "throttling", ] # Patterns that indicate provider-side overload, NOT a per-credential rate @@ -212,6 +220,12 @@ _PAYLOAD_TOO_LARGE_PATTERNS = [ "request entity too large", "payload too large", "error code: 413", + # Anthropic's structured 413 error type. Normally arrives with an HTTP + # 413 status (handled by the status path), but aggregators/proxies can + # re-wrap it into a plain message with no status attribute — route it to + # the same compression recovery. (port of anomalyco/opencode#37848) + "request_too_large", + "request exceeds the maximum size", ] # Image-size patterns. Matched against 400 bodies (not 413) because most @@ -298,6 +312,10 @@ _CONTEXT_OVERFLOW_PATTERNS = [ "max input token", "input token", "exceeds the maximum number of input tokens", + # Together/Fireworks-style: "Input length 131393 exceeds the maximum + # allowed input length of 131040 tokens." No other pattern in this list + # matches that wording. (port of anomalyco/opencode#37848) + "maximum allowed input length", ] # Model not found patterns @@ -321,6 +339,30 @@ _MODEL_NOT_FOUND_PATTERNS = [ "no endpoints found that support tool use", ] +# Malformed-message-array 400s. Deterministic request-shape rejections that +# describe the *transcript* being invalid, not a parameter. The canonical +# case: a stream dies mid-response and Hermes persists a content-less +# assistant stub; on the next turn the Anthropic message schema (and the +# litellm/Bedrock proxies in front of it) reject the whole request with +# "all messages must have non-empty content except for the optional final +# assistant message" / errorCode INVALID_REQUEST_BODY +# These are NOT context overflow — the input may be tiny — but a large +# session used to mis-route them into the compression loop via the generic +# "400 + large session" heuristic below, ending in "Cannot compress further" +# every retry (the input is unchanged, so compression cannot help). Match +# the message-shape signals explicitly and fail fast as a format_error so the +# loop stops looping. The empty-stub creation is the root cause (fixed in +# chat_completion_helpers); this pattern stops the misclassification symptom +# for transcripts that already contain a poisoned stub. +_INVALID_MESSAGE_BODY_PATTERNS = [ + "must have non-empty content", + "messages must have non-empty", + "invalid_request_body", + "text content blocks must be non-empty", + "content field is required", + "messages: at least one message is required", +] + # Request-validation patterns — the request is malformed and will fail # identically on every retry. Some OpenAI-compatible gateways (notably # codex.nekos.me) return these as 5xx instead of the standard 4xx, which @@ -413,6 +455,7 @@ _CONTENT_POLICY_BLOCKED_PATTERNS = [ _AUTH_PATTERNS = [ "invalid api key", "invalid_api_key", + "gateway_auth_failed", "authentication", "unauthorized", "forbidden", @@ -1270,6 +1313,33 @@ def _classify_400( should_fallback=True, ) + # Malformed message array (empty-content assistant stub, etc.). Must be + # checked BEFORE context_overflow: the input can be tiny, so the generic + # "400 + large session" heuristic would otherwise mis-route it into the + # compression loop and thrash until "Cannot compress further" on every + # retry (the request is unchanged, so compression cannot fix it). This is + # a deterministic request-shape rejection — fail fast as a non-retryable + # format_error and fall back. Checked against the message text AND the + # structured error code, since proxies (litellm/Bedrock) surface the + # signal in errorCode=INVALID_REQUEST_BODY. + if ( + any(p in error_msg for p in _INVALID_MESSAGE_BODY_PATTERNS) + or error_code_lower == "invalid_request_body" + ): + logger.warning( + "Malformed message array 400 (invalid request body) classified as " + "format_error, NOT context overflow — failing fast + falling back " + "instead of entering the compression loop. This usually means an " + "empty-content assistant stub is in the transcript; num_messages=%s " + "approx_tokens=%s. error=%.200s", + num_messages, approx_tokens, error_msg, + ) + return result_fn( + FailoverReason.format_error, + retryable=False, + should_fallback=True, + ) + # Empty-provider-response advisories must not enter compression. They # often mention "max_tokens" as a possible cause and used to match the # bare overflow pattern, then thrash compress until "Cannot compress @@ -1330,6 +1400,18 @@ def _classify_400( # Responses API (and some providers) use flat body: {"message": "..."} if not err_body_msg: err_body_msg = str(body.get("message") or "").strip().lower() + # litellm / Bedrock proxies use a custom shape: {"errorMessage": "...", + # "errorCode": "...", "errorArgs": {"reason": "..."}}. Without these + # keys err_body_msg stays "" and a long, descriptive rejection is + # wrongly treated as a "generic" (bare) error below, which — on a + # large session — mis-routes into the compression loop. Recognize + # them so the is_generic heuristic sees the real message length. + if not err_body_msg: + err_body_msg = str(body.get("errorMessage") or "").strip().lower() + if not err_body_msg: + _args = body.get("errorArgs") + if isinstance(_args, dict): + err_body_msg = str(_args.get("reason") or "").strip().lower() is_generic = len(err_body_msg) < 30 or err_body_msg in {"error", ""} # Absolute token/message-count thresholds are only a proxy for smaller # context windows. Large-context sessions can have many messages while @@ -1628,7 +1710,7 @@ def _extract_error_code(body: dict) -> str: return nested_code # Top-level code - code = body.get("code") or body.get("error_code") or "" + code = body.get("code") or body.get("error_code") or body.get("errorCode") or "" if isinstance(code, (str, int)): text = str(code).strip() if text and text != "400": @@ -1648,6 +1730,16 @@ def _extract_message(error: Exception, body: dict) -> str: msg = body.get("message", "") if isinstance(msg, str) and msg.strip(): return msg.strip()[:500] + # litellm / Bedrock proxy shape: {"errorMessage": "...", + # "errorArgs": {"reason": "..."}}. + msg = body.get("errorMessage", "") + if isinstance(msg, str) and msg.strip(): + return msg.strip()[:500] + args = body.get("errorArgs") + if isinstance(args, dict): + reason = args.get("reason", "") + if isinstance(reason, str) and reason.strip(): + return reason.strip()[:500] # Fallback to str(error) return str(error)[:500] diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.py index 1c25f1e6cf0a..cde63f15fc17 100644 --- a/agent/gemini_native_adapter.py +++ b/agent/gemini_native_adapter.py @@ -73,7 +73,7 @@ def probe_gemini_tier( api_key: str, base_url: str = DEFAULT_GEMINI_BASE_URL, *, - model: str = "gemini-2.5-flash", + model: str = "gemini-3.6-flash", timeout: float = 10.0, ) -> str: """Probe a Google AI Studio API key and return its tier. @@ -154,8 +154,8 @@ def is_free_tier_quota_error(error_message: str) -> bool: _FREE_TIER_GUIDANCE = ( - "\n\nYour Google API key is on the free tier (<= 250 requests/day for " - "gemini-2.5-flash). Hermes typically makes 3-10 API calls per user turn, " + "\n\nYour Google API key is on the free tier (a few hundred requests/day " + "for Gemini Flash models). Hermes typically makes 3-10 API calls per user turn, " "so the free tier is exhausted in a handful of messages and cannot sustain " "an agent session. Enable billing on your Google Cloud project and " "regenerate the key in a billing-enabled project: " @@ -163,6 +163,42 @@ _FREE_TIER_GUIDANCE = ( ) +def is_standard_key_auth_error( + status: int, error_message: str, reason: str = "" +) -> bool: + """Return True when a Gemini 401 indicates Google rejected the key TYPE. + + Google began rejecting unrestricted legacy "Standard" Google Cloud API + keys on the Gemini API on June 19, 2026, and ALL Standard keys stop + working in September 2026. The rejection surfaces as a misleading 401 + telling the user to supply an OAuth 2 access token ("Request had invalid + authentication credentials. Expected OAuth 2 access token, login cookie + or other valid authentication credential."), optionally carrying + ``google.rpc.ErrorInfo`` reason ``ACCESS_TOKEN_TYPE_UNSUPPORTED``. + + Scoped narrowly so a plain bad key (reason ``API_KEY_INVALID``, + "API key not valid") keeps its existing message. + """ + if status != 401: + return False + if reason == "ACCESS_TOKEN_TYPE_UNSUPPORTED": + return True + return "expected oauth 2 access token" in (error_message or "").lower() + + +_STANDARD_KEY_GUIDANCE = ( + "\n\nGoogle Gemini rejected this API key's type — you do NOT need OAuth. " + "Google began rejecting legacy 'Standard' Google Cloud keys for the " + "Gemini API on June 19, 2026, and all Standard keys stop working in " + "September 2026. Open https://aistudio.google.com/api-keys, check the " + "key's type and status, and create a replacement Gemini API key (or, as " + "a temporary bridge, restrict the Standard key to " + "generativelanguage.googleapis.com). Then update GEMINI_API_KEY / " + "GOOGLE_API_KEY in ~/.hermes/.env and restart your session. " + "Details: https://ai.google.dev/gemini-api/docs/api-key" +) + + class GeminiAPIError(Exception): """Error shape compatible with Hermes retry/error classification.""" @@ -270,8 +306,12 @@ def _translate_tool_call_to_gemini(tool_call: Dict[str, Any]) -> Dict[str, Any]: } } thought_signature = _tool_call_extra_signature(tool_call) - if thought_signature: - part["thoughtSignature"] = thought_signature + # Fallback sentinel for cross-provider tool_calls (e.g. fallback from + # xAI/Anthropic to Gemini, where the original tool_call carries no + # Gemini thoughtSignature). Mirrors gemini_cloudcode_adapter.py:106. + # Without this, Gemini 3 thinking models reject replayed history with + # 400 INVALID_ARGUMENT on the missing thoughtSignature. + part["thoughtSignature"] = thought_signature or "skip_thought_signature_validator" return part @@ -281,9 +321,13 @@ def _translate_tool_result_to_gemini( ) -> Dict[str, Any]: tool_name_by_call_id = tool_name_by_call_id or {} tool_call_id = str(message.get("tool_call_id") or "") + # A tool result can carry the unwrapped internal tool name (for example, + # an MCP tool invoked through the `tool_call` bridge). Gemini requires + # functionResponse.name to echo the matching functionCall.name, so the + # call-id mapping must take precedence over the internal result name. name = str( - message.get("name") - or tool_name_by_call_id.get(tool_call_id) + tool_name_by_call_id.get(tool_call_id) + or message.get("name") or tool_call_id or "tool" ) @@ -820,6 +864,12 @@ def gemini_http_error( if status == 429 and is_free_tier_quota_error(err_message or body_text): message = message + _FREE_TIER_GUIDANCE + # Legacy "Standard" Google Cloud key rejection (June 19, 2026 onward) -> + # Google's raw 401 misleadingly tells the user to use OAuth. Append the + # actual fix (mint a new Gemini API key in AI Studio). + if is_standard_key_auth_error(status, err_message or body_text, reason): + message = message + _STANDARD_KEY_GUIDANCE + return GeminiAPIError( message, code=code, @@ -930,7 +980,7 @@ class GeminiNativeClient: def _create_chat_completion( self, *, - model: str = "gemini-2.5-flash", + model: str = "gemini-3.6-flash", messages: Optional[List[Dict[str, Any]]] = None, stream: bool = False, tools: Any = None, diff --git a/agent/gemini_schema.py b/agent/gemini_schema.py index b0985422fbb1..665fd79a37e4 100644 --- a/agent/gemini_schema.py +++ b/agent/gemini_schema.py @@ -2,6 +2,7 @@ from __future__ import annotations +import math from typing import Any, Dict # Gemini's ``FunctionDeclaration.parameters`` field accepts the ``Schema`` @@ -76,15 +77,31 @@ def sanitize_gemini_schema(schema: Any) -> Dict[str, Any]: # Gemini's Schema validator requires every ``enum`` entry to be a string, # even when the parent ``type`` is ``integer`` / ``number`` / ``boolean``. - # OpenAI / OpenRouter / Anthropic accept typed enums (e.g. Discord's - # ``auto_archive_duration: {type: integer, enum: [60, 1440, 4320, 10080]}``), - # so we only drop the ``enum`` when it would collide with Gemini's rule. - # Keeping ``type: integer`` plus the human-readable description gives the - # model enough guidance; the tool handler still validates the value. + # Preserve those constraints by stringifying scalar values while keeping + # the declared type intact; Gemini uses the strings as schema metadata and + # still emits typed tool arguments at runtime. enum_val = cleaned.get("enum") type_val = cleaned.get("type") if isinstance(enum_val, list) and type_val in {"integer", "number", "boolean"}: - if any(not isinstance(item, str) for item in enum_val): + stringified = [] + for item in enum_val: + if isinstance(item, str): + value = item + elif isinstance(item, bool): + value = "true" if item else "false" + elif ( + isinstance(item, (int, float)) + and not isinstance(item, bool) + and math.isfinite(item) + ): + value = str(item) + else: + continue + if value not in stringified: + stringified.append(value) + if stringified: + cleaned["enum"] = stringified + else: cleaned.pop("enum", None) # Gemini validates ``required`` strictly against the same node's diff --git a/agent/i18n.py b/agent/i18n.py index b55b8128c92d..24f8ab0a0237 100644 --- a/agent/i18n.py +++ b/agent/i18n.py @@ -25,7 +25,8 @@ Language resolution order: 3. ``display.language`` from config.yaml 4. ``"en"`` (baseline) -Supported languages: en, zh, ja, de, es, fr, tr, uk. Unknown values fall back to en. +Supported languages: en, zh, zh-hant, ja, de, es, fr, tr, uk, af, ko, it, ga, +pt, ru, hu, ar. Unknown values fall back to en. """ from __future__ import annotations @@ -41,7 +42,7 @@ logger = logging.getLogger(__name__) SUPPORTED_LANGUAGES: tuple[str, ...] = ( "en", "zh", "zh-hant", "ja", "de", "es", "fr", "tr", "uk", - "af", "ko", "it", "ga", "pt", "ru", "hu", + "af", "ko", "it", "ga", "pt", "ru", "hu", "ar", ) DEFAULT_LANGUAGE = "en" @@ -78,6 +79,9 @@ _LANGUAGE_ALIASES: dict[str, str] = { "russian": "ru", "русский": "ru", "ru-ru": "ru", # Hungarian "hungarian": "hu", "magyar": "hu", "hu-hu": "hu", + # Arabic — bare "arabic"/endonym plus the common regional BCP-47 tags. + "arabic": "ar", "العربية": "ar", + "ar-sa": "ar", "ar-eg": "ar", "ar-ae": "ar", "ar-ma": "ar", "ar-dz": "ar", } _catalog_cache: dict[str, dict[str, str]] = {} diff --git a/agent/image_routing.py b/agent/image_routing.py index 8cfa085527c4..a8337c9ac6ad 100644 --- a/agent/image_routing.py +++ b/agent/image_routing.py @@ -181,6 +181,8 @@ def _supports_vision_override( cfg: Optional[Dict[str, Any]], provider: str, model: str, + *, + requested_provider: str = "", ) -> Optional[bool]: """Resolve user-declared vision capability from config.yaml. @@ -188,9 +190,14 @@ def _supports_vision_override( 1. ``model.supports_vision`` (top-level shortcut for the active model) 2. ``providers..models..supports_vision`` (named custom providers — ``provider`` may be the runtime-resolved - value ``"custom"`` and/or the user-declared name under - ``model.provider``; both are tried. For ``custom:`` syntax, - the stripped ```` is also tried as a provider key.) + value ``"custom"``, the runtime's originally requested provider, + and/or the user-declared name under ``model.provider``; all are + tried. For ``custom:`` syntax, the stripped ```` is also + tried as a provider key.) + 2b. ``custom_providers`` (legacy list form) ``.models.`` + + Under (2) and (2b), the per-model capability key may be written as + either ``supports_vision`` or the shorter ``vision`` alias; both work. Returns None when no override is set, so the caller falls through to models.dev. Returns False explicitly only when the user wrote a @@ -210,23 +217,30 @@ def _supports_vision_override( # get rewritten to provider="custom" at runtime # (hermes_cli/runtime_provider.py:_resolve_named_custom_runtime), so the # config still holds the user-declared name under model.provider. Try - # both as candidate provider keys, plus the stripped suffix from - # "custom:" (where is the key under providers:). + # both as candidate provider keys. Either identity may use the + # "custom:" form while providers: is keyed by bare . config_provider = str(model_cfg.get("provider") or "").strip() - # Extract the stripped name from "custom:" if present - stripped_suffix = "" - if config_provider.startswith("custom:"): - stripped_suffix = config_provider[len("custom:"):] + provider_candidates: List[str] = [] + for candidate in (requested_provider, provider, config_provider): + if not candidate: + continue + provider_candidates.append(candidate) + if candidate.startswith("custom:"): + stripped_candidate = candidate[len("custom:"):] + if stripped_candidate: + provider_candidates.append(stripped_candidate) providers_raw = cfg.get("providers") providers_cfg: Dict[str, Any] = providers_raw if isinstance(providers_raw, dict) else {} - for p in dict.fromkeys(filter(None, (provider, config_provider, stripped_suffix))): + for p in dict.fromkeys(provider_candidates): entry_raw = providers_cfg.get(p) entry: Dict[str, Any] = entry_raw if isinstance(entry_raw, dict) else {} models_raw = entry.get("models") models_cfg: Dict[str, Any] = models_raw if isinstance(models_raw, dict) else {} per_model_raw = models_cfg.get(model) per_model: Dict[str, Any] = per_model_raw if isinstance(per_model_raw, dict) else {} - coerced = _coerce_capability_bool(per_model.get("supports_vision")) + coerced = _coerce_capability_bool( + per_model.get("supports_vision", per_model.get("vision")) + ) if coerced is not None: return coerced @@ -235,28 +249,26 @@ def _supports_vision_override( # may appear as the raw name or "custom:" at runtime). custom_providers = cfg.get("custom_providers") if isinstance(custom_providers, list): - # Build candidate names: the provider value and the config provider - # value, both raw and with "custom:" prefix stripped/added. - candidate_names: set = set() - for p in filter(None, (provider, config_provider)): - candidate_names.add(p) - if p.startswith("custom:"): - candidate_names.add(p[len("custom:"):]) - else: - candidate_names.add(f"custom:{p}") - for entry_raw in custom_providers: - if not isinstance(entry_raw, dict): - continue - entry_name = str(entry_raw.get("name") or "").strip() - if entry_name not in candidate_names: - continue - models_raw = entry_raw.get("models") - models_cfg = models_raw if isinstance(models_raw, dict) else {} - per_model_raw = models_cfg.get(model) - per_model = per_model_raw if isinstance(per_model_raw, dict) else {} - coerced = _coerce_capability_bool(per_model.get("supports_vision")) - if coerced is not None: - return coerced + # Candidate priority matters when the CLI-selected provider differs + # from model.provider. Walk identities first, then config entries, so + # list order cannot let the persisted default shadow the live route. + for candidate in dict.fromkeys(provider_candidates): + candidate_name = candidate.strip().lower() + for entry_raw in custom_providers: + if not isinstance(entry_raw, dict): + continue + entry_name = str(entry_raw.get("name") or "").strip().lower() + if entry_name != candidate_name: + continue + models_raw = entry_raw.get("models") + models_cfg = models_raw if isinstance(models_raw, dict) else {} + per_model_raw = models_cfg.get(model) + per_model = per_model_raw if isinstance(per_model_raw, dict) else {} + coerced = _coerce_capability_bool( + per_model.get("supports_vision", per_model.get("vision")) + ) + if coerced is not None: + return coerced return None @@ -376,6 +388,8 @@ def _lookup_supports_vision( provider: str, model: str, cfg: Optional[Dict[str, Any]] = None, + *, + requested_provider: str = "", ) -> Optional[bool]: """Return True/False if we can resolve caps, None if unknown. @@ -383,7 +397,34 @@ def _lookup_supports_vision( (so custom/local models declared as vision-capable don't fall through to text routing in ``auto`` mode), then falls back to models.dev. """ - override = _supports_vision_override(cfg, provider, model) + # Named custom providers are canonicalized to ``provider="custom"`` by + # runtime resolution. The original CLI/config name is carried in the + # context-local main runtime so capability lookup can still select the + # exact custom_providers entry. Require an exact provider+model match: + # background/auxiliary lookups must never borrow another turn's identity. + if not requested_provider: + try: + from agent.auxiliary_client import _runtime_main_value + + runtime_provider = str( + _runtime_main_value("provider") or "" + ).strip().lower() + runtime_model = str(_runtime_main_value("model") or "").strip() + lookup_provider = str(provider or "").strip().lower() + lookup_model = str(model or "").strip() + if runtime_provider == lookup_provider and runtime_model == lookup_model: + requested_provider = str( + _runtime_main_value("requested_provider") or "" + ).strip() + except Exception: + pass + + override = _supports_vision_override( + cfg, + provider, + model, + requested_provider=requested_provider, + ) if override is not None: return override if not provider or not model: @@ -421,6 +462,8 @@ def decide_image_input_mode( provider: str, model: str, cfg: Optional[Dict[str, Any]], + *, + requested_provider: str = "", ) -> str: """Return ``"native"`` or ``"text"`` for the given turn. @@ -428,6 +471,7 @@ def decide_image_input_mode( provider: active inference provider ID (e.g. ``"anthropic"``, ``"openrouter"``). model: active model slug as it would be sent to the provider. cfg: loaded config.yaml dict, or None. When None, behaves as auto. + requested_provider: provider identity before runtime canonicalization. """ mode_cfg = "auto" if isinstance(cfg, dict): @@ -444,7 +488,17 @@ def decide_image_input_mode( # explicit auxiliary.vision config acts as a *fallback* for text-only # main models — it should not preempt native vision on a model that # can natively inspect the pixels (issue #29135). - supports = _lookup_supports_vision(provider, model, cfg) + if requested_provider: + supports = _lookup_supports_vision( + provider, + model, + cfg, + requested_provider=requested_provider, + ) + else: + # Keep the long-standing three-argument call contract for callers and + # tests that replace the capability lookup hook. + supports = _lookup_supports_vision(provider, model, cfg) if supports is True: return "native" if _explicit_aux_vision_override(cfg): diff --git a/agent/insights.py b/agent/insights.py index 086150c279ef..9d148a15446b 100644 --- a/agent/insights.py +++ b/agent/insights.py @@ -113,6 +113,13 @@ class InsightsEngine: """ cutoff = time.time() - (days * 86400) + # Token/cost totals may still sit on the SessionDB's async + # accounting queue; drain so the report reflects exact counters. + # (self.db may be a raw sqlite3 connection in tests — guard.) + flush = getattr(self.db, "flush_token_counts", None) + if callable(flush): + flush() + # Gather raw data sessions = self._get_sessions(cutoff, source) tool_usage = self._get_tool_usage(cutoff, source) diff --git a/agent/iteration_budget.py b/agent/iteration_budget.py index 213b97c02265..7d50026c1701 100644 --- a/agent/iteration_budget.py +++ b/agent/iteration_budget.py @@ -2,7 +2,7 @@ Extracted from ``run_agent.py``. Each ``AIAgent`` instance (parent or subagent) holds an :class:`IterationBudget`; the parent's cap comes from -``max_iterations`` (default 90), each subagent's cap comes from +``max_iterations`` (default 500), each subagent's cap comes from ``delegation.max_iterations`` (default 50). ``run_agent`` re-exports ``IterationBudget`` so existing @@ -18,7 +18,7 @@ class IterationBudget: """Thread-safe iteration counter for an agent. Each agent (parent or subagent) gets its own ``IterationBudget``. - The parent's budget is capped at ``max_iterations`` (default 90). + The parent's budget is capped at ``max_iterations`` (default 500). Each subagent gets an independent budget capped at ``delegation.max_iterations`` (default 50) — this means total iterations across parent + subagents can exceed the parent's cap. diff --git a/agent/learning_graph_render.py b/agent/learning_graph_render.py index 3602ee270e61..479b2f5b4b74 100644 --- a/agent/learning_graph_render.py +++ b/agent/learning_graph_render.py @@ -403,7 +403,6 @@ def _category_counts(payload: dict[str, Any]) -> list[tuple[str, int]]: def category_color_map(payload: dict[str, Any]) -> dict[str, str]: """Deterministic, evenly-spread hue per skill category (theme-independent).""" clusters = _category_counts(payload) - n = max(1, len(clusters)) # Golden-angle hue spacing so adjacent categories never collide in color. return {cat: rgb_to_hex(_hsl_to_rgb((i * 137.508) % 360, 0.55, 0.62)) for i, (cat, _c) in enumerate(clusters)} diff --git a/agent/lsp/cli.py b/agent/lsp/cli.py index 139baa213f77..607c156d102a 100644 --- a/agent/lsp/cli.py +++ b/agent/lsp/cli.py @@ -55,7 +55,7 @@ def register_subparser(subparsers: argparse._SubParsersAction) -> None: help="Even attempt servers marked manual-install (best effort)", ) - sub_restart = sub.add_parser( + sub.add_parser( "restart", help="Tear down running LSP clients (next edit re-spawns)", ) diff --git a/agent/lsp/client.py b/agent/lsp/client.py index 9207cb75bdaa..3411f5300b34 100644 --- a/agent/lsp/client.py +++ b/agent/lsp/client.py @@ -56,6 +56,8 @@ from pathlib import Path from typing import Any, Awaitable, Callable, Dict, List, Optional, Set from urllib.parse import quote, unquote +from hermes_cli._subprocess_compat import windows_hide_flags + from agent.lsp.protocol import ( ERROR_CONTENT_MODIFIED, ERROR_METHOD_NOT_FOUND, @@ -294,6 +296,12 @@ class LSPClient: cmd = self._command if sys.platform == "win32": cmd = self._win_wrap_cmd(cmd) + # Suppress the cmd.exe console window that would otherwise flash + # every time we launch a ``.cmd``-wrapped language server + # (e.g. pyright-langserver.CMD) from a console-less host such as + # a VS Code/Zed extension running the ACP adapter. + # windows_hide_flags() is CREATE_NO_WINDOW on Windows, 0 on POSIX. + creationflags = windows_hide_flags() try: # start_new_session=True detaches the LSP server into its own @@ -312,6 +320,7 @@ class LSPClient: env=env, cwd=self._cwd, start_new_session=True, + creationflags=creationflags, ) except FileNotFoundError as e: raise LSPProtocolError( diff --git a/agent/lsp/eventlog.py b/agent/lsp/eventlog.py index b38627504b4a..f118ccf0acea 100644 --- a/agent/lsp/eventlog.py +++ b/agent/lsp/eventlog.py @@ -40,7 +40,7 @@ from __future__ import annotations import logging import os import threading -from typing import Tuple +from typing import List, Tuple # Dedicated logger name so the documented grep recipe survives a # ``logging.getLogger(__name__)`` rename of any internal module. @@ -188,6 +188,25 @@ def log_spawn_failed(server_id: str, workspace_root: str, exc: BaseException) -> ) +def log_reaped(keys: List[Tuple[str, str]], idle_timeout: float) -> None: + """Idle clients were shut down by the reaper. INFO — one line per + sweep so users can correlate memory drops with LSP activity. + + Also clears the ``log_active`` announce cache for the reaped keys so + a later respawn re-announces at INFO instead of logging a misleading + DEBUG "reused client". + """ + with _announce_lock: + for key in keys: + _announced_active.discard(key) + summary = ", ".join(f"{sid} ({root})" for sid, root in keys) + _emit( + "reaper", + logging.INFO, + f"reaped {len(keys)} idle client(s) after {idle_timeout:.0f}s: {summary}", + ) + + def reset_announce_caches() -> None: """Test-only: clear the dedup caches. Production code never calls this.""" with _announce_lock: @@ -209,5 +228,6 @@ __all__ = [ "log_timeout", "log_server_error", "log_spawn_failed", + "log_reaped", "reset_announce_caches", ] diff --git a/agent/lsp/install.py b/agent/lsp/install.py index 079033b772ad..2671e7ccd32d 100644 --- a/agent/lsp/install.py +++ b/agent/lsp/install.py @@ -30,11 +30,12 @@ import logging import os import shutil import subprocess -import sys import threading from pathlib import Path from typing import Any, Dict, Optional +from hermes_cli._subprocess_compat import windows_hide_flags + logger = logging.getLogger("agent.lsp.install") # Package-name → install-strategy hint registry. Each entry is a @@ -122,10 +123,9 @@ def _is_windows() -> bool: def hermes_lsp_bin_dir() -> Path: """Return the Hermes-owned bin staging dir for LSP servers.""" - home = os.environ.get("HERMES_HOME") - if home is None: - home = os.path.join(os.path.expanduser("~"), ".hermes") - p = Path(home) / "lsp" / "bin" + from hermes_constants import get_hermes_home + + p = get_hermes_home() / "lsp" / "bin" p.mkdir(parents=True, exist_ok=True) return p @@ -265,9 +265,10 @@ def _install_npm( [npm, "install", "--prefix", str(staging), "--silent", "--no-fund", "--no-audit", *install_targets], check=False, capture_output=True, - text=True, + text=True, encoding="utf-8", errors="replace", timeout=300, stdin=subprocess.DEVNULL, + creationflags=windows_hide_flags(), ) if proc.returncode != 0: logger.warning( @@ -313,10 +314,11 @@ def _install_go(pkg: str, bin_name: str) -> Optional[str]: [go, "install", pkg], check=False, capture_output=True, - text=True, + text=True, encoding="utf-8", errors="replace", timeout=600, env=env, stdin=subprocess.DEVNULL, + creationflags=windows_hide_flags(), ) if proc.returncode != 0: logger.warning( diff --git a/agent/lsp/manager.py b/agent/lsp/manager.py index d3b4244790b1..757f7ebc7b9e 100644 --- a/agent/lsp/manager.py +++ b/agent/lsp/manager.py @@ -59,6 +59,7 @@ from agent.lsp.workspace import ( logger = logging.getLogger("agent.lsp.manager") DEFAULT_IDLE_TIMEOUT = 600 # seconds; servers idle for >10min get reaped +MIN_IDLE_TIMEOUT = 30 # floor for config values; must exceed any per-op wait budget class _BackgroundLoop: @@ -176,6 +177,7 @@ class LSPService: self._spawning: Dict[Tuple[str, str], asyncio.Future] = {} self._last_used: Dict[Tuple[str, str], float] = {} self._state_lock = threading.Lock() + self._idle_reaper_task: Optional[asyncio.Task] = None # Delta baseline: file path → snapshot of diagnostics taken # immediately before a write. ``get_diagnostics_sync`` filters @@ -183,6 +185,9 @@ class LSPService: # introduced by the current edit. self._delta_baseline: Dict[str, List[Dict[str, Any]]] = {} + if self._enabled and self._idle_timeout > 0: + self._loop.run(self._start_idle_reaper(), timeout=2.0) + @classmethod def create_from_config(cls) -> Optional["LSPService"]: """Build a service from ``hermes_cli.config`` settings. @@ -205,6 +210,16 @@ class LSPService: wait_mode = lsp_cfg.get("wait_mode", "document") wait_timeout = float(lsp_cfg.get("wait_timeout", DIAGNOSTICS_DOCUMENT_WAIT)) install_strategy = lsp_cfg.get("install_strategy", "auto") + try: + idle_timeout = float(lsp_cfg.get("idle_timeout", DEFAULT_IDLE_TIMEOUT)) + except (TypeError, ValueError): + idle_timeout = DEFAULT_IDLE_TIMEOUT + if 0 < idle_timeout < MIN_IDLE_TIMEOUT: + # A timeout below the per-operation wait budget could reap a + # client mid-flight; the resulting outer timeout would then + # mark the (server, workspace) pair broken for the process + # lifetime. Clamp to a safe floor (0 still disables). + idle_timeout = MIN_IDLE_TIMEOUT servers_cfg = lsp_cfg.get("servers") or {} disabled = [] binary_overrides: Dict[str, List[str]] = {} @@ -235,6 +250,7 @@ class LSPService: env_overrides=env_overrides, init_overrides=init_overrides, disabled_servers=disabled, + idle_timeout=idle_timeout, ) # ------------------------------------------------------------------ @@ -434,6 +450,7 @@ class LSPService: # ``_clients`` with a half-initialized state. with self._state_lock: client = self._clients.pop(key, None) + self._last_used.pop(key, None) if client is not None: try: # Fire-and-forget shutdown — give it a second to cleanup, @@ -470,7 +487,7 @@ class LSPService: except Exception as e: # noqa: BLE001 logger.debug("snapshot open/wait failed: %s", e) return [] - self._last_used[(client.server_id, client.workspace_root)] = time.time() + self._touch(client) if not fresh: # No fresh data for the pre-edit content — an empty baseline # is safe: worst case the delta filter removes less, never @@ -499,7 +516,7 @@ class LSPService: except Exception as e: # noqa: BLE001 logger.debug("open/wait failed for %s: %s", file_path, e) return None - self._last_used[(client.server_id, client.workspace_root)] = time.time() + self._touch(client) if not fresh: return None return list(client.diagnostics_for(file_path, fresh_only=True)) @@ -539,6 +556,7 @@ class LSPService: with self._state_lock: client = self._clients.get(key) if client is not None and client.is_running: + self._last_used[key] = time.time() eventlog.log_active(srv.server_id, per_server_root) return client spawning = self._spawning.get(key) @@ -589,7 +607,7 @@ class LSPService: return None with self._state_lock: self._clients[key] = client - self._last_used[key] = time.time() + self._last_used[key] = time.time() eventlog.log_active(srv.server_id, per_server_root) spawn_future.set_result(client) return client @@ -597,7 +615,63 @@ class LSPService: with self._state_lock: self._spawning.pop(key, None) + async def _start_idle_reaper(self) -> None: + self._idle_reaper_task = asyncio.create_task(self._idle_reaper_loop()) + + def _touch(self, client: LSPClient) -> None: + """Refresh the last-used timestamp for a client we just used. + + Guarded on membership so a reaped-mid-operation client can't + resurrect an orphan ``_last_used`` entry after the reaper popped + the key. All writers and the reaper run on the background loop + thread; the lock keeps this consistent with the reader anyway. + """ + key = (client.server_id, client.workspace_root) + with self._state_lock: + if key in self._clients: + self._last_used[key] = time.time() + + async def _idle_reaper_loop(self) -> None: + interval = min(60.0, self._idle_timeout) + while True: + await asyncio.sleep(interval) + try: + await self._reap_idle_once() + except asyncio.CancelledError: + raise + except Exception as e: # noqa: BLE001 + # A transient sweep error must not kill the reaper — + # otherwise one bad shutdown permanently re-opens the + # unbounded-accumulation leak this loop exists to fix. + logger.debug("LSP idle reaper sweep error: %s", e) + + async def _reap_idle_once(self) -> None: + cutoff = time.time() - self._idle_timeout + with self._state_lock: + idle_keys = [ + key + for key in self._clients + if self._last_used.get(key, 0) < cutoff + ] + clients = [self._clients.pop(key) for key in idle_keys] + for key in idle_keys: + self._last_used.pop(key, None) + if clients: + eventlog.log_reaped( + [(c.server_id, c.workspace_root) for c in clients], + self._idle_timeout, + ) + await asyncio.gather( + *(client.shutdown() for client in clients), + return_exceptions=True, + ) + async def _shutdown_async(self) -> None: + reaper = self._idle_reaper_task + self._idle_reaper_task = None + if reaper is not None: + reaper.cancel() + await asyncio.gather(reaper, return_exceptions=True) with self._state_lock: clients = list(self._clients.values()) self._clients.clear() diff --git a/agent/lsp/servers.py b/agent/lsp/servers.py index 4056ba4dbab6..fc2a0b261693 100644 --- a/agent/lsp/servers.py +++ b/agent/lsp/servers.py @@ -710,9 +710,9 @@ def _find_pses_bundle(ctx: ServerContext) -> Optional[str]: env_path = os.environ.get("PSES_BUNDLE_PATH") if env_path: candidates.append(env_path) - home = os.environ.get("HERMES_HOME") or os.path.join( - os.path.expanduser("~"), ".hermes" - ) + from hermes_constants import get_hermes_home + + home = str(get_hermes_home()) candidates.append(os.path.join(home, "lsp", "PowerShellEditorServices")) for cand in candidates: @@ -796,9 +796,9 @@ def _spawn_powershell_es(root: str, ctx: ServerContext) -> Optional[SpawnSpec]: def hermes_lsp_session_dir() -> str: """Return (and create) the dir for PSES session/log scratch files.""" - home = os.environ.get("HERMES_HOME") or os.path.join( - os.path.expanduser("~"), ".hermes" - ) + from hermes_constants import get_hermes_home + + home = str(get_hermes_home()) d = os.path.join(home, "lsp", "pses") os.makedirs(d, exist_ok=True) return d diff --git a/agent/manual_compression_feedback.py b/agent/manual_compression_feedback.py index 91ada6ec4909..b2e12d683423 100644 --- a/agent/manual_compression_feedback.py +++ b/agent/manual_compression_feedback.py @@ -7,6 +7,36 @@ from typing import Any, Sequence from agent.redact import redact_sensitive_text +def describe_compression_lock_skip(lock_signal: Any) -> str: + """User-facing text for a manual /compress skipped by the compression lock. + + ``lock_signal`` is ``agent._compression_skipped_due_to_lock`` (or the + ``holder`` carried by the TUI's ``CompressionLockHeld``): a descriptive + holder string when another compressor CONFIRMED holds the lock, or + ``True``/``None`` when acquisition failed without a confirmed holder + (``hermes_state.try_acquire_compression_lock`` catches ``sqlite3.Error`` + internally and returns ``False``, so a failed acquire is NOT proof that + another compression is running). The two cases must be worded + differently: claiming "already in progress" on an unconfirmed failure + misdirects the user when the real problem is a broken lock subsystem. + """ + holder = ( + lock_signal + if isinstance(lock_signal, str) and lock_signal.strip() + else None + ) + if holder: + return ( + f"⏳ Compression already in progress for this session " + f"(holder: {holder}). Please wait for it to finish." + ) + return ( + "⏳ Compression skipped: could not acquire this session's " + "compression lock. Another compression may still be running, or " + "the lock check failed — try again shortly." + ) + + def summarize_manual_compression( before_messages: Sequence[dict[str, Any]], after_messages: Sequence[dict[str, Any]], diff --git a/agent/memory_manager.py b/agent/memory_manager.py index 3909f2ebcd39..6f3bbadd6f05 100644 --- a/agent/memory_manager.py +++ b/agent/memory_manager.py @@ -80,8 +80,17 @@ def normalize_tool_schema(schema: Any) -> Optional[Dict[str, Any]]: return schema -def memory_provider_tools_enabled(enabled_toolsets: Optional[List[str]]) -> bool: +def memory_provider_tools_enabled( + enabled_toolsets: Optional[List[str]], + disabled_toolsets: Optional[List[str]] = None, + *, + memory_tool_present: bool = False, +) -> bool: """Return whether external memory-provider tools should be exposed.""" + if disabled_toolsets and "memory" in disabled_toolsets: + return False + if memory_tool_present: + return True if enabled_toolsets is None: return True if not enabled_toolsets: @@ -110,9 +119,10 @@ def inject_memory_provider_tools(agent: Any) -> int: for tool in tools if isinstance(tool, dict) } - if ( - "memory" not in existing_tool_names - and not memory_provider_tools_enabled(getattr(agent, "enabled_toolsets", None)) + if not memory_provider_tools_enabled( + getattr(agent, "enabled_toolsets", None), + getattr(agent, "disabled_toolsets", None), + memory_tool_present="memory" in existing_tool_names, ): return 0 diff --git a/agent/message_sanitization.py b/agent/message_sanitization.py index 29a4b8691ae8..dc4df3dd2702 100644 --- a/agent/message_sanitization.py +++ b/agent/message_sanitization.py @@ -14,6 +14,7 @@ re-exports from ``run_agent`` remain in place so existing imports from __future__ import annotations +import hashlib import json import logging import re @@ -474,4 +475,378 @@ __all__ = [ "_sanitize_tools_non_ascii", "_strip_images_from_messages", "_sanitize_structure_non_ascii", + # call_id policy owners (F4 consolidation) + "deterministic_call_id", + "coalesce_tool_call_id", + "uniquify_tool_call_ids", + # reasoning_content policy owners (F4 consolidation) + "reasoning_echo_family", + "matches_reasoning_echo_family", + "needs_reasoning_echo", + "apply_reasoning_content_policy", + "reapply_reasoning_echo", ] + + +# --------------------------------------------------------------------------- +# call_id policy — single owner (audit F4, incident chain I4) +# --------------------------------------------------------------------------- +# +# Three forked policy sites converged here: +# * agent/codex_responses_adapter.py `_deterministic_call_id` — hash +# synthesis when a provider omits call_id (fa3ab2ffd0 → e45f2b39e2). +# * run_agent.AIAgent._get_tool_call_id_static — `call_id or id` +# coalescing for dicts and SDK objects. +# * run_agent.AIAgent._uniquify_tool_call_ids — duplicate-id repair with +# deterministic `_d` suffixes (#58327 loss class). +# +# NOT consolidated (different scheme on purpose): +# agent/transports/codex_event_projector._deterministic_call_id maps codex +# app-server ITEM ids (`codex__`), not chat tool-call +# content; merging the two would change ids and invalidate prompt caches. +# +# HARD INVARIANT: everything here must stay deterministic (never uuid4) and +# byte-identical for existing inputs — these ids feed prompt-cache prefixes. + + +def deterministic_call_id(fn_name: str, arguments: str, index: int = 0) -> str: + """Generate a deterministic call_id from tool call content. + + Used as a fallback when the API doesn't provide a call_id. + Deterministic IDs prevent cache invalidation — random UUIDs would + make every API call's prefix unique, breaking OpenAI's prompt cache. + """ + seed = f"{fn_name}:{arguments}:{index}" + digest = hashlib.sha256(seed.encode("utf-8", errors="replace")).hexdigest()[:12] + return f"call_{digest}" + + +def coalesce_tool_call_id(tc: Any) -> str: + """Extract the effective call ID from a tool_call entry (dict or object). + + Single owner for the ``call_id or id`` coalescing rule: Codex Responses + tool calls carry ``call_id`` (authoritative pairing key), Chat + Completions ones carry ``id`` only. Returns ``""`` when neither is set. + """ + if isinstance(tc, dict): + return (tc.get("call_id", "") or tc.get("id", "") or "").strip() + return (getattr(tc, "call_id", "") or getattr(tc, "id", "") or "").strip() + + +def uniquify_tool_call_ids(tool_calls: list) -> list: + """Ensure every tool call in a single assistant turn has a distinct id. + + Some models/providers reuse one call id across different calls in a + single batch (observed with native Kimi Responses replays, Ollama- + compatible endpoints, and degraded models at long context; same bug + class as openclaw/openclaw#110518 / #110956). Duplicate ids are lossy + downstream: the pre-API sanitizer keeps only the first call/result + pair per id (#58327), so the later call's result silently vanishes + from every replayed payload, and strict providers (Anthropic + tool_use, DeepSeek) reject duplicate ids outright. + + The first occurrence keeps its id; later collisions get a + deterministic ``_d`` suffix — never a random UUID, which would + break prompt-cache prefix stability across replays. Mutates the + entries in place (SDK models / SimpleNamespace / dicts) and returns + the same list. Blank/missing ids are left for the deterministic + fallback in ``build_assistant_message``. + """ + seen: set = set() + for tc in tool_calls or []: + # Same coalescing rule as ``coalesce_tool_call_id`` but tolerant of + # non-string ids (degraded models can emit ints/None here). + if isinstance(tc, dict): + raw = tc.get("call_id") or tc.get("id") or "" + else: + raw = getattr(tc, "call_id", None) or getattr(tc, "id", None) or "" + raw = raw.strip() if isinstance(raw, str) else "" + if not raw: + continue + # Composite Responses ids ("call_x|fc_y") collide on the call + # half — that's the pairing key providers enforce per turn. + cid = raw.split("|", 1)[0] + if not cid: + continue + if cid not in seen: + seen.add(cid) + continue + n = 2 + new_id = f"{cid}_d{n}" + while new_id in seen: + n += 1 + new_id = f"{cid}_d{n}" + seen.add(new_id) + + def _renamed(value): + # Preserve a composite id's response-item half so the + # provider's real fc_/item id survives the rename. + if isinstance(value, str) and "|" in value: + return f"{new_id}|{value.split('|', 1)[1]}" + return new_id + + try: + if isinstance(tc, dict): + if tc.get("id"): + tc["id"] = _renamed(tc["id"]) + else: + tc["id"] = new_id + if tc.get("call_id"): + tc["call_id"] = new_id + else: + tc.id = _renamed(getattr(tc, "id", None)) + if getattr(tc, "call_id", None): + tc.call_id = new_id + except Exception: + logger.warning( + "Could not uniquify duplicate tool call id %s", cid + ) + continue + _fn = tc.get("function") if isinstance(tc, dict) else getattr(tc, "function", None) + _fn_name = (_fn.get("name") if isinstance(_fn, dict) else getattr(_fn, "name", None)) or "?" + logger.warning( + "Model reused tool call id %s within one turn; renamed the " + "duplicate to %s (tool=%s) to keep call/result pairing " + "lossless.", cid, new_id, _fn_name, + ) + return tool_calls + + +# --------------------------------------------------------------------------- +# reasoning_content policy — single owner (audit F4) +# --------------------------------------------------------------------------- +# +# The strip-vs-repad decision was previously forked across the wire files in +# separate incident commits (2b3a4f0af8 strip for strict providers, +# b5495db701 re-pad for require-side, 94b3131be7/9a9f8a6d99 kimi pad). The +# POLICY — which provider direction gets which treatment — lives here as one +# rule table + apply functions; adapters keep only SYNTAX mapping (e.g. +# anthropic_adapter turning reasoning_content into a thinking block). +# +# Direction table: +# require-side (echo-back enforced; replays 400 without the field): +# kimi — provider kimi-coding/kimi-coding-cn, or host api.kimi.com / +# moonshot.ai / moonshot.cn. Host-driven on purpose: +# aggregators re-exporting kimi models reject the echo. +# deepseek — provider "deepseek", model contains "deepseek", or host +# api.deepseek.com (#15250; V4 rejects empty-string pads, +# hence the " " single-space pad, #17341). +# mimo — provider "xiaomi", model contains "mimo", or host +# *.xiaomimimo.com. +# strict side (field rejected with 400/422 "Extra inputs are not +# permitted"): everyone else — Mistral, Cerebras, Groq, SambaNova, … +# (#45655). Strip the key entirely, even a single-space pad. + +_REASONING_ECHO_RULES: tuple = ( + # (family, exact providers (raw), exact providers (lowered), + # model substrings (lowered), base_url hosts) + ("kimi", frozenset({"kimi-coding", "kimi-coding-cn"}), frozenset(), (), + ("api.kimi.com", "moonshot.ai", "moonshot.cn")), + ("deepseek", frozenset(), frozenset({"deepseek"}), ("deepseek",), + ("api.deepseek.com",)), + ("mimo", frozenset(), frozenset({"xiaomi"}), ("mimo",), + ("api.xiaomimimo.com", "xiaomimimo.com")), +) + + +def _family_rule(family: str) -> tuple: + for rule in _REASONING_ECHO_RULES: + if rule[0] == family: + return rule + raise KeyError(family) + + +def matches_reasoning_echo_family( + family: str, provider: Any, model: Any, base_url: Any +) -> bool: + """True when (provider, model, base_url) matches one echo-back family. + + Families can overlap (e.g. a deepseek-named model pointed at a kimi + host); this membership test is independent per family so per-family + predicates keep their original semantics. + """ + from utils import base_url_host_matches + + _, raw_providers, lowered_providers, model_subs, hosts = _family_rule(family) + provider_lower = (provider or "").lower() + model_lower = (model or "").lower() + if provider in raw_providers or provider_lower in lowered_providers: + return True + if any(sub in model_lower for sub in model_subs): + return True + return any(base_url_host_matches(base_url, host) for host in hosts) + + +def reasoning_echo_family(provider: Any, model: Any, base_url: Any) -> "str | None": + """Classify the provider direction for the reasoning_content echo policy. + + Returns ``"kimi"``, ``"deepseek"``, or ``"mimo"`` (first match in table + order) when the target endpoint enforces reasoning_content echo-back on + assistant turns, else ``None`` (strict/indifferent side — the field must + be stripped). + """ + for rule in _REASONING_ECHO_RULES: + if matches_reasoning_echo_family(rule[0], provider, model, base_url): + return rule[0] + return None + + +def needs_reasoning_echo(provider: Any, model: Any, base_url: Any) -> bool: + """True when the endpoint requires reasoning_content echo-back.""" + return reasoning_echo_family(provider, model, base_url) is not None + + +def apply_reasoning_content_policy( + source_msg: dict, api_msg: dict, needs_thinking_pad: bool +) -> None: + """Copy provider-facing reasoning fields onto an API replay message. + + ``needs_thinking_pad`` is the require-side flag (see + ``needs_reasoning_echo`` / the agent's cached + ``_needs_thinking_reasoning_pad``). Mutates ``api_msg`` in place. + """ + if source_msg.get("role") != "assistant": + return + + # 1. Explicit reasoning_content already set. + # + # When the active provider enforces the thinking-mode echo-back + # (DeepSeek / Kimi / MiMo), preserve it verbatim — that includes their + # own space-placeholder written at creation time and any valid reasoning + # from the same provider. Sessions persisted BEFORE #17341 have + # empty-string placeholders pinned at creation time; DeepSeek V4 Pro + # rejects those with HTTP 400, so upgrade "" → " " on replay. + # + # When the active provider does NOT enforce echo-back, strip the field + # entirely. Strict OpenAI-compatible providers (Mistral, Cerebras, Groq, + # SambaNova, …) reject ANY reasoning_content key in input messages with + # HTTP 400/422 ("Extra inputs are not permitted"), even an empty string + # or a single-space pad. This is the cross-provider fallback case: a + # reasoning primary (DeepSeek/Kimi/MiMo) pads history with " ", then a + # fallback to a strict provider replays that pad and 422s. Stripping + # here covers the rebuild path; ``reapply_reasoning_echo`` covers the + # already-built api_messages path. Refs #45655. + existing = source_msg.get("reasoning_content") + if isinstance(existing, str): + if not needs_thinking_pad: + api_msg.pop("reasoning_content", None) + elif existing == "": + api_msg["reasoning_content"] = " " + else: + api_msg["reasoning_content"] = existing + return + + # 2. Cross-provider poisoned history (#15748): on DeepSeek/Kimi, + # if the source turn has tool_calls AND a 'reasoning' field but no + # 'reasoning_content' key, the 'reasoning' text was written by a + # prior provider (e.g. MiniMax) — DeepSeek's own _build_assistant_message + # pins reasoning_content at creation time for tool-call turns, so the + # shape (reasoning set, reasoning_content absent, tool_calls present) + # is unreachable from same-provider DeepSeek history after this fix. + # Inject a single space to satisfy the API without leaking another + # provider's chain of thought to DeepSeek/Kimi. Space (not "") + # because DeepSeek V4 Pro rejects empty-string reasoning_content + # in thinking mode (refs #17341). + normalized_reasoning = source_msg.get("reasoning") + if ( + needs_thinking_pad + and source_msg.get("tool_calls") + and isinstance(normalized_reasoning, str) + and normalized_reasoning + ): + api_msg["reasoning_content"] = " " + return + + # 3. Healthy session: promote 'reasoning' field to 'reasoning_content' + # for providers that use the internal 'reasoning' key. + # This must happen before the unconditional empty-string fallback so + # genuine reasoning content is not overwritten (#15812 regression in + # PR #15478). Only promote for providers that enforce echo-back — + # strict providers reject the field (refs #45655). + if isinstance(normalized_reasoning, str) and normalized_reasoning: + if needs_thinking_pad: + api_msg["reasoning_content"] = normalized_reasoning + else: + api_msg.pop("reasoning_content", None) + return + + # 4. DeepSeek / Kimi thinking mode: all assistant messages need + # reasoning_content. Inject a single space to satisfy the provider's + # requirement when no explicit reasoning content is present. Covers + # both tool-call turns (already-poisoned history with no reasoning + # at all) and plain text turns. Space (not "") because DeepSeek V4 + # Pro tightened validation and rejects empty string with HTTP 400 + # ("The reasoning content in the thinking mode must be passed back + # to the API"). Refs #17341. + if needs_thinking_pad: + api_msg["reasoning_content"] = " " + return + + # 5. reasoning_content was present but not a string (e.g. None after + # context compaction). Don't pass null to the API. + api_msg.pop("reasoning_content", None) + + +def reapply_reasoning_echo(api_messages: list, needs_thinking_pad: bool) -> int: + """Re-pad (or strip) assistant turns' reasoning_content for the active provider. + + ``api_messages`` is built once, before the retry loop, while the *primary* + provider is active. A mid-conversation fallback can then switch providers, + so the reasoning fields baked into ``api_messages`` are shaped for the + *prior* provider and must be reconciled against the *current* one: + + * Switching TO a require-side provider (DeepSeek / Kimi / MiMo thinking + mode): assistant turns built when the prior provider did NOT need the + echo-back go out without ``reasoning_content`` and the new provider + rejects them with HTTP 400 ("The reasoning_content in the thinking mode + must be passed back"). Re-apply the pad. + + * Switching TO a strict provider that rejects the field (Mistral, + Cerebras, Groq, SambaNova, …): assistant turns built under a reasoning + primary carry a ``reasoning_content`` pad (often a single space ``" "``), + and the strict provider rejects it with HTTP 400/422 ("Extra inputs are + not permitted"). Strip the field. This is the exact cross-provider + fallback bug from #45655 — a DeepSeek primary pads history with ``" "``, + the request falls back to Mistral, and Mistral 422s on the stale pad. + + Calling this immediately before building the request kwargs reconciles the + fields against the *current* provider. It is idempotent and safe to call + every iteration; it covers every fallback path. + + Returns the number of assistant turns whose reasoning_content was added or + removed. + """ + changed = 0 + for api_msg in api_messages: + if api_msg.get("role") != "assistant": + continue + if needs_thinking_pad: + if api_msg.get("reasoning_content"): + continue + apply_reasoning_content_policy(api_msg, api_msg, needs_thinking_pad) + if api_msg.get("reasoning_content"): + changed += 1 + else: + # Strict provider — strip any stale reasoning_content pad left + # over from a reasoning primary so the fallback request doesn't + # 400/422 on it. + if "reasoning_content" in api_msg: + api_msg.pop("reasoning_content", None) + changed += 1 + return changed + + +# --------------------------------------------------------------------------- +# Image / multimodal parts — evaluated, NOT consolidated (verdict: syntax) +# --------------------------------------------------------------------------- +# +# The per-adapter image handling is format-specific SYNTAX, not shared policy: +# * anthropic_adapter (~1817): data-URL → Anthropic `source: {type: base64}` +# block mapping — Anthropic wire shape only. +# * codex_responses_adapter (~113/165/812): chat `image_url` parts → +# Responses `input_image` items and image counting for log summaries — +# Responses wire shape only. +# * transports/chat_completions: pass-through (native format). +# The one genuinely shared image POLICY — removing images when a server +# rejects them while preserving tool_call_id pairing — already has a single +# owner here: ``_strip_images_from_messages`` above. diff --git a/agent/moa_loop.py b/agent/moa_loop.py index 6d1aad9c3750..173816c8cbd1 100644 --- a/agent/moa_loop.py +++ b/agent/moa_loop.py @@ -10,7 +10,9 @@ from __future__ import annotations import hashlib import logging -from concurrent.futures import ThreadPoolExecutor +import re +import threading +from concurrent.futures import ThreadPoolExecutor, wait as _futures_wait from typing import Any from agent.auxiliary_client import call_llm @@ -19,6 +21,136 @@ from agent.transports import get_transport logger = logging.getLogger(__name__) +# --- MoA privacy filter (config: moa.privacy_filter — '' | display | full) --- +# +# Advisor (reference) outputs can echo PII from the conversation — emails, +# phone numbers, credentials pasted by the user — into surfaces the user may +# not expect: the labelled reference blocks rendered in the UI, saved MoA +# trace files, and (in `full` mode) the guidance block injected into the +# aggregator prompt (issue #59959). Secret/credential shapes (API-key +# prefixes, JWTs, private keys, DB connection strings, E.164 phone numbers) +# are handled by the repo's central redactor, ``agent.redact +# .redact_sensitive_text`` — the MoA filter never re-implements those. The +# two patterns below cover the PII classes the central redactor deliberately +# leaves alone for log/tool output (emails and formatted phone numbers). +# +# Pattern safety: advisory text is frequently code-review-shaped — line +# numbers, timestamps, git SHAs, IDs, IP addresses. A bare 10-digit match +# would mangle all of those, so the phone pattern requires clearly delimited +# formatting: a parenthesized area code and/or explicit `-`/`.` separators +# between groups ((555) 123-4567, 555-123-4567, 555.123.4567, +1 555-123-4567). +# Undelimited digit runs (5551234567), dates (2026-07-12), times (12:34:56), +# hex IDs, and dotted quads never match. International numbers in E.164 form +# (+14155551234) are already masked by the central redactor. +_MOA_EMAIL_RE = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b") +_MOA_PHONE_RE = re.compile( + r"(? Any: + """Redact secrets + PII from one advisor/reference text surface. + + Centralized secret shapes first (force=True: the MoA privacy filter is + its own explicit opt-in, independent of the global log-redaction toggle; + code_file=True: advisory text is prose/code, so the ENV/JSON assignment + heuristics that mangle source snippets stay off), then the MoA-specific + email/formatted-phone patterns. Non-string inputs pass through unchanged. + """ + if not isinstance(text, str) or not text: + return text + from agent.redact import redact_sensitive_text + + text = redact_sensitive_text(text, force=True, code_file=True) + text = _MOA_EMAIL_RE.sub("[redacted email]", text) + text = _MOA_PHONE_RE.sub("[redacted phone]", text) + return text + + +def _moa_privacy_mode(moa_raw: Any) -> str: + """Resolve the normalized privacy-filter mode from a raw ``moa`` config.""" + from hermes_cli.moa_config import coerce_privacy_filter + + raw = moa_raw if isinstance(moa_raw, dict) else {} + return coerce_privacy_filter(raw.get("privacy_filter")) + + +def _redact_reference_outputs( + reference_outputs: list[tuple[str, str, Any]], +) -> list[tuple[str, str, Any]]: + """Return reference-output tuples with their advisor text redacted. + + The ``_RefAccounting`` third slot is left as-is — accounting fields carry + no advisor text; the full-output/input trace fields are redacted + separately at trace-stash time (see create()) so the LIVE cache keeps raw + accounting objects untouched. + """ + return [ + (label, _redact_reference_text(text), acct) + for label, text, acct in reference_outputs + ] + + +def _redact_trace_messages(messages: Any) -> Any: + """Redact message copies destined for trace persistence. + + Handles both string content and structured content-part lists (e.g. + cache_control-decorated text parts). Unknown shapes pass through. + """ + if not isinstance(messages, list): + return messages + out: list[Any] = [] + for m in messages: + if not isinstance(m, dict): + out.append(m) + continue + content = m.get("content") + if isinstance(content, str): + out.append({**m, "content": _redact_reference_text(content)}) + elif isinstance(content, list): + out.append( + { + **m, + "content": [ + {**p, "text": _redact_reference_text(p.get("text"))} + if isinstance(p, dict) and isinstance(p.get("text"), str) + else p + for p in content + ], + } + ) + else: + out.append(m) + return out + + +def _redact_trace_accounting(acct: Any) -> Any: + """Return a copy of a ``_RefAccounting`` with its trace text redacted. + + Traces persist the advisor's FULL input messages and output to disk, so a + privacy-filtered run must not write raw PII there. Usage/cost fields are + copied verbatim (numbers, no text). Non-accounting objects pass through. + """ + if not isinstance(acct, _RefAccounting): + return acct + return _RefAccounting( + acct.usage, + acct.cost_usd, + acct.cost_status, + acct.cost_source, + messages=_redact_trace_messages(acct.messages), + output=_redact_reference_text(acct.output), + model=acct.model, + provider=acct.provider, + temperature=acct.temperature, + ) + + + # Upper bound on concurrent reference-model calls. References are independent # advisory calls (no tools, no inter-dependence), so we fan them out the same # way delegate_task runs a batch: all in flight at once, results collected when @@ -105,6 +237,16 @@ _REFERENCE_SYSTEM_PROMPT = ( "you should not try to or apologize for being unable to. A separate " "aggregator/orchestrator model holds those capabilities and will take the " "actual actions.\n\n" + "CRITICAL: You must NEVER claim or imply that you have executed a command, " + "downloaded a file, accessed a URL, or performed any action. You can only " + "analyze and advise based on the conversation context. Examples of what to " + "avoid:\n" + "- Bad: \"I ran curl and got 404.\"\n" + "- Bad: \"I downloaded the file successfully.\"\n" + "- Bad: \"I checked the repository and found...\"\n" + "- Good: \"Based on the error pattern, a curl request to that URL would likely return 404.\"\n" + "- Good: \"The conversation suggests downloading this file may help.\"\n" + "- Good: \"From the context, checking the repository would reveal...\"\n\n" "The conversation below is the current state of a task handled by that " "acting agent. Your job is to give your most intelligent analysis of that " "state: understand the goal, reason about the problem, and advise on what " @@ -115,7 +257,8 @@ _REFERENCE_SYSTEM_PROMPT = ( "asking for access.\n\n" "Respond with your advice directly — no preamble, no disclaimers about " "tools or access. Your response is private guidance handed to the " - "aggregator, not an answer shown to the user." + "aggregator, not an answer shown to the user. NEVER claim to have executed " + "anything." ) @@ -212,11 +355,30 @@ def _slot_runtime(slot: dict[str, Any]) -> dict[str, Any]: out["api_key"] = rt["api_key"] if rt.get("api_mode"): out["api_mode"] = rt["api_mode"] + request_overrides = rt.get("request_overrides") + if isinstance(request_overrides, dict): + extra_body = request_overrides.get("extra_body") + if isinstance(extra_body, dict) and extra_body: + out["extra_body"] = dict(extra_body) except Exception as exc: # pragma: no cover - defensive logger.debug("MoA slot runtime resolution failed for %s: %s", _slot_label(slot), exc) return out +def _merge_slot_extra_body( + slot_extra_body: Any, + caller_extra_body: Any, +) -> Any: + """Merge slot defaults with a caller override for ``call_llm``.""" + if isinstance(slot_extra_body, dict) and slot_extra_body: + if isinstance(caller_extra_body, dict): + return {**slot_extra_body, **caller_extra_body} + if caller_extra_body: + return caller_extra_body + return dict(slot_extra_body) + return caller_extra_body + + def _maybe_apply_moa_cache_control( messages: list[dict[str, Any]], runtime: dict[str, Any], @@ -226,10 +388,10 @@ def _maybe_apply_moa_cache_control( Reuses the SAME policy function as the main agent loop (``anthropic_prompt_cache_policy``) resolved against the slot's own - provider/base_url/api_mode/model, and the SAME breakpoint layout - (``apply_anthropic_cache_control``, system_and_3). This keeps advisor and - aggregator calls decorated exactly like an acting agent on that provider - would be — no MoA-specific caching logic to drift. + provider/base_url/api_mode/model and shared marker helper + (``apply_anthropic_cache_control``). MoA has no per-session static prefix, + so it uses the helper's legacy system-and-3 fallback without carrying a + separate caching strategy. Returns the messages unchanged on any resolution error or when the policy says the route doesn't honor markers. @@ -262,13 +424,15 @@ def _maybe_apply_moa_cache_control( def _run_reference( - slot: dict[str, str], + slot: dict[str, Any], ref_messages: list[dict[str, Any]], *, temperature: float | None = None, max_tokens: int | None = None, + reference_timeout: float | None = None, + context_length_cache: Any = None, ) -> tuple[str, str, Any]: - """Call one reference model and return ``(label, text, usage)``. + """Call one reference model and return ``(label, text, accounting)``. The slot is resolved to its provider's real runtime (via ``_slot_runtime``) and called through the same ``call_llm`` request-building path any model @@ -302,10 +466,25 @@ def _run_reference( # trimmed view (_reference_messages) already strips the agent's own # system prompt, so this is the only system message the reference sees. messages = [{"role": "system", "content": _REFERENCE_SYSTEM_PROMPT}, *ref_messages] - # Apply the same Anthropic-style prompt-caching decoration the main - # agent loop applies (system_and_3 breakpoints). The advisory view is - # append-only across iterations (new turns append before the trailing - # synthetic marker), so on cache-honoring routes (Claude via + # Trim to fit THIS reference model's context window. Reference models + # may have a smaller window than the aggregator (e.g. kimi-k2.7-code + # @ 262K advising a glm-5.2 @ 1M conversation); without this trim the + # provider returns a hard HTTP 400 which the except below silently + # converts to a [failed: …] note (issue #60345). Estimated AFTER the + # advisory system prompt is prepended so its tokens count against the + # budget too. + messages = _trim_messages_for_reference( + messages, + slot, + runtime, + reserve_output_tokens=max_tokens, + context_length_cache=context_length_cache, + ) + # Apply the Anthropic-style prompt-caching decoration used by the main + # agent loop. This fixed reference prompt has no session-specific + # prefix split, so the helper uses its legacy system-and-3 fallback. + # The advisory view is append-only across iterations (new turns append + # before the trailing synthetic marker), so on cache-honoring routes (Claude via # OpenRouter/native, MiniMax, Qwen/DashScope) iteration N+1's prefix # replays iteration N's cached prefix. Without this, Claude advisors # served ZERO cache reads across an entire benchmark run (measured: @@ -314,12 +493,38 @@ def _run_reference( # (their caching is automatic; markers are ignored harmlessly, but we # only decorate when the policy says the route honors them). messages = _maybe_apply_moa_cache_control(messages, runtime) + # Per-slot max_tokens takes precedence over the preset-level + # reference_max_tokens passed in by the caller. This lets each + # reference model have its own output cap independently. + _slot_max_tokens: int | None = slot.get("max_tokens") + _effective_max_tokens = _slot_max_tokens if _slot_max_tokens is not None else max_tokens + extra_headers = None + # Normalize provider aliases (github, github-copilot, github-models, + # ...) through the auxiliary client's canonical alias table so slot + # configs that spell Copilot differently still get the header. + from agent.auxiliary_client import _normalize_aux_provider + + if _normalize_aux_provider(str(runtime.get("provider") or "")) in ( + "copilot", + "copilot-acp", + ): + # Copilot Pro/Pro+ gates some premium chat models on request + # attribution. The main agent marks the first API request of a + # user turn as ``x-initiator: user``; MoA reference fan-out is also + # directly serving the user's current turn, not a background agent + # task, so mirror that header here. Without it, Claude/Gemini + # Copilot advisors can be rejected as unavailable to the + # ``copilot-language-server`` integrator even though standalone + # Copilot calls work. + extra_headers = {"x-initiator": "user"} response = call_llm( task="moa_reference", messages=messages, temperature=temperature, - max_tokens=max_tokens, + max_tokens=_effective_max_tokens, + timeout=reference_timeout, reasoning_config=_slot_reasoning_config(slot), + extra_headers=extra_headers, **runtime, ) usage = CanonicalUsage() @@ -378,12 +583,162 @@ def _run_reference( ) +# Output-token headroom reserved inside the reference's context window when +# the preset does not cap advisor output (reference_max_tokens=None). Roughly +# one long-form advisory answer; generous enough for thinking models' visible +# output without starving the input budget. +_REFERENCE_DEFAULT_OUTPUT_RESERVE = 8192 + +# Additional estimation slack: estimate_messages_tokens_rough is a rough +# chars/4 heuristic and providers tokenize less favorably on code/JSON-heavy +# transcripts, so keep a safety fraction of the window unbudgeted. +_REFERENCE_TRIM_SAFETY_FRACTION = 0.10 + + +def _trim_messages_for_reference( + messages: list[dict[str, Any]], + slot: dict[str, str], + runtime: dict[str, Any], + *, + reserve_output_tokens: int | None = None, + context_length_cache: Any = None, +) -> list[dict[str, Any]]: + """Trim an advisory request to fit within a reference model's context window. + + Reference models may have a smaller context window than the aggregator or + the main conversation. Without this trim, a reference whose window is + exceeded gets a hard HTTP 400 from the provider, which ``_run_reference``'s + try/except silently converts to a ``[failed: …]`` note — the MoA turn + silently degrades to fewer references (issue #60345). + + ``messages`` is the FULL request as it will be sent — the advisory system + prompt already prepended — so the estimate covers everything the provider + will count. The budget reserves ``reserve_output_tokens`` (the preset's + ``reference_max_tokens`` when set, else a sane constant) for the model's + response plus a safety fraction for estimator error. + + Trimming drops the OLDEST conversation frames (right after the system + prompt) and preserves two invariants of the advisory view, which is + text-only user/assistant turns (``_reference_messages`` renders tool + calls/results inline, so there are no tool-result frames to orphan): + + - the system prompt (index 0) is always kept; + - the first non-system message stays ``user``-first — after each pop, + any now-leading assistant turns are popped too, so no provider ever + sees an assistant-first conversation; + - the trailing user turn (the synthetic judge-the-state marker) and at + least one preceding turn are always kept, even if still over budget — + a too-long-but-recent view beats an empty request. + + ``context_length_cache`` is an optional per-turn dict keyed by + ``(provider, model)`` so one fan-out (and every iteration reusing the + cache) resolves each model's window at most once instead of re-probing + metadata sources per-reference-per-iteration. When the window cannot be + resolved, messages are returned unchanged. + """ + if not messages: + return messages + + from agent.model_metadata import ( + estimate_messages_tokens_rough, + get_model_context_length, + ) + + model = str(slot.get("model") or "") + provider = str(runtime.get("provider") or slot.get("provider") or "") + if not model: + return messages + + cache_key = (provider, model) + context_length: int | None = None + if isinstance(context_length_cache, dict) and cache_key in context_length_cache: + context_length = context_length_cache[cache_key] + else: + try: + context_length = get_model_context_length( + model=model, + base_url=str(runtime.get("base_url") or ""), + api_key=str(runtime.get("api_key") or ""), + provider=provider, + ) + except Exception: + logger.debug( + "MoA reference context-length resolution failed for %s", + _slot_label(slot), + ) + context_length = None + if isinstance(context_length_cache, dict): + # Cache failures too (as None) — a flaky metadata source should + # not be re-probed for every reference of every iteration. + context_length_cache[cache_key] = context_length + + if not isinstance(context_length, int) or context_length <= 0: + return messages + + reserve = ( + int(reserve_output_tokens) + if isinstance(reserve_output_tokens, int) and reserve_output_tokens > 0 + else _REFERENCE_DEFAULT_OUTPUT_RESERVE + ) + budget = int(context_length * (1.0 - _REFERENCE_TRIM_SAFETY_FRACTION)) - reserve + if budget <= 0: + return messages + + estimated = estimate_messages_tokens_rough(messages) + if estimated <= budget: + return messages + + has_system = bool(messages) and messages[0].get("role") == "system" + head = [messages[0]] if has_system else [] + body = list(messages[1:] if has_system else messages) + + # Keep the trailing user turn plus at least one preceding turn. + while len(body) > 2 and estimate_messages_tokens_rough(head + body) > budget: + body.pop(0) + # Preserve the user-first invariant: never leave the advisory + # conversation starting on an assistant turn after a pop. + while len(body) > 2 and body[0].get("role") == "assistant": + body.pop(0) + # The loop can stop with two frames left where the first is an + # assistant turn — enforce user-first even then (a lone trailing user + # turn is a valid request; an assistant-first one is not). + while len(body) > 1 and body[0].get("role") == "assistant": + body.pop(0) + + trimmed = head + body + dropped = len(messages) - len(trimmed) + if dropped: + logger.info( + "MoA reference %s: estimated %d tokens exceeds budget %d " + "(window %d, output reserve %d); dropped %d oldest message(s).", + _slot_label(slot), + estimated, + budget, + context_length, + reserve, + dropped, + ) + return trimmed + + +_REFERENCE_POLL_INTERVAL_S = 5.0 + +# Sentinel text for a reference slot whose wait was aborted by a user +# interrupt. Shared by _run_references_parallel (which writes it) and the +# facade cache logic (which must never cache it as real advice). +_INTERRUPTED_REFERENCE_NOTE = "[skipped: interrupted by user]" + + def _run_references_parallel( - reference_models: list[dict[str, str]], + reference_models: list[dict[str, Any]], ref_messages: list[dict[str, Any]], *, temperature: float | None = None, max_tokens: int | None = None, + progress_callback: Any = None, + reference_timeout: float | None = None, + agent: Any = None, + late_accounting_sink: Any = None, ) -> list[tuple[str, str, Any]]: """Fan out all reference models in parallel, returning outputs in order. @@ -393,8 +748,30 @@ def _run_references_parallel( ``Reference {idx}`` labelling stays stable. MoA presets that reference another MoA preset are skipped here (recursion guard) with a labelled note. - Each element is ``(label, text, usage)`` where usage is a - ``CanonicalUsage`` (zeroed for skipped/failed references). + If ``progress_callback`` is provided it is invoked as each reference + completes: ``progress_callback(refs_done, refs_total, label)``. The total + matches ``len(reference_models)`` so listeners can render a status-bar + progress like ``MOA: 2/3 refs done``. Best-effort — failures are logged + but never break the fan-out (display must never block a turn). + + Each element is ``(label, text, accounting)`` where accounting is a + ``_RefAccounting`` object (zeroed for skipped/failed/interrupted + references). + + When *agent* is given, the fan-out is interruptible: waiting for the + batch is broken into ``_REFERENCE_POLL_INTERVAL_S``-second polls (instead + of one blocking ``future.result()`` per reference) so a user interrupt + mid-turn can abort the wait — mirroring the same interrupt check + ``agent.tool_executor`` already applies to its own concurrent tool + batch. This does not add or change any per-reference *timeout* (that is + ``reference_timeout`` / ``auxiliary.moa_reference.timeout``, resolved + elsewhere) — it only lets the caller stop waiting early. References + already in flight cannot be forcibly killed (``call_llm`` is a blocking + HTTP call with no interrupt hook of its own, same limitation + tool_executor has for tools without an interrupt check); an interrupted + reference's own timeout still reaps its thread independently. *agent* is + optional and defaults to ``None``, preserving the uninterruptible + blocking behavior for any caller that doesn't pass it. """ from agent.usage_pricing import CanonicalUsage @@ -402,7 +779,7 @@ def _run_references_parallel( return [] results: list[tuple[str, str, Any] | None] = [None] * len(reference_models) - futures = {} + futures: dict[Any, int] = {} workers = min(_MAX_REFERENCE_WORKERS, len(reference_models)) # Reference slots run on bare executor threads, which start with an empty # contextvars.Context — propagate the parent turn's context (approval @@ -410,7 +787,16 @@ def _run_references_parallel( # advisor calls attribute to the same conversation as the acting turn. from tools.thread_context import propagate_context_to_thread - with ThreadPoolExecutor(max_workers=workers) as executor: + total = len(reference_models) + completed = 0 + executor = ThreadPoolExecutor(max_workers=workers) + interrupted = False + # Per-fan-out context-length cache shared by every reference worker, so + # duplicate (provider, model) slots resolve their window once per turn + # instead of re-probing metadata sources per reference (dict get/set is + # GIL-atomic; a rare duplicate probe on a first-use race is harmless). + _ctx_len_cache: dict[tuple[str, str], int | None] = {} + try: for idx, slot in enumerate(reference_models): if slot.get("provider") == "moa": results[idx] = ( @@ -426,12 +812,79 @@ def _run_references_parallel( ref_messages, temperature=temperature, max_tokens=max_tokens, + reference_timeout=reference_timeout, + context_length_cache=_ctx_len_cache, ) ] = idx + # Collect every reference before returning — the aggregator needs the - # complete set, so there is no early-exit / first-completed path here. - for future, idx in futures.items(): - results[idx] = future.result() + # complete set, so there is no early-exit / first-completed path + # here, other than a user interrupt. Progress callbacks fire as each + # reference completes so frontends can render "MOA: k/n refs done". + pending = set(futures) + while pending: + done, pending = _futures_wait(pending, timeout=_REFERENCE_POLL_INTERVAL_S) + for future in done: + idx = futures[future] + results[idx] = future.result() + completed += 1 + if progress_callback is not None: + try: + label = _slot_label(reference_models[idx]) + progress_callback(completed, total, label) + except Exception as exc: # pragma: no cover - display must never break + logger.debug("MoA progress_callback failed: %s", exc) + if not pending: + break + if agent is not None and getattr(agent, "_interrupt_requested", False): + interrupted = True + break + + if interrupted: + for future, idx in futures.items(): + if results[idx] is not None: + continue + if future.cancel(): + # Never dispatched — genuinely nothing was billed. + results[idx] = ( + _slot_label(reference_models[idx]), + _INTERRUPTED_REFERENCE_NOTE, + _RefAccounting(CanonicalUsage()), + ) + elif future.done(): + # Finished between the interrupt check and now — the call + # completed and billed, so keep its REAL output and + # accounting rather than zeroing it with a placeholder. + results[idx] = future.result() + else: + # Already running — cannot be force-killed (see + # docstring); leave it be so the caller isn't blocked, + # and note that its output was abandoned. The provider + # call is still in flight and WILL bill when it + # completes, so hand its eventual accounting to the + # caller's sink instead of silently dropping it. + label = _slot_label(reference_models[idx]) + results[idx] = ( + label, + _INTERRUPTED_REFERENCE_NOTE, + _RefAccounting(CanonicalUsage()), + ) + if late_accounting_sink is not None: + def _record_late(f: Any, _label: str = label) -> None: + try: + _lbl, _txt, _acct = f.result() + except Exception: # pragma: no cover - defensive + return + try: + late_accounting_sink(_label, _acct) + except Exception: # pragma: no cover - defensive + logger.debug( + "MoA: late accounting sink failed for %s", + _label, + ) + future.add_done_callback(_record_late) + finally: + executor.shutdown(wait=not interrupted, cancel_futures=interrupted) return [r for r in results if r is not None] @@ -456,21 +909,35 @@ def _render_tool_calls(tool_calls: Any) -> str: The advisory view cannot carry real ``tool_calls`` payloads (strict providers reject tool_calls the reference never produced), so the agent's actions are flattened to text the reference can read and reason about. + + Tolerates both dict-shaped and ``SimpleNamespace``-shaped entries (with a + nested ``function`` of either kind), so the helper works uniformly against + an OpenAI-style transport and against SDK-style stream-stitched responses. + Without this shape tolerance, a SimpleNamespace-sourced entry rendered as + ``[called tool: tool]`` and silently lost the function name. """ lines: list[str] = [] for tc in tool_calls or []: - fn = (tc.get("function") or {}) if isinstance(tc, dict) else {} - name = fn.get("name") or (tc.get("name") if isinstance(tc, dict) else "") or "tool" - args = fn.get("arguments") - if isinstance(args, str): - args_text = args - elif args is not None: + if isinstance(tc, dict): + fn = tc.get("function") or {} + fn_name = fn.get("name") if isinstance(fn, dict) else getattr(fn, "name", None) + fn_args = fn.get("arguments") if isinstance(fn, dict) else getattr(fn, "arguments", None) + top_name = tc.get("name") + else: + fn = getattr(tc, "function", None) + fn_name = getattr(fn, "name", None) if fn is not None else None + fn_args = getattr(fn, "arguments", None) if fn is not None else None + top_name = getattr(tc, "name", None) + name = fn_name or top_name or "tool" + if isinstance(fn_args, str): + args_text = fn_args + elif fn_args is not None: try: import json - args_text = json.dumps(args, ensure_ascii=False) + args_text = json.dumps(fn_args, ensure_ascii=False) except Exception: - args_text = str(args) + args_text = str(fn_args) else: args_text = "" lines.append(f"[called tool: {name}({args_text})]" if args_text else f"[called tool: {name}]") @@ -660,45 +1127,128 @@ def _preset_temperature(preset: dict[str, Any], key: str) -> float | None: return None +def _is_failed_reference(text: str) -> bool: + """Return whether a reference output is an internal failure/skip sentinel. + + Covers both the ``[failed: …]`` notes produced when a reference call + raises (which may embed raw provider error text) and the + ``[skipped: …]`` recursion-guard notes — neither is real advice, so + neither belongs in the aggregator prompt. + """ + sentinel = text.lstrip().lower() + return sentinel.startswith("[failed:") or sentinel.startswith("[skipped:") + + +def _successful_references( + reference_outputs: list[tuple[str, str, Any]], +) -> list[tuple[str, str, Any]]: + """Filter failed advice while preserving each accounting payload.""" + return [output for output in reference_outputs if not _is_failed_reference(output[1])] + + +def _failed_reference_labels( + reference_outputs: list[tuple[str, str, Any]], +) -> list[str]: + return [label for label, text, _accounting in reference_outputs if _is_failed_reference(text)] + + +def _degraded_notice(failed_labels: list[str], policy: str) -> str: + if not failed_labels or policy.strip().lower() == "silent": + return "" + return f"[Reference models unavailable: {', '.join(failed_labels)}]" + + def aggregate_moa_context( *, user_prompt: str, api_messages: list[dict[str, Any]], - reference_models: list[dict[str, str]], - aggregator: dict[str, str], + reference_models: list[dict[str, Any]], + aggregator: dict[str, Any], temperature: float | None = None, aggregator_temperature: float | None = None, - max_tokens: int | None = None, + reference_max_tokens: int | None = None, + reference_timeout: float | None = None, + degraded_reference_policy: str = "loud", + agent: Any = None, ) -> str: """Run configured reference models and synthesize their advice. Failures are returned as model-specific notes instead of aborting the normal agent loop; the main model can still act with partial context. - ``max_tokens`` is ``None`` by default: MoA does not cap reference or - aggregator output, so each model uses its own maximum. ``call_llm`` omits - the parameter entirely when it is ``None`` (see its docstring), which also - sidesteps providers that reject ``max_tokens`` outright. A hardcoded cap - here previously truncated long aggregator syntheses. + ``reference_max_tokens`` applies ONLY to the reference fan-out — the + aggregator's own synthesis call is never capped, so it always uses its + model's own maximum. ``call_llm`` omits the parameter entirely when it + is ``None`` (see its docstring), which also sidesteps providers that + reject ``max_tokens`` outright. A hardcoded cap on the aggregator call + previously truncated long aggregator syntheses (#53580) — passing + ``reference_max_tokens`` to both calls here would silently reintroduce + that regression. ``temperature`` / ``aggregator_temperature`` are ``None`` by default: - like max_tokens, ``call_llm`` omits temperature when None so the - provider default applies — matching single-model agent behavior. Presets - may still pin explicit values. + like ``reference_max_tokens``, ``call_llm`` omits temperature when None + so the provider default applies — matching single-model agent behavior. + Presets may still pin explicit values. + + ``agent``, when passed, lets the reference fan-out be aborted early on a + user interrupt — see ``_run_references_parallel``'s docstring. """ + reference_models = [slot for slot in reference_models if slot.get("enabled", True)] reference_outputs: list[tuple[str, str, Any]] = [] ref_messages = _reference_messages(api_messages) reference_outputs = _run_references_parallel( reference_models, ref_messages, temperature=temperature, - max_tokens=max_tokens, + max_tokens=reference_max_tokens, + reference_timeout=reference_timeout, + agent=agent, ) + successful_outputs = _successful_references(reference_outputs) + failed_labels = _failed_reference_labels(reference_outputs) + + # 'full' privacy mode (moa.privacy_filter) also covers this one-shot /moa + # synthesis path: advisor text is redacted before it reaches the + # synthesizing aggregator. 'display' does not apply here — this path has + # no user-visible reference blocks or trace records of its own. Redaction + # runs on the successful outputs only (failed refs are already filtered + # into the degraded notice). + try: + from hermes_cli.config import load_config as _load_config + + if _moa_privacy_mode((_load_config() or {}).get("moa")) == "full": + successful_outputs = _redact_reference_outputs(successful_outputs) + except Exception: # pragma: no cover - privacy filter must never break a turn + logger.debug("MoA privacy filter check failed", exc_info=True) + joined = "\n\n".join( f"Reference {idx} — {label}:\n{text}" - for idx, (label, text, _usage) in enumerate(reference_outputs, start=1) + for idx, (label, text, _accounting) in enumerate(successful_outputs, start=1) ) + degraded = _degraded_notice(failed_labels, degraded_reference_policy) + if degraded: + joined = f"{joined}\n\n{degraded}" if joined else degraded + + # Skip the aggregator call when every reference failed or was skipped — + # synthesising over zero real advice wastes tokens and can block for the + # full provider timeout (observed: ~6 min on SenseNova) before returning + # a non-retryable error that leaves the session hanging. The early return + # carries only the sanitized unavailability notice (never raw provider + # error text) so the main agent loop can still act in single-model mode. + if reference_outputs and not successful_outputs: + logger.warning( + "MoA: all %d reference(s) failed — skipping aggregator synthesis", + len(reference_outputs), + ) + notice = degraded or "[Reference models unavailable]" + return ( + "[Mixture of Agents context — all reference models failed. " + "Proceeding without aggregated guidance.]\n" + f"References: {', '.join(_slot_label(slot) for slot in reference_models)}\n\n" + f"{notice}" + ) + synth_prompt = ( "You are the aggregator in a Mixture of Agents process. Synthesize the " "reference responses into concise, actionable guidance for the main " @@ -729,7 +1279,6 @@ def aggregate_moa_context( task="moa_aggregator", messages=agg_messages, temperature=aggregator_temperature, - max_tokens=max_tokens, reasoning_config=_aggregator_reasoning_config(aggregator), **agg_runtime, ) @@ -788,10 +1337,67 @@ def _attach_reference_guidance(agg_messages: list[dict[str, Any]], guidance: str agg_messages.append({"role": "user", "content": guidance}) +def peel_reference_guidance( + messages: list[dict[str, Any]], + guidance: Any, +) -> list[dict[str, Any]]: + """Remove reference guidance previously attached by ``_attach_reference_guidance``. + + Exact inverse of the three attach shapes above (string merge, trailing + text part, appended user message) — kept adjacent so the two evolve + together; a drifting separator or shape would make the peel silently + no-op and let a cache breakpoint land on the turn-varying guidance + block (the bug class #72626 fixes). + + Used by the failover redecoration chokepoint: redecoration must run on + the base transcript so the last cache breakpoint does not land on the + guidance; callers then rebase via ``rebase_prepared_request``. + + Returns a new list (input list and its messages are not mutated). + """ + if not guidance or not messages: + return messages + guidance_text = str(guidance) + last = messages[-1] + if not isinstance(last, dict) or last.get("role") != "user": + return messages + content = last.get("content") + if content == guidance_text: + # Attach shape (c): guidance was appended as its own user message. + return list(messages[:-1]) + suffix = "\n\n" + guidance_text + if isinstance(content, str) and content.endswith(suffix): + # Attach shape (a): merged into a trailing string user turn. + peeled = dict(last) + peeled["content"] = content[: -len(suffix)] + return [*messages[:-1], peeled] + if isinstance(content, list) and content: + last_part = content[-1] + if isinstance(last_part, dict) and last_part.get("type", "text") == "text": + text = last_part.get("text") or "" + if text == suffix or text == guidance_text: + # Attach shape (b): guidance rode as its own trailing part. + peeled = dict(last) + peeled["content"] = list(content[:-1]) + if not peeled["content"]: + # The guidance part was the only content — mirror the + # string shape (c) and drop the whole message rather + # than leaving an empty-content user turn behind. + return list(messages[:-1]) + return [*messages[:-1], peeled] + if text.endswith(suffix): + new_part = dict(last_part) + new_part["text"] = text[: -len(suffix)] + peeled = dict(last) + peeled["content"] = [*content[:-1], new_part] + return [*messages[:-1], peeled] + return messages + + class MoAChatCompletions: """OpenAI-chat-compatible facade where the aggregator is the acting model.""" - def __init__(self, preset_name: str, reference_callback: Any = None): + def __init__(self, preset_name: str, reference_callback: Any = None, agent: Any = None): self.preset_name = preset_name or "default" # Optional display hook. Called as reference outputs become available so # frontends can show each reference model's answer as a labelled block @@ -799,9 +1405,22 @@ class MoAChatCompletions: # reference_callback(event, **kwargs) # where event is one of: # "moa.reference" kwargs: index, count, label, text + # "moa.progress" kwargs: refs_done, refs_total, label + # (fired once per reference completion — drives + # status-bar progress like ``MOA: 2/3 refs done``) + # "moa.phase" kwargs: phase, refs_done, refs_total, aggregator + # (fired on phase transitions, currently + # phase="aggregator" right before the aggregator + # acts; phase="reference" mirrors ``moa.progress`` + # so listeners can rely on a single event family) # "moa.aggregating" kwargs: aggregator (label), ref_count # Never raises into the model call — display is best-effort. self.reference_callback = reference_callback + # Back-reference to the owning AIAgent, so the reference fan-out can + # check agent._interrupt_requested (see _run_references_parallel). + # Optional — a caller that doesn't pass it just keeps the fan-out + # uninterruptible, as it was before. + self._agent = agent # State-scoped reference cache. The agent loop calls create() once per # tool-loop iteration; references should re-run whenever the task STATE # advances — i.e. on every new user message AND every new tool result — @@ -823,6 +1442,10 @@ class MoAChatCompletions: self._pending_reference_usage: Any = CanonicalUsage() self._pending_reference_cost: Any = None + # Guards pending usage/cost against concurrent late-accounting + # callbacks (see _record_late_reference_accounting), which fire on + # executor worker threads after an interrupted fan-out returns. + self._accounting_lock = threading.Lock() # Resolved aggregator slot ({provider, model, ...}) from the most recent # create(); read by session cost accounting to price the aggregator's # acting turn at its real model instead of the virtual preset name. @@ -831,6 +1454,18 @@ class MoAChatCompletions: # caller to stitch in the live session_id + resolved aggregator output # and flush to the trace file (only when moa.save_traces is on). self._pending_trace: Any = None + # every_n fan-out cadence state. The iteration counter is scoped to a + # single USER TURN (not the facade lifetime): it counts create() calls + # since the last new user message and resets whenever the user-turn + # signature changes, so cadence position never leaks across turns — + # iteration 1 of every turn is always on-cadence (fresh advice for a + # fresh request). See the fanout handling in create(). + self._fanout_iteration_count = 0 + self._fanout_turn_sig: str | None = None + self._fanout_last_state_sig: str | None = None + # Normalized moa.privacy_filter mode for the current turn ('' | + # 'display' | 'full'), refreshed from config on every create(). + self._privacy_mode: str = "" def consume_reference_usage(self) -> tuple[Any, Any]: """Pop pending reference-fan-out usage + cost, resetting both to empty. @@ -843,12 +1478,42 @@ class MoAChatCompletions: """ from agent.usage_pricing import CanonicalUsage - usage = self._pending_reference_usage or CanonicalUsage() - cost = self._pending_reference_cost - self._pending_reference_usage = CanonicalUsage() - self._pending_reference_cost = None + with self._accounting_lock: + usage = self._pending_reference_usage or CanonicalUsage() + cost = self._pending_reference_cost + self._pending_reference_usage = CanonicalUsage() + self._pending_reference_cost = None return usage, cost + def _record_late_reference_accounting(self, label: str, accounting: Any) -> None: + """Fold a late-completing interrupted reference's real spend in. + + When a user interrupt aborts the fan-out wait, references already in + flight keep running (they cannot be force-killed) and DO bill when + they complete. Their placeholder results carry zeroed accounting, so + without this hook that spend would vanish from session accounting. + The fan-out registers this as a done-callback on abandoned futures; + it folds the eventual real usage/cost into the pending totals, where + the next ``consume_reference_usage`` pick-up records it. Thread-safe: + done-callbacks fire on executor worker threads. + """ + from agent.usage_pricing import CanonicalUsage + + if not isinstance(accounting, _RefAccounting): + return + with self._accounting_lock: + if isinstance(accounting.usage, CanonicalUsage): + self._pending_reference_usage = ( + self._pending_reference_usage or CanonicalUsage() + ) + accounting.usage + if accounting.cost_usd is not None: + self._pending_reference_cost = ( + self._pending_reference_cost or 0 + ) + accounting.cost_usd + logger.debug( + "MoA: recorded late accounting for interrupted reference %s", label + ) + def consume_and_save_trace( self, session_id: Any = None, aggregator_output_fallback: Any = None ) -> None: @@ -946,9 +1611,17 @@ class MoAChatCompletions: extra_body: Any = agg_kwargs.get("extra_body") # Record the exact aggregator INPUT (incl. the injected reference # context) into the pending trace so a trace captures what the - # aggregator actually saw, not a reconstruction. + # aggregator actually saw, not a reconstruction. Traces are a + # persisted surface: when the privacy filter is active, the stored + # COPY is redacted ('display' mode's live aggregator input stays raw — + # only the on-disk record is filtered; 'full' mode's input is already + # redacted upstream, so this is a near no-op there). if self._pending_trace is not None: - self._pending_trace["aggregator_input_messages"] = agg_messages + self._pending_trace["aggregator_input_messages"] = ( + _redact_trace_messages([dict(m) for m in agg_messages]) + if getattr(self, "_privacy_mode", "") + else agg_messages + ) self._pending_trace["aggregator_label"] = _slot_label(aggregator) # The aggregator is the acting model. Resolve its slot to the provider's # real runtime (base_url/api_key/api_mode) and call it through the same @@ -976,18 +1649,26 @@ class MoAChatCompletions: # actually governs the aggregator stream, not just call_llm's default. if api_kwargs.get("timeout") is not None: stream_kwargs["timeout"] = api_kwargs["timeout"] + agg_runtime = _slot_runtime(aggregator) + # _slot_runtime may carry the provider's request_overrides.extra_body; + # pop it and merge with the caller's extra_body (caller wins) so the + # explicit kwarg below never collides with **agg_runtime. + agg_extra_body = _merge_slot_extra_body( + agg_runtime.pop("extra_body", None), + extra_body, + ) _agg_response = call_llm( task="moa_aggregator", messages=agg_messages, temperature=aggregator_temperature, max_tokens=max_tokens, tools=tools, - extra_body=extra_body, + extra_body=agg_extra_body, # Prepared requests must retain the acting aggregator's reasoning # policy exactly as the direct create() path does (#64187). reasoning_config=_aggregator_reasoning_config(aggregator), **stream_kwargs, - **_slot_runtime(aggregator), + **agg_runtime, ) # Non-streaming path (quiet mode / eval / subagents): the aggregator # output is available inline, so capture it into the pending trace now. @@ -1016,9 +1697,20 @@ class MoAChatCompletions: from hermes_cli.config import load_config from hermes_cli.moa_config import resolve_moa_preset - preset = resolve_moa_preset(load_config().get("moa") or {}, self.preset_name) + _moa_raw = load_config().get("moa") or {} + preset = resolve_moa_preset(_moa_raw, self.preset_name) + # Privacy filter mode: '' (off, default) | 'display' | 'full'. See + # coerce_privacy_filter / the pattern block at the top of this module. + # Remembered on self so _call_prepared_aggregator (which may run on a + # later prepared-request call without re-reading config) redacts the + # trace's aggregator input consistently with this turn's fan-out. + privacy_mode = _moa_privacy_mode(_moa_raw) + self._privacy_mode = privacy_mode messages = list(api_kwargs.get("messages") or []) - reference_models = preset.get("reference_models") or [] + reference_models = [ + slot for slot in (preset.get("reference_models") or []) + if slot.get("enabled", True) + ] aggregator = preset.get("aggregator") or {} # Expose the resolved aggregator slot so session cost accounting can # price the aggregator's acting turn at its REAL model/provider. The @@ -1043,6 +1735,16 @@ class MoAChatCompletions: # explicit values. See _preset_temperature. temperature = _preset_temperature(preset, "reference_temperature") aggregator_temperature = _preset_temperature(preset, "aggregator_temperature") + # None (the default) = no per-preset override; the fan-out inherits + # auxiliary.moa_reference.timeout (900s default) via call_llm's own + # per-task timeout resolution. Explicit per-preset values are honored. + raw_reference_timeout = preset.get("reference_timeout") + reference_timeout = ( + float(raw_reference_timeout) if raw_reference_timeout else None + ) + degraded_reference_policy = str( + preset.get("degraded_reference_policy") or "loud" + ) if aggregator_temperature is None and api_kwargs.get("temperature") is not None: # The acting agent's own configured temperature (if any) still # applies to the aggregator, which IS the acting model. @@ -1059,17 +1761,39 @@ class MoAChatCompletions: reference_outputs: list[tuple[str, str, Any]] = [] ref_messages = _reference_messages(messages) - # Fan-out cadence. "per_iteration" (default): advisors re-run whenever - # the advisory view changes — i.e. every tool iteration, since the - # view grows with each tool result. "user_turn": advisors run ONCE per - # user turn; subsequent tool iterations reuse that turn's advice and - # the aggregator acts alone (the original MoA shape: synthesize at the - # start, then let the acting model work). Implemented by hashing only - # the prefix up to the LAST USER message so mid-turn growth doesn't - # change the signature — iteration 2+ becomes a cache HIT. - fanout_mode = str(preset.get("fanout") or "per_iteration").strip().lower() + # Fan-out cadence. "user_turn" (default — cheapest cadence, #67199): + # advisors run ONCE per user turn; subsequent tool iterations reuse + # that turn's advice and the aggregator acts alone (the original MoA + # shape: synthesize at the start, then let the acting model work). + # Implemented by hashing only the prefix up to the LAST USER message + # so mid-turn growth doesn't change the signature — iteration 2+ + # becomes a cache HIT. "per_iteration": advisors re-run whenever the + # advisory view changes — i.e. every tool iteration, since the view + # grows with each tool result; advice tracks live task state at the + # cost of multiplying advisor latency/spend by tool-loop depth. + # "every_n:" (N >= 2): the middle ground (issue #63393 — advisor + # fan-out multiplies latency/cost by the tool-iteration count). + # Advisors run on iteration 1 of a user turn and then every Nth tool + # iteration; the iterations in between REUSE the cached guidance from + # the last on-cadence run (same mechanism as user_turn's cache HIT — + # the aggregator still gets advice every iteration, it's just not + # refreshed against the very latest tool results). The iteration + # counter is scoped per user turn and resets on a new user message, + # so every turn starts with fresh advice. + fanout_mode = str(preset.get("fanout") or "user_turn").strip().lower() + every_n = 0 + if fanout_mode.startswith("every_n:"): + try: + every_n = int(fanout_mode.split(":", 1)[1]) + except (TypeError, ValueError): + every_n = 0 + if every_n < 2: + # every_n:1 semantically IS per-iteration; degrade there, + # mirroring _coerce_fanout's collapse of degenerate N. + fanout_mode = "per_iteration" sig_messages = ref_messages - if fanout_mode == "user_turn": + turn_prefix = ref_messages + if fanout_mode in ("user_turn",) or every_n >= 2: # Find the last REAL user message. The advisory view appends a # synthetic user marker (_ADVISORY_INSTRUCTION) when it ends on an # assistant turn — i.e. on every tool iteration after the first — @@ -1084,19 +1808,51 @@ class MoAChatCompletions: last_user_idx = _i break if last_user_idx is not None: - sig_messages = ref_messages[: last_user_idx + 1] + turn_prefix = ref_messages[: last_user_idx + 1] + if fanout_mode == "user_turn": + sig_messages = turn_prefix + + def _hash_messages(msgs: list[dict[str, Any]]) -> str: + return hashlib.sha256( + "\u0000".join( + f"{m.get('role')}:{m.get('content')}" for m in msgs + ).encode("utf-8", "replace") + ).hexdigest() + + # every_n cadence bookkeeping: advance the per-turn iteration counter + # only when the advisory STATE actually advanced (a redundant create() + # with identical state — e.g. a streaming retry — must not consume a + # cadence slot), and reset it whenever the user-turn prefix changes. + _every_n_reuse = False + if every_n >= 2: + _turn_sig = _hash_messages(turn_prefix) + if _turn_sig != self._fanout_turn_sig: + self._fanout_turn_sig = _turn_sig + self._fanout_iteration_count = 0 + self._fanout_last_state_sig = None + _state_sig = _hash_messages(ref_messages) + if _state_sig != self._fanout_last_state_sig: + self._fanout_last_state_sig = _state_sig + self._fanout_iteration_count += 1 + # Iteration 1 is on-cadence; then every Nth iteration after it. + _on_cadence = (self._fanout_iteration_count - 1) % every_n == 0 + _every_n_reuse = not _on_cadence and bool(self._ref_cache_outputs) # Turn-scoped cache: only run + display references when the advisory # view changed (i.e. a new user turn). Within one turn the agent loop # calls create() once per tool iteration; in user_turn mode the # signature is stable across those iterations (prefix hash above), so # the fan-out runs once per user turn and iterations reuse the advice. - _sig = hashlib.sha256( - "\u0000".join( - f"{m.get('role')}:{m.get('content')}" for m in sig_messages - ).encode("utf-8", "replace") - ).hexdigest() + _sig = _hash_messages(sig_messages) _cache_key = (self.preset_name, _sig, tuple(_slot_label(s) for s in reference_models)) + if _every_n_reuse: + # Off-cadence every_n iteration: pin the key to the last + # on-cadence run so the lookup below is a HIT and its guidance is + # reused (no advisor calls, no double accounting, no re-emit) — + # exactly the user_turn cache-HIT path. When the cache is empty + # (defensive; a new turn resets the counter to on-cadence) the + # flag above stays False and the references run normally. + _cache_key = self._ref_cache_key _refs_from_cache = _cache_key == self._ref_cache_key and bool(self._ref_cache_outputs) if _refs_from_cache: @@ -1104,22 +1860,54 @@ class MoAChatCompletions: # References already ran (and were accounted) earlier this turn; # this create() is a repeat tool-iteration reusing the cached # advice. Charging their tokens/cost again here would multiply - # advisor spend by the tool-iteration count, so pending is zero. - self._pending_reference_usage = CanonicalUsage() - self._pending_reference_cost = None + # advisor spend by the tool-iteration count, so nothing new is + # deposited — but do NOT zero the pending totals: a + # late-completing interrupted reference may have deposited its + # real spend since the last consume(), and that must survive + # until the next consume_reference_usage() pick-up. # Likewise no trace on a cache HIT — the full turn was already # traced on the MISS that ran the references. A repeat iteration is # not a new MoA turn. self._pending_trace = None else: + # Per-reference progress callback: emits ``moa.progress`` so + # listeners can render ``MOA: N/M refs done`` in the status bar as + # each reference completes. The callback is bound to self so it + # goes through the same display hook as the existing + # ``moa.reference`` / ``moa.aggregating`` events. + def _progress(done: int, total: int, label: str) -> None: + self._emit( + "moa.progress", + refs_done=done, + refs_total=total, + label=label, + ) + reference_outputs = _run_references_parallel( reference_models, ref_messages, temperature=temperature, max_tokens=reference_max_tokens, + progress_callback=_progress, + reference_timeout=reference_timeout, + agent=self._agent, + late_accounting_sink=self._record_late_reference_accounting, ) - self._ref_cache_key = _cache_key - self._ref_cache_outputs = list(reference_outputs) + interrupted_any = any( + text == _INTERRUPTED_REFERENCE_NOTE + for _lbl, text, _acct in reference_outputs + ) + if interrupted_any: + # An interrupted fan-out is a partial snapshot, not real + # advice for this state. Caching it would replay the + # placeholder notes on every subsequent iteration of the + # turn (a cache HIT never re-runs the references), so leave + # the cache empty and let the next create() re-run them. + self._ref_cache_key = None + self._ref_cache_outputs = [] + else: + self._ref_cache_key = _cache_key + self._ref_cache_outputs = list(reference_outputs) # Sum the advisor fan-out's token usage AND cost so the caller can # fold advisor spend into session accounting exactly once per turn. # Only the freshly run references (cache MISS) contribute; a cache @@ -1136,16 +1924,35 @@ class MoAChatCompletions: _ref_usage = _ref_usage + _acct.usage if _acct.cost_usd is not None: _ref_cost = (_ref_cost or 0) + _acct.cost_usd - self._pending_reference_usage = _ref_usage - self._pending_reference_cost = _ref_cost + with self._accounting_lock: + # Fold (don't overwrite): a late-completing interrupted + # reference from a PREVIOUS turn may have deposited its real + # spend here between consume() calls — keep it. + self._pending_reference_usage = ( + self._pending_reference_usage or CanonicalUsage() + ) + _ref_usage + if _ref_cost is not None: + self._pending_reference_cost = ( + self._pending_reference_cost or 0 + ) + _ref_cost # Stash the full reference fan-out for trace persistence. The # aggregator input/label are filled in below once agg_messages is # built; the aggregator OUTPUT is stitched in by the caller # (consume_and_save_trace) once the response resolves — the caller # holds the live session_id and the resolved aggregator response. + # Traces are a persisted, user-readable surface, so ANY active + # privacy mode ('display' or 'full') redacts the advisor text and + # the full per-advisor input/output carried by _RefAccounting. + if privacy_mode: + _trace_refs = [ + (label, _redact_reference_text(text), _redact_trace_accounting(acct)) + for label, text, acct in reference_outputs + ] + else: + _trace_refs = list(reference_outputs) self._pending_trace = { "preset": self.preset_name, - "reference_outputs": list(reference_outputs), + "reference_outputs": _trace_refs, "aggregator_slot": aggregator, "aggregator_temperature": aggregator_temperature, } @@ -1155,17 +1962,31 @@ class MoAChatCompletions: # actually ran them). The user sees one labelled block per # reference (rendered like a thinking block) so the MoA process is # visible rather than a silent pause. Best-effort: never blocks the - # turn. + # turn. Reference blocks are a user-visible surface: both privacy + # modes redact them (the cache keeps the RAW text — redaction + # always happens at the consuming surface, so a mid-session mode + # change never leaks or double-redacts). _ref_count = len(reference_outputs) - for _idx, (_label, _text, _usage) in enumerate(reference_outputs, start=1): + for _idx, (_label, _text, _accounting) in enumerate(reference_outputs, start=1): self._emit( "moa.reference", index=_idx, count=_ref_count, label=_label, - text=_text, + text=_redact_reference_text(_text) if privacy_mode else _text, ) if _ref_count: + # Phase transition: reference fan-out is complete, the + # aggregator is about to act. Listeners that prefer a single + # event family for phase tracking can switch on ``phase`` + # instead of subscribing to ``moa.aggregating`` separately. + self._emit( + "moa.phase", + phase="aggregator", + refs_done=_ref_count, + refs_total=_ref_count, + aggregator=_slot_label(aggregator), + ) self._emit( "moa.aggregating", aggregator=_slot_label(aggregator), @@ -1174,16 +1995,58 @@ class MoAChatCompletions: guidance: str | None = None agg_messages = [dict(m) for m in messages] - if reference_outputs: + successful_outputs = _successful_references(reference_outputs) + failed_labels = _failed_reference_labels(reference_outputs) + joined = "" + _agg_refs: list = [] + if successful_outputs: + # 'full' privacy mode: redact the advisor text that reaches the + # AGGREGATOR too (issue #59959's literal ask). 'display' leaves + # the aggregator input raw so synthesis quality is unaffected. + # The redaction is applied to a per-call copy — the cache always + # holds raw advisor text (see the emit comment above). Failed + # refs are already filtered out; only successful advisor text is + # joined (and redacted when requested). + _agg_refs = ( + _redact_reference_outputs(successful_outputs) + if privacy_mode == "full" + else successful_outputs + ) joined = "\n\n".join( f"Reference {idx} — {label}:\n{text}" - for idx, (label, text, _usage) in enumerate(reference_outputs, start=1) + for idx, (label, text, _usage) in enumerate(_agg_refs, start=1) ) + degraded = _degraded_notice(failed_labels, degraded_reference_policy) + if reference_outputs and not successful_outputs: + # Every reference failed or was skipped: don't wrap a wall of + # failure sentinels in "use the reference responses below" + # guidance — the aggregator IS the acting model, so it simply + # acts alone this turn. Under the loud policy it still gets the + # sanitized unavailability notice so it can disclose degraded + # mode; under silent it gets nothing. + logger.warning( + "MoA: all %d reference(s) failed — acting aggregator-alone " + "without reference guidance", + len(reference_outputs), + ) + if degraded: + guidance = ( + "[Mixture of Agents reference context]\n" + f"Preset: {self.preset_name}\n" + f"Aggregator/acting model: {_slot_label(aggregator)}\n\n" + "All reference models failed this turn — no advisory " + "guidance is available. Act on your own judgment.\n\n" + f"{degraded}" + ) + _attach_reference_guidance(agg_messages, guidance) + elif joined or degraded: + if degraded: + joined = f"{joined}\n\n{degraded}" if joined else degraded guidance = ( "[Mixture of Agents reference context]\n" f"Preset: {self.preset_name}\n" f"Aggregator/acting model: {_slot_label(aggregator)}\n" - f"References: {', '.join(label for label, _, _ in reference_outputs)}\n\n" + f"References: {', '.join(label for label, _, _ in _agg_refs)}\n\n" "Use the reference responses below as private context. You are the aggregator and acting model: " "answer the user directly or call tools as needed.\n\n" f"{joined}" @@ -1202,9 +2065,11 @@ class MoAChatCompletions: class MoAClient: - def __init__(self, preset_name: str, reference_callback: Any = None): + def __init__(self, preset_name: str, reference_callback: Any = None, agent: Any = None): self.chat = type("_MoAChat", (), {})() - self.chat.completions = MoAChatCompletions(preset_name, reference_callback=reference_callback) + self.chat.completions = MoAChatCompletions( + preset_name, reference_callback=reference_callback, agent=agent, + ) def consume_reference_usage(self) -> Any: """Pop the pending reference-fan-out usage from the completions facade. @@ -1234,3 +2099,85 @@ class MoAClient: return self.chat.completions.consume_and_save_trace( session_id, aggregator_output_fallback=aggregator_output_fallback ) + + +def build_moa_facade(agent, preset_name: Any = None) -> MoAClient: + """Build the MoA facade client for ``agent``, wiring the reference relay. + + Single construction point for ``MoAClient`` wherever the agent's shared + client is (re)built: initial setup (``agent_init``), turn-start fallback + restore (``restore_primary_runtime``), transient transport recovery + (``try_recover_primary_transport``), and mid-session model switches + (``switch_model``). + + Constructing a bare ``MoAClient(preset)`` at any of those sites silently + drops the ``reference_callback`` relay that ``agent_init`` wires to + ``agent.tool_progress_callback`` — after a fallback+restore cycle the + facade would still work, but every frontend (CLI spinner, TUI, desktop, + gateway) would stop receiving ``moa.reference`` / ``moa.aggregating`` + display events for the rest of the session (#53802). + + The relay reads ``agent.tool_progress_callback`` at *emit* time, so a + callback attached after client construction is picked up automatically. + Best-effort and display-only — it never raises into the model call. + """ + def _moa_reference_relay(event: str, **kwargs: Any) -> None: + cb = getattr(agent, "tool_progress_callback", None) + if cb is None: + return + try: + if event == "moa.reference": + label = str(kwargs.get("label") or "") + text = str(kwargs.get("text") or "") + idx = kwargs.get("index") + count = kwargs.get("count") + cb( + "moa.reference", + label, + text, + None, + moa_index=idx, + moa_count=count, + ) + elif event == "moa.progress": + # Per-reference completion. Frontends render this as a + # status-bar progress indicator like ``MOA: N/M refs done``. + cb( + "moa.progress", + str(kwargs.get("label") or ""), + None, + None, + moa_refs_done=kwargs.get("refs_done"), + moa_refs_total=kwargs.get("refs_total"), + ) + elif event == "moa.phase": + # Phase transition (currently only ``phase="aggregator"`` + # fires once the fan-out is done). Subscribers can switch + # on ``moa_phase`` to know which phase is active. + cb( + "moa.phase", + str(kwargs.get("aggregator") or ""), + None, + None, + moa_phase=kwargs.get("phase"), + moa_refs_done=kwargs.get("refs_done"), + moa_refs_total=kwargs.get("refs_total"), + ) + elif event == "moa.aggregating": + cb( + "moa.aggregating", + str(kwargs.get("aggregator") or ""), + None, + None, + moa_ref_count=kwargs.get("ref_count"), + ) + except Exception: + pass + + return MoAClient( + str(preset_name or getattr(agent, "model", None) or "default"), + reference_callback=_moa_reference_relay, + # Thread the agent through so the reference fan-out wait can be + # aborted on a user interrupt (see _run_references_parallel). + agent=agent, + ) diff --git a/agent/model_metadata.py b/agent/model_metadata.py index a358a6217c54..99f18d8851a1 100644 --- a/agent/model_metadata.py +++ b/agent/model_metadata.py @@ -13,18 +13,40 @@ import os import re import time from pathlib import Path -from typing import Any, Dict, List, Optional, Tuple +from typing import Any, Dict, List, Optional, Tuple, TYPE_CHECKING from urllib.parse import urlparse -import requests import yaml +if TYPE_CHECKING: # pragma: no cover — runtime import is lazy (see below) + import requests + from utils import atomic_json_write, base_url_host_matches, base_url_hostname from hermes_constants import OPENROUTER_MODELS_URL logger = logging.getLogger(__name__) +# ``requests`` (with urllib3) costs ~27 ms of the `import cli` waterfall and +# is only used inside the fetch functions below. It's resolved lazily: +# ``_ensure_requests()`` populates the module global on the runtime path, and +# the PEP 562 ``__getattr__`` covers external attribute access — notably +# ``patch("agent.model_metadata.requests.get")`` in tests, which resolves the +# attribute at patch time. + + +def _ensure_requests(): + if "requests" not in globals(): + import requests as _requests + globals()["requests"] = _requests + return globals()["requests"] + + +def __getattr__(name: str): + if name == "requests": + return _ensure_requests() + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + def _resolve_requests_verify() -> bool | str: """Resolve SSL verify setting for `requests` calls from env vars. @@ -123,6 +145,67 @@ _ENDPOINT_MODEL_CACHE_TTL = 300 _ENDPOINT_PROBE_TTL_SECONDS = 3600.0 _endpoint_probe_path_cache: Dict[str, tuple] = {} +# ── Disk L2 for local-endpoint probe results ──────────────────────────────── +# The in-process caches above die with the process, so every CLI cold start +# with a local model re-paid the probe waterfall in AIAgent.__init__: +# detect_local_server_type (up to 4 HTTP GETs, ≤2 s each on a hung server) +# + /api/show (≤3 s). A short-TTL disk cache makes back-to-back CLI +# invocations hit disk instead of the network. Only SUCCESSFUL probes are +# persisted (a down server must not pin a negative verdict), and the TTL is +# short enough that swapping the server on a port (stop Ollama, start +# LM Studio) is picked up within minutes — strictly fresher than the 1 h +# in-process TTL that already accepts that staleness. +_LOCAL_PROBE_DISK_TTL_SECONDS = 300.0 + + +def _local_probe_disk_cache_path() -> Path: + from hermes_constants import get_hermes_home + return get_hermes_home() / "cache" / "local_endpoint_probes.json" + + +def _load_local_probe_disk_cache() -> Dict[str, Any]: + try: + with _local_probe_disk_cache_path().open("r", encoding="utf-8") as f: + data = json.load(f) + return data if isinstance(data, dict) else {} + except Exception: + return {} + + +def _local_probe_disk_get(kind: str, key: str) -> Optional[Any]: + """Return a fresh cached value for ``kind:key``, else None.""" + entry = _load_local_probe_disk_cache().get(f"{kind}:{key}") + if not isinstance(entry, dict): + return None + try: + if (time.time() - float(entry["ts"])) >= _LOCAL_PROBE_DISK_TTL_SECONDS: + return None + return entry["value"] + except Exception: + return None + + +def _local_probe_disk_put(kind: str, key: str, value: Any) -> None: + """Persist a successful probe result. Best-effort; prunes stale entries.""" + try: + now = time.time() + data = _load_local_probe_disk_cache() + data = { + k: v + for k, v in data.items() + if isinstance(v, dict) + and (now - float(v.get("ts", 0))) < _LOCAL_PROBE_DISK_TTL_SECONDS + } + data[f"{kind}:{key}"] = {"value": value, "ts": now} + atomic_json_write( + _local_probe_disk_cache_path(), + data, + indent=0, + separators=(",", ":"), + ) + except Exception as e: + logger.debug("Failed to save local probe disk cache: %s", e) + def _get_model_metadata_cache_path() -> Path: """Return path to the OpenRouter model metadata disk cache.""" @@ -215,6 +298,7 @@ DEFAULT_CONTEXT_LENGTHS = { # OpenRouter-prefixed models resolve via OpenRouter live API or models.dev. "claude-fable-5": 1000000, "claude-fable": 1000000, + "claude-opus-5": 1000000, "claude-sonnet-5": 1000000, "claude-opus-4-8": 1000000, "claude-opus-4.8": 1000000, @@ -751,6 +835,13 @@ def detect_local_server_type(base_url: str, api_key: str = "") -> Optional[str]: if cached is not None and (time.monotonic() - cached[1]) < _ENDPOINT_PROBE_TTL_SECONDS: return cached[0] + # Disk L2: a fresh cross-process verdict skips the HTTP waterfall + # entirely (back-to-back CLI invocations, cron ticks). + disk_hit = _local_probe_disk_get("server_type", server_url) + if isinstance(disk_hit, str): + _endpoint_probe_path_cache[server_url] = (disk_hit, time.monotonic()) + return disk_hit + headers = _auth_headers(api_key) result: Optional[str] = None @@ -803,6 +894,7 @@ def detect_local_server_type(base_url: str, api_key: str = "") -> Optional[str]: if result is not None: _endpoint_probe_path_cache[server_url] = (result, time.monotonic()) + _local_probe_disk_put("server_type", server_url, result) return result @@ -925,6 +1017,7 @@ def fetch_model_metadata(force_refresh: bool = False) -> Dict[str, Dict[str, Any return _model_metadata_cache try: + _ensure_requests() # Tuple (connect, read) — flat timeout=10 means urllib3 can block 10s per # retry stage through proxies that 403 CONNECT, ballooning to minutes # (#46620). 5s connect / 10s read fails fast on unreachable hosts. @@ -981,6 +1074,7 @@ def fetch_endpoint_model_metadata( normalized = _normalize_base_url(base_url) if not normalized or _is_openrouter_base_url(normalized): return {} + _ensure_requests() if not force_refresh: cached = _endpoint_model_metadata_cache.get(normalized) @@ -1522,6 +1616,13 @@ def query_ollama_num_ctx(model: str, base_url: str, api_key: str = "") -> Option if server_type != "ollama": return None + # Disk L2: /api/show results are stable for a given (model, server) on + # human timescales — skip the HTTP roundtrip on fresh cross-process hits. + _disk_key = f"{server_url}|{bare_model}" + disk_hit = _local_probe_disk_get("ollama_num_ctx", _disk_key) + if isinstance(disk_hit, int) and disk_hit > 0: + return disk_hit + headers = _auth_headers(api_key) try: @@ -1539,7 +1640,9 @@ def query_ollama_num_ctx(model: str, base_url: str, api_key: str = "") -> Option parts = line.strip().split() if len(parts) >= 2: try: - return int(parts[-1]) + _ctx = int(parts[-1]) + _local_probe_disk_put("ollama_num_ctx", _disk_key, _ctx) + return _ctx except ValueError: pass @@ -1547,7 +1650,9 @@ def query_ollama_num_ctx(model: str, base_url: str, api_key: str = "") -> Option model_info = data.get("model_info", {}) for key, value in model_info.items(): if "context_length" in key and isinstance(value, (int, float)): - return int(value) + _ctx = int(value) + _local_probe_disk_put("ollama_num_ctx", _disk_key, _ctx) + return _ctx except Exception: pass return None @@ -1881,6 +1986,7 @@ def _query_anthropic_context_length(model: str, base_url: str, api_key: str) -> "x-api-key": api_key, "anthropic-version": "2023-06-01", } + _ensure_requests() resp = requests.get(url, headers=headers, timeout=(5, 10), verify=_resolve_requests_verify()) if resp.status_code != 200: return None @@ -1988,6 +2094,7 @@ def _fetch_codex_oauth_context_lengths_with_source( headers["ChatGPT-Account-Id"] = acct_id try: + _ensure_requests() resp = requests.get( "https://chatgpt.com/backend-api/codex/models?client_version=1.0.0", headers=headers, @@ -2201,11 +2308,18 @@ def get_model_context_length( # acting context, so they're ignored here. if (provider or "").strip().lower() == "moa": try: - from hermes_cli.config import load_config + from hermes_cli.config import ( + get_compatible_custom_providers, + load_config, + ) from hermes_cli.moa_config import resolve_moa_preset from hermes_cli.runtime_provider import resolve_runtime_provider - preset = resolve_moa_preset(load_config().get("moa") or {}, model) + config = load_config() + effective_custom_providers = custom_providers + if effective_custom_providers is None: + effective_custom_providers = get_compatible_custom_providers(config) + preset = resolve_moa_preset(config.get("moa") or {}, model) agg = preset.get("aggregator") or {} agg_provider = str(agg.get("provider") or "").strip() agg_model = str(agg.get("model") or "").strip() @@ -2215,7 +2329,8 @@ def get_model_context_length( agg_model, base_url=rt.get("base_url", "") or "", api_key=rt.get("api_key", "") or "", - provider=agg_provider, + provider=rt.get("provider") or agg_provider, + custom_providers=effective_custom_providers, ) except Exception: logger.debug("MoA aggregator context-length resolution failed", exc_info=True) @@ -2420,21 +2535,27 @@ def get_model_context_length( if context_length is not None: return context_length if not _is_known_provider_base_url(base_url): - # 2b. Ollama native /api/show — any URL might be an Ollama server - # (local, cloud, or custom hosting). Non-Ollama servers return - # 404/405 quickly. Fall through on failure. - ctx = _query_ollama_api_show(model, base_url, api_key=api_key) - if ctx is not None: - if not _skip_persistent_context_cache(base_url, provider): - save_context_length(model, base_url, ctx) - return ctx - # 3. Try querying local server directly + # For local endpoints, run the probe that respects configured + # Modelfile context values first. _query_local_context_length + # prefers num_ctx from Modelfile, while _query_ollama_api_show + # returns the GGUF training max first which can be larger and + # would create a false-safe window for compression (#63122). + # Non-local endpoints preserve the existing GGUF-first behavior. if is_local_endpoint(base_url): local_ctx = _query_local_context_length(model, base_url, api_key=api_key) if local_ctx and local_ctx > 0: if not _skip_persistent_context_cache(base_url, provider): _maybe_cache_local_context_length(model, base_url, local_ctx) return local_ctx + # 2b. Ollama native /api/show — non-local endpoints preserve + # the existing generic /api/show GGUF-first behavior. + # Non-Ollama servers return 404/405 quickly. + ctx = _query_ollama_api_show(model, base_url, api_key=api_key) + if ctx is not None: + if not _skip_persistent_context_cache(base_url, provider): + save_context_length(model, base_url, ctx) + return ctx + # 3. Probe-down fallback after endpoint-specific detection failed logger.info( "Could not detect context length for model %r at %s — " "defaulting to %s tokens (probe-down). Set model.context_length " @@ -2730,14 +2851,92 @@ def estimate_messages_tokens_rough(messages: List[Dict[str, Any]]) -> int: image — the Anthropic pricing model — instead of counting raw base64 character length. Without this, a single ~1MB screenshot would be estimated at ~250K tokens and trigger premature context compression. + + Per-message results are memoized (see ``_estimate_message_tokens_cached``) + keyed on a deep *identity fingerprint* of the message, so re-walking a + long history every iteration only pays for messages whose object graph + actually changed. The memo is exact: equal fingerprints imply identical + leaf objects and structure, hence an identical estimate. """ _IMAGE_TOKEN_COST = 1500 - text_tokens = 0 - image_tokens = 0 + total = 0 for msg in messages: - text_tokens += _estimate_message_tokens_without_images(msg) - image_tokens += _count_image_tokens(msg, _IMAGE_TOKEN_COST) - return text_tokens + image_tokens + total += _estimate_message_tokens_cached(msg, _IMAGE_TOKEN_COST) + return total + + +# --- Per-message token-estimate memo ------------------------------------- +# +# ``estimate_messages_tokens_rough`` is called on the full history every +# loop iteration (conversation_loop preflight), repeatedly during compaction +# telemetry, and inside an O(n^2) shrink loop in moa_loop. The per-message +# helpers are pure functions of the message's value, so a memo keyed on a +# fingerprint that uniquely determines the value is exactly equivalent. +# +# Fingerprint design (soundness argument): +# * strings are fingerprinted by ``id()`` AND pinned (a strong reference is +# stored in the cache entry). While the entry lives, that id cannot be +# reused by another object, so id-equality implies object-equality — +# strings are immutable, so value-equality too (no #50372-style aliasing). +# * ints/floats/bools/None are fingerprinted by value. +# * dicts/lists recurse structurally, preserving key order — ``str(shadow)`` +# depends on insertion order, so order is part of the key. +# * any other type aborts the memo and falls through to a direct compute. +# Equal fingerprints therefore imply deep-equal messages built from identical +# immutable leaves ⇒ identical ``str(shadow)`` bytes ⇒ identical estimate. +# +# Because the api_messages build shallow-copies history dicts each iteration, +# the copies share the same content strings — so unchanged history messages +# hit the memo even though the outer dicts are fresh objects every turn. +_MSG_TOKENS_CACHE: Dict[Any, Tuple[list, int]] = {} +_MSG_TOKENS_CACHE_MAX = 4096 + + +def _msg_fingerprint(value: Any, pins: list) -> Any: + if value is None or value is True or value is False: + return value + t = type(value) + if t is str: + pins.append(value) + return ("s", id(value)) + if t is int or t is float: + return ("n", t.__name__, value) + if t is dict: + return ("d", tuple( + (_msg_fingerprint(k, pins), _msg_fingerprint(v, pins)) + for k, v in value.items() + )) + if t is list: + return ("l", tuple(_msg_fingerprint(v, pins) for v in value)) + if t is tuple: + return ("t", tuple(_msg_fingerprint(v, pins) for v in value)) + raise ValueError("unfingerprintable message value") + + +def _estimate_message_tokens_cached(msg: Any, image_cost: int) -> int: + try: + pins: list = [] + key = _msg_fingerprint(msg, pins) + hash(key) + except Exception: + return ( + _estimate_message_tokens_without_images(msg) + + _count_image_tokens(msg, image_cost) + ) + cached = _MSG_TOKENS_CACHE.get(key) + if cached is not None: + return cached[1] + tokens = ( + _estimate_message_tokens_without_images(msg) + + _count_image_tokens(msg, image_cost) + ) + _MSG_TOKENS_CACHE[key] = (pins, tokens) + while len(_MSG_TOKENS_CACHE) > _MSG_TOKENS_CACHE_MAX: + try: + _MSG_TOKENS_CACHE.pop(next(iter(_MSG_TOKENS_CACHE))) + except (StopIteration, KeyError, RuntimeError): + break + return tokens def _count_image_tokens(msg: Dict[str, Any], cost_per_image: int) -> int: diff --git a/agent/models_dev.py b/agent/models_dev.py index 590f77806abf..aed49b0d1d5c 100644 --- a/agent/models_dev.py +++ b/agent/models_dev.py @@ -8,11 +8,15 @@ of 4000+ models across 109+ providers. Provides: (reasoning, tools, vision, PDF, audio), modalities, knowledge cutoff, open-weights flag, family grouping, deprecation status -Data resolution order (like TypeScript OpenCode): - 1. Bundled snapshot (ships with the package — offline-first) - 2. Disk cache (~/.hermes/models_dev_cache.json) - 3. Network fetch (https://models.dev/api.json) - 4. Background refresh every 60 minutes +Data resolution order: + 1. In-memory cache (fresh, or stale served immediately while a single + background daemon thread refreshes) + 2. Disk cache (~/.hermes/models_dev_cache.json — any age; stale data is + served rather than blocking callers on the network) + 3. Network fetch (https://models.dev/api.json) — only when no cache + exists at all; failed refreshes back off for 5 minutes process-wide +Latency-sensitive callers (gateway route-identity checks) pass +``allow_network=False`` and never touch the network. Other modules should import the dataclasses and query functions from here rather than parsing the raw JSON themselves. @@ -20,6 +24,7 @@ rather than parsing the raw JSON themselves. import json import logging +import threading import time from dataclasses import dataclass from pathlib import Path @@ -33,10 +38,15 @@ logger = logging.getLogger(__name__) MODELS_DEV_URL = "https://models.dev/api.json" _MODELS_DEV_CACHE_TTL = 3600 # 1 hour in-memory +_MODELS_DEV_RETRY_DELAY = 300 # 5 minutes after a failed refresh # In-memory cache _models_dev_cache: Dict[str, Any] = {} _models_dev_cache_time: float = 0 +_models_dev_retry_after: float = 0 +_models_dev_fetch_lock = threading.Lock() +_models_dev_refresh_lock = threading.Lock() +_models_dev_refresh_in_flight = False # --------------------------------------------------------------------------- @@ -237,27 +247,157 @@ def _save_disk_cache(data: Dict[str, Any]) -> None: logger.debug("Failed to save models.dev disk cache: %s", e) -def fetch_models_dev(force_refresh: bool = False) -> Dict[str, Any]: +def _fetch_models_dev_from_network() -> Dict[str, Any]: + """Fetch the live models.dev registry without touching local caches. + + Raises on network errors and on an empty/invalid registry payload. + """ + # Tuple (connect, read): a flat timeout=15 let a blackholed connect + # stall the first-turn critical path for the full 15 s. 5 s connect + # fails fast on unreachable hosts; 10 s read still tolerates a slow + # registry response (matches the OpenRouter fetch convention in + # agent/model_metadata.py). + response = requests.get(MODELS_DEV_URL, timeout=(5, 10)) + response.raise_for_status() + data = response.json() + if not isinstance(data, dict) or not data: + raise ValueError("models.dev returned an empty or invalid registry") + return data + + +def _mark_stale_cache_grace() -> None: + """Give stale cache data a short in-memory grace before retrying refresh. + + Only ever moves the timestamp forward: if a background refresh completed + between the caller's staleness check and this call, the fresh timestamp + is preserved instead of being rewound to a 5-minute grace. + """ + global _models_dev_cache_time + grace_time = time.time() - _MODELS_DEV_CACHE_TTL + _MODELS_DEV_RETRY_DELAY + if grace_time > _models_dev_cache_time: + _models_dev_cache_time = grace_time + + +def _commit_registry(data: Dict[str, Any], *, where: str) -> None: + """Persist a freshly fetched registry: disk + in-mem + clear backoff. + + Callers must hold ``_models_dev_fetch_lock`` so a failing refresh on one + path can never stomp the state a succeeding refresh on the other path + just committed (e.g. a failing background worker re-arming the backoff + immediately after a successful ``force_refresh``). + """ + global _models_dev_cache, _models_dev_cache_time, _models_dev_retry_after + _save_disk_cache(data) + _models_dev_cache = data + _models_dev_cache_time = time.time() + _models_dev_retry_after = 0 + logger.debug( + "Refreshed models.dev registry (%s): %d providers, %d total models", + where, + len(data), + sum(len(p.get("models", {})) for p in data.values() if isinstance(p, dict)), + ) + + +def _note_refresh_failure(exc: Exception, *, where: str) -> None: + """Record a failed refresh: arm the process-wide 5-minute backoff. + + Callers must hold ``_models_dev_fetch_lock`` (see ``_commit_registry``). + """ + global _models_dev_retry_after + _models_dev_retry_after = time.time() + _MODELS_DEV_RETRY_DELAY + logger.debug( + "models.dev refresh failed (%s); retry suppressed for %ds: %s", + where, + _MODELS_DEV_RETRY_DELAY, + exc, + ) + + +def _background_refresh_models_dev() -> None: + """Best-effort refresh after serving stale cache data.""" + global _models_dev_refresh_in_flight + try: + data = _fetch_models_dev_from_network() + with _models_dev_fetch_lock: + _commit_registry(data, where="background") + except Exception as e: + with _models_dev_fetch_lock: + _note_refresh_failure(e, where="background") + finally: + with _models_dev_refresh_lock: + _models_dev_refresh_in_flight = False + + +def _start_background_refresh_models_dev() -> None: + """Start one daemon refresh worker if none is already running. + + Honors the process-wide failure backoff: after a failed refresh, + no new background worker is spawned until ``_models_dev_retry_after``. + """ + global _models_dev_refresh_in_flight + if time.time() < _models_dev_retry_after: + return + with _models_dev_refresh_lock: + if _models_dev_refresh_in_flight: + return + _models_dev_refresh_in_flight = True + thread = threading.Thread( + target=_background_refresh_models_dev, + name="models-dev-refresh", + daemon=True, + ) + try: + thread.start() + except Exception as e: + # Thread/fd exhaustion: clear the flag so refresh isn't disabled + # for the rest of the process lifetime. Callers still get stale data. + with _models_dev_refresh_lock: + _models_dev_refresh_in_flight = False + logger.debug("Failed to start models.dev refresh thread: %s", e) + + +def fetch_models_dev( + force_refresh: bool = False, *, allow_network: bool = True +) -> Dict[str, Any]: """Fetch models.dev registry. Cache hierarchy: in-mem → disk → network. Returns the full registry dict keyed by provider ID, or empty dict on failure. Cache hierarchy (when ``force_refresh=False``): - 1. In-memory cache, populated and < TTL old → return immediately. - 2. **Disk cache file < TTL old by mtime → load, populate in-mem, return.** - No network call. Saves ~500 ms per cold-start agent construction; - ``models.dev`` only changes when providers add new models, so a - 1 hour staleness window is acceptable (same TTL as in-mem cache). - 3. Network fetch → on success, save to disk + in-mem and return. - 4. Network fails → fall back to ANY available disk cache (even stale) - with a short 5 min in-mem grace period before retrying network. + 1. Fresh in-memory cache → return immediately. + 2. Stale in-memory cache → return immediately and refresh in a single + background daemon thread. Callers never block on the network while + any cache exists; ``models.dev`` only changes when providers add + new models, so stale data is preferable to a foreground timeout. + 3. Disk cache file (any age) → load, populate in-mem, return + immediately. Stale disk caches trigger the same background refresh. + 4. No cache at all → singleflight foreground network fetch. On + success, save to disk + in-mem and return. + 5. Any failed refresh (foreground or background) suppresses further + automatic refreshes for 5 minutes process-wide. When ``force_refresh=True`` (used by ``hermes config refresh``, the - \"refresh model catalog\" code path), stages 1 and 2 are skipped. The - function always hits the network and only falls back to disk if the - network call fails. + \"refresh model catalog\" code path), cache fast paths and the failure + backoff are bypassed; the function hits the network and only falls back + to cached data if the call fails. When ``allow_network=False``, any + memory or disk cache is returned regardless of age and no request is + made — used by latency-sensitive paths (gateway route-identity checks) + that must never wait on the network. """ - global _models_dev_cache, _models_dev_cache_time + global _models_dev_cache, _models_dev_cache_time, _models_dev_retry_after + + if not allow_network: + if _models_dev_cache: + return _models_dev_cache + disk_data = _load_disk_cache() + if disk_data: + _models_dev_cache = disk_data + disk_age = _disk_cache_age_seconds() + _models_dev_cache_time = ( + time.time() - disk_age if disk_age is not None else 0 + ) + return _models_dev_cache # Stage 1: fresh in-memory cache wins. This is the hot path on # long-lived processes — no I/O, no system calls. @@ -268,54 +408,82 @@ def fetch_models_dev(force_refresh: bool = False) -> Dict[str, Any]: ): return _models_dev_cache - # Stage 2: fresh-by-mtime disk cache short-circuits the network call. - # Only kicks in on cold-start processes (in-mem cache is empty or - # expired) and only when the user hasn't asked for a forced refresh. - # Skipped if the disk cache file is missing, unreadable, or older - # than _MODELS_DEV_CACHE_TTL. + # Stage 2: stale in-memory cache is still better than blocking provider + # resolution on a foreground network timeout. Refresh it in the background. + if not force_refresh and _models_dev_cache: + _mark_stale_cache_grace() + _start_background_refresh_models_dev() + logger.debug( + "Using stale in-memory models.dev cache; refreshing in background" + ) + return _models_dev_cache + + # Stage 3: disk cache short-circuits the network call. + # Only kicks in on cold-start processes (in-mem cache is empty) and only + # when the user hasn't asked for a forced refresh. A stale disk cache is + # deliberately usable: provider/model resolution should not hang just + # because models.dev is unreachable. if not force_refresh: disk_age = _disk_cache_age_seconds() - if disk_age is not None and disk_age < _MODELS_DEV_CACHE_TTL: + if disk_age is not None: disk_data = _load_disk_cache() if disk_data: _models_dev_cache = disk_data - # Anchor in-mem TTL to the disk file's age so we don't - # extend an already-aging cache by another full hour. - _models_dev_cache_time = time.time() - disk_age - logger.debug( - "Loaded models.dev from fresh disk cache " - "(%d providers, age=%.0fs)", len(disk_data), disk_age, - ) + if disk_age < _MODELS_DEV_CACHE_TTL: + # Anchor in-mem TTL to the disk file's age so we don't + # extend an already-aging cache by another full hour. + _models_dev_cache_time = time.time() - disk_age + logger.debug( + "Loaded models.dev from fresh disk cache " + "(%d providers, age=%.0fs)", len(disk_data), disk_age, + ) + else: + _mark_stale_cache_grace() + _start_background_refresh_models_dev() + logger.debug( + "Using stale models.dev disk cache (age=%.0fs); " + "refreshing in background", + disk_age, + ) return _models_dev_cache - # Stage 3: network fetch. - try: - response = requests.get(MODELS_DEV_URL, timeout=15) - response.raise_for_status() - data = response.json() - if isinstance(data, dict) and data: - _models_dev_cache = data - _models_dev_cache_time = time.time() - _save_disk_cache(data) - logger.debug( - "Fetched models.dev registry: %d providers, %d total models", - len(data), - sum(len(p.get("models", {})) for p in data.values() if isinstance(p, dict)), - ) + # Failed automatic refreshes are process-wide. Avoid making every caller + # retry the same unreachable endpoint while no usable cache exists. + if not force_refresh and time.time() < _models_dev_retry_after: + return _models_dev_cache + + # Stage 4: singleflight foreground network fetch — only reached when no + # memory or disk cache exists (or on force_refresh). Recheck state after + # acquiring the lock because another caller may have refreshed or + # established backoff while we waited. + with _models_dev_fetch_lock: + now = time.time() + if not force_refresh: + if _models_dev_cache: + return _models_dev_cache + if now < _models_dev_retry_after: + return _models_dev_cache + + try: + data = _fetch_models_dev_from_network() + _commit_registry(data, where="foreground") return data - except Exception as e: - logger.debug("Failed to fetch models.dev: %s", e) + except Exception as e: + _note_refresh_failure(e, where="foreground") - # Stage 4: network failed — fall back to whatever disk cache exists, - # even if it's stale. Give it a short 5 min in-mem TTL so we retry - # the network soon instead of serving stale data for a full hour. - if not _models_dev_cache: - _models_dev_cache = _load_disk_cache() - if _models_dev_cache: - _models_dev_cache_time = time.time() - _MODELS_DEV_CACHE_TTL + 300 - logger.debug("Loaded models.dev from disk cache (%d providers)", len(_models_dev_cache)) + # Stage 5: network failed — return any stale memory/disk cache. Cache + # freshness remains expired; the retry-after timestamp controls when + # the next automatic request is allowed. + if not _models_dev_cache: + _models_dev_cache = _load_disk_cache() + _models_dev_cache_time = 0 + if _models_dev_cache: + logger.debug( + "Loaded stale models.dev disk cache (%d providers)", + len(_models_dev_cache), + ) - return _models_dev_cache + return _models_dev_cache def lookup_models_dev_context(provider: str, model: str) -> Optional[int]: @@ -671,7 +839,9 @@ def _parse_provider_info(provider_id: str, raw: Dict[str, Any]) -> ProviderInfo: # Provider-level queries # --------------------------------------------------------------------------- -def get_provider_info(provider_id: str) -> Optional[ProviderInfo]: +def get_provider_info( + provider_id: str, *, allow_network: bool = True +) -> Optional[ProviderInfo]: """Get full provider metadata from models.dev. Accepts either a Hermes provider ID (e.g. "kilocode") or a models.dev @@ -680,7 +850,14 @@ def get_provider_info(provider_id: str) -> Optional[ProviderInfo]: # Resolve Hermes ID → models.dev ID mdev_id = PROVIDER_TO_MODELS_DEV.get(provider_id, provider_id) - data = fetch_models_dev() + # NOTE: keep the zero-argument call on the default path. Dozens of test + # sites monkeypatch fetch_models_dev with zero-arg lambdas; passing the + # kwarg unconditionally would break them all (they raise TypeError). + data = ( + fetch_models_dev() + if allow_network + else fetch_models_dev(allow_network=False) + ) raw = data.get(mdev_id) if not isinstance(raw, dict): return None diff --git a/agent/monitoring/__init__.py b/agent/monitoring/__init__.py new file mode 100644 index 000000000000..ee45ff01649e --- /dev/null +++ b/agent/monitoring/__init__.py @@ -0,0 +1,29 @@ +"""Hermes gateway monitoring. + +Service health monitoring plus redacted operational diagnostics for the +gateway daemon, exported over OTLP to an operator-configured endpoint. + +``emitter`` is the in-process event bus: producers (gateway status hooks, +the diagnostic log handler) hand typed events to a fire-and-forget queue, +and subscribers (the OTLP streamers) consume them off the hot path. The +emitter never blocks or raises into gateway code (the hot-path invariant), +and nothing is persisted locally — monitoring is an egress path, not a store. + +Deliberately out of scope here: run/model/tool trajectory capture, usage +analytics, and any content-bearing signal. Those planes are served by the +NeMo Relay integration and its Hermes-owned subscribers. +""" + +from __future__ import annotations + +from . import emitter, events + +emit = emitter.emit +get_emitter = emitter.get_emitter + +__all__ = [ + "emitter", + "events", + "emit", + "get_emitter", +] diff --git a/agent/monitoring/cron_health.py b/agent/monitoring/cron_health.py new file mode 100644 index 000000000000..2ed0f1cb9b2e --- /dev/null +++ b/agent/monitoring/cron_health.py @@ -0,0 +1,201 @@ +"""Content-free cron service-health and execution telemetry projection.""" + +from __future__ import annotations + +import hashlib +import logging +import re +from dataclasses import dataclass +from datetime import datetime +from typing import Any, Optional + +from agent.monitoring.events import CronExecutionEvent +from agent.monitoring.gateway_health import GatewayHealthSnapshot, GatewayMetric +from cron.jobs import ( + _compute_grace_seconds, + get_catch_up_occurrence_count, + get_ticker_heartbeat_age, + get_ticker_success_age, + load_jobs, +) +from cron.scheduler import get_running_job_ids +from hermes_time import now as _hermes_now + +logger = logging.getLogger(__name__) +_KNOWN_STATUSES = {"claimed", "running", "completed", "failed", "unknown"} +_KNOWN_SOURCES = {"builtin", "direct", "external"} +_KNOWN_DELIVERY_OUTCOMES = {"delivered", "failed", "suppressed", "not_configured"} + + +@dataclass(frozen=True, slots=True) +class CronHealthSnapshot: + metrics: list[GatewayMetric] + events: list[CronExecutionEvent] + + +def _now() -> datetime: + return _hermes_now() + + +def _job_key(raw: Any) -> str: + value = str(raw or "unknown").encode("utf-8", errors="replace") + return f"sha256:{hashlib.sha256(value).hexdigest()[:24]}" + + +def classify_cron_error(raw: Any) -> str: + text = str(raw or "").lower() + if ( + re.search(r"\b(?:authentication|authenticated|authenticate|authorization|authorized|authorize|unauthorized|forbidden)\b", text) + or re.search(r"\bbearer\b", text) + or re.search(r"\b(?:access|api|refresh) token\b", text) + or re.search(r"\b(?:401|403)\b", text) + ): + return "auth_failed" + if "rate limit" in text or "429" in text or "quota" in text: + return "rate_limited" + if "timeout" in text or "timed out" in text: + return "timeout" + if any(value in text for value in ("network", "connection", "dns", "socket", "unreachable")): + return "network_error" + if "dispatch" in text or "executor" in text: + return "dispatch_failed" + if "interrupt" in text or "owner exited" in text or "restarted" in text: + return "interrupted" + if "empty response" in text: + return "empty_response" + if any(value in text for value in ("config", "missing", "invalid")): + return "invalid_config" + return "unknown" + + +def _parse_time(raw: Any) -> Optional[datetime]: + try: + return datetime.fromisoformat(str(raw)) if raw else None + except (TypeError, ValueError): + return None + + +def _duration_ms(record: dict[str, Any]) -> Optional[int]: + start = _parse_time(record.get("started_at")) or _parse_time(record.get("claimed_at")) + finish = _parse_time(record.get("finished_at")) + if start is None or finish is None: + return None + try: + duration = int((finish - start).total_seconds() * 1000) + except (TypeError, ValueError): + return None + return max(0, duration) + + +def project_execution_event( + record: dict[str, Any], *, delivery_outcome: Optional[str] = None +) -> CronExecutionEvent: + status = str(record.get("status") or "unknown").lower() + source = str(record.get("source") or "unknown").lower() + if source not in _KNOWN_SOURCES and source != "unknown": + source = "external" + outcome = str(delivery_outcome).lower() if delivery_outcome is not None else None + return CronExecutionEvent( + status=status if status in _KNOWN_STATUSES else "unknown", + job_key=_job_key(record.get("job_id")), + source=source if source in _KNOWN_SOURCES else "unknown", + duration_ms=_duration_ms(record), + delivery_outcome=( + outcome if outcome in _KNOWN_DELIVERY_OUTCOMES else None + ), + error_class=( + classify_cron_error(record.get("error")) + if status in {"failed", "unknown"} + else None + ), + ) + + +def emit_execution_state( + record: Optional[dict[str, Any]], *, delivery_outcome: Optional[str] = None +) -> None: + """Best-effort lifecycle emit; terminal states synchronously cross the queue barrier.""" + if not record: + return + try: + from agent.monitoring import emitter + + event = project_execution_event(record, delivery_outcome=delivery_outcome) + target = emitter.get_emitter() + target.emit(event) + if event.status in {"completed", "failed", "unknown"}: + target.flush(timeout=1.0) + except Exception: + logger.debug("cron execution telemetry emit failed", exc_info=True) + + +def _is_overdue(job: dict[str, Any], now: datetime) -> bool: + if not job.get("enabled", True): + return False + next_run = _parse_time(job.get("next_run_at")) + schedule = job.get("schedule") + if next_run is None or not isinstance(schedule, dict): + return False + try: + if next_run.tzinfo is None and now.tzinfo is not None: + next_run = next_run.replace(tzinfo=now.tzinfo) + lateness = (now - next_run).total_seconds() + return lateness > _compute_grace_seconds(schedule) + except (TypeError, ValueError): + return False + + +def build_cron_health_snapshot() -> CronHealthSnapshot: + metrics: list[GatewayMetric] = [] + for name, reader in ( + ("hermes.cron.scheduler.heartbeat_age_seconds", get_ticker_heartbeat_age), + ("hermes.cron.scheduler.last_success_age_seconds", get_ticker_success_age), + ): + try: + value = reader() + if value is not None: + metrics.append(GatewayMetric(name, max(0.0, float(value)), {})) + except Exception: + logger.debug("cron freshness metric unavailable", exc_info=True) + + try: + metrics.append( + GatewayMetric( + "hermes.cron.scheduler.catch_up_occurrences", + get_catch_up_occurrence_count(), + {}, + ) + ) + except Exception: + logger.debug("cron catch-up metric unavailable", exc_info=True) + + try: + jobs = load_jobs() + enabled = [job for job in jobs if job.get("enabled", True)] + metrics.append(GatewayMetric("hermes.cron.jobs.enabled", len(enabled), {})) + metrics.append( + GatewayMetric( + "hermes.cron.jobs.overdue", + sum(1 for job in enabled if _is_overdue(job, _now())), + {}, + ) + ) + except Exception: + logger.debug("cron job metrics unavailable", exc_info=True) + + try: + metrics.append( + GatewayMetric("hermes.cron.jobs.running", len(get_running_job_ids()), {}) + ) + except Exception: + logger.debug("cron running-job metric unavailable", exc_info=True) + return CronHealthSnapshot(metrics=metrics, events=[]) + + +__all__ = [ + "CronHealthSnapshot", + "build_cron_health_snapshot", + "classify_cron_error", + "emit_execution_state", + "project_execution_event", +] diff --git a/agent/monitoring/emitter.py b/agent/monitoring/emitter.py new file mode 100644 index 000000000000..18a0d4851ae0 --- /dev/null +++ b/agent/monitoring/emitter.py @@ -0,0 +1,211 @@ +"""Monitoring emitter: fire-and-forget queue + background dispatcher. + +The emitter is the single seam between producers (gateway status hooks, the +diagnostic log handler) and consumers (the OTLP streamers). Its contract is +the hot-path invariant: + + ``emit()`` MUST return in O(microseconds), MUST NOT block on disk/network, + and MUST NEVER raise into the caller. A monitoring failure is logged + locally and dropped — it can never affect the gateway or a session. + +Mechanism: + * ``emit(event)`` does a non-blocking ``queue.put_nowait`` wrapped in a bare + except. On a full queue it drops the *oldest* event and counts the drop. + * A daemon thread drains the queue and fans each batch out to subscribers + (the OTLP metric/span/log streamers). Each subscriber is fail-isolated — + a slow or raising subscriber never affects the hot path or its peers. + +Nothing is persisted here. Monitoring is an egress path, not a local store; +if no subscriber is attached, events simply age out of the ring buffer. +""" + +from __future__ import annotations + +import logging +import queue +import threading +import time +from typing import Any, Dict, Optional + +logger = logging.getLogger(__name__) + +_MAX_QUEUE = 10_000 # ring-buffer depth; oldest dropped when full +_DRAIN_BATCH = 256 + + +class MonitoringEmitter: + """Owns the queue, the dispatcher thread, and the subscriber list.""" + + def __init__(self, *, enabled: bool = True) -> None: + self._enabled = enabled + self._q: "queue.Queue[Dict[str, Any]]" = queue.Queue(maxsize=_MAX_QUEUE) + self._dropped = 0 + self._dispatched = 0 + self._stop = threading.Event() + self._started = False + self._lock = threading.Lock() + self._thread: Optional[threading.Thread] = None + # Live subscribers (the OTLP streamers). Called from the dispatcher + # thread, fully fail-isolated. Each subscriber is callable(batch: list[dict]). + self._subscribers: list = [] + + # ── public API (hot path) ─────────────────────────────────────────────── + def emit(self, event: Any) -> None: + """Enqueue an event. Never blocks, never raises. + + ``event`` may be a dataclass with ``to_dict()`` or a plain dict. + """ + if not self._enabled: + return + try: + payload = event.to_dict() if hasattr(event, "to_dict") else dict(event) + payload.setdefault("ts_ns", time.time_ns()) + self._ensure_started() + try: + self._q.put_nowait(payload) + except queue.Full: + # Drop oldest to make room — bounded memory, newest-wins. + try: + self._q.get_nowait() + self._q.task_done() + self._dropped += 1 + self._q.put_nowait(payload) + except Exception: + self._dropped += 1 + except Exception: # the hot-path invariant: never propagate + logger.debug("monitoring emit failed", exc_info=True) + + # ── lifecycle ─────────────────────────────────────────────────────────── + def _ensure_started(self) -> None: + if self._started: + return + with self._lock: + if self._started: + return + self._thread = threading.Thread( + target=self._run, name="hermes-monitoring-dispatch", daemon=True + ) + self._thread.start() + self._started = True + + def _run(self) -> None: + while not self._stop.is_set(): + try: + first = self._q.get(timeout=0.5) + except queue.Empty: + continue + batch = [first] + while len(batch) < _DRAIN_BATCH: + try: + batch.append(self._q.get_nowait()) + except queue.Empty: + break + try: + self._dispatch(batch) + finally: + for _ in batch: + self._q.task_done() + + def _dispatch(self, batch) -> None: + # Fan-out to subscribers (OTLP streamers) — fully fail-isolated. + for sub in list(self._subscribers): + try: + sub(batch) + except Exception: + logger.debug("monitoring subscriber failed", exc_info=True) + self._dispatched += len(batch) + + def subscribe(self, callback) -> None: + """Register a live batch subscriber (callable(batch: list[dict])).""" + if callback not in self._subscribers: + self._subscribers.append(callback) + self._enabled = True + + def unsubscribe(self, callback) -> None: + try: + self._subscribers.remove(callback) + except ValueError: + pass + if not self._subscribers: + self._enabled = False + + # ── introspection / shutdown (tests, CLI) ─────────────────────────────── + def flush(self, timeout: float = 2.0) -> None: + """Wait boundedly for queued and in-flight batches to finish dispatch.""" + if timeout <= 0: + return + + finished = threading.Event() + + def _wait_for_completion() -> None: + self._q.join() + finished.set() + + waiter = threading.Thread( + target=_wait_for_completion, + name="hermes-monitoring-flush", + daemon=True, + ) + waiter.start() + finished.wait(timeout=timeout) + + def stats(self) -> Dict[str, int]: + return { + "queued": self._q.qsize(), + "dispatched": self._dispatched, + "dropped": self._dropped, + "subscribers": len(self._subscribers), + } + + def close(self) -> None: + self._stop.set() + if self._thread is not None: + self._thread.join(timeout=2.0) + self._started = False + + +# ── process-wide singleton ────────────────────────────────────────────────── +_EMITTER: Optional[MonitoringEmitter] = None +_EMITTER_LOCK = threading.Lock() + + +def get_emitter() -> MonitoringEmitter: + """Return the process-wide monitoring emitter.""" + global _EMITTER + if _EMITTER is not None: + return _EMITTER + with _EMITTER_LOCK: + if _EMITTER is None: + # Collection is opt-in. A plane exporter enables the singleton by + # attaching its first subscriber; until then producers are no-ops. + _EMITTER = MonitoringEmitter(enabled=False) + return _EMITTER + + +def emit(event: Any) -> None: + """Module-level convenience: emit via the singleton.""" + get_emitter().emit(event) + + +def reset_emitter_for_tests(emitter: Optional[MonitoringEmitter] = None) -> None: + """Swap the singleton (tests only).""" + global _EMITTER + with _EMITTER_LOCK: + if _EMITTER is not None and emitter is not _EMITTER: + try: + _EMITTER.close() + except Exception: + pass + _EMITTER = emitter + + +# Back-compat alias for the salvaged class name used in emozilla's tests. +TelemetryEmitter = MonitoringEmitter + +__all__ = [ + "MonitoringEmitter", + "TelemetryEmitter", + "get_emitter", + "emit", + "reset_emitter_for_tests", +] diff --git a/agent/monitoring/events.py b/agent/monitoring/events.py new file mode 100644 index 000000000000..a17f4a49425d --- /dev/null +++ b/agent/monitoring/events.py @@ -0,0 +1,86 @@ +"""Typed gateway monitoring events. + +Content-free service-health and redacted diagnostic events for the gateway +daemon. These are the only event shapes the monitoring plane emits: no +prompts, messages, tool args/results, session history, or usage analytics. +""" + +from __future__ import annotations + +import time +from dataclasses import dataclass, field, asdict +from typing import Any, Dict, Optional + + +def _now_ns() -> int: + return time.time_ns() + + +@dataclass(slots=True) +class GatewayHealthEvent: + """Content-free gateway health snapshot or lifecycle event.""" + + name: str + gateway_state: Optional[str] = None + old_state: Optional[str] = None + new_state: Optional[str] = None + exit_reason: Optional[str] = None + restart_requested: Optional[bool] = None + active_agents: int = 0 + gateway_busy: bool = False + gateway_drainable: bool = False + platform_count: int = 0 + fatal_platform_count: int = 0 + profile: Optional[str] = None + install_id: Optional[str] = None + version: Optional[str] = None + supervision_mode: Optional[str] = None + pid: Optional[int] = None + ts_ns: int = field(default_factory=_now_ns) + + def to_dict(self) -> Dict[str, Any]: + return {"event": "gateway_health", **asdict(self)} + + +@dataclass(slots=True) +class GatewayDiagnosticEvent: + """Redacted gateway diagnostic event for operator-owned observability.""" + + name: str + subsystem: str + error_class: str = "unknown" + error_code: Optional[str] = None + platform: Optional[str] = None + old_state: Optional[str] = None + new_state: Optional[str] = None + profile: Optional[str] = None + version: Optional[str] = None + severity: str = "warning" + ts_ns: int = field(default_factory=_now_ns) + source_logger: Optional[str] = None + + def to_dict(self) -> Dict[str, Any]: + return {"event": "gateway_diagnostic", **asdict(self)} + + +@dataclass(slots=True) +class CronExecutionEvent: + """Content-free durable cron execution lifecycle projection.""" + + status: str + job_key: str + source: str = "unknown" + duration_ms: Optional[int] = None + delivery_outcome: Optional[str] = None + error_class: Optional[str] = None + ts_ns: int = field(default_factory=_now_ns) + + def to_dict(self) -> Dict[str, Any]: + return {"event": "cron_execution", **asdict(self)} + + +__all__ = [ + "GatewayHealthEvent", + "GatewayDiagnosticEvent", + "CronExecutionEvent", +] diff --git a/agent/monitoring/gateway_health.py b/agent/monitoring/gateway_health.py new file mode 100644 index 000000000000..752473fe31bb --- /dev/null +++ b/agent/monitoring/gateway_health.py @@ -0,0 +1,469 @@ +"""Gateway health and diagnostics signal producer. + +This module keeps the plane narrow: service health monitoring plus +redacted operational diagnostics. It reuses the existing gateway runtime-status +contract and emits content-free metrics/events. No prompts, messages, tool args, +session history, audit records, or product analytics belong here. +""" + +from __future__ import annotations + +import hashlib +import logging +import re +from dataclasses import dataclass +from typing import Any, Dict, List, Optional + +from agent.monitoring.events import GatewayDiagnosticEvent, GatewayHealthEvent + + +@dataclass(frozen=True, slots=True) +class GatewayMetric: + name: str + value: int | float + attributes: Dict[str, str] + + +@dataclass(frozen=True, slots=True) +class GatewayHealthSnapshot: + metrics: List[GatewayMetric] + events: List[GatewayHealthEvent | GatewayDiagnosticEvent] + + +_RUNNING_PLATFORM_STATES = {"running", "connected", "ok", "ready"} +_FATAL_PLATFORM_STATES = {"fatal", "degraded", "error", "failed"} +_KNOWN_GATEWAY_STATES = { + "starting", "draining", "stopping", "stopped", "startup_failed", "unknown" +} | _RUNNING_PLATFORM_STATES | _FATAL_PLATFORM_STATES +_KNOWN_PLATFORM_STATES = _RUNNING_PLATFORM_STATES | _FATAL_PLATFORM_STATES | { + "connecting", "disconnected", "disabled", "paused", "retrying", "unknown" +} +_SUPERVISION_MODES = {"systemd", "s6", "container", "launchd", "manual", "unknown"} +_SOURCE_LOGGER_RE = re.compile(r"^gateway(?:\.[A-Za-z_][A-Za-z0-9_]*)*$") + + +def _allowed_logger(name: str) -> bool: + return name == "gateway" or name.startswith("gateway.") + + +def source_logger_for_export(name: Any) -> Optional[str]: + """Return a bounded source-controlled gateway logger name for OTLP scope.""" + value = str(name or "") + return value if len(value) <= 128 and _SOURCE_LOGGER_RE.fullmatch(value) else None + + +def redact_gateway_message(message: Any) -> str: + """Redact gateway diagnostic free text for operator-owned export. + + Single scrub path: everything goes through + ``agent.monitoring.redaction.redact_for_export`` (unconditional + secrets + PII), then is length-bounded. + """ + try: + from agent.monitoring.redaction import redact_for_export + redacted = redact_for_export(str(message or "")) or "" + except Exception: + redacted = "[redaction-unavailable]" + return redacted[:500] + + +def classify_gateway_error(raw: Any) -> str: + s = str(raw or "").lower() + if any(k in s for k in ("auth", "token", "unauthorized", "forbidden", "401", "403")): + return "auth_failed" + if "rate" in s and "limit" in s: + return "rate_limited" + if "timeout" in s or "timed out" in s: + return "timeout" + if any( + k in s + for k in ( + "network", + "connection", + "dns", + "socket", + "connect call failed", + "failed to connect", + "cannot connect", + "unreachable", + "name resolution", + ) + ): + return "network_error" + if any(k in s for k in ("config", "missing", "invalid")): + return "invalid_config" + if "startup" in s: + return "startup_failed" + if "fatal" in s: + return "platform_fatal" + return "unknown" + + +def classify_exit_reason( + raw: Any, *, state: Any, restart_requested: bool +) -> Optional[str]: + """Reduce free-form shutdown text to a bounded operational class.""" + if restart_requested: + return "restart_requested" + state_name = str(state or "").lower() + if raw is None and state_name != "startup_failed": + return None + classified = classify_gateway_error(raw) + if state_name == "startup_failed": + return classified if classified != "unknown" else "startup_failed" + text = str(raw or "").lower() + if "signal" in text or "sigterm" in text or "sigint" in text: + return "signal" + if state_name == "stopped" and any(word in text for word in ("shutdown", "stop")): + return "planned_stop" + return classified + + +def _bounded_state(raw: Any, *, allowed: set[str]) -> str: + state = str(raw or "unknown").lower() + return state if state in allowed else "unknown" + + +def _safe_metric_value(raw: Any, *, limit: int = 128) -> str: + try: + from agent.monitoring.redaction import redact_for_export + value = redact_for_export(str(raw or "")) or "unknown" + except Exception: + return "unknown" + return value[:limit] + + +def _safe_instance_id(raw: Any) -> str: + """Return a stable opaque instance key without exporting the source ID.""" + value = str(raw or "unknown").encode("utf-8", errors="replace") + return f"sha256:{hashlib.sha256(value).hexdigest()[:24]}" + + +def subsystem_for_logger(logger_name: str) -> str: + if logger_name == "gateway.relay" or logger_name.startswith("gateway.relay."): + return "platform.relay" + if logger_name.startswith("gateway.platforms."): + parts = logger_name.split(".") + if len(parts) >= 3 and parts[2]: + return f"platform.{parts[2]}" + if logger_name.startswith("gateway.platforms"): + return "platform" + if logger_name.startswith("gateway"): + return "gateway" + return "gateway" + + +def platform_for_subsystem(subsystem: str) -> Optional[str]: + if subsystem.startswith("platform."): + return subsystem.split(".", 1)[1] or None + return None + + +def _parse_active_agents(raw: Any) -> int: + try: + from gateway.status import parse_active_agents + return parse_active_agents(raw) + except Exception: + try: + return max(0, int(raw)) + except (TypeError, ValueError): + return 0 + + +def _derive_busy(gateway_running: bool, gateway_state: Any, active_agents: Any) -> bool: + try: + from gateway.status import derive_gateway_busy + return derive_gateway_busy( + gateway_running=gateway_running, + gateway_state=gateway_state, + active_agents=active_agents, + ) + except Exception: + return bool(gateway_running and gateway_state == "running" and _parse_active_agents(active_agents) > 0) + + +def _derive_drainable(gateway_running: bool, gateway_state: Any) -> bool: + try: + from gateway.status import derive_gateway_drainable + return derive_gateway_drainable(gateway_running=gateway_running, gateway_state=gateway_state) + except Exception: + return bool(gateway_running and gateway_state == "running") + + +def _base_attrs(*, profile: str, install_id: str, version: str, supervision_mode: str) -> Dict[str, str]: + mode = str(supervision_mode or "unknown").lower() + return { + "service.instance.id": _safe_instance_id(install_id), + "service.version": _safe_metric_value(version, limit=64), + "hermes.supervision_mode": mode if mode in _SUPERVISION_MODES else "unknown", + } + + +def _metric(name: str, value: int | float, attrs: Dict[str, str], **extra: str) -> GatewayMetric: + out = dict(attrs) + for key, val in extra.items(): + if val is not None: + out[key] = _safe_metric_value(val) + return GatewayMetric(name=name, value=value, attributes=out) + + +def build_gateway_health_snapshot( + runtime: Optional[dict[str, Any]], + *, + gateway_running: bool, + profile: str, + install_id: str, + version: str, + supervision_mode: str = "unknown", +) -> GatewayHealthSnapshot: + """Convert gateway_state.json-compatible runtime state into P0 signals.""" + runtime = runtime or {} + gateway_state = _bounded_state( + runtime.get("gateway_state"), allowed=_KNOWN_GATEWAY_STATES + ) + active_agents = _parse_active_agents(runtime.get("active_agents", 0)) + busy = _derive_busy(gateway_running, gateway_state, active_agents) + drainable = _derive_drainable(gateway_running, gateway_state) + platforms = runtime.get("platforms") if isinstance(runtime.get("platforms"), dict) else {} + base = _base_attrs(profile=profile, install_id=install_id, version=version, supervision_mode=supervision_mode) + + metrics: list[GatewayMetric] = [ + _metric("hermes.gateway.up", 1 if gateway_running else 0, base), + _metric("hermes.gateway.active_agents", active_agents, base), + _metric("hermes.gateway.busy", 1 if busy else 0, base), + _metric("hermes.gateway.drainable", 1 if drainable else 0, base), + _metric("hermes.gateway.restart_requested", 1 if runtime.get("restart_requested") else 0, base), + ] + if gateway_state: + metrics.append(_metric("hermes.gateway.state", 1, base, **{"hermes.gateway.state": str(gateway_state)})) + + fatal_count = 0 + events: list[GatewayHealthEvent | GatewayDiagnosticEvent] = [] + for platform, pdata in platforms.items(): + pdata = pdata if isinstance(pdata, dict) else {} + state = _bounded_state( + pdata.get("state"), allowed=_KNOWN_PLATFORM_STATES + ) + raw_error = pdata.get("error_code") or pdata.get("error_message") + error_code = classify_gateway_error(raw_error) + is_up = state in _RUNNING_PLATFORM_STATES + is_degraded = state in _FATAL_PLATFORM_STATES + if is_degraded: + fatal_count += 1 + metrics.append(_metric( + "hermes.platform.up", + 1 if is_up else 0, + base, + **{"hermes.platform": str(platform), "hermes.platform.state": state}, + )) + metrics.append(_metric( + "hermes.platform.degraded", + 1 if is_degraded else 0, + base, + **{"hermes.platform": str(platform), "hermes.platform.state": state, "hermes.error_code": error_code}, + )) + if is_degraded: + events.append(GatewayDiagnosticEvent( + name="platform.fatal", + subsystem=f"platform.{platform}", + platform=str(platform), + error_code=error_code, + error_class=classify_gateway_error(error_code or pdata.get("error_message")), + profile=profile, + version=version, + severity="error" if state == "fatal" else "warning", + )) + + events.insert(0, GatewayHealthEvent( + name="gateway.health_snapshot", + gateway_state=str(gateway_state) if gateway_state is not None else None, + active_agents=active_agents, + gateway_busy=busy, + gateway_drainable=drainable, + platform_count=len(platforms), + fatal_platform_count=fatal_count, + profile=profile, + install_id=install_id, + version=version, + supervision_mode=supervision_mode, + pid=_coerce_pid(runtime.get("pid")), + )) + return GatewayHealthSnapshot(metrics=metrics, events=events) + + +def _safe_profile() -> str: + try: + from hermes_cli.profiles import get_active_profile_name + return str(get_active_profile_name() or "default") + except Exception: + return "default" + + +def _safe_version() -> str: + try: + from hermes_cli import __version__ + return str(__version__) + except Exception: + return "unknown" + + +def emit_runtime_status_transition(previous: Optional[dict[str, Any]], current: dict[str, Any]) -> None: + """Emit immediate content-free gateway events for runtime status changes. + + Called by gateway.status.write_runtime_status after persisting the new status. + Fully fail-open: failures never affect gateway status writes. + """ + try: + from agent.monitoring import emitter + out: list[GatewayHealthEvent | GatewayDiagnosticEvent] = [] + profile = _safe_profile() + version = _safe_version() + old_gateway_state = _bounded_state( + (previous or {}).get("gateway_state"), allowed=_KNOWN_GATEWAY_STATES + ) if (previous or {}).get("gateway_state") is not None else None + new_gateway_state = _bounded_state( + current.get("gateway_state"), allowed=_KNOWN_GATEWAY_STATES + ) if current.get("gateway_state") is not None else None + if old_gateway_state != new_gateway_state and new_gateway_state: + out.append(GatewayHealthEvent( + name="gateway.lifecycle", + gateway_state=new_gateway_state, + old_state=old_gateway_state, + new_state=new_gateway_state, + exit_reason=classify_exit_reason( + current.get("exit_reason"), + state=new_gateway_state, + restart_requested=bool(current.get("restart_requested")), + ), + restart_requested=bool(current.get("restart_requested")), + active_agents=_parse_active_agents(current.get("active_agents", 0)), + profile=profile, + version=version, + pid=_coerce_pid(current.get("pid")), + )) + if new_gateway_state == "startup_failed": + out.append(GatewayDiagnosticEvent( + name="gateway.startup_failed", + subsystem="gateway", + error_class=classify_gateway_error(current.get("exit_reason") or "startup_failed"), + error_code=classify_gateway_error(current.get("exit_reason") or "startup_failed"), + profile=profile, + version=version, + severity="error", + )) + if new_gateway_state == "stopped": + out.append(GatewayHealthEvent( + name="gateway.exit", + gateway_state=new_gateway_state, + old_state=old_gateway_state, + new_state=new_gateway_state, + exit_reason=classify_exit_reason( + current.get("exit_reason"), + state=new_gateway_state, + restart_requested=bool(current.get("restart_requested")), + ), + restart_requested=bool(current.get("restart_requested")), + active_agents=_parse_active_agents(current.get("active_agents", 0)), + profile=profile, + version=version, + pid=_coerce_pid(current.get("pid")), + )) + + old_platforms_raw = (previous or {}).get("platforms") + new_platforms_raw = current.get("platforms") + old_platforms = old_platforms_raw if isinstance(old_platforms_raw, dict) else {} + new_platforms = new_platforms_raw if isinstance(new_platforms_raw, dict) else {} + for platform, pdata in new_platforms.items(): + pdata = pdata if isinstance(pdata, dict) else {} + prev_raw = old_platforms.get(platform, {}) + prev = prev_raw if isinstance(prev_raw, dict) else {} + old_state = _bounded_state( + prev.get("state"), allowed=_KNOWN_PLATFORM_STATES + ) if prev.get("state") is not None else None + new_state = _bounded_state( + pdata.get("state"), allowed=_KNOWN_PLATFORM_STATES + ) if pdata.get("state") is not None else None + if old_state == new_state or not new_state: + continue + error_code = classify_gateway_error(pdata.get("error_code") or pdata.get("error_message")) + severity = "error" if new_state.lower() in {"fatal", "failed", "error"} else "warning" + out.append(GatewayDiagnosticEvent( + name="platform.state_change", + subsystem=f"platform.{platform}", + platform=str(platform), + old_state=old_state, + new_state=new_state, + error_code=error_code, + error_class=error_code, + profile=profile, + version=version, + severity=severity, + )) + if new_state.lower() in _FATAL_PLATFORM_STATES: + out.append(GatewayDiagnosticEvent( + name="platform.fatal", + subsystem=f"platform.{platform}", + platform=str(platform), + error_code=error_code, + error_class=error_code, + profile=profile, + version=version, + severity=severity, + )) + for ev in out: + emitter.emit(ev) + except Exception: + logging.getLogger(__name__).debug("gateway runtime status transition emit failed", exc_info=True) + + +def _coerce_pid(raw: Any) -> Optional[int]: + try: + pid = int(raw) + except (TypeError, ValueError): + return None + return pid if pid > 0 else None + + +class GatewayDiagnosticLogHandler(logging.Handler): + """Allowlisted warning/error bridge for gateway-owned diagnostics.""" + + def __init__(self, *, profile: str = "default", version: str = "unknown") -> None: + super().__init__(level=logging.WARNING) + self.profile = profile + self.version = version + + def emit(self, record: logging.LogRecord) -> None: + try: + if record.levelno < logging.WARNING: + return + if not _allowed_logger(record.name): + return + subsystem = subsystem_for_logger(record.name) + message = record.getMessage() + error_class = classify_gateway_error(message) + event = GatewayDiagnosticEvent( + name=f"gateway.log.{record.levelname.lower()}", + subsystem=subsystem, + source_logger=source_logger_for_export(record.name), + platform=platform_for_subsystem(subsystem), + error_class=error_class, + error_code=error_class, + profile=self.profile, + version=self.version, + severity=record.levelname.lower(), + ) + from agent.monitoring import emitter + emitter.get_emitter().emit(event) + except Exception: + logging.getLogger(__name__).debug("gateway diagnostic emit failed", exc_info=True) + + +__all__ = [ + "GatewayMetric", + "GatewayHealthSnapshot", + "GatewayDiagnosticLogHandler", + "build_gateway_health_snapshot", + "classify_gateway_error", + "source_logger_for_export", + "redact_gateway_message", +] diff --git a/agent/monitoring/gateway_health_export.py b/agent/monitoring/gateway_health_export.py new file mode 100644 index 000000000000..0a377c99ab30 --- /dev/null +++ b/agent/monitoring/gateway_health_export.py @@ -0,0 +1,643 @@ +"""Gateway Health & Diagnostics OTLP export runtime. + +This exporter emits operator-owned gateway service-health metrics plus +narrow redacted diagnostic events. It is deliberately in-process and fail-open so +it works under systemd, launchd, s6, containers, tmux, nohup, or a simple shell +without a sidecar/watchdog dependency. +""" + +from __future__ import annotations + +import logging +import os +import re +import threading +from dataclasses import dataclass +from typing import Any, Dict, Optional + +logger = logging.getLogger(__name__) + +_DEFAULT_DIAGNOSTIC_SCOPE = "hermes.gateway.diagnostics" + +_RESOURCE_ATTRIBUTE_KEYS = frozenset({ + "service.name", + "service.namespace", + "service.version", + "service.instance.id", + "deployment.environment.name", + "cloud.provider", + "cloud.platform", + "cloud.region", + "telemetry.scope", +}) +_DIAGNOSTIC_ATTRIBUTE_KEYS = frozenset({ + "name", + "subsystem", + "error_class", + "error_code", + "platform", + "old_state", + "new_state", + "version", + "severity", +}) +_SAFE_RESOURCE_VALUE = re.compile(r"^[A-Za-z0-9._:/-]{1,128}$") + + +def _redact_string(raw: Any, *, limit: int = 500) -> str: + try: + from agent.monitoring.redaction import redact_for_export + return (redact_for_export(str(raw or "")) or "[redacted]")[:limit] + except Exception: + return "[redaction-unavailable]" + + +def _safe_resource_attributes(raw: Any) -> Dict[str, str]: + """Allowlist bounded resource labels and reject values changed by redaction.""" + attrs: Dict[str, str] = {} + if not isinstance(raw, dict): + return attrs + for key, value in raw.items(): + key = str(key) + if key not in _RESOURCE_ATTRIBUTE_KEYS or value is None: + continue + if key == "service.instance.id": + from agent.monitoring.gateway_health import _safe_instance_id + attrs[key] = _safe_instance_id(value) + continue + text = str(value) + if not _SAFE_RESOURCE_VALUE.fullmatch(text): + continue + if _redact_string(text, limit=128) != text: + continue + attrs[key] = text + return attrs + + +def _runtime_resource_attributes( + config: Dict[str, Any], *, telemetry_scope: str +) -> Dict[str, str]: + """Build the safe OTLP resource shared by metrics and diagnostic logs.""" + gh = _gateway_health_config(config) + attrs = _safe_resource_attributes(gh.get("resource_attributes")) + from agent.monitoring.gateway_health import _safe_instance_id + + attrs["service.name"] = "hermes-gateway" + attrs["service.instance.id"] = _safe_instance_id(_install_id(config)) + attrs["telemetry.scope"] = telemetry_scope + return attrs + + +def _diagnostic_log_attributes(event: Dict[str, Any]) -> Dict[str, Any]: + attrs: Dict[str, Any] = {} + for key in _DIAGNOSTIC_ATTRIBUTE_KEYS: + value = event.get(key) + if value is None: + continue + attrs[f"hermes.{key}"] = _redact_string(value) if isinstance(value, str) else value + return attrs + + +@dataclass(slots=True) +class GatewayHealthExportRuntime: + enabled: bool + reason: str = "disabled" + streamer: Any = None + metric_provider: Any = None + log_handler: Any = None + log_streamer: Any = None + thread: Optional[threading.Thread] = None + stop_event: Optional[threading.Event] = None + + def shutdown(self) -> None: + if self.stop_event is not None: + self.stop_event.set() + if self.thread is not None: + self.thread.join(timeout=0.25) + if self.log_handler is not None: + try: + logging.getLogger().removeHandler(self.log_handler) + except Exception: + pass + + # All producers above are now stopped. Drain queued and in-flight + # events before detaching subscribers so the terminal lifecycle event + # cannot race exporter shutdown. The barrier is bounded and fail-open. + try: + from agent.monitoring.emitter import get_emitter + emitter = get_emitter() + emitter.flush(timeout=1.0) + if self.streamer is not None: + emitter.unsubscribe(self.streamer) + if self.log_streamer is not None: + emitter.unsubscribe(self.log_streamer) + except Exception: + pass + + # Network flush/close runs under one bounded daemon-thread deadline and + # can never delay gateway teardown indefinitely. + closeables = [ + item for item in (self.streamer, self.log_streamer, self.metric_provider) + if item is not None + ] + + def _close() -> None: + for item in closeables: + try: + item.shutdown() + except Exception: + pass + + if closeables: + worker = threading.Thread( + target=_close, + name="hermes-gateway-health-export-shutdown", + daemon=True, + ) + worker.start() + worker.join(timeout=2.0) + + self.streamer = None + self.log_streamer = None + self.metric_provider = None + self.thread = None + self.stop_event = None + + +def _gateway_health_config(config: Dict[str, Any]) -> Dict[str, Any]: + mon = (config or {}).get("monitoring") or {} + return mon.get("gateway_health_export") or {} + + +def _otlp_config(config: Dict[str, Any]) -> Dict[str, Any]: + mon = (config or {}).get("monitoring") or {} + export = mon.get("export") or {} + return export.get("otlp") or {} + + +def _enabled(config: Dict[str, Any]) -> bool: + gh = _gateway_health_config(config) + otlp = _otlp_config(config) + return bool(gh.get("enabled") and otlp.get("enabled") and otlp.get("endpoint")) + + +def _require_metrics_sdk(*, auto_install: bool = True, prompt: bool = False) -> Dict[str, Any]: + if auto_install: + try: + from tools.lazy_deps import ensure as _lazy_ensure + _lazy_ensure("export.otlp", prompt=prompt) + except Exception: + pass + try: + from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter + from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter + from opentelemetry.metrics import Observation + from opentelemetry.trace import INVALID_SPAN_ID, INVALID_TRACE_ID, TraceFlags + from opentelemetry._logs import LogRecord + from opentelemetry._logs.severity import SeverityNumber + from opentelemetry.sdk._logs import LoggerProvider + from opentelemetry.sdk._logs.export import BatchLogRecordProcessor + from opentelemetry.sdk.metrics import MeterProvider + from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader + from opentelemetry.sdk.resources import Resource + return { + "OTLPLogExporter": OTLPLogExporter, + "OTLPMetricExporter": OTLPMetricExporter, + "Observation": Observation, + "LogRecord": LogRecord, + "LoggerProvider": LoggerProvider, + "INVALID_SPAN_ID": INVALID_SPAN_ID, + "INVALID_TRACE_ID": INVALID_TRACE_ID, + "TraceFlags": TraceFlags, + "SeverityNumber": SeverityNumber, + "BatchLogRecordProcessor": BatchLogRecordProcessor, + "MeterProvider": MeterProvider, + "PeriodicExportingMetricReader": PeriodicExportingMetricReader, + "Resource": Resource, + } + except Exception as exc: + raise RuntimeError(f"OTLP metrics SDK unavailable: {exc}") from exc + + +def _resolve_headers(headers_env: Optional[Dict[str, str]]) -> Dict[str, str]: + resolved: Dict[str, str] = {} + for header_name, env_name in (headers_env or {}).items(): + val = os.environ.get(str(env_name)) + if val: + resolved[str(header_name)] = val + return resolved + + +def _metric_endpoint(endpoint: str) -> str: + if endpoint.endswith("/v1/traces"): + return endpoint[: -len("/v1/traces")] + "/v1/metrics" + return endpoint + + +def _logs_endpoint(endpoint: str) -> str: + if endpoint.endswith("/v1/traces"): + return endpoint[: -len("/v1/traces")] + "/v1/logs" + if endpoint.endswith("/v1/metrics"): + return endpoint[: -len("/v1/metrics")] + "/v1/logs" + return endpoint + + +def _version() -> str: + try: + from hermes_cli import __version__ + return str(__version__) + except Exception: + return "unknown" + + +def _profile() -> str: + try: + from hermes_cli.profiles import get_active_profile_name + return str(get_active_profile_name() or "default") + except Exception: + return "default" + + +def _install_id(config: Dict[str, Any]) -> str: + try: + from agent.monitoring.policy import ensure_install_id + return str(ensure_install_id(config)) + except Exception: + return "unknown" + + +def _supervision_mode() -> str: + if os.environ.get("INVOCATION_ID"): + return "systemd" + if os.environ.get("S6_CMD_ARG0") or os.environ.get("S6_VERSION"): + return "s6" + if os.environ.get("container") or os.path.exists("/.dockerenv"): + return "container" + if os.environ.get("LAUNCHD_SOCKET"): + return "launchd" + return "manual" + + +def _read_gateway_snapshot(config: Dict[str, Any]): + from agent.monitoring.gateway_health import build_gateway_health_snapshot + try: + from gateway.status import read_runtime_status + runtime = read_runtime_status() or {} + except Exception: + runtime = {} + return build_gateway_health_snapshot( + runtime, + gateway_running=True, + profile=_profile(), + install_id=_install_id(config), + version=_version(), + supervision_mode=_supervision_mode(), + ) + + +def _read_cron_snapshot(): + from agent.monitoring.cron_health import build_cron_health_snapshot + + return build_cron_health_snapshot() + + +def _read_background_work_count() -> int: + """Count live background/subagent work that ``active_agents`` does NOT include. + + ``hermes.gateway.active_agents`` counts foreground turns + in-flight cron + jobs + API runs, but deliberately excludes backgrounded ``delegate_task`` + subagents, ``terminal(background=true)`` processes, kanban workers, and the + runner's own background tasks (they are tracked only for the scale-to-zero + suspend guard, ``_scale_to_zero_has_live_background_work``). Without this + metric a peer churning through delegated subagents shows ``active_agents=0`` + on the fleet dashboard. Best-effort and content-free: a single integer, + no job/task identity. Returns 0 if a source can't be imported. + + Delegation is counted TASK-granular (``active_task_count``): a fan-out batch + of N subagents contributes N, not 1, so the metric reflects real concurrent + subagent load rather than dispatch-unit/pool-slot count. This intentionally + differs from the async pool's capacity accounting (one batch = one slot). + """ + total = 0 + try: + from tools.async_delegation import active_task_count + + total += max(0, int(active_task_count())) + except Exception: + logger.debug("background-work async-delegation count failed", exc_info=True) + try: + from tools.process_registry import process_registry + + total += max(0, int(process_registry.count_running())) + except Exception: + logger.debug("background-work process-registry count failed", exc_info=True) + return total + + +def _read_background_delegations_count() -> int: + """Count live async delegation UNITS (dispatch/pool slots). + + Complements ``_read_background_work_count`` (which is task-granular): this + counts each ``delegate_task`` dispatch as ONE regardless of fan-out width, + matching the async pool's capacity accounting (a batch = one slot). Together + the two metrics let an operator see both slot pressure + (``background_delegations``, alert vs ``max_concurrent_children``) and real + concurrent subagent load (``background_work``). Delegations only — it does + not include ``terminal(background)`` / kanban work, which are already folded + into ``background_work``. Best-effort; 0 if the source can't be imported. + """ + try: + from tools.async_delegation import active_count + + return max(0, int(active_count())) + except Exception: + logger.debug("background-delegations count failed", exc_info=True) + return 0 + + +def _read_runtime_snapshot(config: Dict[str, Any]): + gateway_snapshot = _read_gateway_snapshot(config) + # Background/subagent work — a distinct metric from active_agents (which + # never counts it). Appended to the gateway snapshot so it rides the same + # base resource attributes (service.instance.id etc.). + try: + from agent.monitoring.gateway_health import GatewayMetric + + base = dict(gateway_snapshot.metrics[0].attributes) if gateway_snapshot.metrics else {} + gateway_snapshot.metrics.append( + GatewayMetric( + name="hermes.gateway.background_work", + value=_read_background_work_count(), + attributes=base, + ) + ) + gateway_snapshot.metrics.append( + GatewayMetric( + name="hermes.gateway.background_delegations", + value=_read_background_delegations_count(), + attributes=base, + ) + ) + except Exception as exc: + logger.warning( + "background-work snapshot unavailable; metric not exported (error_type=%s)", + type(exc).__name__, + ) + logger.debug("background-work snapshot traceback", exc_info=True) + try: + cron_snapshot = _read_cron_snapshot() + except Exception as exc: + # Content-free visibility: cron telemetry silently dropping out is a + # release-relevant regression, so surface it at WARNING with only the + # exception *type* name (never the message, which could carry paths or + # other environment detail). exc_info stays on the DEBUG record. + logger.warning( + "cron health snapshot unavailable; cron telemetry not exported (error_type=%s)", + type(exc).__name__, + ) + logger.debug("cron health snapshot traceback", exc_info=True) + return gateway_snapshot + gateway_snapshot.metrics.extend(cron_snapshot.metrics) + return gateway_snapshot + + +def _emit_snapshot_events(config: Dict[str, Any]) -> None: + gh = _gateway_health_config(config) + if not gh.get("diagnostic_events_enabled", True): + return + try: + from agent.monitoring import emitter + snapshot = _read_runtime_snapshot(config) + for event in snapshot.events: + emitter.emit(event) + except Exception: + logger.debug("gateway health snapshot emit failed", exc_info=True) + + +def _start_metric_provider(config: Dict[str, Any], sdk: Dict[str, Any]) -> Any: + gh = _gateway_health_config(config) + if not gh.get("metrics_enabled", True): + return None + otlp = _otlp_config(config) + endpoint = _metric_endpoint(str(otlp.get("endpoint"))) + headers = _resolve_headers(otlp.get("headers_env")) + exporter = sdk["OTLPMetricExporter"](endpoint=endpoint, headers=headers or None) + interval_ms = max(5, int(gh.get("export_interval_seconds", 60))) * 1000 + reader = sdk["PeriodicExportingMetricReader"](exporter, export_interval_millis=interval_ms) + resource_attrs = _runtime_resource_attributes( + config, telemetry_scope="gateway_health" + ) + provider = sdk["MeterProvider"]( + metric_readers=[reader], + resource=sdk["Resource"].create(resource_attrs), + ) + meter = provider.get_meter("hermes.gateway.health") + Observation = sdk["Observation"] + + metric_names = [ + "hermes.gateway.up", + "hermes.gateway.state", + "hermes.gateway.active_agents", + "hermes.gateway.busy", + "hermes.gateway.drainable", + "hermes.gateway.restart_requested", + "hermes.gateway.background_work", + "hermes.gateway.background_delegations", + "hermes.platform.up", + "hermes.platform.degraded", + "hermes.cron.scheduler.heartbeat_age_seconds", + "hermes.cron.scheduler.last_success_age_seconds", + "hermes.cron.scheduler.catch_up_occurrences", + "hermes.cron.jobs.enabled", + "hermes.cron.jobs.running", + "hermes.cron.jobs.overdue", + ] + + def callback(name: str): + def _cb(_options=None): + try: + snapshot = _read_runtime_snapshot(config) + return [Observation(m.value, m.attributes) for m in snapshot.metrics if m.name == name] + except Exception: + logger.debug("gateway metric callback failed", exc_info=True) + return [] + return _cb + + for metric_name in metric_names: + meter.create_observable_gauge(metric_name, callbacks=[callback(metric_name)]) + return provider + + +def _severity_number(sdk: Dict[str, Any], severity: Any) -> Any: + SeverityNumber = sdk["SeverityNumber"] + sev = str(severity or "warning").lower() + if sev in {"critical", "fatal"}: + return SeverityNumber.FATAL + if sev == "error": + return SeverityNumber.ERROR + if sev in {"info", "information"}: + return SeverityNumber.INFO + if sev == "debug": + return SeverityNumber.DEBUG + return SeverityNumber.WARN + + +class GatewayDiagnosticLogStreamer: + """Emitter subscriber that sends gateway diagnostic events as OTLP logs.""" + + def __init__(self, config: Dict[str, Any], sdk: Dict[str, Any]): + otlp = _otlp_config(config) + headers = _resolve_headers(otlp.get("headers_env")) + endpoint = _logs_endpoint(str(otlp.get("endpoint"))) + resource_attrs = _runtime_resource_attributes( + config, telemetry_scope="gateway_diagnostics" + ) + self._provider = sdk["LoggerProvider"](resource=sdk["Resource"].create(resource_attrs)) + self._processor = sdk["BatchLogRecordProcessor"]( + sdk["OTLPLogExporter"](endpoint=endpoint, headers=headers or None) + ) + self._provider.add_log_record_processor(self._processor) + self._logger = self._provider.get_logger(_DEFAULT_DIAGNOSTIC_SCOPE) + self._LogRecord = sdk["LogRecord"] + self._sdk = sdk + self.exported = 0 + + def __call__(self, batch: list[Dict[str, Any]]) -> None: + from agent.monitoring.gateway_health import source_logger_for_export + + for ev in batch: + if ev.get("event") != "gateway_diagnostic": + continue + attrs = _diagnostic_log_attributes(ev) + # Preserve the source-controlled Python logger as the OTel + # instrumentation scope. This adds precise code attribution without + # turning a fluid module layout into a maintained subsystem enum. + # Rendered messages stay out because they may contain arbitrary IDs, + # names, paths, or configured strings. A future, separately gated + # ``diagnostic_detail: redacted_message`` mode may add best-effort + # free text when an observability plane defines that privacy policy. + source_logger = source_logger_for_export(ev.get("source_logger")) + otel_logger = ( + self._provider.get_logger(source_logger) + if source_logger is not None + else self._logger + ) + body = "gateway diagnostic" + record = self._LogRecord( + timestamp=ev.get("ts_ns"), + trace_id=self._sdk["INVALID_TRACE_ID"], + span_id=self._sdk["INVALID_SPAN_ID"], + trace_flags=self._sdk["TraceFlags"].DEFAULT, + severity_text=str(ev.get("severity") or "warning").upper(), + severity_number=_severity_number(self._sdk, ev.get("severity")), + body=_redact_string(body), + attributes=attrs, + ) + otel_logger.emit(record) + self.exported += 1 + + def shutdown(self) -> None: + try: + from agent.monitoring.emitter import get_emitter + get_emitter().unsubscribe(self) + except Exception: + pass + try: + self._processor.force_flush() + self._provider.shutdown() + except Exception: + pass + + +def _start_diagnostic_log_streamer(config: Dict[str, Any], sdk: Dict[str, Any]) -> GatewayDiagnosticLogStreamer: + from agent.monitoring.emitter import get_emitter + streamer = GatewayDiagnosticLogStreamer(config, sdk) + get_emitter().subscribe(streamer) + return streamer + + +def _start_snapshot_thread(config: Dict[str, Any], stop_event: threading.Event) -> threading.Thread: + interval = max(5, int(_gateway_health_config(config).get("logs_export_interval_seconds", 5))) + + def _run() -> None: + while not stop_event.wait(interval): + _emit_snapshot_events(config) + + thread = threading.Thread(target=_run, name="hermes-gateway-health-export", daemon=True) + thread.start() + return thread + + +def _attach_log_handler(config: Dict[str, Any]) -> Any: + gh = _gateway_health_config(config) + if not gh.get("diagnostic_events_enabled", True) or not gh.get("warning_error_events_enabled", True): + return None + from agent.monitoring.gateway_health import GatewayDiagnosticLogHandler + handler = GatewayDiagnosticLogHandler(profile=_profile(), version=_version()) + root = logging.getLogger() + if handler not in root.handlers: + root.addHandler(handler) + return handler + + +def _gateway_health_event(ev: Dict[str, Any]) -> bool: + return ev.get("event") in {"gateway_health", "cron_execution"} + + +def start_gateway_health_export(config: Dict[str, Any]) -> GatewayHealthExportRuntime: + """Start P0 gateway health export if configured. Never raises.""" + if not _enabled(config): + return GatewayHealthExportRuntime(enabled=False, reason="disabled") + gh = _gateway_health_config(config) + runtime = GatewayHealthExportRuntime(enabled=True, reason="enabled") + sdk: Optional[Dict[str, Any]] = None + + if gh.get("metrics_enabled", True) or gh.get("diagnostic_events_enabled", True): + try: + sdk = _require_metrics_sdk(prompt=False) + except Exception: + logger.warning( + "monitoring.gateway_health_export.enabled but OTLP SDK is unavailable; " + "install 'hermes-agent[otlp]'", + exc_info=True, + ) + return GatewayHealthExportRuntime(enabled=False, reason="otlp_unavailable") + + if gh.get("metrics_enabled", True) and sdk is not None: + try: + runtime.metric_provider = _start_metric_provider(config, sdk) + except Exception: + logger.warning("gateway health OTLP metrics failed to start", exc_info=True) + runtime.shutdown() + return GatewayHealthExportRuntime(enabled=False, reason="metrics_start_failed") + + if gh.get("diagnostic_events_enabled", True) and sdk is not None: + try: + from agent.monitoring import otlp_exporter + runtime.streamer = otlp_exporter.start_streaming(config, event_filter=_gateway_health_event) + if runtime.streamer is None: + raise RuntimeError("gateway health span streamer did not start") + runtime.log_streamer = _start_diagnostic_log_streamer(config, sdk) + except Exception: + logger.debug("gateway diagnostic OTLP export failed to start", exc_info=True) + runtime.shutdown() + return GatewayHealthExportRuntime(enabled=False, reason="diagnostics_start_failed") + + try: + runtime.log_handler = _attach_log_handler(config) + except Exception: + logger.debug("gateway diagnostic log handler failed to attach", exc_info=True) + if gh.get("diagnostic_events_enabled", True): + try: + _emit_snapshot_events(config) + runtime.stop_event = threading.Event() + runtime.thread = _start_snapshot_thread(config, runtime.stop_event) + except Exception: + logger.debug("gateway health snapshot thread failed to start", exc_info=True) + return runtime + + +__all__ = [ + "GatewayHealthExportRuntime", + "start_gateway_health_export", +] diff --git a/agent/monitoring/otlp_exporter.py b/agent/monitoring/otlp_exporter.py new file mode 100644 index 000000000000..cde95673ec5f --- /dev/null +++ b/agent/monitoring/otlp_exporter.py @@ -0,0 +1,272 @@ +"""Export monitoring events to an OpenTelemetry Collector over OTLP/HTTP. + +Maps gateway monitoring events to OTel spans and sends them to the endpoint +configured under ``monitoring.export.otlp``. Lets an operator stream Hermes +gateway health into their own observability stack (OTEL Collector, DataDog, +and similar). + +Notes: + * The destination is operator-configured; this module only sends to that + endpoint. No default destination ships. + * ``opentelemetry-sdk`` + ``opentelemetry-exporter-otlp-proto-http`` are an + optional extra (``pip install hermes-agent[otlp]``), imported lazily so the + dependency is only required when OTLP export is actually used. + * ``headers_env`` maps a header name to an environment variable name; values + are read from the environment at export time and never logged or stored. + * The continuous subscriber runs in the emitter's dispatcher thread and is + fail-isolated, so an export error cannot affect the gateway. + +Only monitoring events (gateway_health / gateway_diagnostic) exist on this +plane; the ``event_filter`` seam is kept so future planes sharing the emitter +cannot silently ride along on this exporter. +""" + +from __future__ import annotations + +import logging +import os +from typing import Any, Callable, Dict, List, Optional + +logger = logging.getLogger(__name__) + + +class OTLPUnavailable(RuntimeError): + """Raised when the optional OpenTelemetry SDK isn't installed.""" + + +def _require_sdk(*, auto_install: bool = True, prompt: bool = True): + """Import the OTel SDK, lazily installing it on first use if needed. + + Routes through tools.lazy_deps (feature 'export.otlp') so a missing SDK + triggers the standard venv install flow — same as every other optional + backend — gated by security.allow_lazy_installs and TTY-prompted. Falls back + to OTLPUnavailable (with a manual install hint) when the SDK can't be made + importable (lazy installs disabled, install failed, or auto_install=False). + + ``auto_install``: attempt the lazy install when missing (default True). + ``prompt``: ask before installing when interactive (default True); pass + False from non-interactive contexts like the continuous streamer. + """ + if auto_install: + try: + from tools.lazy_deps import ensure as _lazy_ensure + _lazy_ensure("export.otlp", prompt=prompt) + except ImportError: + pass # lazy_deps unavailable — fall through to the import attempt + except Exception: + # FeatureUnavailable (lazy installs disabled / declined / failed) — + # fall through; the import below raises OTLPUnavailable with the hint. + pass + try: + from opentelemetry.sdk.trace import TracerProvider + from opentelemetry.sdk.trace.export import BatchSpanProcessor + from opentelemetry.sdk.resources import Resource + from opentelemetry.exporter.otlp.proto.http.trace_exporter import ( + OTLPSpanExporter, + ) + from opentelemetry.trace import SpanKind + return { + "TracerProvider": TracerProvider, + "BatchSpanProcessor": BatchSpanProcessor, + "Resource": Resource, + "OTLPSpanExporter": OTLPSpanExporter, + "SpanKind": SpanKind, + } + except Exception as e: # ImportError or partial install + raise OTLPUnavailable( + "OTLP export requires the optional dependency. Install with:\n" + " pip install 'hermes-agent[otlp]'\n" + f"(import error: {e})" + ) + + +def _resolve_headers(headers_env: Optional[Dict[str, str]]) -> Dict[str, str]: + """Resolve {header_name: ENV_VAR_NAME} -> {header_name: value} from env. + + The config stores environment variable names, not secret values; values are + read from the environment here. Missing variables are skipped (and noted at + debug level without the value). + """ + resolved: Dict[str, str] = {} + for header_name, env_name in (headers_env or {}).items(): + val = os.environ.get(str(env_name)) + if val: + resolved[str(header_name)] = val + else: + logger.debug("OTLP header %s: env var %s not set; skipping", + header_name, env_name) + return resolved + + +def _otlp_config(config: Dict[str, Any]) -> Dict[str, Any]: + mon = (config or {}).get("monitoring") or {} + export = mon.get("export") or {} + return export.get("otlp") or {} + + +def build_exporter(config: Dict[str, Any]): + """Construct an OTLP span exporter from config. Raises OTLPUnavailable if no SDK.""" + sdk = _require_sdk() + otlp = _otlp_config(config) + endpoint = otlp.get("endpoint") + if not endpoint: + raise ValueError("monitoring.export.otlp.endpoint is not set") + headers = _resolve_headers(otlp.get("headers_env")) + return sdk["OTLPSpanExporter"](endpoint=endpoint, headers=headers or None) + + +def _resource_attributes(config: Dict[str, Any]) -> Dict[str, str]: + from agent.monitoring.gateway_health import _safe_instance_id + from agent.monitoring.policy import ensure_install_id + + return { + "service.name": "hermes-gateway", + "service.instance.id": _safe_instance_id(ensure_install_id(config)), + "telemetry.scope": "gateway_monitoring", + } + + +def _make_provider(config: Dict[str, Any]): + sdk = _require_sdk() + resource = sdk["Resource"].create(_resource_attributes(config)) + provider = sdk["TracerProvider"](resource=resource) + processor = sdk["BatchSpanProcessor"](build_exporter(config)) + provider.add_span_processor(processor) + return provider, processor + + +# ── event -> span attribute mapping ────────────────────────────────────────── +def _span_attrs(ev: Dict[str, Any]) -> Dict[str, Any]: + """Span attributes for a monitoring event (content-free by construction).""" + kind = ev.get("event") + attrs: Dict[str, Any] = {"hermes.event": kind or "unknown"} + keep_by_kind = { + "gateway_health": ("name", "gateway_state", "old_state", "new_state", + "exit_reason", "restart_requested", "active_agents", + "gateway_busy", "gateway_drainable", "platform_count", + "fatal_platform_count", "version", + "supervision_mode", "pid"), + "gateway_diagnostic": ("name", "subsystem", "error_class", "error_code", + "platform", "old_state", "new_state", + "version", "severity"), + "cron_execution": ("status", "job_key", "source", "duration_ms", + "delivery_outcome", "error_class"), + } + for col in keep_by_kind.get(kind, ()): # type: ignore[arg-type] + v = ev.get(col) + if v is not None: + if isinstance(v, str): + try: + from agent.monitoring.redaction import redact_for_export + v = (redact_for_export(v) or "[redacted]")[:500] + except Exception: + v = "[redaction-unavailable]" + attrs[f"hermes.{col}"] = v + return attrs + + +def export_batch(provider, batch: List[Dict[str, Any]]) -> int: + """Map a batch of events to OTel spans. Returns spans created.""" + tracer = provider.get_tracer("hermes.monitoring") + n = 0 + for ev in batch: + try: + name = f"hermes.{ev.get('event', 'event')}" + span = tracer.start_span(name, attributes=_span_attrs(ev)) + span.end() + n += 1 + except Exception: + logger.debug("OTLP span map failed", exc_info=True) + return n + + +# ── continuous streaming subscriber ───────────────────────────────────────── +class OTLPStreamer: + """A live subscriber that pushes each emitter batch to OTLP as it lands. + + Register with ``emitter.subscribe(streamer)``. Fail-isolated by the emitter. + """ + + def __init__( + self, + config: Dict[str, Any], + *, + event_filter: Optional[Callable[[Dict[str, Any]], bool]] = None, + ): + self._provider, self._processor = _make_provider(config) + self._event_filter = event_filter + self.exported = 0 + + def __call__(self, batch: List[Dict[str, Any]]) -> None: + if self._event_filter is not None: + batch = [ev for ev in batch if self._event_filter(ev)] + if not batch: + return + self.exported += export_batch(self._provider, batch) + + def shutdown(self) -> None: + try: + from agent.monitoring.emitter import get_emitter + get_emitter().unsubscribe(self) + except Exception: + pass + try: + self._processor.force_flush() + self._provider.shutdown() + except Exception: + pass + + +def is_available() -> bool: + """True when the OTel SDK is already importable. Does NOT auto-install — + this is a pure check (e.g. for status display).""" + try: + _require_sdk(auto_install=False) + return True + except OTLPUnavailable: + return False + + +def is_enabled(config: Dict[str, Any]) -> bool: + otlp = _otlp_config(config) + return bool(otlp.get("enabled") and otlp.get("endpoint")) + + +def start_streaming( + config: Dict[str, Any], + *, + event_filter: Optional[Callable[[Dict[str, Any]], bool]] = None, +) -> Optional[OTLPStreamer]: + """If OTLP is enabled, attach a streamer to the singleton emitter. + + ``event_filter`` scopes the exporter to its plane, e.g. gateway-health + export, so enabling one plane cannot silently export unrelated events. + + Non-interactive context (startup): attempts a lazy install with prompt=False + so a configured-but-missing SDK is installed once (gated by + security.allow_lazy_installs), then streams. If it still can't load, logs and + no-ops — never blocks or raises into startup. + """ + if not is_enabled(config): + return None + try: + _require_sdk(prompt=False) + except OTLPUnavailable: + logger.warning("monitoring.export.otlp.enabled but the OTel SDK could not " + "be installed/imported; install 'hermes-agent[otlp]'") + return None + from agent.monitoring.emitter import get_emitter + streamer = OTLPStreamer(config, event_filter=event_filter) + get_emitter().subscribe(streamer) + return streamer + + +__all__ = [ + "OTLPUnavailable", + "OTLPStreamer", + "build_exporter", + "export_batch", + "is_available", + "is_enabled", + "start_streaming", +] diff --git a/agent/monitoring/policy.py b/agent/monitoring/policy.py new file mode 100644 index 000000000000..1a42ce195caa --- /dev/null +++ b/agent/monitoring/policy.py @@ -0,0 +1,57 @@ +"""Install identity for gateway monitoring. + +The install id is a stable, resettable pseudonymous identifier attached to +exported health signals so an operator can tell instances apart in their +collector. It carries no account identity and can be rotated by clearing +``monitoring.install_id`` in config. +""" + +from __future__ import annotations + +import logging +import uuid +from typing import Any, Dict + +logger = logging.getLogger(__name__) + + +def ensure_install_id(config: Dict[str, Any]) -> str: + """Return a stable install id, minting and persisting one when empty. + + The id must survive gateway restarts (it becomes ``service.instance.id`` + on exported signals), so a freshly minted UUID is written back to + config.yaml immediately. The write is fail-open: if persisting fails + (read-only home, managed scope), the ephemeral id is still returned and + a new one is minted next start. + + Clearing ``monitoring.install_id`` (e.g. ``hermes config set + monitoring.install_id ""``) rotates the id on the next gateway start. + """ + mon = config.get("monitoring") if isinstance(config, dict) else None + existing = (mon or {}).get("install_id") if isinstance(mon, dict) else None + if isinstance(existing, str) and existing.strip(): + return existing + + minted = str(uuid.uuid4()) + try: + from hermes_cli.config import load_config, save_config + + fresh = load_config() + if isinstance(fresh, dict): + slot = fresh.setdefault("monitoring", {}) + if isinstance(slot, dict) and not str(slot.get("install_id") or "").strip(): + slot["install_id"] = minted + save_config(fresh) + except Exception: + logger.debug("install_id persist failed; using ephemeral id", exc_info=True) + # Keep the in-memory config consistent for this process either way. + if isinstance(config, dict): + config.setdefault("monitoring", {}) + if isinstance(config["monitoring"], dict): + config["monitoring"]["install_id"] = minted + return minted + + +__all__ = [ + "ensure_install_id", +] diff --git a/agent/monitoring/redaction.py b/agent/monitoring/redaction.py new file mode 100644 index 000000000000..312875901e6b --- /dev/null +++ b/agent/monitoring/redaction.py @@ -0,0 +1,71 @@ +"""Redaction applied to monitoring data before egress. + +One unconditional scrub, no modes, no knobs. Every string that leaves the +process passes through ``redact_for_export``: + + * Secrets first — wraps ``agent/redact.py::redact_sensitive_text(force=True)`` + plus bearer/token-shape patterns, and fails CLOSED: if the redactor cannot + run, the raw string is never emitted. + * PII second — e-mail addresses, phone numbers, and UUID-shaped identifiers + are rewritten to ``[email]`` / ``[phone]`` / ``[id]``. + +There is deliberately no setting to weaken this. The monitoring plane is +content-free by design: rendered log messages are not exported, and bounded +structured strings are still scrubbed as defense-in-depth. This redactor also +remains available for a future, explicitly gated redacted-message detail mode. +""" + +from __future__ import annotations + +import re +from typing import Optional + +# ── secret shapes (belt-and-suspenders on top of agent/redact.py) ─────────── +_BEARER_RE = re.compile(r"\bBearer\s+[A-Za-z0-9._~+\-/]+=*", re.IGNORECASE) +_TOKEN_RE = re.compile( + r"\b(xox[baprs]-[A-Za-z0-9-]+|sk-[A-Za-z0-9_-]{8,}|gh[pousr]_[A-Za-z0-9_]{8,})\b" +) +_SECRET_LITERAL_RE = re.compile(r"\*{3,}") +_BEARER_RESIDUE_RE = re.compile(r"\bBearer\s+\[[^\]]+\]", re.IGNORECASE) + +# ── PII shapes ─────────────────────────────────────────────────────────────── +_EMAIL_RE = re.compile(r"[A-Za-z0-9._%+\-]+@[A-Za-z0-9.\-]+\.[A-Za-z]{2,}") +# E.164-ish and common separators; conservative to avoid nuking code/IDs. +_PHONE_RE = re.compile( + r"(? str: + """Always-on secret redaction. force=True so user config can't disable it.""" + try: + from agent.redact import redact_sensitive_text + out = redact_sensitive_text(text, force=True) + except Exception: + # Fail CLOSED: if the redactor can't run, do not emit the raw string. + return "[redaction-unavailable]" + out = _BEARER_RE.sub("[redacted]", out) + out = _TOKEN_RE.sub("[redacted]", out) + out = _SECRET_LITERAL_RE.sub("[redacted]", out) + out = _BEARER_RESIDUE_RE.sub("[redacted]", out) + return out + + +def redact_for_export(text: Optional[str]) -> Optional[str]: + """Scrub a string for egress: secrets, then PII. Unconditional.""" + if text is None: + return None + out = _secret_redact(str(text)) + out = _EMAIL_RE.sub("[email]", out) + out = _UUID_RE.sub("[id]", out) + out = _PHONE_RE.sub("[phone]", out) + return out + + +__all__ = [ + "redact_for_export", +] diff --git a/agent/nous_rate_guard.py b/agent/nous_rate_guard.py index 415d367ca17b..0234eef2ea23 100644 --- a/agent/nous_rate_guard.py +++ b/agent/nous_rate_guard.py @@ -117,7 +117,7 @@ def record_nous_rate_limit( # Atomic write: write to temp file + rename fd, tmp_path = tempfile.mkstemp(dir=state_dir, suffix=".tmp") try: - with os.fdopen(fd, "w") as f: + with os.fdopen(fd, "w", encoding="utf-8") as f: json.dump(state, f) atomic_replace(tmp_path, path) except Exception: diff --git a/agent/prompt_builder.py b/agent/prompt_builder.py index 18360baf38c2..f4766141a39f 100644 --- a/agent/prompt_builder.py +++ b/agent/prompt_builder.py @@ -197,7 +197,13 @@ SKILLS_GUIDANCE = ( "skill with skill_manage so you can reuse it next time.\n" "When using a skill and finding it outdated, incomplete, or wrong, " "patch it immediately with skill_manage(action='patch') — don't wait to be asked. " - "Skills that aren't maintained become liabilities." + "Skills that aren't maintained become liabilities.\n" + "\n" + "## Skill Safety Rule\n" + "1. **UNAVAILABLE** — If a skill placeholder contains `[SKILL_PRUNED]`, the skill content was lost in compression and is inaccessible.\n" + "2. **RELOAD** — Before performing any action that depends on a skill, re-check its content with `skill_view(name='...')` if it shows `[SKILL_PRUNED]`.\n" + "3. **WAIT** — If a skill is loading or was just pruned, wait for the reload confirmation before proceeding.\n" + "4. **DEDUP** — After reloading a pruned skill, **ignore any remaining `[SKILL_PRUNED]` markers for that same skill** — they are historical artifacts from previous compactions and do not need further action." ) KANBAN_GUIDANCE = ( @@ -566,16 +572,18 @@ def computer_use_guidance(platform_name: Optional[str] = None) -> str: "Background delivery is the DEFAULT and the co-work path, but it is " "the first rung, not the only one. Read each action's structured " "result and climb only when the driver tells you to:\n" - "- `effect: 'confirmed'` + `verified: true` — the driver read the " - "result back. Done.\n" + "- `effect: 'confirmed'` (or `verified: true`) — done, even if an " + "advisory escalation is also present. Never repeat successful input.\n" "- `effect: 'unverifiable'` — the input was delivered but the driver " - "can't confirm it. Re-capture and check the screenshot/tree yourself " - "before deciding it worked.\n" - "- `effect: 'suspected_noop'`, `code: 'background_unavailable'`, or an " - "`escalation.recommended` field — the action did NOT land. Follow " - "`escalation.recommended`:\n" + "can't confirm it. Get fresh state and check it before any retry; an " + "escalation recommendation does not override this rule.\n" + "- `effect: 'suspected_noop'` or a structured refusal such as " + "`code: 'background_unavailable'` — escalation is allowed. Follow " + "the recommended rung when present:\n" " - `'px'` → re-issue addressing the target by `coordinate=[x,y]` " "read off the screenshot instead of `element`.\n" + " - `'page'` → use the exact-bound typed browser page rung below " + "before native foreground escalation. Do not start a legacy page workflow.\n" " - `'foreground'` (or a pixel click still didn't land) → re-issue " "the SAME action with `delivery_mode='foreground'`. This briefly " "raises the window; it needs its own approval and is only appropriate " @@ -585,6 +593,21 @@ def computer_use_guidance(platform_name: Optional[str] = None) -> str: "as a prediction from the app being Electron/Chromium/GTK. Do not " "silently retry the same rung expecting a different result, and do " "not conclude 'cua-driver can't drive this app' — climb the ladder.\n\n" + "## Typed browser page rung\n" + "For `recommended='page'` or supported browser PAGE content, use the namespaced " + "`cua_browser_*` actions: bind with `cua_browser_state` using the exact " + "native `(pid, window_id)`, require `binding_quality='exact'` and " + "`mutation_allowed=true`, select its opaque `tab_id`, then take a " + "fresh semantic snapshot before using a current `ref`. After every " + "typed mutation, call `cua_browser_state` again before another action. " + "Input defaults to trusted; `input_route='dom_event'` is an explicit " + "downgrade, never an automatic retry. Use native capture/input for " + "browser chrome, OS permission prompts, native dialogs, and unsupported " + "targets. Browser setup is a separately approved action; attaching an " + "existing profile is enforced by cua-driver's immutable permission " + "mode: standard requires a certified protected host and fails closed " + "when Hermes has none; explicit Hermes YOLO uses a private unrestricted " + "daemon after the user's launch/session risk acceptance.\n\n" "## Background mode rules\n" "- Do NOT use `raise_window=true` on `focus_app` unless the user " "explicitly asked you to bring a window to front. Input routing to " @@ -889,7 +912,14 @@ PLATFORM_HINTS = { "You're responding through an API server. The rendering layer is unknown — " "assume plain text. No markdown formatting (no asterisks, bullets, headers, " "code fences). Treat this like a conversation, not a document. Keep responses " - "brief and natural." + "brief and natural. " + "File/media delivery: images referenced as MEDIA:/absolute/path tags " + "(.png/.jpg/.jpeg/.gif/.webp/.bmp, up to 5MB) are inlined as base64 data " + "URLs in responses on the chat, completions, and responses endpoints. " + "Non-image files are NOT intercepted anywhere, and the runs endpoint " + "intercepts nothing — a MEDIA: tag there renders as literal text exposing " + "a raw host filesystem path. For those cases, state the plain file path " + "in your response text instead of a MEDIA: tag." ), "webui": ( "You are in the Hermes WebUI, a browser-based chat interface. " diff --git a/agent/prompt_caching.py b/agent/prompt_caching.py index 9a2fdf4ccce6..1a0326c79df3 100644 --- a/agent/prompt_caching.py +++ b/agent/prompt_caching.py @@ -1,9 +1,11 @@ """Anthropic prompt caching strategy. -Single layout: ``system_and_3``. 4 cache_control breakpoints — system -prompt + last 3 non-system messages, all at the same TTL (5m or 1h). -Reduces input token costs by ~75% on multi-turn conversations within a -single session. +The default layout uses 4 cache_control breakpoints: the static system +prefix, the end of the system prompt, and the last 2 non-system messages. +When a static system prefix is unavailable, it falls back to one system +breakpoint plus the last 3 messages. All markers use the same TTL (5m or 1h). +This preserves intra-session caching while allowing new sessions to reuse the +stable system-prompt prefix. Pure functions -- no class state, no AIAgent dependency. """ @@ -81,30 +83,128 @@ def _build_marker(ttl: str) -> Dict[str, str]: return marker +def _apply_system_cache_markers( + message: dict, + cache_marker: dict, + static_system_prefix: str | None, + *, + native_anthropic: bool, +) -> int: + """Mark the static system prefix and full prompt when they can be split. + + The system prompt remains one stored string. Splitting it only in the + outgoing request keeps session persistence and non-Anthropic transports + unchanged while making the stable prefix independently cacheable. + """ + content = message.get("content") + if ( + isinstance(static_system_prefix, str) + and static_system_prefix + and isinstance(content, str) + and content.startswith(static_system_prefix) + ): + suffix = content[len(static_system_prefix):] + if suffix: + message["content"] = [ + { + "type": "text", + "text": static_system_prefix, + "cache_control": cache_marker, + }, + {"type": "text", "text": suffix, "cache_control": cache_marker}, + ] + return 2 + + _apply_cache_marker(message, cache_marker, native_anthropic=native_anthropic) + return 1 + + +def strip_anthropic_cache_control( + api_messages: List[Dict[str, Any]], +) -> List[Dict[str, Any]]: + """Remove ``cache_control`` markers and undo decoration-produced list shapes. + + Used before re-applying decoration after a mid-turn provider failover so + the mutated, undecorated shape (image shrink / ASCII cleanup / etc.) is + preserved while markers match the *new* provider's cache policy (#72626). + + Flattening back to a plain string is restricted to the exact shapes + :func:`apply_anthropic_cache_control` produces from string content — + a single ``{"type": "text"}`` part, or the two-part ``[static, volatile]`` + system split — so the ``""``-join is provably byte-exact. Organic + multi-part text (merged user turns, imported transcripts) and parts + carrying extra keys (``citations`` etc.) keep their structure; only + per-part markers are removed. Marker removal is copy-on-write on the + part dicts: content parts may alias the persistent conversation history + (the per-call copy is shallow), and stripping must never rewrite the + stored transcript. + + Mutates the top-level message dicts of ``api_messages`` in place and + returns the same list. + """ + for msg in api_messages: + if not isinstance(msg, dict): + continue + msg.pop("cache_control", None) + content = msg.get("content") + if not isinstance(content, list): + continue + if any(isinstance(part, dict) and "cache_control" in part for part in content): + content = [ + {k: v for k, v in part.items() if k != "cache_control"} + if isinstance(part, dict) and "cache_control" in part + else part + for part in content + ] + msg["content"] = content + decoration_shape = content and all( + isinstance(part, dict) + and part.get("type", "text") == "text" + and isinstance(part.get("text"), str) + and set(part.keys()) <= {"type", "text"} + for part in content + ) and ( + len(content) == 1 + or (msg.get("role") == "system" and len(content) == 2) + ) + if decoration_shape: + msg["content"] = "".join(part["text"] for part in content) + return api_messages + + def apply_anthropic_cache_control( api_messages: List[Dict[str, Any]], cache_ttl: str = "5m", native_anthropic: bool = False, + static_system_prefix: str | None = None, ) -> List[Dict[str, Any]]: - """Apply system_and_3 caching strategy to messages for Anthropic models. + """Apply Anthropic cache-control markers to API messages. - Places up to 4 cache_control breakpoints: system prompt + last 3 non-system - messages, all at the same TTL. + When ``static_system_prefix`` exactly matches the beginning of a string + system prompt, it receives an early marker and the full system prompt gets + a trailing marker. The remaining two markers target the latest cacheable + non-system messages. Without that prefix, the legacy system-and-3 layout + is retained. Returns: - Deep copy of messages with cache_control breakpoints injected. + Shallow copy of message list with selective deep copies of modified messages. """ - messages = copy.deepcopy(api_messages) - if not messages: - return messages + if not api_messages: + return api_messages + messages = list(api_messages) marker = _build_marker(cache_ttl) breakpoints_used = 0 if messages[0].get("role") == "system": - _apply_cache_marker(messages[0], marker, native_anthropic=native_anthropic) - breakpoints_used += 1 + messages[0] = copy.deepcopy(messages[0]) + breakpoints_used = _apply_system_cache_markers( + messages[0], + marker, + static_system_prefix, + native_anthropic=native_anthropic, + ) remaining = 4 - breakpoints_used non_sys = [ @@ -114,6 +214,7 @@ def apply_anthropic_cache_control( and _can_carry_marker(messages[i], native_anthropic=native_anthropic) ] for idx in non_sys[-remaining:]: + messages[idx] = copy.deepcopy(messages[idx]) _apply_cache_marker(messages[idx], marker, native_anthropic=native_anthropic) return messages diff --git a/agent/proxy_sources/__init__.py b/agent/proxy_sources/__init__.py new file mode 100644 index 000000000000..34af31ca6fb2 --- /dev/null +++ b/agent/proxy_sources/__init__.py @@ -0,0 +1,8 @@ +"""Egress proxy integrations. + +Currently ships an iron-proxy (ironsh/iron-proxy) wrapper that intercepts +outbound traffic from remote terminal sandboxes and swaps proxy tokens +for real upstream credentials at the network edge. + +Design notes live in :mod:`agent.proxy_sources.iron_proxy`. +""" diff --git a/agent/proxy_sources/iron_proxy.py b/agent/proxy_sources/iron_proxy.py new file mode 100644 index 000000000000..277cd0186549 --- /dev/null +++ b/agent/proxy_sources/iron_proxy.py @@ -0,0 +1,2494 @@ +"""iron-proxy (`ironsh/iron-proxy`) integration for credential-injecting egress control. + +Why +--- + +Remote terminal sandboxes (Docker, Modal, SSH) currently see real upstream +API credentials. A prompt-injected agent inside one of these sandboxes can +``cat ~/.config/openrouter/auth.json`` or ``printenv | grep -i key`` and +exfiltrate them. + +iron-proxy is a TLS-intercepting egress firewall (Apache-2.0, Go binary, by +ironsh). It sits between the sandbox and the internet, enforces a default-deny +allowlist on outbound hosts, and *swaps proxy tokens for real credentials* +on the way out. The sandbox only ever holds opaque proxy tokens — leaking +them is useless, since they only work behind the configured trusted proxy +boundary (the CA private key and proxy endpoint integrity are part of that +boundary: if traffic can be redirected to attacker-controlled proxy +infrastructure, the guarantee no longer holds). + +Design summary +-------------- + +* The ``iron-proxy`` binary is auto-installed into ``/bin/iron-proxy`` + on first use. Hermes pins one upstream version (``_IRON_PROXY_VERSION``) + and downloads the matching tar.gz from the official GitHub Releases page, + verifying the SHA-256 against the release's ``checksums.txt``. + +* A long-lived CA at ``/proxy/ca.{crt,key}`` is generated on + first ``hermes egress setup``. Sandboxes trust this CA so iron-proxy can + terminate TLS and rewrite headers. + +* The proxy config lives at ``/proxy/proxy.yaml``. It enumerates + the per-provider allowlists and the ``secrets`` transform that does the + Authorization-header swap. + +* Token mappings (proxy token -> real credential lookup) live alongside the + config. The real credential is **never** written to the config — iron-proxy + reads it from its own environment via ``{type: env, var: NAME}``. When + Bitwarden Secrets Manager is configured, the real value is pulled there + at proxy startup instead. + +* The proxy runs as a managed subprocess (``hermes egress start``), pidfile + at ``/proxy/iron-proxy.pid``. Daemon output (including + per-request records on v0.39) goes to ``/proxy/iron-proxy.log``; + ``audit.log`` is pre-created but reserved for a future pin that supports + ``log.audit_path``. + +* Failures (binary missing, port collision, bad config) emit a one-line + warning and do *not* block agent startup. The Docker backend refuses to + start a sandbox with the proxy enabled-but-down, with a clear error. + +This module is intentionally subprocess-driven rather than depending on any +iron-proxy Python bindings — a single cross-platform binary is easier to +lazy-install than a wheels-with-extension dependency, and we keep maintenance +to a "bump the pinned version" loop. +""" + +from __future__ import annotations + +import hashlib +import ipaddress +import json +import logging +import os +import platform +import shutil +import signal +import stat +import subprocess +import tarfile +import tempfile +import threading +import time +import urllib.error +import urllib.request +from dataclasses import dataclass, field +from pathlib import Path +from typing import Dict, List, Optional, Tuple + +logger = logging.getLogger(__name__) + + +# --------------------------------------------------------------------------- +# Configuration constants +# --------------------------------------------------------------------------- + +# Pinned upstream version. Bump in a follow-up PR — never auto-resolve "latest" +# because upstream YAML schema is allowed to change between releases and we +# want updates to be deliberate. +_IRON_PROXY_VERSION = "0.39.0" + +_IRON_PROXY_RELEASE_BASE = ( + f"https://github.com/ironsh/iron-proxy/releases/download/v{_IRON_PROXY_VERSION}" +) +_IRON_PROXY_CHECKSUM_NAME = "checksums.txt" +# Detached signature for checksums.txt + the signing public key, both shipped on +# the release. Used for optional GPG verification of the release channel +# (maxpetrusenko P1): SHA-256 only protects the archive if checksums.txt itself +# came from an uncompromised channel; verifying its signature closes that gap. +_IRON_PROXY_CHECKSUM_SIG_NAME = "checksums.txt.asc" +_IRON_PROXY_PUBKEY_NAME = "public-key.asc" + +# How long to wait for HTTP downloads and subprocess interactions, in seconds. +_DOWNLOAD_TIMEOUT = 120 # binary is ~16MB +_RUN_TIMEOUT = 30 +_STARTUP_GRACE_SECONDS = 5 + +# Management (operator) API. iron-proxy v0.39 ships an authenticated +# loopback HTTP endpoint (``management.listen`` + ``management.api_key_env``) +# whose ``POST /v1/reload`` re-reads proxy.yaml and atomically swaps the +# transform pipeline in-place — no restart, no dropped connections. We +# always enable it on generated configs: it binds loopback only and every +# request needs the bearer key below. ``hermes egress reload`` is the +# client. +# +# The key is minted at setup time, stored at +# ``/proxy/management.token`` (0600), and injected into the +# daemon's env under this name at start. v0.39 validates at startup that +# the named env var is non-empty when management.listen is set. +_MGMT_API_KEY_ENV = "HERMES_IRON_PROXY_MGMT_KEY" +# The management listener binds loopback at tunnel_port + 2 (tunnel_port +# is CONNECT/MITM, +1 is the plain-HTTP forward listener). +_MGMT_PORT_OFFSET = 2 +_MGMT_RELOAD_TIMEOUT = 15 + +# Default listen ports. HTTPS_PROXY semantics use a single CONNECT tunnel, +# so we expose only the tunnel listener for v1 — no need to put the sandbox +# DNS at the iron-proxy IP. This greatly simplifies wiring. +_DEFAULT_TUNNEL_PORT = 9090 + +# Hosts allowed by default for AI inference traffic. Anything else is 403'd. +_DEFAULT_ALLOWED_HOSTS: Tuple[str, ...] = ( + "openrouter.ai", + "*.openrouter.ai", + "api.openai.com", + "api.anthropic.com", + "generativelanguage.googleapis.com", + "api.x.ai", + "api.mistral.ai", + "api.groq.com", + "api.together.xyz", + "api.deepseek.com", + "inference.nousresearch.com", +) + +# Provider env-var name -> upstream host (or list of hosts) on which the +# Authorization Bearer token should be swapped. +_BEARER_PROVIDERS: Dict[str, Tuple[str, ...]] = { + "OPENROUTER_API_KEY": ("openrouter.ai", "*.openrouter.ai"), + "OPENAI_API_KEY": ("api.openai.com",), + "GROQ_API_KEY": ("api.groq.com",), + "TOGETHER_API_KEY": ("api.together.xyz",), + "DEEPSEEK_API_KEY": ("api.deepseek.com",), + "MISTRAL_API_KEY": ("api.mistral.ai",), + "XAI_API_KEY": ("api.x.ai",), + "NOUS_API_KEY": ("inference.nousresearch.com",), +} + + +# Providers whose API authenticates with a NON-Authorization header. +# iron-proxy v0.39's ``secrets.replace.match_headers`` targets arbitrary +# header names (case-insensitive; confirmed by the iron-proxy author on +# PR #30179 and verified in the pinned v0.39.0 source — ``swapHeaders`` +# + ``parseHeaderMatchers``), so these are first-class swapped providers, +# not "uncovered". +# +# ``aliases`` are interchangeable env-var names for the SAME upstream +# credential (Hermes' auth.py keys Google on both GEMINI_API_KEY and +# GOOGLE_API_KEY). Aliased names MUST collapse into a single mapping: +# every rule carries ``require: true``, and two require-rules on the same +# host reject each other's requests (each rule whose own token isn't +# present returns ActionReject). The sandbox receives the minted token +# under the canonical name AND every alias so SDKs reading either work. +_HEADER_AUTH_PROVIDERS: Dict[str, Dict[str, Tuple[str, ...]]] = { + # Anthropic native: x-api-key. Authorization is also matched so an + # SDK sending the token as a Bearer (OAuth-style) still swaps. + "ANTHROPIC_API_KEY": { + "hosts": ("api.anthropic.com",), + "match_headers": ("x-api-key", "Authorization"), + "aliases": (), + }, + # Azure OpenAI: api-key header (AAD bearer flows use Authorization). + "AZURE_OPENAI_API_KEY": { + "hosts": ( + "*.openai.azure.com", + "*.cognitiveservices.azure.com", + "*.services.ai.azure.com", + ), + "match_headers": ("api-key", "Authorization"), + "aliases": (), + }, + # Google AI Studio (Gemini): x-goog-api-key header; the SDKs that pass + # ``?key=`` as a query param are covered by match_query, which + # scans every query parameter for the token value. + "GEMINI_API_KEY": { + "hosts": ("generativelanguage.googleapis.com",), + "match_headers": ("x-goog-api-key",), + "aliases": ("GOOGLE_API_KEY",), + }, +} + + +# Providers whose env-var names we recognize but whose auth genuinely cannot +# be swapped by a static header/query replacement (SigV4 request signing, +# OAuth tokens minted by an SDK from a service-account file). Presence is +# surfaced as a warning at setup/status time — these are generic cloud creds +# that are usually present for unrelated tooling (terraform, gcloud, aws-cli), +# so they never block the proxy from starting. +# +# NOTE: this list used to include Anthropic / Azure OpenAI / Gemini, with an +# LLM-specific fail-closed tier (``proxy.fail_on_uncovered_providers``). +# Those providers moved to ``_HEADER_AUTH_PROVIDERS`` once we wired +# ``match_headers`` (upstream confirmed support on the pinned v0.39.0), which +# emptied the fail-closed tier — the flag and its refuse-start path were +# deleted rather than kept as a dead toggle. +_NON_BEARER_PROVIDERS: Tuple[str, ...] = ( + # AWS Bedrock / SageMaker: SigV4-signed requests. + "AWS_ACCESS_KEY_ID", + "AWS_SECRET_ACCESS_KEY", + # GCP Vertex AI: OAuth bearer minted by the SDK from a service-account + # file, not a static env key. + "GOOGLE_APPLICATION_CREDENTIALS", +) + + +# Default SSRF-protection deny list applied to the proxy's outbound traffic. +# Mirrors the public docs promise ("cloud metadata IPs are refused by default +# regardless of allowlist"). Tests / dev setups that need loopback can pass +# an explicit override (e.g. [] to disable, or a smaller subset). +_DEFAULT_UPSTREAM_DENY_CIDRS: Tuple[str, ...] = ( + "127.0.0.0/8", # IPv4 loopback + "::1/128", # IPv6 loopback + "169.254.0.0/16", # IPv4 link-local incl. AWS/GCP/Azure IMDS + "fe80::/10", # IPv6 link-local + "10.0.0.0/8", # RFC1918 + "172.16.0.0/12", # RFC1918 + "192.168.0.0/16", # RFC1918 + "fc00::/7", # IPv6 ULA + # IPv4-mapped IPv6 (``::ffff:0:0/96``) covers the dual-stack case + # where an upstream resolves to e.g. ``::ffff:169.254.169.254`` and + # the kernel hands the v4-mapped form to the socket — that would + # otherwise be a clean SSRF bypass to IMDS through the v6 path. + "::ffff:0:0/96", + # RFC6598 / CGNAT — used by AWS VPC for shared services, K8s pod + # networks, many cloud overlays. Not strictly RFC1918 but operators + # universally want it denied for the same reasons. + "100.64.0.0/10", + # RFC2544 benchmark range — rare in practice but occasionally used + # for internal services and never legitimate as an upstream. + "198.18.0.0/15", +) + + +# Min env vars the iron-proxy subprocess actually needs. Everything else +# is stripped — see ``_build_proxy_subprocess_env`` for the rationale. +_PROXY_SUBPROCESS_ENV_ALLOWLIST: Tuple[str, ...] = ( + "PATH", + "HOME", + "TMPDIR", + "TZ", + "LANG", + "LC_ALL", + "LC_CTYPE", + "NO_COLOR", + "SSL_CERT_DIR", + "SSL_CERT_FILE", + "SYSTEMROOT", # Windows + "USERPROFILE", # Windows +) + + +# Env vars that must be stripped from the subprocess env even if they're on +# the allowlist or named in mappings — these would either recurse the proxy +# back through itself or send its traffic through a corporate proxy. +_PROXY_SUBPROCESS_ENV_STRIP: Tuple[str, ...] = ( + "HTTPS_PROXY", "https_proxy", + "HTTP_PROXY", "http_proxy", + "ALL_PROXY", "all_proxy", + "NO_PROXY", "no_proxy", +) + + +# SIGKILL doesn't exist on Windows. We fall back to SIGTERM there, which the +# OS treats as a hard terminate via TerminateProcess() — equivalent semantics. +_KILL_SIGNAL = getattr(signal, "SIGKILL", signal.SIGTERM) + + +# Cached ``iron-proxy --version`` output keyed by binary path. ``get_status`` +# is invoked per Docker-container-create; the version string is constant for +# a given binary so a one-shot subprocess call is plenty. +_VERSION_CACHE: Dict[str, str] = {} + + +# --------------------------------------------------------------------------- +# Public dataclasses +# --------------------------------------------------------------------------- + + +@dataclass +class ProxyStatus: + """Snapshot of the iron-proxy installation + runtime state.""" + + enabled: bool = False + binary_path: Optional[Path] = None + binary_version: Optional[str] = None + config_path: Optional[Path] = None + ca_cert_path: Optional[Path] = None + pid: Optional[int] = None + listening: bool = False + tunnel_port: int = _DEFAULT_TUNNEL_PORT + warnings: List[str] = field(default_factory=list) + + @property + def installed(self) -> bool: + return self.binary_path is not None and self.binary_path.exists() + + @property + def configured(self) -> bool: + return ( + self.config_path is not None + and self.config_path.exists() + and self.ca_cert_path is not None + and self.ca_cert_path.exists() + ) + + +@dataclass +class TokenMapping: + """Map a sandbox-visible proxy token to a real upstream credential lookup. + + ``real_env_name`` is the env-var name iron-proxy reads at egress time. + When Bitwarden is configured as the credential source for the proxy, + iron-proxy's *own* environment is populated from bws on startup — the + sandbox still sees only ``proxy_token``. + + ``match_headers`` names the request headers iron-proxy scans for the + proxy token (default: ``Authorization`` for bearer providers; e.g. + ``("x-api-key", "Authorization")`` for Anthropic native). + + ``alias_env_names`` are additional env-var names the SANDBOX receives + the same proxy token under (e.g. ``GOOGLE_API_KEY`` for + ``GEMINI_API_KEY``). They do not appear in the iron-proxy config — + only one secrets rule is emitted per mapping, keyed on + ``real_env_name``. + """ + + proxy_token: str + real_env_name: str + upstream_hosts: Tuple[str, ...] + match_headers: Tuple[str, ...] = ("Authorization",) + alias_env_names: Tuple[str, ...] = () + + +# --------------------------------------------------------------------------- +# Paths +# --------------------------------------------------------------------------- + + +def _hermes_bin_dir() -> Path: + from hermes_constants import get_hermes_home + + return get_hermes_home() / "bin" + + +def _proxy_state_dir_ro() -> Path: + """Return the proxy state dir without creating it. + + Read-only callers (status probes, pidfile reads, version queries) use + this — there's no reason to materialize ``~/.hermes/proxy/`` just to + check whether a pidfile exists. + """ + from hermes_constants import get_hermes_home + + return get_hermes_home() / "proxy" + + +def _proxy_state_dir() -> Path: + """Return the proxy state dir, creating it with 0o700 if absent. + + Writable callers (CA gen, config write, mappings write, start_proxy) + use this. We force 0o700 — the dir holds the CA signing key, audit + log, and pidfile, so traversal by other local users is undesirable. + The chmod is unconditional so a pre-existing dir with a slack umask + gets tightened on first access. + """ + d = _proxy_state_dir_ro() + d.mkdir(parents=True, exist_ok=True) + try: + d.chmod(0o700) + except OSError: + # On Windows the chmod is a no-op for POSIX modes; on shared + # filesystems we may not own the dir. Don't fail here — the + # individual files still get explicit perms. + pass + return d + + +def _platform_binary_name() -> str: + return "iron-proxy.exe" if platform.system() == "Windows" else "iron-proxy" + + +def _platform_asset_name() -> str: + """Map (uname, arch) → upstream release asset filename. + + iron-proxy ships ``iron-proxy___.tar.gz``. + Windows builds aren't published upstream as of v0.39.0; we raise a + clear error for callers on Windows. + """ + + system = platform.system() + machine = platform.machine().lower() + + if system == "Linux": + arch = "arm64" if machine in ("arm64", "aarch64") else "amd64" + return f"iron-proxy_{_IRON_PROXY_VERSION}_linux_{arch}.tar.gz" + if system == "Darwin": + arch = "arm64" if machine in ("arm64", "aarch64") else "amd64" + return f"iron-proxy_{_IRON_PROXY_VERSION}_darwin_{arch}.tar.gz" + if system == "Windows": + raise RuntimeError( + "iron-proxy does not ship native Windows binaries as of " + f"v{_IRON_PROXY_VERSION}. Run the proxy on a Linux/macOS host, " + "or inside WSL." + ) + + raise RuntimeError( + f"Unsupported platform for iron-proxy auto-install: {system} {machine}" + ) + + +# --------------------------------------------------------------------------- +# Binary discovery + lazy install +# --------------------------------------------------------------------------- + + +def find_iron_proxy(*, install_if_missing: bool = False) -> Optional[Path]: + """Return a path to a usable ``iron-proxy`` binary, or None. + + Resolution order: + 1. ``/bin/iron-proxy`` (our managed copy — preferred) + 2. ``shutil.which("iron-proxy")`` (system PATH) + + When ``install_if_missing`` is True and neither resolves, calls + :func:`install_iron_proxy` to download and verify the pinned version. + """ + + managed = _hermes_bin_dir() / _platform_binary_name() + if managed.exists() and os.access(managed, os.X_OK): + return managed + + system = shutil.which("iron-proxy") + if system: + return Path(system) + + if install_if_missing: + try: + return install_iron_proxy() + except Exception as exc: # noqa: BLE001 — never block startup + logger.warning("iron-proxy auto-install failed: %s", exc) + return None + return None + + +def install_iron_proxy(*, force: bool = False) -> Path: + """Download, verify, and install the pinned ``iron-proxy`` binary. + + Returns the path to the installed executable. Raises on any failure + (network, checksum, extraction). Callers in the auto-install path catch + these; the user-facing ``hermes proxy install`` surface lets them + propagate so the wizard can show a clear error. + """ + + bin_dir = _hermes_bin_dir() + bin_dir.mkdir(parents=True, exist_ok=True) + target = bin_dir / _platform_binary_name() + + if target.exists() and not force: + return target + + asset_name = _platform_asset_name() + asset_url = f"{_IRON_PROXY_RELEASE_BASE}/{asset_name}" + checksum_url = f"{_IRON_PROXY_RELEASE_BASE}/{_IRON_PROXY_CHECKSUM_NAME}" + + with tempfile.TemporaryDirectory(prefix="hermes-iron-proxy-") as tmpdir: + tmp = Path(tmpdir) + archive_path = tmp / asset_name + checksum_path = tmp / _IRON_PROXY_CHECKSUM_NAME + + logger.info("Downloading %s", asset_url) + _http_download(asset_url, archive_path) + _http_download(checksum_url, checksum_path) + + # Defense-in-depth (maxpetrusenko P1): verify the GPG signature of + # checksums.txt before trusting it. The archive download honors ambient + # proxy env (urllib), so a compromised channel could serve a matching + # binary + checksums pair; the detached signature + pinned public key + # close that release-channel tamper gap. Best-effort: if gpg or the + # signature assets aren't available we log and fall back to the SHA-256 + # check alone rather than hard-failing offline installs. + _verify_checksums_signature(tmp, checksum_path) + + expected = _expected_sha256(checksum_path, asset_name) + actual = _sha256_file(archive_path) + if expected.lower() != actual.lower(): + raise RuntimeError( + f"Checksum mismatch for {asset_name}: " + f"expected {expected}, got {actual}" + ) + + with tarfile.open(archive_path, "r:gz") as tf: + member = _pick_tar_member(tf, _platform_binary_name()) + # PEP 706 data filter — strips ownership/mode replay (we set + # chmod explicitly below) AND rejects symlink/hardlink members + # that escape the extraction dir. Required on 3.12+ to silence + # the deprecation warning and on 3.14+ to opt into the + # tarbomb-rejecting default. + try: + tf.extract(member, tmp, filter="data") # noqa: S202 + except TypeError: + # Python < 3.12 — filter kw didn't exist yet; the + # _pick_tar_member sanitization already rejects path + # traversal so this is acceptable. + tf.extract(member, tmp) # noqa: S202 + extracted = tmp / member.name + + # Stage into the final directory then atomically rename so the new + # binary is never visible half-written. + fd, staged = tempfile.mkstemp(dir=str(bin_dir), prefix=".iron-proxy_") + os.close(fd) + shutil.copy2(extracted, staged) + os.chmod( + staged, + stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR + | stat.S_IRGRP | stat.S_IXGRP + | stat.S_IROTH | stat.S_IXOTH, + ) + os.replace(staged, target) + + # Invalidate the version cache so a freshly-installed binary + # re-probes ``--version`` on the next ``get_status()`` call instead + # of returning the pre-upgrade string. Long-lived processes that + # bump the pinned version via ``force=True`` need this. + _VERSION_CACHE.pop(str(target), None) + + logger.info("Installed iron-proxy %s at %s", _IRON_PROXY_VERSION, target) + return target + + +def _http_download(url: str, dest: Path) -> None: + req = urllib.request.Request(url, headers={"User-Agent": "hermes-agent"}) + try: + with urllib.request.urlopen(req, timeout=_DOWNLOAD_TIMEOUT) as resp: # noqa: S310 + with open(dest, "wb") as f: + shutil.copyfileobj(resp, f) + except urllib.error.URLError as exc: + raise RuntimeError(f"Failed to download {url}: {exc}") from exc + + +def _verify_checksums_signature(tmp: Path, checksum_path: Path) -> bool: + """Best-effort GPG verification of ``checksums.txt`` (maxpetrusenko P1). + + Downloads the detached signature (``checksums.txt.asc``) and the release + signing key (``public-key.asc``), imports the key into an ephemeral + keyring, and verifies the signature over ``checksum_path``. + + Returns True when the signature is verified. Returns False (with a warning) + when verification is unavailable — ``gpg`` not installed, or the signature / + public-key assets are missing from the release. Raises RuntimeError ONLY + when verification actively FAILS (a present-but-bad signature), which is a + tamper signal we must not ignore. + + Rationale for graceful degradation on "unavailable": the SHA-256 check + against ``checksums.txt`` remains in force regardless, and many install + hosts (CI, minimal containers) won't have gpg. We harden when we can and + never make gpg a hard dependency for a working install. + """ + gpg = shutil.which("gpg") + if not gpg: + logger.warning( + "gpg not found on PATH — skipping iron-proxy release-signature " + "verification (SHA-256 checksum check still enforced)." + ) + return False + + sig_url = f"{_IRON_PROXY_RELEASE_BASE}/{_IRON_PROXY_CHECKSUM_SIG_NAME}" + pubkey_url = f"{_IRON_PROXY_RELEASE_BASE}/{_IRON_PROXY_PUBKEY_NAME}" + sig_path = tmp / _IRON_PROXY_CHECKSUM_SIG_NAME + pubkey_path = tmp / _IRON_PROXY_PUBKEY_NAME + + try: + _http_download(sig_url, sig_path) + _http_download(pubkey_url, pubkey_path) + except RuntimeError as exc: + logger.warning( + "iron-proxy release signature assets unavailable (%s) — skipping " + "GPG verification (SHA-256 checksum check still enforced).", exc, + ) + return False + + # Ephemeral keyring so we never touch the user's real GPG home. + gnupg_home = tmp / "gnupg" + gnupg_home.mkdir(mode=0o700, exist_ok=True) + base_cmd = [gpg, "--homedir", str(gnupg_home), "--batch", "--no-tty"] + + imp = subprocess.run( # noqa: S603 — gpg path from trusted PATH lookup + [*base_cmd, "--import", str(pubkey_path)], + capture_output=True, timeout=60, + ) + if imp.returncode != 0: + logger.warning( + "Could not import iron-proxy signing key — skipping GPG " + "verification (SHA-256 still enforced): %s", + imp.stderr.decode("utf-8", "replace")[:200], + ) + return False + + verify = subprocess.run( # noqa: S603 + [*base_cmd, "--verify", str(sig_path), str(checksum_path)], + capture_output=True, timeout=60, + ) + if verify.returncode != 0: + # A present signature that does NOT verify is a tamper signal — fail hard. + raise RuntimeError( + "iron-proxy checksums.txt failed GPG signature verification — " + "refusing to install (possible release-channel tampering). " + f"gpg: {verify.stderr.decode('utf-8', 'replace')[:300]}" + ) + logger.info("Verified iron-proxy checksums.txt GPG signature.") + return True + + +def _expected_sha256(checksum_file: Path, asset_name: str) -> str: + """Parse the standard ``sha256sum`` output: `` ``.""" + + text = checksum_file.read_text(encoding="utf-8", errors="replace") + for line in text.splitlines(): + parts = line.strip().split() + if len(parts) >= 2 and parts[-1] == asset_name: + return parts[0] + raise RuntimeError( + f"No checksum entry for {asset_name} in {checksum_file.name}" + ) + + +def _sha256_file(path: Path) -> str: + h = hashlib.sha256() + with open(path, "rb") as f: + for chunk in iter(lambda: f.read(65536), b""): + h.update(chunk) + return h.hexdigest() + + +def _pick_tar_member(tf: tarfile.TarFile, binary_name: str) -> tarfile.TarInfo: + """Find the binary inside the upstream tar. + + iron-proxy's archive is typically flat (binary at root) but we tolerate + a top-level directory. Members must be regular files with a leaf name + matching ``binary_name``, no absolute paths, and no ``..`` traversal. + """ + + candidates: List[tarfile.TarInfo] = [] + for member in tf.getmembers(): + if not member.isfile(): + continue + if member.name.startswith("/") or ".." in Path(member.name).parts: + continue + if Path(member.name).name == binary_name: + candidates.append(member) + if not candidates: + raise RuntimeError( + f"Could not find {binary_name} inside downloaded archive " + f"(members: {[m.name for m in tf.getmembers()[:5]]}...)" + ) + candidates.sort(key=lambda m: len(m.name)) + return candidates[0] + + +def iron_proxy_version(binary: Path) -> str: + """Return ``iron-proxy --version`` output, stripped. Empty on failure. + + Cached by binary path: ``get_status`` is called per Docker container + create, but the version string is constant for a given binary. A + single subprocess invocation is plenty. + """ + + key = str(binary) + cached = _VERSION_CACHE.get(key) + if cached is not None: + return cached + + try: + # Build a minimal env: only PATH, HOME, and locale vars. + # The version probe is a one-shot subprocess — forwarding + # the full host env (OPENAI_API_KEY, ANTHROPIC_API_KEY, etc.) + # to a PATH-resolved or unverified binary is an unnecessary + # credential leak. Reuse the same allowlist the daemon + # subprocess uses (see _build_proxy_subprocess_env). + minimal_env: Dict[str, str] = {} + parent = os.environ + for name in _PROXY_SUBPROCESS_ENV_ALLOWLIST: + if name in parent: + minimal_env[name] = parent[name] + # The S603 warning is legitimate for the PATH-fallback case + # (find_iron_proxy → shutil.which), but --version with a + # scrubbed env is safe regardless of binary provenance. + res = subprocess.run( # noqa: S603 + [str(binary), "--version"], + capture_output=True, + text=True, encoding="utf-8", errors="replace", + timeout=_RUN_TIMEOUT, + env=minimal_env, + ) + except (OSError, subprocess.TimeoutExpired): + return "" + out = (res.stdout or res.stderr or "").strip() + # Don't cache empty output — that would poison ``hermes egress + # status`` for the lifetime of the process if the first probe hit a + # corrupt binary or a flag-rename in a newer upstream. Re-probe on + # the next call instead. + if out: + _VERSION_CACHE[key] = out + return out + + +# --------------------------------------------------------------------------- +# CA cert generation +# --------------------------------------------------------------------------- + + +def ensure_ca_cert(*, force: bool = False) -> Tuple[Path, Path]: + """Generate (or return existing) iron-proxy CA cert + key. + + Uses the host's ``openssl`` binary. We don't try to bind to a Python + crypto library — openssl is universally available on the platforms we + support, and it sidesteps cryptography-package licensing/distribution + surface. + """ + + state = _proxy_state_dir() + ca_crt = state / "ca.crt" + ca_key = state / "ca.key" + + if ca_crt.exists() and ca_key.exists() and not force: + return ca_crt, ca_key + + if shutil.which("openssl") is None: + raise RuntimeError( + "openssl not found on PATH. Install OpenSSL (apt: `openssl`, " + "brew: `openssl`) to generate the iron-proxy CA cert." + ) + + # 10-year cert. iron-proxy mints short-lived leaf certs from this CA, + # so the CA itself only rotates when the user explicitly forces it. + with tempfile.TemporaryDirectory(prefix="hermes-proxy-ca-") as tmpdir: + tmp = Path(tmpdir) + tmp_key = tmp / "ca.key" + tmp_crt = tmp / "ca.crt" + + subprocess.run( # noqa: S603 — openssl path is trusted PATH lookup + ["openssl", "genrsa", "-out", str(tmp_key), "4096"], + check=True, + capture_output=True, + timeout=60, + ) + subprocess.run( # noqa: S603 + [ + "openssl", "req", "-x509", "-new", "-nodes", + "-key", str(tmp_key), + "-sha256", "-days", "3650", + "-subj", "/CN=hermes iron-proxy CA", + "-addext", "basicConstraints=critical,CA:TRUE", + "-addext", "keyUsage=critical,keyCertSign", + "-out", str(tmp_crt), + ], + check=True, + capture_output=True, + timeout=60, + ) + + # Move into place with private permissions. CRITICAL: the key + # has to be created with 0o600 from the very first byte — a + # ``shutil.copy2`` followed by ``os.chmod`` leaves a TOCTOU window + # where the private key is world-readable on multi-user hosts. + key_bytes = tmp_key.read_bytes() + crt_bytes = tmp_crt.read_bytes() + + # Stage with explicit 0o600, then atomically rename into place. + # O_NOFOLLOW guards against a symlink at ca_key (defence-in-depth + # — the state dir is 0o700-owned but a malicious local user with + # the same uid could pre-create one). + key_staged = ca_key.with_suffix(ca_key.suffix + ".staged") + open_flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC + # O_NOFOLLOW exists on POSIX; on Windows we just rely on the + # default semantics. + if hasattr(os, "O_NOFOLLOW"): + open_flags |= os.O_NOFOLLOW + # Best-effort: pre-unlink any existing staged file so the open + # with O_CREAT is always against a fresh inode. + try: + key_staged.unlink() + except FileNotFoundError: + pass + fd = os.open(str(key_staged), open_flags, 0o600) + try: + with os.fdopen(fd, "wb") as f: + f.write(key_bytes) + except Exception: + try: + os.close(fd) + except OSError: + pass + raise + os.replace(key_staged, ca_key) + + # Cert is public — 0o644 is fine and matches typical PEM layout. + ca_crt.write_bytes(crt_bytes) + os.chmod(ca_crt, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH) + + logger.info("Generated iron-proxy CA at %s", ca_crt) + return ca_crt, ca_key + + +# --------------------------------------------------------------------------- +# Proxy config + token mapping generation +# --------------------------------------------------------------------------- + + +def mint_proxy_token(prefix: str = "hermes-proxy") -> str: + """Mint a fresh opaque token to hand to the sandbox. + + The token has no internal structure beyond a recognizable prefix — + iron-proxy matches on exact equality. We use a 128-bit random suffix + (32 hex chars from a SHA-256 of 32 bytes of os.urandom). At that + entropy the birthday-bound collision probability is below 2^-64 for + up to 2^32 tokens, which is plenty for a proxy-scoped namespace. + """ + + return f"{prefix}-{hashlib.sha256(os.urandom(32)).hexdigest()[:32]}" + + +def _management_token_path() -> Path: + return _proxy_state_dir() / "management.token" + + +def ensure_management_token(*, force: bool = False) -> str: + """Return the management-API bearer key, minting it on first call. + + Stored at ``/proxy/management.token`` with 0600 perms. + The daemon receives it via the ``HERMES_IRON_PROXY_MGMT_KEY`` env var + (named in the generated config's ``management.api_key_env``); + ``hermes egress reload`` reads the same file to authenticate. + """ + + p = _management_token_path() + if not force and p.exists(): + try: + existing = p.read_text(encoding="utf-8").strip() + if existing: + return existing + except OSError: + pass + token = mint_proxy_token(prefix="hermes-mgmt") + fd = os.open( + str(p), + os.O_WRONLY | os.O_CREAT | os.O_TRUNC | getattr(os, "O_NOFOLLOW", 0), + 0o600, + ) + try: + os.fchmod(fd, 0o600) + except (OSError, AttributeError): + pass + try: + os.write(fd, token.encode("utf-8")) + finally: + os.close(fd) + return token + + +def _read_management_token() -> Optional[str]: + p = _proxy_state_dir_ro() / "management.token" + try: + token = p.read_text(encoding="utf-8").strip() + except OSError: + return None + return token or None + + +def _read_management_listen_from_config( + config_path: Optional[Path] = None, +) -> Optional[Tuple[str, int]]: + """Return ``(host, port)`` of the management listener, if configured.""" + + cfg = config_path or (_proxy_state_dir_ro() / "proxy.yaml") + if not cfg.exists(): + return None + try: + import yaml + except ImportError: + return None + try: + data = yaml.safe_load(cfg.read_text(encoding="utf-8")) + except (OSError, yaml.YAMLError): + return None + listen = ((data or {}).get("management") or {}).get("listen") or "" + if not isinstance(listen, str) or ":" not in listen: + return None + host, _, port_s = listen.rpartition(":") + try: + port = int(port_s) + except ValueError: + return None + return (host or "127.0.0.1", port) + + +def reload_proxy() -> bool: + """Hot-reload the running daemon's ruleset via the management API. + + POSTs to ``/v1/reload`` on the loopback management listener; the daemon + re-reads proxy.yaml and atomically swaps the transform pipeline — + validation failures leave the running config untouched (HTTP 422). + + Returns True on a successful reload. Raises ``RuntimeError`` with an + actionable message when the daemon isn't running, the config predates + management-API support (no ``management`` block → restart required), + or the reload is rejected. + """ + + pid = _read_pid() + if not pid or not _pid_alive(pid): + raise RuntimeError( + "iron-proxy is not running — nothing to reload. " + "Run `hermes egress start`." + ) + mgmt = _read_management_listen_from_config() + if mgmt is None: + raise RuntimeError( + "The generated proxy.yaml has no management listener (written " + "before reload support). Re-run `hermes egress setup` and use " + "`hermes egress restart` this one time." + ) + token = _read_management_token() + if not token: + raise RuntimeError( + "management.token is missing — re-run `hermes egress setup`, " + "then `hermes egress restart`." + ) + + import urllib.error + import urllib.request + + host, port = mgmt + req = urllib.request.Request( + f"http://{host}:{port}/v1/reload", + method="POST", + headers={"Authorization": f"Bearer {token}"}, + data=b"", + ) + try: + with urllib.request.urlopen(req, timeout=_MGMT_RELOAD_TIMEOUT) as resp: + if resp.status == 200: + return True + raise RuntimeError( + f"management API returned unexpected status {resp.status}" + ) + except urllib.error.HTTPError as exc: + body = "" + try: + body = exc.read().decode("utf-8", errors="replace")[:500] + except OSError: + pass + if exc.code == 422: + raise RuntimeError( + f"iron-proxy rejected the new config (validation failed; " + f"the running ruleset is unchanged): {body}" + ) from exc + if exc.code == 401: + raise RuntimeError( + "management API rejected our key (401). The running " + "daemon was started with a different management.token — " + "run `hermes egress restart`." + ) from exc + raise RuntimeError( + f"management reload failed (HTTP {exc.code}): {body}" + ) from exc + except (urllib.error.URLError, OSError) as exc: + # A daemon started from a pre-management config is alive but has + # no listener on the management port. + raise RuntimeError( + f"could not reach the management API at {host}:{port} ({exc}). " + "If the daemon was started before reload support, run " + "`hermes egress restart` once." + ) from exc + + +def _default_http_listen(tunnel_port: int) -> List[str]: + """Build the single host:port bind the proxy should listen on. + + iron-proxy v0.39 supports exactly ONE ``proxy.http_listen`` bind per + daemon process, so this returns a one-element list and the choice of + host matters: + + * **Linux:** bind the docker bridge gateway (``172.17.0.1`` by + default). Sandboxes reach the proxy via + ``host.docker.internal:host-gateway``, which Docker resolves to + exactly this bridge gateway IP on Linux — a loopback-only bind is + unreachable from inside containers there. The bridge IP is still + host-local (it's an address on the host's ``docker0`` interface), + so host-side tooling and the status probe can reach it too. When + no docker bridge is detected (docker not installed / not started), + fall back to loopback — there are no sandboxes to serve in that + state, and the operator gets a warning. + * **macOS / Windows Docker Desktop:** ``host.docker.internal`` + resolves via VPNkit to the host, so a loopback bind is reachable + from containers and is the least-exposed choice. + + We never bind ``0.0.0.0`` — that would expose the proxy (and, with a + leaked sandbox token, the user's API quota) to anyone on the local + network. The bridge-gateway bind is reachable by other containers + on the default bridge network, which is unavoidable given v0.39's + single-bind limit; requests still require a minted proxy token and + an allowlisted upstream. + """ + + if platform.system() == "Linux": + bridge_ip = _detect_docker_bridge_ip() + if bridge_ip and bridge_ip != "127.0.0.1": + return [f"{bridge_ip}:{tunnel_port}"] + logger.warning( + "No docker bridge (docker0) detected — binding iron-proxy to " + "loopback only. Docker sandboxes will NOT be able to reach " + "the proxy until it is restarted with docker running." + ) + return [f"127.0.0.1:{tunnel_port}"] + + +def _detect_docker_bridge_ip() -> Optional[str]: + """Return the docker0 bridge IPv4, if present, else None. + + Best-effort: we try ``ip -4 addr show docker0`` first. Anything that + fails, doesn't parse as a strict IPv4, or parses as an address we + must NOT bind to (unspecified, loopback, multicast, reserved, public) + returns None — callers handle that as "no bridge bind". + + SECURITY: a hostile ``ip`` shim earlier on the operator's PATH used + to be able to inject ``0.0.0.0`` here and re-open INADDR_ANY binding + that the rest of the bind-policy work explicitly closed. We + validate via :mod:`ipaddress` and reject anything that isn't + plausibly a docker bridge IP (private + non-special). + """ + + candidate: Optional[str] = None + try: + res = subprocess.run( # noqa: S603 — ip is a system binary + ["ip", "-4", "-o", "addr", "show", "docker0"], + capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=2, + ) + if res.returncode == 0: + for line in res.stdout.splitlines(): + parts = line.split() + # Expected: ": docker0 inet 172.17.0.1/16 ..." + for i, tok in enumerate(parts): + if tok == "inet" and i + 1 < len(parts): + candidate = parts[i + 1].split("/")[0] + break + if candidate is not None: + break + except (OSError, subprocess.TimeoutExpired): + return None + + if not candidate: + return None + + # Stdlib validation: rejects garbage strings AND special-purpose + # addresses that must not be used as a bind target. + try: + addr = ipaddress.IPv4Address(candidate) + except (ipaddress.AddressValueError, ValueError): + return None + # Reject: + # - 0.0.0.0 / INADDR_ANY (is_unspecified) + # - 127.0.0.0/8 (is_loopback — already in deny list) + # - 224.0.0.0/4 (is_multicast) + # - 240.0.0.0/4 (is_reserved) + # - 169.254.0.0/16 (is_link_local — IMDS range, never docker0) + # - global / public IPs (is_global — docker0 must be RFC1918) + if ( + addr.is_unspecified + or addr.is_loopback + or addr.is_multicast + or addr.is_reserved + or addr.is_link_local + or addr.is_global + ): + logger.warning( + "Refusing suspicious docker bridge IP %s reported by `ip`; " + "skipping bridge bind.", candidate, + ) + return None + + return str(addr) + + +def build_proxy_config( + *, + mappings: List[TokenMapping], + ca_cert: Path, + ca_key: Path, + tunnel_port: int = _DEFAULT_TUNNEL_PORT, + audit_log: Optional[Path] = None, + allowed_hosts: Optional[List[str]] = None, + upstream_deny_cidrs: Optional[List[str]] = None, + http_listen: Optional[List[str]] = None, +) -> Dict: + """Build the iron-proxy YAML config (as a dict) for a given mapping set. + + The dict is YAML-serializable via ``yaml.safe_dump``. iron-proxy reads + real secrets from its OWN environment via ``source: {type: env, var: ...}``; + the sandbox never sees them. + + Bind policy: the sandbox-facing listeners (``tunnel_listen`` on + ``tunnel_port``, plain-HTTP ``http_listen`` on ``tunnel_port + 1``) + bind the docker bridge gateway on Linux (``172.17.0.1`` or whatever + ``docker0`` resolves to — that's what ``host.docker.internal`` + resolves to inside containers there) and loopback on macOS / Windows + Docker Desktop. We do NOT bind ``0.0.0.0`` — a LAN peer with a + leaked sandbox token could otherwise spend the operator's API quota + against any allowlisted upstream. + + SSRF policy: ``upstream_deny_cidrs`` defaults to a conservative deny + list covering loopback, link-local (incl. AWS/GCP/Azure IMDS at + 169.254.169.254), and RFC1918. Pass an explicit ``[]`` to opt out of + the deny list entirely (only sensible in hermetic tests). + + Schema mirrors the official iron-proxy schema as of v0.39.0. Notable + points: + + * The ``dns`` section is required by the binary even when we only use the + CONNECT tunnel. We point it at loopback so it doesn't conflict with + anything else and disable the listener. + * The ``proxy.tunnel_listen`` is what sandboxes hit via ``HTTPS_PROXY``. + ``http_listen`` / ``https_listen`` are present (loopback only) so the + proxy boots; sandboxes never route directly to them. + * ``allowlist`` transform takes ``domains:`` and ``cidrs:``, not ``hosts:``. + * ``secrets`` transform takes ``secrets:`` (plural), each with a + ``source``, a ``replace.proxy_value`` (the sandbox-visible token), and + a list of ``rules`` saying which hosts the swap should fire on. + """ + + hosts: List[str] = list(allowed_hosts or _DEFAULT_ALLOWED_HOSTS) + for m in mappings: + for h in m.upstream_hosts: + if h not in hosts: + hosts.append(h) + + secrets_rules = [] + for m in mappings: + match_headers = list(m.match_headers or ("Authorization",)) + secrets_rules.append({ + "source": {"type": "env", "var": m.real_env_name}, + "replace": { + "proxy_value": m.proxy_token, + # Per-provider header set: bearer providers match only + # Authorization; header-auth providers (Anthropic native + # x-api-key, Azure api-key, Gemini x-goog-api-key) match + # their native header (+ Authorization where the provider + # also accepts bearer flows). v0.39 matches header names + # case-insensitively — see parseHeaderMatchers upstream. + "match_headers": match_headers, + # The token is also accepted as a query param — v0.39 scans + # every query parameter for the token value, which covers + # SDKs that pass ``?key=`` (Gemini) as well as + # bearer-in-query styles. Body matching is off — we + # don't want body inspection forced for every request. + "match_query": True, + "match_body": False, + # Fail closed (maxpetrusenko P1): when a request reaches an + # allowlisted upstream WITHOUT the proxy token present in a + # matched location, reject it instead of forwarding as-is. + # Without this, a real provider key that a sandbox process + # sent directly (not via the minted token) would still pass + # the proxy boundary to the allowed host. With require=true, + # iron-proxy returns ActionReject when no token swap fired + # (v0.39 secrets transform: replaceConfig.Require, enforced in + # TransformRequest — verified present in the pinned version). + "require": True, + }, + "rules": [{"host": h} for h in m.upstream_hosts], + }) + + # SSRF protection: default-deny cloud metadata + loopback + RFC1918. + # Callers can pass [] to opt out entirely (hermetic tests need this for + # talking to a loopback upstream). None means "use the default". + deny_cidrs: List[str] + if upstream_deny_cidrs is None: + deny_cidrs = list(_DEFAULT_UPSTREAM_DENY_CIDRS) + else: + deny_cidrs = list(upstream_deny_cidrs) + + # Listen addresses. iron-proxy v0.39 takes a single string per + # listener field — there is no plural ``http_listens`` form, despite + # earlier drafts of this module claiming v0.39 accepts both. An + # empirical strings(1) audit + a live "start the binary and observe + # the YAML unmarshal error" confirms the singular form is the only + # one the binary accepts. + # + # LISTENER ROLES (verified live against the v0.39 binary): + # * ``tunnel_listen`` is the CONNECT + MITM listener. HTTPS through + # ``HTTPS_PROXY`` issues CONNECT — this is the listener sandboxes + # must reach. A CONNECT sent to ``http_listen`` is NOT terminated: + # v0.39 forwards it upstream as a regular request and the upstream + # responds 400. + # * ``http_listen`` is the absolute-form plain-HTTP forward listener + # (``HTTP_PROXY`` for ``http://`` URLs). Transforms fire here too. + # Both get the sandbox-facing bind host: tunnel on ``tunnel_port``, + # plain HTTP on ``tunnel_port + 1``. + # + # The bind host comes from _default_http_listen: the docker bridge + # gateway on Linux (containers reach the proxy via + # host.docker.internal, which maps to the bridge gateway there — + # loopback would be unreachable from inside sandboxes) and loopback + # on macOS/Windows Docker Desktop (where host.docker.internal routes + # to the host via VPNkit). + listens = list(http_listen) if http_listen else _default_http_listen(tunnel_port) + primary_listen = listens[0] if listens else f"127.0.0.1:{tunnel_port}" + bind_host = primary_listen.rsplit(":", 1)[0] or "127.0.0.1" + plain_http_listen = f"{bind_host}:{tunnel_port + 1}" + + log_block: Dict = {"level": "info"} + # NOTE: ``log.audit_path`` is NOT a field in iron-proxy v0.39's + # ``config.Log`` struct — the binary rejects it with + # ``field audit_path not found in type config.Log``. Per-request + # audit records are written to the same log destination as + # everything else at this binary version; the operator-facing + # ``audit.log`` file we pre-create is still useful as a sentinel + # for monitoring (logrotate target, downstream tail watchers) but + # the daemon does not write to it directly. The kwarg is kept so + # we're forward-compatible with a future v0.40+ that adds the + # field; if you upgrade _IRON_PROXY_VERSION and the upstream gains + # ``log.audit_path``, re-enable the line below. + # if audit_log is not None: + # log_block["audit_path"] = str(audit_log) + _ = audit_log # consumed by ensure_audit_log() / docs only on v0.39 + + return { + # DNS section is required by the binary's config parser, but we run + # in tunnel-only mode so the DNS listener never binds an exposed port. + # Sandboxes reach the proxy via HTTPS_PROXY/CONNECT, not via DNS + # redirection. + "dns": { + "listen": "127.0.0.1:0", # ephemeral loopback — effectively disabled + "proxy_ip": "127.0.0.1", + }, + "proxy": { + # tunnel_listen is the CONNECT/MITM listener — what sandboxes + # hit via `HTTPS_PROXY=http://host:tunnel_port` for HTTPS + # upstreams (curl/requests/node issue CONNECT through it). + # http_listen handles absolute-form plain-HTTP forwards + # (`HTTP_PROXY` for http:// URLs) on tunnel_port+1. Both + # bind the docker bridge gateway on Linux / loopback on + # Docker Desktop — NEVER 0.0.0.0. LAN peers with a leaked + # sandbox token would otherwise be able to spend the + # operator's API quota against any allowlisted upstream. + "tunnel_listen": primary_listen, + "http_listen": plain_http_listen, + # The HTTPS-listener (direct TLS termination, no CONNECT) + # gets a loopback ephemeral port — we don't expose it. + "https_listen": "127.0.0.1:0", + "max_request_body_bytes": 16 * 1024 * 1024, + "max_response_body_bytes": 0, + "upstream_response_header_timeout": "120s", + # SSRF protection: deny outbound to cloud metadata + loopback by + # default. An empty list opts out entirely. + "upstream_deny_cidrs": deny_cidrs, + }, + # iron-proxy v0.39 starts a Prometheus-style metrics server by + # default on ``:9090`` — which is the SAME port as our default + # ``tunnel_port: 9090``, causing a guaranteed bind collision on + # startup. Pin the metrics listener to an ephemeral loopback + # port (``127.0.0.1:0``) so the metrics binding can't collide + # with the proxy listener regardless of what tunnel_port the + # operator chose. NOTE: ``:0`` means the kernel picks a fresh + # random port each start and nothing records it — metrics are + # effectively disabled/undiscoverable at this pin. If we want + # scrapable metrics later, allocate a fixed port and surface it + # in ``ProxyStatus`` / ``hermes egress status``. + "metrics": { + "listen": "127.0.0.1:0", + }, + # Operator-facing management API — loopback only, bearer-key + # authenticated (key read from the env var named below; injected + # by ``start_proxy`` from ``management.token``). ``POST /v1/reload`` + # re-reads THIS config file and atomically swaps the transform + # pipeline — `hermes egress reload` applies allowlist/token/mapping + # changes without a restart. Loopback deliberately: sandboxes must + # never reach the management surface, so it does NOT bind the + # docker bridge like the traffic listeners do. + "management": { + "listen": f"127.0.0.1:{tunnel_port + _MGMT_PORT_OFFSET}", + "api_key_env": _MGMT_API_KEY_ENV, + }, + "tls": { + "ca_cert": str(ca_cert), + "ca_key": str(ca_key), + "cert_cache_size": 1000, + "leaf_cert_expiry_hours": 168, + }, + "transforms": [ + { + "name": "allowlist", + "config": {"domains": hosts}, + }, + { + "name": "secrets", + "config": {"secrets": secrets_rules}, + }, + ], + "log": log_block, + } + + +def ensure_audit_log(audit_path: Path) -> None: + """Create the audit log file with private permissions (0o600). + + Called from the wizard right before ``start_proxy``. On the pinned + v0.39 the daemon never writes this file (no ``log.audit_path`` + config field), so the pre-create is purely forward-compat: when the + pin moves to a version that supports a dedicated audit stream, the + file already exists with tight permissions and the daemon inherits + them instead of creating it under the default umask. + + Raises :class:`RuntimeError` on any OSError (planted symlink, + immutable parent dir, full disk) so the caller can decide how to + surface it. The wizard treats this as a WARNING on v0.39 — the + file is non-load-bearing until the version bump — but the qualified + message keeps operators from wiring monitoring to a path that can't + exist. + """ + + try: + # Use os.open + O_CREAT to avoid races on the chmod. + open_flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND + if hasattr(os, "O_NOFOLLOW"): + open_flags |= os.O_NOFOLLOW + fd = os.open(str(audit_path), open_flags, 0o600) + try: + # Tighten perms even if the file already existed under a + # slacker umask. + os.fchmod(fd, 0o600) + finally: + os.close(fd) + except OSError as exc: + raise RuntimeError( + f"Refusing to start: could not pre-create audit log " + f"{audit_path} with restrictive permissions ({exc}). " + f"Move or chmod any existing file at that path and retry." + ) from exc + + +def write_proxy_config(config: Dict) -> Path: + """Serialize the config dict to ``/proxy/proxy.yaml``. + + Uses ``yaml.safe_dump`` so we never emit Python tags. + """ + + try: + import yaml # PyYAML is already a Hermes dep + except ImportError as exc: + raise RuntimeError( + "PyYAML is required to write the iron-proxy config but is not " + "installed." + ) from exc + + state = _proxy_state_dir() + out = state / "proxy.yaml" + tmp_path = state / ".proxy.yaml.tmp" + with open(tmp_path, "w", encoding="utf-8") as f: + yaml.safe_dump(config, f, default_flow_style=False, sort_keys=False) + # Tighten perms on the temp file BEFORE the atomic replace so the + # final path is never briefly world-readable under a slack umask + # (the config embeds proxy token values). chmod-after-replace would + # leave a TOCTOU window; the 0o700 state dir mitigates but same-uid + # processes could still race. + os.chmod(tmp_path, stat.S_IRUSR | stat.S_IWUSR) + os.replace(tmp_path, out) + return out + + +def write_mappings(mappings: List[TokenMapping]) -> Path: + """Persist the sandbox-visible proxy tokens to ``mappings.json``. + + The Docker backend reads this file to inject the right tokens as env + vars when starting a sandbox. The file is NOT read by iron-proxy + itself — the mapping is already baked into ``proxy.yaml``. + """ + + state = _proxy_state_dir() + out = state / "mappings.json" + payload = { + "version": 1, + "tokens": [ + { + "proxy_token": m.proxy_token, + "env_name": m.real_env_name, + "upstream_hosts": list(m.upstream_hosts), + "match_headers": list(m.match_headers), + "alias_env_names": list(m.alias_env_names), + } + for m in mappings + ], + } + tmp_path = state / ".mappings.json.tmp" + with open(tmp_path, "w", encoding="utf-8") as f: + json.dump(payload, f, indent=2) + # chmod before the atomic replace — see write_proxy_config. The + # mappings file holds proxy token values, so close the TOCTOU window + # rather than chmod-ing after the file is already at its final path. + os.chmod(tmp_path, stat.S_IRUSR | stat.S_IWUSR) + os.replace(tmp_path, out) + return out + + +def load_mappings() -> List[TokenMapping]: + """Read mappings.json, if it exists. Empty list on any error.""" + + state = _proxy_state_dir() + f = state / "mappings.json" + if not f.exists(): + return [] + try: + payload = json.loads(f.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as exc: + logger.warning("Failed to read iron-proxy mappings.json: %s", exc) + return [] + out: List[TokenMapping] = [] + for item in payload.get("tokens", []): + try: + out.append(TokenMapping( + proxy_token=item["proxy_token"], + real_env_name=item["env_name"], + upstream_hosts=tuple(item.get("upstream_hosts") or ()), + # Pre-header-auth mappings.json files (written before the + # match_headers/alias fields existed) load with the bearer + # defaults — identical to their behavior at write time. + match_headers=tuple(item.get("match_headers") or ("Authorization",)), + alias_env_names=tuple(item.get("alias_env_names") or ()), + )) + except (KeyError, TypeError): + continue + return out + + +def discover_provider_mappings( + *, + available_env_names: Optional[List[str]] = None, +) -> List[TokenMapping]: + """Mint a TokenMapping for every known provider whose env var is set. + + Pass ``available_env_names`` to override the lookup source (used by the + Bitwarden adapter so we mint mappings for keys that *will* be in the + proxy's environment even if they aren't in the host process env right + now). + """ + + if available_env_names is not None: + names = set(available_env_names) + else: + names = {k for k, v in os.environ.items() if v} + + mappings: List[TokenMapping] = [] + for env_name, hosts in _BEARER_PROVIDERS.items(): + if env_name not in names: + continue + mappings.append(TokenMapping( + proxy_token=mint_proxy_token(prefix=env_name.lower().replace("_api_key", "")), + real_env_name=env_name, + upstream_hosts=hosts, + )) + for env_name, spec in _HEADER_AUTH_PROVIDERS.items(): + aliases = tuple(spec.get("aliases") or ()) + # A mapping is minted when the canonical name OR any alias is + # available. Aliases collapse into ONE mapping (single secrets + # rule) because two require-rules on the same host would reject + # each other's requests. The canonical env name is what + # iron-proxy reads — when only the alias is set in the host env, + # the subprocess-env builder mirrors it (see + # ``_build_proxy_subprocess_env``). + if env_name not in names and not any(a in names for a in aliases): + continue + mappings.append(TokenMapping( + proxy_token=mint_proxy_token(prefix=env_name.lower().replace("_api_key", "")), + real_env_name=env_name, + upstream_hosts=tuple(spec["hosts"]), + match_headers=tuple(spec["match_headers"]), + alias_env_names=aliases, + )) + return mappings + + +def discover_uncovered_providers( + *, + available_env_names: Optional[List[str]] = None, +) -> List[str]: + """Return env-var names for providers we recognize but can't proxy. + + AWS Bedrock (SigV4) and GCP Vertex (SDK-minted OAuth) can't be swapped + by a static header replacement. When any of these are configured, the + sandbox is holding real credentials that the proxy can't strip — the + isolation guarantee is incomplete for those providers. + + The wizard and ``hermes egress status`` use this to print a warning. + (Anthropic / Azure OpenAI / Gemini used to be here; they're now + first-class swapped providers via ``_HEADER_AUTH_PROVIDERS``.) + """ + + if available_env_names is not None: + names = set(available_env_names) + else: + names = {k for k, v in os.environ.items() if v} + + return [n for n in _NON_BEARER_PROVIDERS if n in names] + + +def merge_mappings( + *, + existing: List[TokenMapping], + discovered: List[TokenMapping], + rotate: bool = False, +) -> List[TokenMapping]: + """Combine an existing mapping set with freshly discovered providers. + + By default this PRESERVES tokens for providers already in ``existing`` — + re-running ``hermes egress setup`` should not invalidate the tokens + baked into containers that are already running. Only newly added + providers get freshly minted tokens. + + When ``rotate=True``, every token in the result is freshly minted + regardless of overlap. The wizard exposes this via ``--rotate-tokens`` + for the rare case where the operator wants to roll all tokens + deliberately (e.g. after a suspected token leak). + + Providers that are in ``existing`` but no longer in ``discovered`` + (operator removed the env var since last setup) are dropped. + """ + + by_name = {m.real_env_name: m for m in existing} + out: List[TokenMapping] = [] + for d in discovered: + prior = by_name.get(d.real_env_name) + if prior is not None and not rotate: + # Preserve the token; refresh hosts/headers/aliases in case + # the provider spec changed since last setup (new upstreams, + # a provider moving from uncovered to header-auth, etc). + out.append(TokenMapping( + proxy_token=prior.proxy_token, + real_env_name=prior.real_env_name, + upstream_hosts=d.upstream_hosts, + match_headers=d.match_headers, + alias_env_names=d.alias_env_names, + )) + else: + out.append(d) + return out + + +# --------------------------------------------------------------------------- +# Subprocess lifecycle +# --------------------------------------------------------------------------- + + +def _pidfile() -> Path: + return _proxy_state_dir() / "iron-proxy.pid" + + +def _read_pid() -> Optional[int]: + # Use the read-only path: don't create the proxy dir just to read the + # pidfile. If neither pid file nor dir exists, the daemon is plainly + # not running. + pf = _proxy_state_dir_ro() / "iron-proxy.pid" + if not pf.exists(): + return None + try: + pid = int(pf.read_text(encoding="utf-8").strip()) + except (OSError, ValueError): + return None + return pid if pid > 0 else None + + +# Nonce env-var set in the iron-proxy subprocess at start_proxy time. Used +# by ``_pid_alive`` to confirm a candidate PID still refers to *our* managed +# binary even across PID recycling (a fresh process can't inherit our +# arbitrary env value). +_HERMES_IRON_PROXY_NONCE_ENV = "HERMES_IRON_PROXY_NONCE" +_proxy_nonce: Optional[str] = None + + +def _pid_proc_starttime(pid: int) -> Optional[str]: + """Return /proc//stat[21] (starttime) on Linux, else None. + + Comparing starttime is the standard cheap way to detect PID recycling + without relying on cmdline scanning. When None, callers fall back to + the cmdline + nonce check. + """ + try: + text = Path(f"/proc/{pid}/stat").read_text(encoding="utf-8") + except OSError: + return None + # /proc//stat: pid (comm-with-parens) state ppid ... fields[21]=starttime + # The "comm" field can contain spaces and parens, so split from the + # right parenthesis instead of using shlex. + rparen = text.rfind(")") + if rparen < 0: + return None + fields = text[rparen + 1:].split() + # field index in the post-")" tail: original 3..n become fields[0..n-3] + # starttime is original field 22 (1-indexed) → tail index 22-3 = 19 + if len(fields) <= 19: + return None + return fields[19] + + +def _persisted_nonce_path() -> Path: + """Path to the on-disk sibling of the pidfile that stores the nonce. + + Written by ``_write_pidfile_safely`` after ``start_proxy`` plants + the nonce in the iron-proxy child env, read by ``_pid_alive`` in a + later CLI invocation (``stop`` / ``status``) so cross-process + PID-recycling defense holds. + """ + return _proxy_state_dir_ro() / "iron-proxy.nonce" + + +def _read_persisted_nonce() -> Optional[str]: + """Read the on-disk nonce written next to the pidfile. + + Returns None when the file is missing, unreadable, or empty — + callers fall back to argv0 basename matching in that case. + """ + p = _persisted_nonce_path() + try: + # O_NOFOLLOW: defence-in-depth against a planted symlink at the + # nonce path; same-uid required to plant one but worth defending + # since the nonce read here decides whether stop_proxy will + # SIGKILL a candidate PID. + flags = os.O_RDONLY + if hasattr(os, "O_NOFOLLOW"): + flags |= os.O_NOFOLLOW + fd = os.open(str(p), flags) + except OSError: + return None + try: + # Ownership check — if the file isn't owned by us, ignore it. + # Same threat model as the pidfile uid check. + try: + st = os.fstat(fd) + if hasattr(os, "getuid") and st.st_uid != os.getuid(): + return None + except AttributeError: + pass + data = os.read(fd, 256).decode("utf-8", errors="ignore").strip() + return data or None + finally: + os.close(fd) + + +def _pid_alive(pid: int) -> bool: + """Return True iff ``pid`` is alive AND is an iron-proxy process. + + Defends against PID reuse via three signals (in priority order): + 1. ``/proc//environ`` contains our nonce (most reliable, Linux) + 2. ``/proc//cmdline`` basename matches the managed binary + 3. ``ps -p `` command line contains the binary path + + The legacy ``"iron-proxy" in cmdline`` match was loose enough to match + ``tail iron-proxy.log`` or an editor with that file open. We tighten + on argv[0] basename plus an in-process nonce instead. + """ + + if pid <= 0: + return False + try: + # Use psutil.pid_exists when available — it's a no-op on Windows + # whereas os.kill(pid, 0) on Windows is actually a hard kill + # (CTRL_C_EVENT to the target's console process group). See + # bpo-14484. windows-footgun: ok — we explicitly skip the + # os.kill probe on Windows below. + import psutil # type: ignore + if not psutil.pid_exists(pid): + return False + except ImportError: + if platform.system() == "Windows": + # On Windows without psutil we can't safely probe — assume + # the pidfile content is fresh and confirm via the cmdline + # path below. os.kill(pid, 0) is NOT safe here. + pass + else: + try: + os.kill(pid, 0) # windows-footgun: ok — POSIX-only branch + except (ProcessLookupError, PermissionError, OSError): + return False + + # Strong proof: nonce env var matches. /proc//environ is null- + # separated KEY=VALUE pairs; substring search is safe. + # + # The nonce can come from either: + # 1. the module-global ``_proxy_nonce`` set during this process's + # own ``start_proxy`` call (same-process case); + # 2. the on-disk ``iron-proxy.nonce`` file written by + # ``_write_pidfile_safely``, used when ``start`` and ``stop`` + # run in separate CLI invocations (cross-process case). + # Either source provides the same defeat-PID-recycling guarantee. + nonce_candidates: List[str] = [] + if _proxy_nonce: + nonce_candidates.append(_proxy_nonce) + on_disk = _read_persisted_nonce() + if on_disk and on_disk not in nonce_candidates: + nonce_candidates.append(on_disk) + if nonce_candidates: + try: + env_bytes = Path(f"/proc/{pid}/environ").read_bytes() + for nonce in nonce_candidates: + needle = f"{_HERMES_IRON_PROXY_NONCE_ENV}={nonce}".encode() + if needle in env_bytes: + return True + except OSError: + pass + + # Fallback: cmdline basename match. argv[0] is the first null- + # separated token in /proc//cmdline. + try: + cmdline_path = Path(f"/proc/{pid}/cmdline") + if cmdline_path.exists(): + tokens = cmdline_path.read_bytes().split(b"\x00") + if tokens: + argv0 = tokens[0].decode("utf-8", errors="ignore") + argv0_base = os.path.basename(argv0) + if argv0_base.startswith("iron-proxy"): + return True + return False + except OSError: + pass + + # macOS / non-Linux fallback: ``ps`` command basename. + try: + res = subprocess.run( # noqa: S603 + ["ps", "-p", str(pid), "-o", "comm="], + capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=2, + ) + if res.returncode == 0: + comm = (res.stdout or "").strip() + return os.path.basename(comm).startswith("iron-proxy") + except (OSError, subprocess.TimeoutExpired): + pass + + # Exotic platforms: be conservative — if the OS says alive we believe + # it. This restores the previous behaviour for non-Linux/non-macOS. + return True + + +def start_proxy( + *, + binary: Optional[Path] = None, + config_path: Optional[Path] = None, + extra_env: Optional[Dict[str, str]] = None, + install_if_missing: bool = True, + refresh_secrets_from_bitwarden: bool = False, + bitwarden_config: Optional[Dict] = None, +) -> ProxyStatus: + """Spawn iron-proxy as a managed background subprocess. + + Idempotent — if the proxy is already running with the expected PID, + just returns the live status. + + ``refresh_secrets_from_bitwarden=True`` re-fetches upstream secrets + via ``bws secret list`` at startup and injects them into the child + env. This delivers the rotation promise that distinguishes + ``credential_source: bitwarden`` from ``credential_source: env``. + Without this flag (or with ``bitwarden_config=None``) the proxy still + starts but uses whatever the host process env happens to contain. + """ + + global _proxy_nonce + + existing = _read_pid() + if existing and _pid_alive(existing): + return get_status() + + bin_path = binary or find_iron_proxy(install_if_missing=install_if_missing) + if bin_path is None: + raise RuntimeError( + "iron-proxy binary not available — run `hermes egress install`." + ) + + cfg = config_path or (_proxy_state_dir() / "proxy.yaml") + if not cfg.exists(): + raise RuntimeError( + f"iron-proxy config not found at {cfg}. " + "Run `hermes egress setup` first." + ) + + # Build a minimal subprocess env. os.environ.copy() would ship every + # secret in the operator's shell to the proxy — /proc//environ + # would then expose OPENAI_API_KEY, AWS keys, etc. to any same-uid + # local process. Defeats the threat model the proxy exists to + # mitigate. + env = _build_proxy_subprocess_env( + extra_env=extra_env, + refresh_from_bitwarden=refresh_secrets_from_bitwarden, + bitwarden_config=bitwarden_config, + ) + + # If the generated config enables the management API, the daemon + # validates at startup that the api_key_env is non-empty. Inject the + # persisted key (minting it if this is a config written by a newer + # setup but the token file was removed). + if _read_management_listen_from_config(cfg) is not None: + env[_MGMT_API_KEY_ENV] = ensure_management_token() + + # Plant a per-start nonce in the child env so ``_pid_alive`` can + # confirm a candidate PID still refers to *our* binary across PID + # recycling. Module-global is fine — only one managed proxy per + # Hermes process. + _proxy_nonce = hashlib.sha256(os.urandom(16)).hexdigest() + env[_HERMES_IRON_PROXY_NONCE_ENV] = _proxy_nonce + + log_path = _proxy_state_dir() / "iron-proxy.log" + # Keep ownership of the fd tight: open with explicit 0o600 so the + # log doesn't get world-readable under a slack umask, then close it + # immediately after Popen (the child has its own dup). Without the + # close-on-success path, every restart leaked one fd in the Hermes + # process. + # + # O_NOFOLLOW (defence-in-depth, same threat model as the pidfile + # path): a same-uid attacker who plants ``iron-proxy.log`` as a + # symlink to e.g. ``~/.ssh/authorized_keys`` would otherwise cause + # every restart to append daemon diagnostics to that file. + log_open_flags = os.O_WRONLY | os.O_CREAT | os.O_APPEND + if hasattr(os, "O_NOFOLLOW"): + log_open_flags |= os.O_NOFOLLOW + try: + log_fd = os.open(str(log_path), log_open_flags, 0o600) + except OSError as exc: + # ELOOP from a planted symlink — refuse with a clear error. + raise RuntimeError( + f"Refusing to write iron-proxy log {log_path}: {exc}. " + "Remove that path manually and retry." + ) from exc + try: + os.fchmod(log_fd, 0o600) # tighten if file pre-existed + except OSError: + pass + # Verify ownership — same st_uid check the pidfile uses. + try: + st = os.fstat(log_fd) + if hasattr(os, "getuid") and st.st_uid != os.getuid(): + os.close(log_fd) + raise RuntimeError( + f"iron-proxy log {log_path} has unexpected owner " + f"uid={st.st_uid}; refusing to write." + ) + except AttributeError: + pass # Windows + + try: + # Use the fd directly via the dup mechanism; Popen will dup() it + # into the child so we can close ours unconditionally below. + # NOTE: on Windows ``start_new_session`` is invalid; we don't + # support Windows for the proxy (the binary itself doesn't ship) + # but the kwarg is POSIX-only and silently ignored on Win. + popen_kwargs: Dict = dict( + env=env, + stdin=subprocess.DEVNULL, + stdout=log_fd, + stderr=subprocess.STDOUT, + ) + if platform.system() != "Windows": + popen_kwargs["start_new_session"] = True + proc = subprocess.Popen( # noqa: S603 — binary path is trusted + [str(bin_path), "-config", str(cfg)], + **popen_kwargs, + ) + except OSError as exc: + os.close(log_fd) + raise RuntimeError(f"failed to spawn iron-proxy: {exc}") from exc + finally: + # Close our copy of the fd whether Popen raised or succeeded. + # The child has its own dup via Popen, so it's still writing. + try: + os.close(log_fd) + except OSError: + pass + + # Write the pidfile IMMEDIATELY after Popen, BEFORE the listening + # verification. If the parent dies during the poll loop (SIGINT, + # OOM, kernel pause), the pidfile is still on disk so the next + # ``hermes egress stop`` can clean up the orphan. Failure paths + # below unlink the pidfile when they kill the child. + pidfile = _pidfile() + try: + _write_pidfile_safely(pidfile, proc.pid) + except RuntimeError: + # Kill the orphan so we don't leave a daemon nobody can stop. + _kill_and_wait(proc, grace_seconds=2) + raise + + # Poll-with-timeout instead of an unconditional 5s sleep. The Go + # binary normally comes up in <200ms; falling through within 100ms + # of liveness keeps Docker container creation snappy. + # + # We scope a Ctrl-C handler around the poll loop so an operator who + # hits Ctrl-C while waiting for ``hermes egress start`` doesn't leak + # an orphan with the port bound. + # + # Probe the CONFIGURED bind host, not loopback unconditionally — on + # Linux the daemon binds the docker bridge gateway, where a loopback + # connect never succeeds and we'd kill a healthy daemon as "never + # came up". + listen_hp = _read_http_listen_from_config() + if listen_hp is not None: + probe_host, tunnel_port = listen_hp + else: + probe_host, tunnel_port = "127.0.0.1", _DEFAULT_TUNNEL_PORT + listening = False + + def _interrupt_handler(_signum, _frame): # pragma: no cover - signal path + # Kill the child and unlink the pidfile, then re-raise so the + # caller sees the interrupt. + _kill_and_wait(proc, grace_seconds=2) + try: + pidfile.unlink() + except FileNotFoundError: + pass + raise KeyboardInterrupt() + + prev_sigint = None + prev_sigterm = None + install_handlers = ( + platform.system() != "Windows" + and threading.current_thread() is threading.main_thread() + ) + if install_handlers: + prev_sigint = signal.signal(signal.SIGINT, _interrupt_handler) + prev_sigterm = signal.signal(signal.SIGTERM, _interrupt_handler) + try: + deadline = time.time() + _STARTUP_GRACE_SECONDS + # Do-while shape: check listening at least once even when the + # grace window is 0 (test harness / synchronous fast-path). + while True: + if proc.poll() is not None: + tail = _tail_log(log_path, lines=20) + try: + pidfile.unlink() + except FileNotFoundError: + pass + raise RuntimeError( + f"iron-proxy exited immediately (code {proc.returncode}). " + f"Last log lines:\n{tail}" + ) + if _port_listening(probe_host, tunnel_port): + listening = True + break + if time.time() >= deadline: + break + time.sleep(0.1) + finally: + if install_handlers: + signal.signal(signal.SIGINT, prev_sigint) + signal.signal(signal.SIGTERM, prev_sigterm) + + # Final exit check — process may have died right at deadline. + if proc.poll() is not None: + tail = _tail_log(log_path, lines=20) + try: + pidfile.unlink() + except FileNotFoundError: + pass + raise RuntimeError( + f"iron-proxy exited immediately (code {proc.returncode}). " + f"Last log lines:\n{tail}" + ) + + # The previous version of this code treated "process still alive at + # deadline" as success. That left iron-proxy running but + # non-listening on the port, with a pidfile pointing at it — + # subsequent restarts would fail with "address in use" because the + # orphan still held the port. Require port-listening for success. + if not listening: + tail = _tail_log(log_path, lines=20) + _kill_and_wait(proc, grace_seconds=2) + try: + pidfile.unlink() + except FileNotFoundError: + pass + raise RuntimeError( + f"iron-proxy did not bind {probe_host}:{tunnel_port} within " + f"{_STARTUP_GRACE_SECONDS}s. Process was killed. " + f"Last log lines:\n{tail}" + ) + + logger.info("Started iron-proxy pid=%s config=%s", proc.pid, cfg) + return get_status() + + +def _write_pidfile_safely(pidfile: Path, pid: int) -> None: + """Write ``pid`` to ``pidfile`` with O_EXCL + O_NOFOLLOW + ownership check. + + O_EXCL means "another start is in progress" if the file already + exists with a live owner — we cleanly fail rather than racing. When + the existing pidfile points at a dead pid (stale crash), we + explicitly unlink it before retrying once. + + Side effect: also persists the in-process nonce to disk so + cross-CLI-invocation ``_pid_alive`` checks (start in one process, + stop in another) can still defeat PID recycling. + """ + open_flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL + if hasattr(os, "O_NOFOLLOW"): + open_flags |= os.O_NOFOLLOW + try: + fd = os.open(str(pidfile), open_flags, 0o600) + except FileExistsError: + # Pidfile already exists. If it points at a live iron-proxy, + # caller's _read_pid + _pid_alive at the top of start_proxy + # should already have returned. Reaching here means EITHER + # the previous _pid_alive check raced (rare; another start in + # flight), OR a stale pidfile survived a crash. Discriminate + # and retry once with O_TRUNC if stale. + existing_pid = _read_pid() + if existing_pid and _pid_alive(existing_pid): + raise RuntimeError( + f"Another iron-proxy start appears to be in progress " + f"(pidfile {pidfile} -> pid {existing_pid}). " + f"Run `hermes egress stop` if that proxy is stuck." + ) + # Stale — unlink and retry. + try: + pidfile.unlink() + except FileNotFoundError: + pass + fd = os.open(str(pidfile), open_flags, 0o600) + except OSError as exc: + # ELOOP from a planted symlink at the pidfile path. + raise RuntimeError( + f"Refusing to write pidfile {pidfile}: {exc}. " + "Remove that path manually and retry." + ) from exc + + try: + # Ownership check — same st_uid pattern the log file uses. + try: + st = os.fstat(fd) + if hasattr(os, "getuid") and st.st_uid != os.getuid(): + raise RuntimeError( + f"pidfile {pidfile} has unexpected owner uid={st.st_uid}" + ) + except AttributeError: + pass # Windows + os.write(fd, str(pid).encode("utf-8")) + finally: + os.close(fd) + + # Persist the nonce next to the pidfile (sibling, 0o600). + # ``stop_proxy`` in a separate CLI invocation can read this and use + # it to confirm the pid still refers to our binary even though the + # module-global ``_proxy_nonce`` is fresh in the new process. + if _proxy_nonce: + noncefile = pidfile.with_suffix(".nonce") + nfd = -1 + try: + nopen = os.O_WRONLY | os.O_CREAT | os.O_TRUNC + if hasattr(os, "O_NOFOLLOW"): + nopen |= os.O_NOFOLLOW + nfd = os.open(str(noncefile), nopen, 0o600) + os.write(nfd, _proxy_nonce.encode("utf-8")) + except OSError: + # Best-effort. Without the nonce file we fall back to + # argv0-basename matching, which is what we did before. + pass + finally: + if nfd >= 0: + try: + os.close(nfd) + except OSError: + pass + + +def _kill_and_wait(proc: "subprocess.Popen", *, grace_seconds: int = 2) -> None: + """Best-effort SIGTERM → wait → SIGKILL for a child we own.""" + try: + proc.terminate() + except OSError: + return + try: + proc.wait(timeout=grace_seconds) + except subprocess.TimeoutExpired: + try: + proc.kill() + except OSError: + pass + try: + proc.wait(timeout=grace_seconds) + except subprocess.TimeoutExpired: + pass + + +def _build_proxy_subprocess_env( + *, + extra_env: Optional[Dict[str, str]] = None, + refresh_from_bitwarden: bool = False, + bitwarden_config: Optional[Dict] = None, +) -> Dict[str, str]: + """Construct the minimal env for the iron-proxy subprocess. + + Allowlists infrastructure vars (PATH, HOME, locale) plus the env vars + named in ``load_mappings()`` (the real upstream secrets the proxy + needs to do the swap). Everything else is stripped — see + ``_PROXY_SUBPROCESS_ENV_STRIP`` for proxy chain protection. + + When ``refresh_from_bitwarden=True`` AND ``bitwarden_config`` is + populated, fetches upstream secrets via the BSM SDK at startup and + merges them in. This is what delivers the rotation guarantee + promised by ``credential_source: bitwarden`` — without it, rotating + a key in the Bitwarden web app doesn't reach the proxy. + """ + + env: Dict[str, str] = {} + parent = os.environ + for name in _PROXY_SUBPROCESS_ENV_ALLOWLIST: + if name in parent: + env[name] = parent[name] + + # The proxy reads the real upstream secrets from its OWN env, indexed + # by ``m.real_env_name`` in the YAML config's ``secrets.source.var`` + # field. Forward those — but only those. For alias providers + # (GEMINI_API_KEY / GOOGLE_API_KEY), the rule is keyed on the canonical + # name; when only the alias is set in the host env, mirror its value + # into the canonical name so the swap still has a real secret. + alias_sources: Dict[str, Tuple[str, ...]] = {} + needed = set() + for m in load_mappings(): + needed.add(m.real_env_name) + if m.alias_env_names: + alias_sources[m.real_env_name] = tuple(m.alias_env_names) + for name in needed: + if name in parent: + env[name] = parent[name] + else: + for alias in alias_sources.get(name, ()): + if parent.get(alias): + env[name] = parent[alias] + break + + # Optional Bitwarden refresh path. Pulled lazily so the proxy module + # doesn't hard-depend on the bitwarden module being importable in + # every install. + if refresh_from_bitwarden and bitwarden_config: + try: + from agent.secret_sources import bitwarden as bw + access_token_name = bitwarden_config.get( + "access_token_env", "BWS_ACCESS_TOKEN" + ) + access_token = parent.get(access_token_name, "").strip() + project_id = bitwarden_config.get("project_id", "") + if access_token and project_id: + secrets, warnings = bw.fetch_bitwarden_secrets( + access_token=access_token, + project_id=project_id, + cache_ttl_seconds=0, + use_cache=False, + ) + # Only inject env names we have a mapping for — extra + # secrets in the BW project shouldn't leak into the proxy + # process unless they're going to be used by the swap. + missing = sorted(needed - set(secrets)) + for n in needed: + if n in secrets: + env[n] = secrets[n] + if missing: + # stephenschoettler #1: don't silently keep stale + # host-env values when BWS mode was explicitly + # selected. An operator on credential_source=bitwarden + # picked it specifically to get rotation; falling back + # to parent env reintroduces the bug class the mode + # is supposed to defeat. ``allow_env_fallback`` is the + # documented, deliberate opt-out — honor it here exactly + # as the empty-token branch below does (the error + # message tells operators to set it, so it must work). + if not (bitwarden_config or {}).get("allow_env_fallback"): + raise RuntimeError( + f"Bitwarden refresh did not return secrets for " + f"{missing}. Either add the secrets to your BWS " + f"project, switch to credential_source: env via " + f"`hermes egress setup --no-bitwarden`, or set " + f"`proxy.allow_env_fallback: true` in config.yaml " + f"to opt into the legacy host-env fallback." + ) + logger.warning( + "Bitwarden refresh did not return secrets for %s — " + "falling back to host env for those names " + "(allow_env_fallback=true).", + missing, + ) + # bws warnings are non-secret status messages (e.g. "no + # project found", "rate limited"), but the taint analyzer + # can't tell that — log the count and let the operator + # rerun under verbose if they need detail. + if warnings: + logger.warning( + "Bitwarden refresh produced %d warning(s); " + "run `hermes secrets bitwarden status` for detail.", + len(warnings), + ) + else: + # NOTE: deliberately do not interpolate access_token_name + # in the log message — CodeQL's taint analyzer treats + # bitwarden_config values as secret-tainted (it can't + # distinguish the env-var NAME from the env-var VALUE). + # The name is non-secret but logging it just trips the + # check for no real benefit. + if not (bitwarden_config or {}).get("allow_env_fallback"): + raise RuntimeError( + "credential_source=bitwarden but the access-token " + "env or project_id is empty. Either set both, " + "switch to credential_source: env, or set " + "`proxy.allow_env_fallback: true` to opt into " + "the legacy fallback behaviour." + ) + logger.warning( + "credential_source=bitwarden but access-token env or " + "project_id is empty — proxy will fall back to parent env " + "(allow_env_fallback=true).", + ) + except (ImportError,) as exc: + # The BWS module or one of its runtime deps isn't importable. + # Mirror the sibling branches: if allow_env_fallback isn't + # explicitly enabled, fail closed — credential_source=bitwarden + # with a unavailable module should not silently degrade to host + # env. A wizard-time check can't catch a dependency that goes + # missing between setup and a later restart. + if not (bitwarden_config or {}).get("allow_env_fallback"): + raise RuntimeError( + "Bitwarden refresh module unavailable at proxy start " + "(credential_source=bitwarden with " + "proxy.allow_env_fallback: false). Either fix the " + "import, switch to credential_source: env, or set " + "`proxy.allow_env_fallback: true` to opt into the " + "legacy fallback behaviour." + ) from exc + logger.warning( + "Bitwarden refresh module unavailable at proxy start, " + "falling back to parent env (allow_env_fallback=true): %s", + exc, + ) + + # Caller-supplied overrides win. This is intentionally last so the + # wizard can inject ad-hoc test secrets without recomputing the BW + # path. + if extra_env: + env.update(extra_env) + + # Strip proxy-recursion-risk vars regardless of how they got in. + for name in _PROXY_SUBPROCESS_ENV_STRIP: + env.pop(name, None) + + env.setdefault("NO_COLOR", "1") + return env + + +def stop_proxy() -> bool: + """Stop the managed iron-proxy. Returns True if it was running.""" + + global _proxy_nonce + + def _cleanup_state_files() -> None: + """Best-effort cleanup of pidfile + persisted nonce.""" + _pidfile().unlink(missing_ok=True) + try: + _persisted_nonce_path().unlink() + except FileNotFoundError: + pass + except OSError: + pass + + pid = _read_pid() + if not pid or not _pid_alive(pid): + _cleanup_state_files() + _proxy_nonce = None + return False + + # Capture starttime BEFORE signalling so we can compare after the + # grace window — if the pid got recycled mid-wait, the starttime + # changes and we abort the SIGKILL. + starttime_before = _pid_proc_starttime(pid) + + try: + os.kill(pid, signal.SIGTERM) + except ProcessLookupError: + _cleanup_state_files() + _proxy_nonce = None + return False + + # Wait up to 5s for graceful exit, then SIGKILL. + deadline = time.time() + 5.0 + while time.time() < deadline: + if not _pid_alive(pid): + break + time.sleep(0.1) + else: + # Verify the pid hasn't been recycled before delivering SIGKILL. + # Two checks: + # 1. /proc//stat starttime is unchanged (Linux) + # 2. _pid_alive() still says it's an iron-proxy process + starttime_after = _pid_proc_starttime(pid) + recycled = ( + starttime_before is not None + and starttime_after is not None + and starttime_before != starttime_after + ) or not _pid_alive(pid) + if recycled: + logger.warning( + "iron-proxy pid=%s appears recycled before SIGKILL; " + "not killing.", pid, + ) + else: + try: + os.kill(pid, _KILL_SIGNAL) + except ProcessLookupError: + pass + + _cleanup_state_files() + _proxy_nonce = None + logger.info("Stopped iron-proxy pid=%s", pid) + return True + + +def get_status() -> ProxyStatus: + """Snapshot the current proxy state — does NOT start anything. + + Crucially, this is called per Docker-container-create when egress + enforcement is on. It must not have side-effects (no mkdir, no + binary version subprocess that takes 30s on a hung binary). The + state dir is read-only here. + """ + + status = ProxyStatus() + listen_hp = _read_http_listen_from_config() + if listen_hp is not None: + probe_host, status.tunnel_port = listen_hp + else: + probe_host = "127.0.0.1" + status.tunnel_port = _DEFAULT_TUNNEL_PORT + + binary = find_iron_proxy(install_if_missing=False) + if binary: + status.binary_path = binary + # Cached — see iron_proxy_version(). First call still costs one + # subprocess; subsequent calls in the same process are dict + # lookups. + status.binary_version = iron_proxy_version(binary) + + state = _proxy_state_dir_ro() + cfg = state / "proxy.yaml" + ca = state / "ca.crt" + if cfg.exists(): + status.config_path = cfg + if ca.exists(): + status.ca_cert_path = ca + + pid = _read_pid() + if pid and _pid_alive(pid): + status.pid = pid + # Probe the configured bind host — on Linux that's the docker + # bridge gateway, where a loopback connect would report a healthy + # daemon as "not listening". + status.listening = _port_listening(probe_host, status.tunnel_port) + + return status + + +def _read_tunnel_port_from_config() -> Optional[int]: + listen = _read_http_listen_from_config() + if listen is None: + return None + return listen[1] + + +def _read_http_listen_from_config() -> Optional[Tuple[str, int]]: + """Return ``(host, port)`` of the configured sandbox-facing listener. + + Reads ``proxy.tunnel_listen`` — the CONNECT/MITM listener sandboxes + hit via ``HTTPS_PROXY`` — falling back to ``proxy.http_listen`` for + configs written before the tunnel/http listener-role split. + + The bind host matters for liveness probes: on Linux the daemon binds + the docker bridge gateway (e.g. ``172.17.0.1``), where a loopback + connect would report "not listening" for a perfectly healthy daemon. + """ + + cfg = _proxy_state_dir_ro() / "proxy.yaml" + if not cfg.exists(): + return None + try: + import yaml + except ImportError: + return None + try: + data = yaml.safe_load(cfg.read_text(encoding="utf-8")) + except (OSError, yaml.YAMLError): + return None + proxy_block = (data or {}).get("proxy") or {} + # The CLI/Docker side calls this "the tunnel port" because that's how + # sandboxes use it (HTTPS_PROXY) — on the iron-proxy side it's the + # tunnel_listen (CONNECT + MITM). http_listen is the plain-HTTP + # forward listener on tunnel_port+1. + listen = proxy_block.get("tunnel_listen") or proxy_block.get("http_listen") or "" + if not isinstance(listen, str) or ":" not in listen: + return None + host, _, port_s = listen.rpartition(":") + try: + port = int(port_s) + except ValueError: + return None + return (host or "127.0.0.1", port) + + +def _port_listening(host: str, port: int) -> bool: + """Cheap TCP connect probe — True iff something accepts on host:port.""" + + import socket + + try: + with socket.create_connection((host, port), timeout=0.5): + return True + except OSError: + return False + + +def _tail_log(path: Path, *, lines: int = 20) -> str: + if not path.exists(): + return "(no log file)" + try: + data = path.read_bytes()[-8192:] + return "\n".join(data.decode("utf-8", errors="replace").splitlines()[-lines:]) + except OSError as exc: + return f"(could not read log: {exc})" + + +# --------------------------------------------------------------------------- +# Test hook +# --------------------------------------------------------------------------- + + +def _reset_for_tests() -> None: + """Clear module-level caches so tests get a fresh start. + + This module owns two mutable globals that need reset between tests: + - ``_VERSION_CACHE`` — subprocess output cache keyed by binary path. + - ``_proxy_nonce`` — the strong-proof token written by ``start_proxy`` + and read by ``_pid_alive`` to defeat PID recycling. + + Today the repo's tests run each file in its own subprocess (per + AGENTS.md) so leakage is bounded, but any in-process caller + (notebooks, ad-hoc scripts, ``pytest -p no:xdist``) would otherwise + see whichever values were probed first regardless of subsequent + ``install_iron_proxy(force=True)`` or ``start_proxy`` calls. + """ + + global _proxy_nonce + _VERSION_CACHE.clear() + _proxy_nonce = None + + +# Make a small set of symbols available without underscored access. +__all__ = [ + "ProxyStatus", + "TokenMapping", + "build_proxy_config", + "discover_provider_mappings", + "discover_uncovered_providers", + "ensure_audit_log", + "ensure_ca_cert", + "ensure_management_token", + "find_iron_proxy", + "get_status", + "install_iron_proxy", + "iron_proxy_version", + "load_mappings", + "merge_mappings", + "mint_proxy_token", + "reload_proxy", + "start_proxy", + "stop_proxy", + "write_mappings", + "write_proxy_config", +] diff --git a/agent/reasoning_timeouts.py b/agent/reasoning_timeouts.py index 13df836b1100..da7fcd2fcbed 100644 --- a/agent/reasoning_timeouts.py +++ b/agent/reasoning_timeouts.py @@ -102,9 +102,18 @@ _REASONING_STALE_TIMEOUT_FLOORS: tuple[tuple[str, int], ...] = ( # ``claude-opus-4`` so non-thinking Claude 3.x or future # non-reasoning Claude variants don't match. ("claude-opus-4", 240), + ("claude-opus-5", 240), ("claude-sonnet-5", 180), ("claude-sonnet-4.5", 180), ("claude-sonnet-4.6", 180), + # Anthropic Mythos-class named reasoning models (claude-fable-5, …). + # 1M context + 128K output — heavier thinking phase than the + # numbered Claude line, so the floor is in the deep-reasoning tier + # alongside o1 / deepseek-r1 / nemotron-3-ultra. Without this + # entry the stale-stream detector kills fable-5's thinking phase + # at the default 180s (300s with context scaling), tripping the + # cross-turn circuit breaker after 5 consecutive stale kills. + ("claude-fable", 600), # xAI Grok reasoning variants. Explicit reasoning-only keys # plus one for the ``non-reasoning`` variant so users picking # the fast variant don't get the 300s floor. Bare ``grok-3``, @@ -137,19 +146,18 @@ _REASONING_STALE_TIMEOUT_FLOORS: tuple[tuple[str, int], ...] = ( # so we accept that community forks inheriting the same prefix are # treated as reasoning models (a reasonable default — the upstream # gateway timing is the same). -_PATTERN_CACHE: dict[str, re.Pattern[str]] = {} - - -def _get_pattern(slug: str) -> re.Pattern[str]: - compiled = _PATTERN_CACHE.get(slug) - if compiled is None: - compiled = re.compile( - r"^" - + re.escape(slug) - + r"(?:$|[\-._])" - ) - _PATTERN_CACHE[slug] = compiled - return compiled +# Pre-compile all patterns at module load time to avoid per-call regex +# compilation and thread-safety issues with the mutable _PATTERN_CACHE. +# The list is built once at import and never mutated afterwards, so it is +# safe for free-threaded Python 3.13+ without any locking. The slug is kept +# in each entry for debuggability (log/inspection), even though _match_any +# only consumes floor + pattern. +_SORTED_REASONING_FLOORS: list[tuple[str, float, re.Pattern[str]]] = [ + (slug, floor, re.compile(r"^" + re.escape(slug) + r"(?:$|[\-._])")) + for slug, floor in sorted( + _REASONING_STALE_TIMEOUT_FLOORS, key=lambda kv: -len(kv[0]) + ) +] def _match_any(model_lower: str) -> Optional[float]: @@ -160,13 +168,8 @@ def _match_any(model_lower: str) -> Optional[float]: order is irrelevant: longest slug wins (so ``o3-mini`` beats ``o3`` on a model like ``openai/o3-mini``). """ - # Sort by slug length descending so longer / more-specific slugs - # win on shared prefixes (o3-mini beats o3). - sorted_floors = sorted( - _REASONING_STALE_TIMEOUT_FLOORS, key=lambda kv: -len(kv[0]) - ) - for slug, floor in sorted_floors: - if _get_pattern(slug).search(model_lower): + for _slug, floor, pattern in _SORTED_REASONING_FLOORS: + if pattern.search(model_lower): return float(floor) return None @@ -206,6 +209,8 @@ def get_reasoning_stale_timeout_floor(model: object) -> Optional[float]: 300.0 >>> get_reasoning_stale_timeout_floor("anthropic/claude-opus-4-6") 240.0 + >>> get_reasoning_stale_timeout_floor("anthropic/claude-fable-5") + 600.0 >>> get_reasoning_stale_timeout_floor("gpt-4o") is None True >>> get_reasoning_stale_timeout_floor("olmo-1") is None diff --git a/agent/redact.py b/agent/redact.py index ebca1ae75f14..bff23934da6c 100644 --- a/agent/redact.py +++ b/agent/redact.py @@ -175,6 +175,85 @@ _YAML_ASSIGN_RE = re.compile( re.IGNORECASE | re.MULTILINE, ) +# Word-boundary validation for the mixed/lowercase key patterns above +# (_CFG_DOTTED_RE, _CFG_ANCHORED_RE, _YAML_ASSIGN_RE). +# +# Those key classes allow arbitrary alphanumeric affixes around the secret +# keyword so real key names like ``client_secret``, ``clientSecret``, and +# ``s3.secret-key`` match. The side effect: ordinary prose/document words that +# merely CONTAIN a keyword also matched — ``Secretary: J.Smith`` (secret), +# ``tokenizer: cl100k_base`` (token), ``author=Smith`` (auth) — mangling +# legitimate content on the surfaces that run these passes (browser snapshots, +# log lines, kanban summaries, CLI-echoed command output). Ported from +# nearai/ironclaw#6129, where the same substring false positive ("Secretary of +# the Treasury" matching the ``secret`` marker) scrubbed legitimate tool +# results from the replayed transcript and sent the model into a re-fetch +# loop. +# +# A keyword occurrence only counts when it sits at a word boundary within the +# key: at the key's edge, next to a non-letter (``_ - . 3``), or at a +# camelCase transition (``clientSecret``, ``secretKey``, ``APIToken``). A +# trailing plural ``s`` is treated as part of the keyword (``secrets:``, +# ``tokens:``). Common concatenated compounds keep matching via explicit +# alternatives (``authtoken`` ngrok, ``authkey`` tailscale, ``secretkey`` +# minio, ``apikey``). Embedded occurrences inside a larger word +# (``secretary``, ``tokenizer``, ``authored``, ``credentialing``) no longer +# match. ALL-CAPS keys keep the legacy embedded matching (``MYTOKEN=…``) — an +# all-caps key is almost never prose, the same rationale as _ENV_ASSIGN_RE. +_KEY_KEYWORD_RE = re.compile( + r"(?:api|auth|access|refresh|session|secret)[ _.\-]?(?:key|token)" + r"|token|secret|passwd|password|credential|auth", + re.IGNORECASE, +) + + +def _is_word_start(s: str, i: int) -> bool: + """True if position ``i`` in ``s`` begins a word (not mid-word).""" + if i == 0: + return True + prev, cur = s[i - 1], s[i] + if not prev.isalpha(): + return True + if cur.isupper() and prev.islower(): + return True # camelCase: clientSecret + # Acronym run ending: APIToken — the 'T' begins a new word when it is + # followed by lowercase while the preceding run is uppercase. + if cur.isupper() and prev.isupper() and i + 1 < len(s) and s[i + 1].islower(): + return True + return False + + +def _is_word_end(s: str, j: int, *, allow_plural: bool = True) -> bool: + """True if position ``j`` (exclusive end) in ``s`` ends a word.""" + if j >= len(s): + return True + cur = s[j] + if not cur.isalpha(): + return True + if cur.isupper() and s[j - 1].islower(): + return True # camelCase continuation: secretKey + if allow_plural and cur in "sS": + return _is_word_end(s, j + 1, allow_plural=False) + return False + + +def _key_has_secret_keyword(key: str) -> bool: + """True if ``key`` contains a secret keyword at a word boundary. + + Post-match validator for _CFG_DOTTED_RE / _CFG_ANCHORED_RE / + _YAML_ASSIGN_RE hits — rejects prose words that merely embed a keyword + (``secretary``, ``tokenizer``, ``authored``). Safe to call with the + _ENV_ASSIGN_RE key too: all-caps keys short-circuit to the legacy + embedded-match behavior. + """ + letters = [c for c in key if c.isalpha()] + if letters and all(c.isupper() for c in letters): + return True # legacy all-caps behavior (MYTOKEN=…) + for m in _KEY_KEYWORD_RE.finditer(key): + if _is_word_start(key, m.start()) and _is_word_end(key, m.end()): + return True + return False + # JSON field patterns: "apiKey": "value", "token": "value", etc. _JSON_KEY_NAMES = r"(?:api_?[Kk]ey|token|secret|password|access_token|refresh_token|auth_token|bearer|secret_value|raw_secret|secret_input|key_material)" _JSON_FIELD_RE = re.compile( @@ -614,6 +693,13 @@ def redact_sensitive_text( # prose/log contexts (issue #2852): ``KEY=os.getenv('X')``. if _ENV_LOOKUP_VALUE_RE.match(value): return m.group(0) + # Keyword must sit at a word boundary within the key — + # ``author=Smith`` / ``press.secretary=…`` are prose, not + # credentials (ported from nearai/ironclaw#6129). All-caps + # keys (the _ENV_ASSIGN_RE shape) short-circuit to legacy + # embedded matching inside the helper. + if not _key_has_secret_keyword(name): + return m.group(0) return f"{name}={quote}{_mask_token(value)}{quote}" text = _ENV_ASSIGN_RE.sub(_redact_env, text) # Lowercase/dotted config keys (issue #16413). Skip URLs entirely — @@ -647,6 +733,11 @@ def redact_sensitive_text( # not a leaked secret value. if _ENV_LOOKUP_VALUE_RE.match(value): return m.group(0) + # Keyword must sit at a word boundary within the key — + # ``Secretary: J.Smith`` / ``tokenizer: cl100k_base`` are + # document text, not credentials (nearai/ironclaw#6129). + if not _key_has_secret_keyword(key): + return m.group(0) return f"{key}{sep}{_mask_token(value)}" text = _YAML_ASSIGN_RE.sub(_redact_yaml, text) diff --git a/agent/relay_llm.py b/agent/relay_llm.py new file mode 100644 index 000000000000..3481ca072376 --- /dev/null +++ b/agent/relay_llm.py @@ -0,0 +1,1130 @@ +"""Core NeMo Relay adapters for physical Hermes provider attempts.""" + +from __future__ import annotations + +import asyncio +import contextvars +import inspect +import json +import logging +from collections.abc import Callable, Iterator +from types import SimpleNamespace +from typing import Any + +from agent import relay_runtime + +logger = logging.getLogger(__name__) + + +_PROVIDER_MESSAGE_EXTENSION_KEYS = frozenset( + {"reasoning_content", "reasoning_details"} +) +_RELAY_INTERNAL_PROVIDER_HEADERS = frozenset( + {"x-dynamo-parent-session-id", "x-dynamo-session-id"} +) + + +def execute( + request: dict[str, Any], + callback: Callable[[dict[str, Any]], Any], + *, + session_id: str, + name: str, + model_name: str, + metadata: dict[str, Any] | None = None, + defer_logical_completion: bool = False, +) -> Any: + """Run one non-streaming physical provider attempt through Relay.""" + runtime, session, parent = relay_runtime.resolve_execution_context(session_id) + if runtime is None or session is None or not runtime.managed_execution_enabled(): + return callback(request) + logical = _logical_parent(runtime, session, parent, metadata) + parent = logical[1] if logical is not None else parent + + relay_request_body = _relay_request_body(request, metadata) + relay_request = runtime.relay.LLMRequest({}, relay_request_body) + codec_baseline_body = _codec_round_trip_request_body( + runtime.relay, + relay_request, + relay_request_body=relay_request_body, + metadata=metadata, + ) + raw_response: dict[str, Any] = {} + callback_error: BaseException | None = None + callback_context = contextvars.copy_context() + + def invoke(next_request: Any) -> Any: + nonlocal callback_error + try: + final_request = _provider_request( + request, + next_request, + relay_request_body=relay_request_body, + codec_baseline_body=codec_baseline_body, + metadata=metadata, + ) + raw = callback_context.copy().run(callback, final_request) + except BaseException as exc: + callback_error = exc + raise + raw_response["value"] = raw + raw_response["json"] = _jsonable(raw) + return raw_response["json"] + + try: + managed = _run_awaitable( + runtime.run_in_session_async( + session, + runtime.relay.llm.execute, + name, + relay_request, + invoke, + handle=parent, + metadata=_jsonable(metadata or {}), + model_name=model_name, + codec=_codec(runtime.relay, metadata), + response_codec=_codec(runtime.relay, metadata), + ) + ) + except BaseException as exc: + if ( + callback_error is not None + and relay_runtime._is_relay_wrapped_callback_error(exc, callback_error) + ): + raise callback_error + if _recover_successful_callback( + raw_response, + relay_error=exc, + callback_error=callback_error, + logical=logical, + defer_logical_completion=defer_logical_completion, + ): + return raw_response["value"] + raise + + if not defer_logical_completion: + _complete_logical(logical, outcome="success") + if "value" in raw_response and _json_equal(managed, raw_response["json"]): + return raw_response["value"] + return _namespace(managed) + + +async def execute_async( + request: dict[str, Any], + callback: Callable[[dict[str, Any]], Any], + *, + session_id: str, + name: str, + model_name: str, + metadata: dict[str, Any] | None = None, + defer_logical_completion: bool = False, +) -> Any: + """Run one asynchronous physical provider attempt through Relay.""" + runtime, session, parent = relay_runtime.resolve_execution_context(session_id) + if runtime is None or session is None or not runtime.managed_execution_enabled(): + return await callback(request) + logical = _logical_parent(runtime, session, parent, metadata) + parent = logical[1] if logical is not None else parent + + relay_request_body = _relay_request_body(request, metadata) + relay_request = runtime.relay.LLMRequest({}, relay_request_body) + codec_baseline_body = _codec_round_trip_request_body( + runtime.relay, + relay_request, + relay_request_body=relay_request_body, + metadata=metadata, + ) + raw_response: dict[str, Any] = {} + callback_error: BaseException | None = None + callback_context = contextvars.copy_context() + + async def invoke(next_request: Any) -> Any: + nonlocal callback_error + try: + final_request = _provider_request( + request, + next_request, + relay_request_body=relay_request_body, + codec_baseline_body=codec_baseline_body, + metadata=metadata, + ) + async def call_provider() -> Any: + return await callback(final_request) + + task = callback_context.copy().run( + asyncio.create_task, + call_provider(), + ) + raw = await task + except BaseException as exc: + callback_error = exc + raise + raw_response["value"] = raw + raw_response["json"] = _jsonable(raw) + return raw_response["json"] + + try: + managed = await runtime.run_in_session_async( + session, + runtime.relay.llm.execute, + name, + relay_request, + invoke, + handle=parent, + metadata=_jsonable(metadata or {}), + model_name=model_name, + codec=_codec(runtime.relay, metadata), + response_codec=_codec(runtime.relay, metadata), + ) + except BaseException as exc: + if ( + callback_error is not None + and relay_runtime._is_relay_wrapped_callback_error(exc, callback_error) + ): + raise callback_error + if _recover_successful_callback( + raw_response, + relay_error=exc, + callback_error=callback_error, + logical=logical, + defer_logical_completion=defer_logical_completion, + ): + return raw_response["value"] + raise + + if not defer_logical_completion: + _complete_logical(logical, outcome="success") + if "value" in raw_response and _json_equal(managed, raw_response["json"]): + return raw_response["value"] + return _namespace(managed) + + +def execute_current( + request: dict[str, Any], + callback: Callable[[dict[str, Any]], Any], + *, + name: str, + model_name: str, + metadata: dict[str, Any] | None = None, + defer_logical_completion: bool = False, +) -> Any: + """Run a provider attempt under the inherited Hermes turn when present.""" + turn = relay_runtime.active_turn() + if turn is None: + return callback(request) + return execute( + request, + callback, + session_id=turn.lease.session_id, + name=name, + model_name=model_name, + metadata=metadata, + defer_logical_completion=defer_logical_completion, + ) + + +async def execute_current_async( + request: dict[str, Any], + callback: Callable[[dict[str, Any]], Any], + *, + name: str, + model_name: str, + metadata: dict[str, Any] | None = None, + defer_logical_completion: bool = False, +) -> Any: + """Run an async provider attempt under the inherited turn when present.""" + turn = relay_runtime.active_turn() + if turn is None: + return await callback(request) + return await execute_async( + request, + callback, + session_id=turn.lease.session_id, + name=name, + model_name=model_name, + metadata=metadata, + defer_logical_completion=defer_logical_completion, + ) + + +def stream_current( + request: dict[str, Any], + stream_factory: Callable[[dict[str, Any]], Any], + *, + name: str, + model_name: str, + finalizer: Callable[[], Any], + metadata: dict[str, Any] | None = None, + defer_logical_completion: bool = False, +) -> Any: + """Run a provider stream under the inherited Hermes turn when present.""" + turn = relay_runtime.active_turn() + if turn is None: + return stream_factory(request) + return stream( + request, + stream_factory, + session_id=turn.lease.session_id, + name=name, + model_name=model_name, + finalizer=finalizer, + metadata=metadata, + defer_logical_completion=defer_logical_completion, + ) + + +def stream( + request: dict[str, Any], + stream_factory: Callable[[dict[str, Any]], Any], + *, + session_id: str, + name: str, + model_name: str, + finalizer: Callable[[], Any], + on_stream_created: Callable[[Any], None] | None = None, + on_chunk: Callable[[Any], None] | None = None, + chunk_adapter: Callable[[Any], Any] | None = None, + accept_chunk: Callable[[Any], bool] | None = None, + completed_response_predicate: Callable[[Any], bool] | None = None, + metadata: dict[str, Any] | None = None, + defer_logical_completion: bool = False, +) -> "ManagedLlmStream": + """Return a synchronous view of one Relay-managed provider stream.""" + return ManagedLlmStream( + request, + stream_factory, + session_id=session_id, + name=name, + model_name=model_name, + finalizer=finalizer, + on_stream_created=on_stream_created, + on_chunk=on_chunk, + chunk_adapter=chunk_adapter, + accept_chunk=accept_chunk, + completed_response_predicate=completed_response_predicate, + metadata=metadata, + defer_logical_completion=defer_logical_completion, + ) + + +class ManagedLlmStream(Iterator[Any]): + """Drive Relay's async stream from Hermes's provider worker thread.""" + + def __init__( + self, + request: dict[str, Any], + stream_factory: Callable[[dict[str, Any]], Any], + *, + session_id: str, + name: str, + model_name: str, + finalizer: Callable[[], Any], + on_stream_created: Callable[[Any], None] | None, + on_chunk: Callable[[Any], None] | None, + chunk_adapter: Callable[[Any], Any] | None, + accept_chunk: Callable[[Any], bool] | None, + completed_response_predicate: Callable[[Any], bool] | None, + metadata: dict[str, Any] | None, + defer_logical_completion: bool, + ) -> None: + self.final_response: Any = None + self._loop: asyncio.AbstractEventLoop | None = None + self._stream: Any = None + self._raw_stream_resource: Any = None + self._closed = False + self._close_error: BaseException | None = None + self._callback_error: BaseException | None = None + self._logical: tuple[relay_runtime.RelayTurnContext, Any, str] | None = None + self._defer_logical_completion = defer_logical_completion + self._on_chunk = on_chunk + self._chunk_adapter = chunk_adapter or _namespace + self._accept_chunk = accept_chunk + self._relay_observes_chunks = False + self._provider_completed = False + self._raw_chunks: list[tuple[Any, Any]] = [] + self.output_modified = False + callback_context = contextvars.copy_context() + + def run_callback(callback: Callable[..., Any], *args: Any) -> Any: + # Relay can invoke stream surfaces while another callback still + # owns the captured Context. A fresh copy is safe to enter. + return callback_context.copy().run(callback, *args) + + runtime, session, parent = relay_runtime.resolve_execution_context(session_id) + if ( + runtime is None + or session is None + or not runtime.managed_execution_enabled() + ): + raw_stream = stream_factory(request) + if completed_response_predicate is not None and completed_response_predicate( + raw_stream + ): + self.final_response = raw_stream + self._stream = iter(()) + else: + self._raw_stream_resource = raw_stream + if on_stream_created is not None: + on_stream_created(raw_stream) + self._stream = iter(raw_stream) + return + + self._logical = _logical_parent(runtime, session, parent, metadata) + if self._logical is not None: + parent = self._logical[1] + relay_request_body = _relay_request_body(request, metadata) + relay_request = runtime.relay.LLMRequest({}, relay_request_body) + codec_baseline_body = _codec_round_trip_request_body( + runtime.relay, + relay_request, + relay_request_body=relay_request_body, + metadata=metadata, + ) + + async def provider_stream(next_request: Any): + raw_stream = None + try: + raw_stream = run_callback( + stream_factory, + _provider_request( + request, + next_request, + relay_request_body=relay_request_body, + codec_baseline_body=codec_baseline_body, + metadata=metadata, + ) + ) + if ( + completed_response_predicate is not None + and run_callback( + completed_response_predicate, + raw_stream, + ) + ): + self.final_response = raw_stream + self._provider_completed = True + return + if on_stream_created is not None: + run_callback(on_stream_created, raw_stream) + raw_iterator = run_callback(iter, raw_stream) + while True: + try: + chunk = run_callback(next, raw_iterator) + except StopIteration: + break + if self._accept_chunk is not None and not run_callback( + self._accept_chunk, + chunk, + ): + break + encoded_chunk = _jsonable(chunk) + self._raw_chunks.append((encoded_chunk, chunk)) + yield encoded_chunk + self._provider_completed = True + except BaseException as exc: + self._callback_error = exc + raise + finally: + close = getattr(raw_stream, "close", None) + if callable(close): + try: + run_callback(close) + except BaseException as exc: + self._close_error = exc + raise + + def observe_chunk(chunk: Any) -> None: + if self._on_chunk is not None: + run_callback(self._on_chunk, _jsonable(chunk)) + + def relay_finalizer() -> Any: + # Relay can invoke the finalizer while unwinding a provider-stream + # failure. Preserve that original callback error instead of + # replacing it with a secondary "missing terminal response" error. + if self._callback_error is not None: + return None + try: + if self.final_response is not None: + return _jsonable(self.final_response) + return _jsonable(run_callback(finalizer)) + except BaseException as exc: + self._callback_error = exc + raise + + loop = asyncio.new_event_loop() + self._loop = loop + self._relay_observes_chunks = True + try: + self._stream = loop.run_until_complete( + runtime.run_in_session_async( + session, + runtime.relay.llm.stream_execute, + name, + relay_request, + provider_stream, + observe_chunk, + relay_finalizer, + handle=parent, + metadata=_jsonable(metadata or {}), + model_name=model_name, + codec=_codec(runtime.relay, metadata), + response_codec=_codec(runtime.relay, metadata), + ) + ) + except BaseException as exc: + if ( + isinstance(exc, Exception) + and self._provider_completed + and self._callback_error is None + ): + logger.warning( + "NeMo Relay stream post-processing failed after provider success; " + "preserving the provider result", + exc_info=True, + ) + self._preserve_pending_provider_chunks() + return + if not self._defer_logical_completion: + _complete_logical( + self._logical, + outcome="cancelled" if _is_cancellation(exc) else "failed", + ) + self._logical = None + loop.close() + self._loop = None + raise + + def __iter__(self) -> "ManagedLlmStream": + return self + + def __next__(self) -> Any: + if self._closed: + raise StopIteration + if self._loop is None: + try: + chunk = next(self._stream) + except StopIteration: + self._close(logical_outcome="cancelled") + raise + if self._accept_chunk is not None and not self._accept_chunk(chunk): + self._close(logical_outcome="cancelled") + raise StopIteration + return chunk + + async def next_chunk() -> Any: + return await anext(self._stream) + + try: + chunk = self._loop.run_until_complete(next_chunk()) + except StopAsyncIteration: + if self._raw_chunks: + self.output_modified = True + if not self._defer_logical_completion: + _complete_logical(self._logical, outcome="success") + self._logical = None + self._close(logical_outcome="cancelled") + raise StopIteration from None + except BaseException as exc: + callback_error = self._callback_error + if ( + callback_error is not None + and relay_runtime._is_relay_wrapped_callback_error(exc, callback_error) + ): + self._close(logical_outcome="failed") + raise callback_error + if ( + isinstance(exc, Exception) + and self._provider_completed + and callback_error is None + ): + logger.warning( + "NeMo Relay stream post-processing failed after provider success; " + "preserving the provider result", + exc_info=True, + ) + self._preserve_pending_provider_chunks() + return next(self) + self._close( + logical_outcome="cancelled" if _is_cancellation(exc) else "failed" + ) + raise + if not self._relay_observes_chunks and self._on_chunk is not None: + self._on_chunk(chunk) + for index, (encoded, raw) in enumerate(self._raw_chunks): + if _json_equal(chunk, encoded): + if index > 0: + self.output_modified = True + del self._raw_chunks[: index + 1] + return raw + self.output_modified = True + return self._chunk_adapter(chunk) + + def close(self) -> None: + """Close an explicitly abandoned stream and cancel its logical call.""" + self._close(logical_outcome="cancelled") + close_error = self._close_error + self._close_error = None + if close_error is not None: + raise close_error + + def _preserve_pending_provider_chunks(self) -> None: + """Switch a failed Relay stream to its undelivered provider chunks.""" + pending = [raw for _encoded, raw in self._raw_chunks] + self._raw_chunks.clear() + loop = self._loop + relay_stream = self._stream + self._loop = None + self._stream = iter(pending) + self._raw_stream_resource = None + self._accept_chunk = None + if loop is not None: + close = getattr(relay_stream, "aclose", None) + if callable(close): + + async def close_stream() -> None: + await close() + + try: + loop.run_until_complete(close_stream()) + except Exception: + logger.debug( + "Relay stream cleanup failed during provider fallback", + exc_info=True, + ) + loop.close() + if not self._defer_logical_completion: + _complete_logical(self._logical, outcome="success") + self._logical = None + + def _close(self, *, logical_outcome: str) -> None: + if self._closed: + return + self._closed = True + loop = self._loop + self._loop = None + if loop is None: + resources = (self._stream, self._raw_stream_resource) + self._stream = None + self._raw_stream_resource = None + closed_ids: set[int] = set() + for resource in resources: + if resource is None or id(resource) in closed_ids: + continue + closed_ids.add(id(resource)) + close = getattr(resource, "close", None) + if callable(close): + try: + close() + except Exception as exc: + if self._close_error is None: + self._close_error = exc + logger.debug( + "Provider stream cleanup failed", + exc_info=True, + ) + if not self._defer_logical_completion: + _complete_logical(self._logical, outcome=logical_outcome) + self._logical = None + return + close = getattr(self._stream, "aclose", None) + if callable(close): + + async def close_stream() -> None: + await close() + + try: + loop.run_until_complete(close_stream()) + except Exception as exc: + if self._close_error is None: + self._close_error = exc + if not self._defer_logical_completion: + _complete_logical(self._logical, outcome=logical_outcome) + self._logical = None + loop.close() + + def __del__(self) -> None: + self._close(logical_outcome="cancelled") + + +class AnthropicStreamAccumulator: + """Rebuild an Anthropic Message from post-intercept SSE events.""" + + def __init__(self) -> None: + self._message: dict[str, Any] = {} + self._blocks: dict[int, dict[str, Any]] = {} + + def observe(self, event: Any) -> None: + payload = _jsonable(event) + if not isinstance(payload, dict): + return + event_type = payload.get("type") + if event_type == "message_start": + message = payload.get("message") + if isinstance(message, dict): + for key in ("id", "type", "role", "model", "usage"): + if key in message: + self._message[key] = message[key] + return + if event_type == "content_block_start": + index = payload.get("index") + block = payload.get("content_block") + if isinstance(index, int) and isinstance(block, dict): + self._blocks[index] = dict(block) + return + if event_type == "content_block_delta": + index = payload.get("index") + delta = payload.get("delta") + if not isinstance(index, int) or not isinstance(delta, dict): + return + block = self._blocks.setdefault(index, {}) + delta_type = delta.get("type") + if delta_type == "text_delta": + block["text"] = str(block.get("text") or "") + str( + delta.get("text") or "" + ) + elif delta_type == "thinking_delta": + block["thinking"] = str(block.get("thinking") or "") + str( + delta.get("thinking") or "" + ) + elif delta_type == "signature_delta": + block["signature"] = str(block.get("signature") or "") + str( + delta.get("signature") or "" + ) + elif delta_type == "input_json_delta": + partial = str(block.pop("_partial_json", "")) + str( + delta.get("partial_json") or "" + ) + block["_partial_json"] = partial + elif delta_type == "citations_delta" and "citation" in delta: + block.setdefault("citations", []).append(delta["citation"]) + return + if event_type == "message_delta": + delta = payload.get("delta") + if isinstance(delta, dict): + for key in ("stop_reason", "stop_sequence"): + if key in delta: + self._message[key] = delta[key] + if "usage" in payload: + usage = payload["usage"] + current_usage = self._message.get("usage") + if isinstance(current_usage, dict) and isinstance(usage, dict): + self._message["usage"] = {**current_usage, **usage} + else: + self._message["usage"] = usage + + def finalize(self) -> dict[str, Any]: + blocks = [] + for index in sorted(self._blocks): + block = dict(self._blocks[index]) + partial = block.pop("_partial_json", None) + if partial is not None: + try: + block["input"] = json.loads(partial) + except (TypeError, ValueError): + block["input"] = partial + blocks.append(block) + return {**self._message, "content": blocks} + + def response(self, base: Any = None) -> Any: + """Return the attribute-shaped response consumed by Hermes.""" + assembled = self.finalize() + base_payload = _jsonable(base) + if not isinstance(base_payload, dict): + base_payload = {} + content = assembled.pop("content", []) + merged = {**base_payload, **assembled} + if content or "content" not in merged: + merged["content"] = content + return _namespace(merged) + + +def _logical_parent( + runtime: relay_runtime.RelayRuntime, + session: Any, + parent: Any, + metadata: dict[str, Any] | None, +) -> tuple[relay_runtime.RelayTurnContext, Any, str] | None: + turn = relay_runtime.active_turn(session.session_id) + request_id = str((metadata or {}).get("api_request_id") or "") + if turn is None or not request_id or turn.lease.host is not runtime: + return None + with turn.finalize_lock: + if turn.closed: + return None + with turn.logical_llm_lock: + handle = turn.logical_llm_calls.get(request_id) + if handle is None: + handle = runtime.run_in_session( + session, + runtime.relay.scope.push, + relay_runtime.LOGICAL_LLM_SCOPE, + runtime.relay.ScopeType.Function, + handle=parent, + input={}, + metadata={ + relay_runtime.RUNTIME_SCHEMA_KEY: relay_runtime.RUNTIME_SCHEMA_VERSION, + relay_runtime.RUNTIME_INSTANCE_KEY: runtime.runtime_id, + "hermes.call_role": str( + (metadata or {}).get("call_role") or "primary" + ), + }, + ) + turn.logical_llm_calls[request_id] = handle + return turn, handle, request_id + + +def _complete_logical( + logical: tuple[relay_runtime.RelayTurnContext, Any, str] | None, + *, + outcome: str, +) -> None: + if logical is None: + return + turn, handle, request_id = logical + lease = turn.lease + if not isinstance(lease.host, relay_runtime.RelayRuntime): + return + with turn.finalize_lock: + with turn.logical_llm_lock: + if turn.logical_llm_calls.get(request_id) is not handle: + return + if lease.session is None: + return + try: + lease.host.run_in_session( + lease.session, + lease.host.relay.scope.pop, + handle, + output={"outcome": outcome}, + metadata={ + relay_runtime.RUNTIME_SCHEMA_KEY: relay_runtime.RUNTIME_SCHEMA_VERSION, + relay_runtime.RUNTIME_INSTANCE_KEY: lease.host.runtime_id, + }, + ) + except Exception: + # The provider result is authoritative. Retain the handle so turn + # finalization can retry cleanup without changing that result. + logger.warning( + "Hermes Relay logical LLM finalization failed", + exc_info=True, + ) + return + with turn.logical_llm_lock: + if turn.logical_llm_calls.get(request_id) is handle: + turn.logical_llm_calls.pop(request_id, None) + + +def _recover_successful_callback( + raw_response: dict[str, Any], + *, + relay_error: BaseException, + callback_error: BaseException | None, + logical: tuple[relay_runtime.RelayTurnContext, Any, str] | None, + defer_logical_completion: bool, +) -> bool: + if ( + not isinstance(relay_error, Exception) + or callback_error is not None + or "value" not in raw_response + ): + return False + logger.warning( + "NeMo Relay LLM post-processing failed after provider success; " + "returning the provider response", + exc_info=True, + ) + if not defer_logical_completion: + _complete_logical(logical, outcome="success") + return True + + +def _is_cancellation(error: BaseException) -> bool: + return isinstance( + error, + (asyncio.CancelledError, InterruptedError, KeyboardInterrupt), + ) + + +def complete_logical_call(api_request_id: str, *, outcome: str) -> None: + """Complete the active turn's logical LLM call after caller validation.""" + turn = relay_runtime.active_turn() + if turn is None or not api_request_id: + return + with turn.logical_llm_lock: + handle = turn.logical_llm_calls.get(api_request_id) + if handle is not None: + _complete_logical((turn, handle, api_request_id), outcome=outcome) + + +def _provider_request( + original: dict[str, Any], + request: Any, + *, + relay_request_body: dict[str, Any], + codec_baseline_body: dict[str, Any] | None, + metadata: dict[str, Any] | None, +) -> dict[str, Any]: + content = getattr(request, "content", request) + if not isinstance(content, dict): + content = relay_request_body + if codec_baseline_body is None or _json_equal(content, relay_request_body): + final = dict(original) + else: + baseline = codec_baseline_body + intercepted = _provider_request_body(content, metadata) + final = dict(original) + # Typed codecs may not represent provider-specific fields. Overlay only + # values that changed from the codec-facing baseline so unrelated + # intercepts cannot delete or normalize unknown provider arguments. + for key in baseline.keys() | intercepted.keys(): + if key not in intercepted: + final.pop(key, None) + elif key not in baseline or not _json_equal( + intercepted[key], + baseline[key], + ): + final[key] = intercepted[key] + _restore_provider_message_extensions( + original, + final, + baseline=baseline, + intercepted=intercepted, + ) + headers = getattr(request, "headers", None) + if isinstance(headers, dict): + headers = { + key: value + for key, value in headers.items() + if str(key).lower() not in _RELAY_INTERNAL_PROVIDER_HEADERS + } + if headers: + final["extra_headers"] = { + **dict(final.get("extra_headers") or {}), + **headers, + } + return final + + +def _relay_request_body( + request: dict[str, Any], metadata: dict[str, Any] | None +) -> dict[str, Any]: + body = _jsonable(request) + if not isinstance(body, dict): + return {} + # The Responses SDK accepts ``tools=None`` as "no tools", while Relay's + # typed Responses codec correctly expects either an array or an absent + # field. Normalize only the codec-facing copy; the original provider + # request is restored when no interceptor changes it. + if str((metadata or {}).get("api_mode") or "") == "codex_responses": + body = dict(body) + if body.get("tools") is None: + body.pop("tools", None) + elif isinstance(body.get("tools"), list): + body["tools"] = [ + { + "type": "function", + "function": { + key: value + for key, value in tool.items() + if key != "type" + }, + } + if isinstance(tool, dict) + and tool.get("type") == "function" + and "function" not in tool + else tool + for tool in body["tools"] + ] + elif str((metadata or {}).get("api_mode") or "") == "chat_completions": + tools = body.get("tools") + if isinstance(tools, list): + body = dict(body) + body["tools"] = [ + {"type": "function", **tool} + if isinstance(tool, dict) + and "function" in tool + and "type" not in tool + else tool + for tool in tools + ] + return body + + +def _restore_provider_message_extensions( + original: dict[str, Any], + final: dict[str, Any], + *, + baseline: dict[str, Any], + intercepted: dict[str, Any], +) -> None: + """Restore provider wire fields that Relay's typed codec cannot represent.""" + original_messages = original.get("messages") + final_messages = final.get("messages") + baseline_messages = baseline.get("messages") + intercepted_messages = intercepted.get("messages") + if not all( + isinstance(messages, list) + for messages in ( + original_messages, + final_messages, + baseline_messages, + intercepted_messages, + ) + ): + return + if not ( + len(original_messages) + == len(final_messages) + == len(baseline_messages) + == len(intercepted_messages) + ): + return + for original_message, final_message, baseline_message, intercepted_message in zip( + original_messages, + final_messages, + baseline_messages, + intercepted_messages, + strict=True, + ): + if not all( + isinstance(message, dict) + for message in ( + original_message, + final_message, + baseline_message, + intercepted_message, + ) + ): + continue + for key in _PROVIDER_MESSAGE_EXTENSION_KEYS: + if ( + key in original_message + and key not in baseline_message + and key not in intercepted_message + and key not in final_message + ): + final_message[key] = original_message[key] + + +def _codec_round_trip_request_body( + relay: Any, + relay_request: Any, + *, + relay_request_body: dict[str, Any], + metadata: dict[str, Any] | None, +) -> dict[str, Any] | None: + """Return the codec-only request shape used to identify real rewrites.""" + codec = _codec(relay, metadata) + if codec is None: + return _provider_request_body(relay_request_body, metadata) + try: + annotated = codec.decode(relay_request) + encoded = codec.encode(annotated, relay_request) + content = getattr(encoded, "content", encoded) + if isinstance(content, dict): + return _provider_request_body(content, metadata) + except Exception: + logger.warning( + "NeMo Relay request codec baseline failed; ignoring request rewrites", + exc_info=True, + ) + return None + logger.warning( + "NeMo Relay request codec returned an unsupported baseline; " + "ignoring request rewrites" + ) + return None + + +def _provider_request_body( + content: dict[str, Any], metadata: dict[str, Any] | None +) -> dict[str, Any]: + body = dict(content) + if str((metadata or {}).get("api_mode") or "") != "codex_responses": + return body + tools = body.get("tools") + if not isinstance(tools, list): + return body + body["tools"] = [ + { + "type": "function", + **dict(tool["function"]), + } + if isinstance(tool, dict) + and tool.get("type") == "function" + and isinstance(tool.get("function"), dict) + else tool + for tool in tools + ] + return body + + +def _codec(relay: Any, metadata: dict[str, Any] | None) -> Any: + api_mode = str((metadata or {}).get("api_mode") or "") + codecs = getattr(relay, "codecs", None) + if codecs is None: + return None + if api_mode == "chat_completions": + codec = getattr(codecs, "OpenAIChatCodec", None) + elif api_mode == "anthropic_messages": + codec = getattr(codecs, "AnthropicMessagesCodec", None) + elif api_mode == "codex_responses": + codec = getattr(codecs, "OpenAIResponsesCodec", None) + else: + codec = None + return codec() if callable(codec) else None + + +def _jsonable(value: Any) -> Any: + if value is None or isinstance(value, (str, int, float, bool)): + return value + if isinstance(value, dict): + return {str(key): _jsonable(item) for key, item in value.items()} + if isinstance(value, (list, tuple, set)): + return [_jsonable(item) for item in value] + model_dump = getattr(type(value), "model_dump", None) + if callable(model_dump): + try: + return _jsonable(value.model_dump(mode="json")) + except Exception: + pass + try: + attributes = { + str(key): item + for key, item in vars(value).items() + if not str(key).startswith("_") + } + except (TypeError, AttributeError): + return str(value) + return _jsonable(attributes) if attributes else str(value) + + +def _namespace(value: Any) -> Any: + if isinstance(value, dict): + return SimpleNamespace(**{ + str(key): _namespace(item) for key, item in value.items() + }) + if isinstance(value, list): + return [_namespace(item) for item in value] + return value + + +def _json_equal(left: Any, right: Any) -> bool: + try: + return json.dumps( + _jsonable(left), sort_keys=True, separators=(",", ":") + ) == json.dumps(_jsonable(right), sort_keys=True, separators=(",", ":")) + except (TypeError, ValueError): + return False + + +def _run_awaitable(value: Any) -> Any: + if not inspect.isawaitable(value): + return value + try: + asyncio.get_running_loop() + except RuntimeError: + return asyncio.run(value) + raise RuntimeError( + "Synchronous Relay LLM execution cannot run on an event-loop thread" + ) diff --git a/agent/relay_runtime.py b/agent/relay_runtime.py new file mode 100644 index 000000000000..533604791a86 --- /dev/null +++ b/agent/relay_runtime.py @@ -0,0 +1,1002 @@ +"""Profile-scoped NeMo Relay runtimes owned by the Hermes agent core.""" + +from __future__ import annotations + +import atexit +import asyncio +import contextvars +import importlib +import inspect +import logging +import threading +import uuid +from dataclasses import dataclass, field +from typing import Any, Callable + +from hermes_constants import get_hermes_home + +logger = logging.getLogger(__name__) + +SESSION_SCOPE = "hermes.session" +TURN_SCOPE = "hermes.turn" +LOGICAL_LLM_SCOPE = "hermes.logical_llm_call" +RUNTIME_SCHEMA_KEY = "hermes.relay.schema_version" +RUNTIME_SCHEMA_VERSION = "hermes.relay.runtime.v1" +RUNTIME_INSTANCE_KEY = "hermes.relay.runtime_instance" +_PROFILE_KEY_CACHE: dict[str, str] = {} + + +@dataclass +class RelaySession: + """One isolated Relay scope stack owned by a Hermes session.""" + + session_id: str + parent_session_id: str = "" + lock: threading.RLock = field(default_factory=threading.RLock, repr=False) + closing: bool = False + handle: Any = None + context: contextvars.Context | None = None + + +class RelayRuntime: + """Own Relay session scopes independently of any exporter or plugin.""" + + def __init__(self, relay: Any = None, *, profile_key: str | None = None) -> None: + self.relay = relay or _load_nemo_relay() + self.profile_key = profile_key or current_profile_key() + self.runtime_id = uuid.uuid4().hex + self._sessions_lock = threading.RLock() + self._sessions: dict[str, RelaySession] = {} + self._subagent_parents: dict[str, str] = {} + self._subagent_parent_handles: dict[str, Any] = {} + self._execution_consumers_lock = threading.RLock() + self._execution_consumers: set[str] = set() + self._shutdown_registered = True + atexit.register(self.shutdown) + + def retain_managed_execution(self, consumer: str) -> None: + """Keep managed LLM and tool execution active for one consumer.""" + if not consumer: + raise ValueError("Relay managed-execution consumer must not be empty") + with self._execution_consumers_lock: + self._execution_consumers.add(consumer) + + def release_managed_execution(self, consumer: str) -> None: + """Release a consumer's managed-execution requirement.""" + with self._execution_consumers_lock: + self._execution_consumers.discard(consumer) + + def managed_execution_enabled(self) -> bool: + """Return whether a Hermes-managed consumer needs the Relay pipeline.""" + with self._execution_consumers_lock: + return bool(self._execution_consumers) + + def ensure_session( + self, + event: dict[str, Any], + *, + data: Any = None, + metadata: dict[str, Any] | None = None, + ) -> RelaySession | None: + """Return the existing session scope or create it once.""" + session_id = _session_id(event) + if not session_id: + return None + with self._sessions_lock: + session = self._sessions.get(session_id) + if session is None: + parent_session_id = self._subagent_parents.get(session_id, "") + session = RelaySession( + session_id=session_id, + parent_session_id=parent_session_id, + ) + self._sessions[session_id] = session + with session.lock: + if session.closing: + return None + if session.handle is None: + parent_handle = None + scope_metadata = { + **(metadata or {}), + RUNTIME_SCHEMA_KEY: RUNTIME_SCHEMA_VERSION, + RUNTIME_INSTANCE_KEY: self.runtime_id, + } + if session.parent_session_id: + with self._sessions_lock: + parent_handle = self._subagent_parent_handles.get(session_id) + if parent_handle is None: + parent = self.ensure_session({ + "session_id": session.parent_session_id + }) + if parent is not None: + parent_handle = parent.handle + scope_metadata["nemo_relay_scope_role"] = "subagent" + context = contextvars.Context() + try: + session.handle = context.run( + self.relay.scope.push, + SESSION_SCOPE, + self.relay.ScopeType.Agent, + handle=parent_handle, + data=data, + input={}, + metadata=scope_metadata, + ) + except Exception: + session.context = None + raise + session.context = context + return session + + def register_subagent( + self, + event: dict[str, Any], + *, + metadata: dict[str, Any] | None = None, + ) -> RelaySession | None: + """Open a child Agent scope under its spawning turn when available.""" + parent_session_id = str(event.get("parent_session_id") or "") + child_session_id = str(event.get("child_session_id") or "") + if ( + not parent_session_id + or not child_session_id + or parent_session_id == child_session_id + ): + return None + parent = self.ensure_session({"session_id": parent_session_id}) + parent_handle = None if parent is None else parent.handle + turn = active_turn(parent_session_id) + if ( + turn is not None + and not turn.closed + and turn.handle is not None + and turn.lease.host is self + and turn.lease.session is not None + and turn.lease.session.session_id == parent_session_id + ): + parent_handle = turn.handle + with self._sessions_lock: + self._subagent_parents[child_session_id] = parent_session_id + if parent_handle is not None: + self._subagent_parent_handles[child_session_id] = parent_handle + return self.ensure_session( + {"session_id": child_session_id}, + metadata=metadata, + ) + + def unregister_subagent(self, event: dict[str, Any]) -> None: + """Close a delegated session and forget its parent relationship.""" + child_session_id = str(event.get("child_session_id") or "") + if not child_session_id: + return + self.close_session({"session_id": child_session_id}) + with self._sessions_lock: + self._subagent_parents.pop(child_session_id, None) + self._subagent_parent_handles.pop(child_session_id, None) + + def get_session(self, session_id: str) -> RelaySession | None: + """Return an active Hermes Relay session without creating one.""" + with self._sessions_lock: + session = self._sessions.get(str(session_id or "")) + if session is None: + return None + with session.lock: + return None if session.closing else session + + def get_session_handle(self, session_id: str) -> Any: + """Return the Relay parent handle for a Hermes session, if active.""" + session = self.get_session(session_id) + return None if session is None else session.handle + + def run_in_session( + self, + session: RelaySession, + callback: Callable[..., Any], + *args: Any, + allow_closing: bool = False, + **kwargs: Any, + ) -> Any: + """Run a Relay operation against a session's isolated scope stack.""" + with session.lock: + if session.closing and not allow_closing: + raise RuntimeError("Hermes Relay session is closing") + if session.context is None or session.handle is None: + raise RuntimeError("Hermes Relay session context is unavailable") + relay_context = session.context.copy() + + context = contextvars.copy_context() + for variable, value in relay_context.items(): + context.run(variable.set, value) + + def invoke() -> Any: + self.relay.get_scope_stack() + return callback(*args, **kwargs) + + # A copy permits a helper called by an existing Relay callback to + # re-enter the same logical session without re-entering Context. + return context.run(invoke) + + async def run_in_session_async( + self, + session: RelaySession, + callback: Callable[..., Any], + *args: Any, + allow_closing: bool = False, + **kwargs: Any, + ) -> Any: + """Create and await an operation inside the session's saved context.""" + with session.lock: + if session.closing and not allow_closing: + raise RuntimeError("Hermes Relay session is closing") + if session.context is None or session.handle is None: + raise RuntimeError("Hermes Relay session context is unavailable") + relay_context = session.context.copy() + + context = contextvars.copy_context() + for variable, value in relay_context.items(): + context.run(variable.set, value) + + async def invoke() -> Any: + self.relay.get_scope_stack() + result = callback(*args, **kwargs) + if inspect.isawaitable(result): + return await result + return result + + task = context.run(asyncio.create_task, invoke()) + return await task + + def emit_mark( + self, + name: str, + event: dict[str, Any], + *, + data: Any = None, + metadata: Any = None, + ) -> bool: + """Emit a mark parented to the Hermes session identified by ``event``.""" + session = self.ensure_session(event) + if session is None: + return False + self.run_in_session( + session, + self.relay.scope.event, + name, + handle=session.handle, + data=data, + metadata=metadata, + ) + return True + + def apply_tool_request_intercepts( + self, + *, + session_id: str, + tool_name: str, + args: dict[str, Any], + ) -> dict[str, Any]: + """Apply Relay request rewriting before Hermes authorizes a tool call.""" + if not self.managed_execution_enabled(): + return args + request_intercepts = getattr( + getattr(self.relay, "tools", None), + "request_intercepts", + None, + ) + if not callable(request_intercepts): + return args + session = self.ensure_session({"session_id": session_id}) + if session is None: + return args + result = self.run_in_session( + session, + request_intercepts, + tool_name, + args, + ) + return result if isinstance(result, dict) else args + + def close_session(self, event: dict[str, Any]) -> None: + """Close one session scope and remove it from the core registry.""" + session_id = _session_id(event) + with self._sessions_lock: + session = self._sessions.get(session_id) + if session is None: + with self._sessions_lock: + self._subagent_parents.pop(session_id, None) + self._subagent_parent_handles.pop(session_id, None) + return + failures: list[str] = [] + with session.lock: + if session.closing: + return + session.closing = True + if session.handle is not None: + try: + self.run_in_session( + session, + self.relay.scope.pop, + session.handle, + output={}, + metadata={ + RUNTIME_SCHEMA_KEY: RUNTIME_SCHEMA_VERSION, + RUNTIME_INSTANCE_KEY: self.runtime_id, + }, + allow_closing=True, + ) + except Exception as exc: + failures.append(f"session scope close failed: {exc}") + try: + self.relay.subscribers.flush() + except Exception as exc: + failures.append(f"subscriber flush failed: {exc}") + with self._sessions_lock: + if self._sessions.get(session_id) is session: + self._sessions.pop(session_id, None) + self._subagent_parents.pop(session_id, None) + self._subagent_parent_handles.pop(session_id, None) + if failures: + logger.warning( + "Hermes Relay session %s closed with errors: %s", + session_id, + "; ".join(failures), + ) + + def shutdown(self) -> None: + """Close all core-owned Relay session scopes.""" + with self._sessions_lock: + session_ids = list(self._sessions) + for session_id in session_ids: + self._safe(self.close_session, {"session_id": session_id}) + if self._shutdown_registered: + try: + atexit.unregister(self.shutdown) + except Exception: + pass + self._shutdown_registered = False + + @staticmethod + def _safe(callback: Callable[..., Any], *args: Any, **kwargs: Any) -> Any: + try: + return callback(*args, **kwargs) + except Exception: + logger.warning("Hermes Relay runtime operation failed", exc_info=True) + return None + + +@dataclass(frozen=True) +class NoopRelayRuntime: + """Explicit reduced-capability host for platforms without Relay wheels.""" + + profile_key: str + reason: str + + @property + def available(self) -> bool: + return False + + def apply_tool_request_intercepts( + self, + *, + session_id: str, + tool_name: str, + args: dict[str, Any], + ) -> dict[str, Any]: + del session_id, tool_name + return args + + @staticmethod + def retain_managed_execution(consumer: str) -> None: + del consumer + + @staticmethod + def release_managed_execution(consumer: str) -> None: + del consumer + + @staticmethod + def managed_execution_enabled() -> bool: + return False + + def shutdown(self) -> None: + """No resources are allocated on unsupported platforms.""" + + +RelayHost = RelayRuntime | NoopRelayRuntime + + +class RelayHostRegistry: + """Own exactly one Relay host for each canonical Hermes profile.""" + + def __init__(self) -> None: + self._lock = threading.RLock() + self._hosts: dict[str, RelayHost] = {} + + def for_profile( + self, + profile_key: str | None = None, + *, + create: bool = True, + ) -> RelayHost | None: + key = profile_key or current_profile_key() + host = self._hosts.get(key) + if host is not None or not create: + return host + with self._lock: + host = self._hosts.get(key) + if host is not None or not create: + return host + try: + host = RelayRuntime(profile_key=key) + except Exception as exc: + logger.warning( + "Hermes Relay runtime initialization failed", exc_info=True + ) + host = NoopRelayRuntime(profile_key=key, reason=str(exc)) + self._hosts[key] = host + return host + + def shutdown_profile(self, profile_key: str) -> None: + with self._lock: + host = self._hosts.pop(profile_key, None) + if host is not None: + host.shutdown() + + def shutdown_all(self) -> None: + with self._lock: + hosts = list(self._hosts.values()) + self._hosts.clear() + for host in hosts: + host.shutdown() + + +HOST_REGISTRY = RelayHostRegistry() + + +@dataclass +class ConversationLease: + """A resumable reference to one profile-scoped conversation scope.""" + + profile_key: str + session_id: str + platform: str + host: RelayHost + session: RelaySession | None + parent_session_id: str = "" + released: bool = False + + +@dataclass +class RelayTurnContext: + """Runtime-only context for one Hermes turn or top-level task.""" + + lease: ConversationLease + turn_id: str + task_id: str + handle: Any = None + logical_llm_calls: dict[str, Any] = field(default_factory=dict, repr=False) + logical_llm_lock: threading.RLock = field( + default_factory=threading.RLock, + repr=False, + ) + finalize_lock: threading.RLock = field( + default_factory=threading.RLock, + repr=False, + ) + _token: contextvars.Token[RelayTurnContext | None] | None = field( + default=None, + repr=False, + ) + _active_registered: bool = field(default=False, repr=False) + closed: bool = False + + +_CURRENT_TURN: contextvars.ContextVar[RelayTurnContext | None] = contextvars.ContextVar( + "hermes_relay_turn", default=None +) + + +class RelaySessionCoordinator: + """Own semantic conversation and turn lifetimes for Hermes core.""" + + def __init__(self, registry: RelayHostRegistry = HOST_REGISTRY) -> None: + self.registry = registry + self._initializer_lock = threading.RLock() + self._session_initializers: dict[ + str, + Callable[[RelayRuntime, dict[str, Any]], None], + ] = {} + self._active_turns_lock = threading.RLock() + self._active_turns: dict[tuple[str, str], set[int]] = {} + + def register_session_initializer( + self, + name: str, + callback: Callable[[RelayRuntime, dict[str, Any]], None], + ) -> None: + """Register idempotent profile/session preparation before scope creation.""" + with self._initializer_lock: + self._session_initializers[name] = callback + + def unregister_session_initializer(self, name: str) -> None: + """Remove a previously registered session initializer.""" + with self._initializer_lock: + self._session_initializers.pop(name, None) + + def _prepare_session( + self, + host: RelayRuntime, + context: dict[str, Any], + ) -> None: + with self._initializer_lock: + initializers = list(self._session_initializers.items()) + for name, callback in initializers: + try: + callback(host, context) + except Exception: + logger.warning( + "Hermes Relay session initializer failed: %s", + name, + exc_info=True, + ) + + def acquire_conversation( + self, + *, + profile_key: str, + session_id: str, + platform: str, + parent_session_id: str = "", + model: str = "", + ) -> ConversationLease: + host = self.registry.for_profile(profile_key) + if host is None: + host = NoopRelayRuntime(profile_key, "Relay host creation was disabled") + session = None + if isinstance(host, RelayRuntime): + try: + session_context = { + "profile_key": profile_key, + "session_id": session_id, + "platform": platform, + "parent_session_id": parent_session_id, + "model": model, + } + self._prepare_session(host, session_context) + metadata = {"hermes.execution_surface": platform or "unknown"} + if parent_session_id and parent_session_id != session_id: + session = host.register_subagent( + { + "parent_session_id": parent_session_id, + "child_session_id": session_id, + }, + metadata=metadata, + ) + else: + session = host.ensure_session( + {"session_id": session_id}, + metadata=metadata, + ) + except Exception: + logger.warning( + "Hermes Relay conversation initialization failed", + exc_info=True, + ) + return ConversationLease( + profile_key=profile_key, + session_id=session_id, + platform=platform, + host=host, + session=session, + parent_session_id=parent_session_id, + ) + + def begin_turn( + self, + lease: ConversationLease, + *, + turn_id: str, + task_id: str, + ) -> RelayTurnContext: + if lease.released: + raise RuntimeError("Hermes Relay conversation lease is released") + turn = RelayTurnContext(lease=lease, turn_id=turn_id, task_id=task_id) + if isinstance(lease.host, RelayRuntime) and lease.session is not None: + try: + turn.handle = lease.host.run_in_session( + lease.session, + lease.host.relay.scope.push, + TURN_SCOPE, + lease.host.relay.ScopeType.Function, + handle=lease.session.handle, + input={}, + metadata={ + RUNTIME_SCHEMA_KEY: RUNTIME_SCHEMA_VERSION, + RUNTIME_INSTANCE_KEY: lease.host.runtime_id, + "hermes.execution_surface": lease.platform or "unknown", + }, + ) + except Exception: + logger.warning("Hermes Relay turn initialization failed", exc_info=True) + turn._token = _CURRENT_TURN.set(turn) + key = (lease.profile_key, lease.session_id) + with self._active_turns_lock: + self._active_turns.setdefault(key, set()).add(id(turn)) + turn._active_registered = True + return turn + + def end_turn( + self, + turn: RelayTurnContext, + *, + outcome: str, + ) -> None: + with turn.finalize_lock: + if turn.closed: + self._reset_turn_context(turn) + return + turn.closed = True + lease = turn.lease + try: + if isinstance(lease.host, RelayRuntime) and lease.session is not None: + self._finish_logical_calls(turn, outcome=outcome) + if turn.handle is not None: + try: + lease.host.run_in_session( + lease.session, + lease.host.relay.scope.pop, + turn.handle, + output={"outcome": outcome}, + metadata={ + RUNTIME_SCHEMA_KEY: RUNTIME_SCHEMA_VERSION, + RUNTIME_INSTANCE_KEY: lease.host.runtime_id, + }, + ) + except Exception: + logger.warning( + "Hermes Relay turn finalization failed", exc_info=True + ) + finally: + try: + # Delegated agents own one turn. Close their conversation + # while the active-turn guard is still held so a parent + # timeout fallback cannot race this terminal boundary. + if ( + lease.parent_session_id + and isinstance(lease.host, RelayRuntime) + ): + lease.host.unregister_subagent({ + "child_session_id": lease.session_id + }) + except Exception: + logger.warning( + "Hermes Relay child conversation finalization failed", + exc_info=True, + ) + finally: + self._unregister_active_turn(turn) + self._reset_turn_context(turn) + + def has_active_turn(self, *, profile_key: str, session_id: str) -> bool: + """Return whether a turn is still running for one profile/session.""" + key = (profile_key, session_id) + with self._active_turns_lock: + return bool(self._active_turns.get(key)) + + def _unregister_active_turn(self, turn: RelayTurnContext) -> None: + if not turn._active_registered: + return + key = (turn.lease.profile_key, turn.lease.session_id) + with self._active_turns_lock: + active = self._active_turns.get(key) + if active is not None: + active.discard(id(turn)) + if not active: + self._active_turns.pop(key, None) + turn._active_registered = False + + def _reset_active_turns_for_tests(self) -> None: + with self._active_turns_lock: + self._active_turns.clear() + + def finish_logical_calls( + self, + turn: RelayTurnContext, + *, + outcome: str, + ) -> None: + """Close logical LLM children before sibling task aggregation scopes.""" + with turn.finalize_lock: + if turn.closed: + return + self._finish_logical_calls(turn, outcome=outcome) + + @staticmethod + def _finish_logical_calls( + turn: RelayTurnContext, + *, + outcome: str, + ) -> None: + lease = turn.lease + if not isinstance(lease.host, RelayRuntime) or lease.session is None: + return + with turn.logical_llm_lock: + logical_calls = list(turn.logical_llm_calls.items()) + turn.logical_llm_calls.clear() + for index in range(len(logical_calls) - 1, -1, -1): + request_id, logical_handle = logical_calls[index] + try: + lease.host.run_in_session( + lease.session, + lease.host.relay.scope.pop, + logical_handle, + output={"outcome": outcome}, + metadata={ + RUNTIME_SCHEMA_KEY: RUNTIME_SCHEMA_VERSION, + RUNTIME_INSTANCE_KEY: lease.host.runtime_id, + }, + ) + except Exception: + with turn.logical_llm_lock: + # Relay scopes are stack-owned. If the newest remaining + # handle cannot close, older handles cannot close safely + # either, so retain the unclosed prefix for diagnostics. + for pending_request_id, pending_handle in logical_calls[ + : index + 1 + ]: + turn.logical_llm_calls.setdefault( + pending_request_id, + pending_handle, + ) + logger.warning( + "Hermes Relay logical LLM finalization failed", + exc_info=True, + ) + break + + @staticmethod + def _reset_turn_context(turn: RelayTurnContext) -> None: + """Reset the originating ContextVar token when called in that context.""" + if turn._token is None: + return + try: + _CURRENT_TURN.reset(turn._token) + except ValueError: + # A copied async/thread context may own terminal cleanup. Keep the + # token so the originating context can clear its stale reference. + return + turn._token = None + + @staticmethod + def release_conversation(lease: ConversationLease) -> None: + """Release a caller lease without closing a resumable conversation.""" + lease.released = True + + def finalize_conversation( + self, + *, + profile_key: str, + session_id: str, + ) -> None: + host = self.registry.for_profile(profile_key, create=False) + if isinstance(host, RelayRuntime): + host.close_session({"session_id": session_id}) + + def shutdown_profile(self, profile_key: str) -> None: + self.registry.shutdown_profile(profile_key) + + +SESSION_COORDINATOR = RelaySessionCoordinator() + + +def current_turn() -> RelayTurnContext | None: + """Return the turn context inherited by current async and thread work.""" + return _CURRENT_TURN.get() + + +def active_turn(session_id: str | None = None) -> RelayTurnContext | None: + """Return a live turn only when it belongs to the active profile/session.""" + turn = current_turn() + if turn is None or turn.closed or turn.lease.released: + return None + if turn.lease.profile_key != current_profile_key(): + return None + if session_id is not None and turn.lease.session_id != session_id: + return None + if isinstance(turn.lease.host, RelayRuntime): + if turn.lease.session is None: + return None + if turn.lease.host.get_session(turn.lease.session_id) is not turn.lease.session: + return None + return turn + + +def resolve_execution_context( + session_id: str, +) -> tuple[RelayRuntime | None, RelaySession | None, Any]: + """Resolve one active turn/session parent for managed Relay execution.""" + turn = active_turn(session_id) + if ( + turn is not None + and isinstance(turn.lease.host, RelayRuntime) + and turn.lease.session is not None + ): + session = turn.lease.session + return turn.lease.host, session, turn.handle or session.handle + # Managed-execution consumers create and retain the profile host before + # reaching an out-of-turn adapter. Do not initialize Relay for the default + # no-consumer path. + runtime = get_runtime(create=False) + if runtime is None: + return None, None, None + if not runtime.managed_execution_enabled(): + return None, None, None + session = runtime.get_session(session_id) + if session is None: + session = runtime.ensure_session({"session_id": session_id}) + return runtime, session, None if session is None else session.handle + + +def emit_mark( + name: str, + *, + session_id: str, + data: Any = None, + metadata: Any = None, +) -> bool: + """Emit a fail-open Relay mark under a Hermes session.""" + runtime = get_runtime(create=False) + if runtime is None: + return False + try: + return runtime.emit_mark( + name, + {"session_id": session_id}, + data=data, + metadata=metadata, + ) + except Exception: + logger.warning("Hermes Relay mark failed: %s", name, exc_info=True) + return False + + +def apply_tool_request_intercepts( + *, + session_id: str, + tool_name: str, + args: dict[str, Any], +) -> dict[str, Any]: + """Return Relay-rewritten arguments at Hermes's authorization boundary.""" + if not session_id: + return args + runtime = get_runtime(create=False) + if runtime is None: + return args + return runtime.apply_tool_request_intercepts( + session_id=session_id, + tool_name=tool_name, + args=args, + ) + + +def ensure_session(*, session_id: str, **context: Any) -> RelaySession | None: + """Create or return the shared Relay session used by Hermes core.""" + runtime = get_runtime() + if runtime is None: + return None + try: + return runtime.ensure_session({"session_id": session_id, **context}) + except Exception: + logger.warning("Hermes Relay session initialization failed", exc_info=True) + return None + + +def run_in_session( + session_id: str, + callback: Callable[..., Any], + *args: Any, + **kwargs: Any, +) -> Any: + """Run a scope, LLM, or tool API against a shared Hermes session.""" + runtime = get_runtime() + if runtime is None: + raise RuntimeError("Hermes Relay runtime is unavailable") + session = runtime.get_session(session_id) + if session is None: + session = runtime.ensure_session({"session_id": session_id}) + if session is None: + raise RuntimeError("Hermes Relay session is unavailable") + return runtime.run_in_session(session, callback, *args, **kwargs) + + +async def run_in_session_async( + session_id: str, + callback: Callable[..., Any], + *args: Any, + **kwargs: Any, +) -> Any: + """Await a Relay operation inside a shared Hermes session context.""" + runtime = get_runtime() + if runtime is None: + raise RuntimeError("Hermes Relay runtime is unavailable") + session = runtime.get_session(session_id) + if session is None: + session = runtime.ensure_session({"session_id": session_id}) + if session is None: + raise RuntimeError("Hermes Relay session is unavailable") + return await runtime.run_in_session_async(session, callback, *args, **kwargs) + + +def get_session_handle(session_id: str) -> Any: + """Return the shared Relay handle for direct core instrumentation.""" + runtime = get_runtime(create=False) + return None if runtime is None else runtime.get_session_handle(session_id) + + +def _is_relay_wrapped_callback_error( + relay_error: BaseException, + callback_error: BaseException, +) -> bool: + """Match Relay's native callback wrapper without masking policy errors.""" + if relay_error is callback_error: + return True + if not isinstance(relay_error, RuntimeError): + return False + callback_type = callback_error.__class__ + type_names = { + callback_type.__name__, + callback_type.__qualname__, + f"{callback_type.__module__}.{callback_type.__qualname__}", + } + message = str(relay_error) + return any( + message.startswith(f"internal error: {type_name}: {callback_error}") + for type_name in type_names + ) + + +def get_runtime( + *, + create: bool = True, + profile_key: str | None = None, +) -> RelayRuntime | None: + """Return the Relay host for the active Hermes profile.""" + host = HOST_REGISTRY.for_profile(profile_key, create=create) + return host if isinstance(host, RelayRuntime) else None + + +def get_host( + *, + create: bool = True, + profile_key: str | None = None, +) -> RelayHost | None: + """Return the explicit real or reduced-capability host for a profile.""" + return HOST_REGISTRY.for_profile(profile_key, create=create) + + +def current_profile_key() -> str: + """Return the canonical profile identity used for runtime isolation.""" + home = get_hermes_home().expanduser() + if not home.is_absolute(): + return str(home.resolve()) + raw = str(home) + cached = _PROFILE_KEY_CACHE.get(raw) + if cached is not None: + return cached + resolved = str(home.resolve()) + return _PROFILE_KEY_CACHE.setdefault(raw, resolved) + + +def _load_nemo_relay() -> Any: + """Load the binding only when a producer or consumer needs Relay.""" + return importlib.import_module("nemo_relay") + + +def _session_id(event: dict[str, Any]) -> str: + return str(event.get("session_id") or "") + + +def _reset_for_tests() -> None: + """Reset all profile-scoped Relay hosts for isolated tests.""" + SESSION_COORDINATOR._reset_active_turns_for_tests() + HOST_REGISTRY.shutdown_all() + _PROFILE_KEY_CACHE.clear() diff --git a/agent/relay_tools.py b/agent/relay_tools.py new file mode 100644 index 000000000000..5023df1bcf92 --- /dev/null +++ b/agent/relay_tools.py @@ -0,0 +1,123 @@ +"""Core NeMo Relay adapter for Hermes tool execution.""" + +from __future__ import annotations + +import asyncio +import contextvars +import inspect +import json +import logging +from collections.abc import Callable +from typing import Any + +from agent import relay_runtime + +logger = logging.getLogger(__name__) + + +def execute( + tool_name: str, + args: dict[str, Any], + callback: Callable[[dict[str, Any]], Any], + *, + session_id: str, + metadata: dict[str, Any] | None = None, +) -> tuple[Any, dict[str, Any]]: + """Run one tool call through Relay and return its final arguments.""" + runtime, session, parent = relay_runtime.resolve_execution_context(session_id) + if runtime is None or session is None or not runtime.managed_execution_enabled(): + return callback(args), args + + observed_args = args + raw_result: dict[str, Any] = {} + callback_error: BaseException | None = None + callback_context = contextvars.copy_context() + + def invoke(next_args: Any) -> Any: + nonlocal callback_error, observed_args + observed_args = next_args if isinstance(next_args, dict) else args + try: + result = callback_context.copy().run(callback, observed_args) + except BaseException as exc: + callback_error = exc + raise + raw_result["value"] = result + raw_result["json"] = _jsonable(result) + return raw_result["json"] + + try: + managed = _run_awaitable( + runtime.run_in_session_async( + session, + runtime.relay.tools.execute, + tool_name, + _jsonable(args), + invoke, + handle=parent, + metadata=_jsonable(metadata or {}), + ) + ) + except BaseException as exc: + if ( + callback_error is not None + and relay_runtime._is_relay_wrapped_callback_error(exc, callback_error) + ): + raise callback_error + if ( + isinstance(exc, Exception) + and callback_error is None + and "value" in raw_result + ): + logger.warning( + "NeMo Relay tool post-processing failed after dispatch success; " + "returning the Hermes tool result", + exc_info=True, + ) + return raw_result["value"], observed_args + raise + + if "value" in raw_result and _json_equal(managed, raw_result["json"]): + return raw_result["value"], observed_args + if isinstance(managed, str): + return managed, observed_args + return json.dumps(_jsonable(managed), ensure_ascii=False), observed_args + + +def _jsonable(value: Any) -> Any: + if value is None or isinstance(value, (str, int, float, bool)): + return value + if isinstance(value, dict): + return {str(key): _jsonable(item) for key, item in value.items()} + if isinstance(value, (list, tuple, set)): + return [_jsonable(item) for item in value] + model_dump = getattr(value, "model_dump", None) + if callable(model_dump): + try: + return _jsonable(model_dump(mode="json")) + except Exception: + pass + try: + return _jsonable(vars(value)) + except (TypeError, AttributeError): + return str(value) + + +def _json_equal(left: Any, right: Any) -> bool: + try: + return json.dumps( + _jsonable(left), sort_keys=True, separators=(",", ":") + ) == json.dumps(_jsonable(right), sort_keys=True, separators=(",", ":")) + except (TypeError, ValueError): + return left == right + + +def _run_awaitable(value: Any) -> Any: + if not inspect.isawaitable(value): + return value + try: + asyncio.get_running_loop() + except RuntimeError: + return asyncio.run(value) + raise RuntimeError( + "Synchronous Hermes Relay tool execution cannot run on an active event-loop thread" + ) diff --git a/agent/retry_utils.py b/agent/retry_utils.py index c4971122394f..58c6231b6006 100644 --- a/agent/retry_utils.py +++ b/agent/retry_utils.py @@ -8,7 +8,9 @@ rate-limited provider concurrently. import random import threading import time -from typing import Any +from datetime import datetime, timezone +from email.utils import parsedate_to_datetime +from typing import Any, Optional # Monotonic counter for jitter seed uniqueness within the same process. # Protected by a lock to avoid race conditions in concurrent retry paths @@ -33,6 +35,58 @@ _ZAI_CODING_OVERLOAD_LONG_BACKOFF = (30.0, 60.0, 90.0, 120.0) _ZAI_CODING_OVERLOAD_SHORT_ATTEMPTS = 3 +def parse_retry_after_seconds(value_or_headers: Any) -> Optional[float]: + """Parse a ``Retry-After`` value into non-negative seconds. + + Accepts either a raw header value (numeric string / HTTP-date / number) + or a headers mapping, in which case the ``Retry-After`` key is looked up + case-insensitively (``.get`` on dict-like objects tries both common + casings; real HTTP header containers like httpx/requests are already + case-insensitive). + + Returns: + Seconds as a ``float`` (negative deltas clamped to ``0.0``), or + ``None`` when the header is absent or unparseable. + """ + raw = value_or_headers + if raw is not None and not isinstance(raw, (str, int, float)): + # Looks like a headers mapping — pull the header out of it. + getter = getattr(raw, "get", None) + if callable(getter): + try: + value = getter("Retry-After") + if value is None: + value = getter("retry-after") + except Exception: + return None + raw = value + else: + return None + if raw is None: + return None + if isinstance(raw, bool): + return None + if isinstance(raw, (int, float)): + return max(0.0, float(raw)) + text = str(raw).strip() + if not text: + return None + try: + return max(0.0, float(text)) + except (TypeError, ValueError): + pass + # HTTP-date form (RFC 7231): seconds until that instant, clamped at 0. + try: + when = parsedate_to_datetime(text) + except (TypeError, ValueError): + return None + if when is None: + return None + if when.tzinfo is None: + when = when.replace(tzinfo=timezone.utc) + return max(0.0, (when - datetime.now(timezone.utc)).total_seconds()) + + def jittered_backoff( attempt: int, *, diff --git a/agent/secret_sources/_cache.py b/agent/secret_sources/_cache.py index 03bd4eb70958..64e1e5e13ca0 100644 --- a/agent/secret_sources/_cache.py +++ b/agent/secret_sources/_cache.py @@ -82,7 +82,9 @@ def resolve_cache_home(home_path: Optional[Path] = None) -> Path: (and tests that don't thread a home through) working. """ if home_path is None: - home_path = Path(os.getenv("HERMES_HOME", Path.home() / ".hermes")) + from hermes_constants import get_hermes_home + + home_path = get_hermes_home() return home_path diff --git a/agent/secret_sources/base.py b/agent/secret_sources/base.py index d4ead7d3f26e..886a02950c5e 100644 --- a/agent/secret_sources/base.py +++ b/agent/secret_sources/base.py @@ -239,6 +239,10 @@ _ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") # ANSI CSI/OSC escape sequences — helper-CLI stderr often carries color # codes that must not reach Hermes' own startup output. +# NOTE: intentionally NOT migrated to tools.ansi_strip.strip_ansi — the +# optional terminator here (``(?:\x07|\x1b\\)?``) also strips *unterminated* +# OSC sequences (common when a CLI is killed mid-write), which strip_ansi +# leaves untouched. strip_ansi is not a superset of this regex. _ANSI_RE = re.compile(r"\x1b(?:\[[0-9;?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)?)") @@ -295,7 +299,7 @@ def run_secret_cli( list(argv), env=env, capture_output=True, - text=True, + text=True, encoding="utf-8", errors="replace", timeout=timeout, stdin=subprocess.DEVNULL, ) diff --git a/agent/secret_sources/bitwarden.py b/agent/secret_sources/bitwarden.py index 8b047880be1a..7e71f0f7fd54 100644 --- a/agent/secret_sources/bitwarden.py +++ b/agent/secret_sources/bitwarden.py @@ -200,7 +200,7 @@ def _platform_asset_name() -> str: res = subprocess.run( ["ldd", "--version"], capture_output=True, - text=True, + text=True, encoding='utf-8', errors='replace', timeout=2, stdin=subprocess.DEVNULL, ) @@ -667,7 +667,10 @@ def _run_bws_list( bws: Path, access_token: str, project_id: str, server_url: str = "" ) -> Tuple[Dict[str, str], List[str]]: cmd = [str(bws), "secret", "list", project_id, "--output", "json"] - env = os.environ.copy() + # bws child intentionally receives the access token; exact preservation + # (BWS_SERVER_URL manual overrides etc. must survive untouched). + from tools.environments.local import build_subprocess_env + env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False) env["BWS_ACCESS_TOKEN"] = access_token # Make sure we're not echoing telemetry / colour codes into json. env.setdefault("NO_COLOR", "1") @@ -684,7 +687,7 @@ def _run_bws_list( cmd, env=env, capture_output=True, - text=True, + text=True, encoding='utf-8', errors='replace', timeout=_BWS_RUN_TIMEOUT, stdin=subprocess.DEVNULL, ) diff --git a/agent/secret_sources/command.py b/agent/secret_sources/command.py index d3a9afb81c24..9bce311ba902 100644 --- a/agent/secret_sources/command.py +++ b/agent/secret_sources/command.py @@ -179,7 +179,10 @@ def _run_helper( ) return None - env = os.environ.copy() + # User-configured secret-helper command: runs with the user's full shell + # env by design (it may need any credential to resolve the secret). + from tools.environments.local import build_subprocess_env + env = build_subprocess_env(scrub_secrets=False, inherit_profile_home=False) env["HERMES_SECRET_KEY"] = secret_key try: diff --git a/agent/secret_sources/onepassword.py b/agent/secret_sources/onepassword.py index 71b064926127..d8216dfcbdfc 100644 --- a/agent/secret_sources/onepassword.py +++ b/agent/secret_sources/onepassword.py @@ -42,7 +42,6 @@ from __future__ import annotations import hashlib import logging import os -import re import shutil import subprocess import time @@ -73,10 +72,10 @@ _OP_RUN_TIMEOUT = 30 # looks for. _DEFAULT_TOKEN_ENV = "OP_SERVICE_ACCOUNT_TOKEN" -# Strip whole ANSI CSI sequences (colour, cursor moves, line erases) from any -# `op` diagnostic we surface — not just the lone ESC byte — so a control -# sequence can't reposition the cursor or hide text after a redaction marker. -_ANSI_CSI_RE = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]") +# ANSI stripping for `op` diagnostics we surface uses the shared +# tools.ansi_strip.strip_ansi (full ECMA-48: CSI, OSC, DCS/SOS/PM/APC, +# C1) so a control sequence can't reposition the cursor or hide text +# after a redaction marker. # Env vars the `op` child actually needs. We build a minimal allowlisted env # rather than copying all of os.environ (which, post-dotenv, holds every @@ -231,7 +230,10 @@ def find_op(binary_path: str = "") -> Optional[Path]: def _scrub(text: str) -> str: """Remove ANSI control sequences and trim, for safe message surfacing.""" - return _ANSI_CSI_RE.sub("", text).replace("\x1b", "").strip() + from tools.ansi_strip import strip_ansi + + # strip_ansi removes well-formed sequences; drop any stray lone ESC too. + return strip_ansi(text).replace("\x1b", "").strip() def _op_child_env(token_value: str) -> Dict[str, str]: diff --git a/agent/shell_hooks.py b/agent/shell_hooks.py index c1cec81df333..5699e4d9eb65 100644 --- a/agent/shell_hooks.py +++ b/agent/shell_hooks.py @@ -100,6 +100,7 @@ emitted by each built-in hook site. child_role – role string of the child agent child_summary – summary of the child's work child_status – exit status string (e.g. "success", "error") + tool_call_history – redacted tool name/input summary/byte counts/status list duration_ms – wall-clock time of the child run in milliseconds """ @@ -464,7 +465,7 @@ def _spawn(spec: ShellHookSpec, stdin_json: str) -> Dict[str, Any]: input=stdin_json, capture_output=True, timeout=spec.timeout, - text=True, + text=True, encoding='utf-8', errors='replace', shell=False, **_popen_kwargs, ) @@ -632,7 +633,7 @@ def allowlist_path() -> Path: def load_allowlist() -> Dict[str, Any]: """Return the parsed allowlist, or an empty skeleton if absent.""" try: - raw = json.loads(allowlist_path().read_text()) + raw = json.loads(allowlist_path().read_text(encoding="utf-8")) except (FileNotFoundError, json.JSONDecodeError, OSError): return {"approvals": []} if not isinstance(raw, dict): diff --git a/agent/skill_commands.py b/agent/skill_commands.py index 11d425b91a52..3f1156a85929 100644 --- a/agent/skill_commands.py +++ b/agent/skill_commands.py @@ -54,6 +54,21 @@ _BUNDLE_MARKER = " skill bundle," _BUNDLE_USER_INSTRUCTION = "\nUser instruction: " _BUNDLE_FIRST_SKILL_BLOCK = "\n\n[Loaded as part of the " +# The skill name sits in the first quoted span of the activation note, for both +# the single-skill and the bundle header ("work" / "/clean /work"). +_SKILL_NAME_RE = re.compile(re.escape(_SKILL_INVOCATION_PREFIX) + r'"([^"]*)"') + +# SQL LIKE pattern matching a skill-expanded turn, for listing queries that +# have to recognize scaffolding before the row reaches Python. The prefix +# contains no LIKE wildcards (`%`, `_`), so it needs no ESCAPE clause. +SKILL_SCAFFOLD_SQL_LIKE = _SKILL_INVOCATION_PREFIX + "%" + +# Marks where a preview query joined the head and tail of a long scaffolded +# message. ``describe_skill_invocation`` may hand back a span that runs across +# the joint (a bundle instruction cut off by the head window); callers cut the +# description there rather than show the skill body on the far side. +SKILL_EXCERPT_JOINT = "\x1e" + def extract_user_instruction_from_skill_message(content: Any) -> Optional[str]: """Recover the user's instruction from a slash-skill-expanded turn. @@ -82,6 +97,45 @@ def extract_user_instruction_from_skill_message(content: Any) -> Optional[str]: return None +def describe_skill_invocation(content: Any, separator: str = " — ") -> Optional[str]: + """Render a slash-skill-expanded turn the way the user typed it. + + The expanded message embeds the whole skill body, so any surface that + summarizes a user turn from its raw content — session titles, sidebar + previews, the ``/rewind`` picker — otherwise shows the skill's own prose + as if the user had written it. That is how a skill's opening line ends up + as a session title. + + Returns ``"/work — fix the title leak"``, or ``"/work"`` for a bare + invocation, or ``None`` when *content* is not skill scaffolding (the + caller should then summarize it as an ordinary message). + + *separator* joins the command and the instruction. Previews use the + default em dash; pass ``" "`` for the literal invocation the user typed, + which is what chat transcripts render. + """ + if not isinstance(content, str) or not content.startswith(_SKILL_INVOCATION_PREFIX): + return None + + match = _SKILL_NAME_RE.match(content) + name = (match.group(1) if match else "").strip() + # Bundle headers already carry their typed "/a /b" keys; a single skill is + # a bare name. + label = name if name.startswith("/") else f"/{name}" + + instruction = extract_user_instruction_from_skill_message(content) + if instruction and instruction is not content: + # An excerpted message (head + tail, joined by SKILL_EXCERPT_JOINT) can + # put the joint inside the matched span — keep only the side the + # instruction marker was found on. + instruction = instruction.split(SKILL_EXCERPT_JOINT)[0] + instruction = " ".join(instruction.split()) + if instruction: + return f"{label}{separator}{instruction}" if name else instruction + + return label if name else None + + def _extract_single_skill_user_instruction(message: str) -> Optional[str]: # Single-skill format appends the user instruction after the skill body, so # the last occurrence is the user-provided one; the body may quote this text. @@ -453,8 +507,8 @@ def reload_skills() -> Dict[str, Any]: } ``description`` is the skill's full SKILL.md frontmatter - ``description:`` field — the same string the system prompt renders - as `` - name: description`` for pre-existing skills. + ``description:`` field. Note: the system prompt skill index + truncates this to the first 57 chars; see ``extract_skill_description``. """ # Snapshot pre-reload state (name -> description) from the current # slash-command cache. Using dicts lets the post-rescan diff carry diff --git a/agent/skill_preprocessing.py b/agent/skill_preprocessing.py index bd0386d58058..19c6eeb80fb3 100644 --- a/agent/skill_preprocessing.py +++ b/agent/skill_preprocessing.py @@ -74,7 +74,7 @@ def run_inline_shell(command: str, cwd: Path | None, timeout: int) -> str: ["bash", "-c", command], cwd=str(cwd) if cwd else None, capture_output=True, - text=True, + text=True, encoding='utf-8', errors='replace', timeout=max(1, int(timeout)), check=False, stdin=subprocess.DEVNULL, diff --git a/agent/skill_utils.py b/agent/skill_utils.py index 9276f145abdd..a302c6981a47 100644 --- a/agent/skill_utils.py +++ b/agent/skill_utils.py @@ -99,7 +99,7 @@ def org_id_of_path(path, skills_dir: Path) -> Optional[str]: return None -def is_excluded_skill_path(path) -> bool: +def is_excluded_skill_path(path, *, root: Optional[Path] = None) -> bool: """True if *path* should be skipped by active skill scanners. Use this on every ``SKILL.md`` path produced by direct ``rglob`` scans to @@ -115,11 +115,11 @@ def is_excluded_skill_path(path) -> bool: from pathlib import PurePath parts = PurePath(str(path)).parts return any(part in EXCLUDED_SKILL_DIRS for part in parts) or is_skill_support_path( - path + path, root=root ) -def is_skill_support_path(path) -> bool: +def is_skill_support_path(path, *, root: Optional[Path] = None) -> bool: """True if *path* is under a support dir of an actual skill root. ``references/``, ``templates/``, ``assets/``, and ``scripts/`` are @@ -141,6 +141,8 @@ def is_skill_support_path(path) -> bool: if part not in SKILL_SUPPORT_DIRS or idx == 0: continue skill_root = Path(*parts[:idx]) + if root is not None and not path_obj.is_absolute(): + skill_root = root / skill_root if (skill_root / "SKILL.md").exists(): return True return False @@ -828,18 +830,31 @@ def resolve_skill_config_values( # ── Description extraction ──────────────────────────────────────────────── +SKILL_PROMPT_DESC_LIMIT = 60 + + +def _normalize_skill_description(frontmatter: Dict[str, Any]) -> str: + """Normalize a skill's description field for comparison/truncation.""" + raw_desc = frontmatter.get("description", "") + return str(raw_desc).strip().strip("'\"") if raw_desc else "" + def extract_skill_description(frontmatter: Dict[str, Any]) -> str: - """Extract a truncated description from parsed frontmatter.""" - raw_desc = frontmatter.get("description", "") - if not raw_desc: + """Extract a system-prompt-length description from parsed frontmatter.""" + desc = _normalize_skill_description(frontmatter) + if not desc: return "" - desc = str(raw_desc).strip().strip("'\"") - if len(desc) > 60: - return desc[:57] + "..." + if len(desc) > SKILL_PROMPT_DESC_LIMIT: + return desc[:SKILL_PROMPT_DESC_LIMIT - 3] + "..." return desc +def is_skill_description_truncated_for_prompt(frontmatter: Dict[str, Any]) -> bool: + """True when the description will be truncated in the system prompt skill index.""" + desc = _normalize_skill_description(frontmatter) + return len(desc) > SKILL_PROMPT_DESC_LIMIT + + # ── File iteration ──────────────────────────────────────────────────────── diff --git a/agent/ssl_guard.py b/agent/ssl_guard.py index 557f8566c32a..ac1b7841b2d8 100644 --- a/agent/ssl_guard.py +++ b/agent/ssl_guard.py @@ -31,7 +31,8 @@ def _skip_ssl_guard_enabled() -> bool: def _repair_hint() -> str: return ( - "Repair: python -m pip install --force-reinstall certifi openai httpx\n" + "Repair: run `hermes doctor --fix` (auto-reinstalls certifi), or " + "manually: python -m pip install --force-reinstall certifi openai httpx\n" "If you configured a custom corporate CA bundle, fix or unset the " "broken CA bundle environment variable." ) diff --git a/agent/subagent_lifecycle.py b/agent/subagent_lifecycle.py new file mode 100644 index 000000000000..bbe63ad0930a --- /dev/null +++ b/agent/subagent_lifecycle.py @@ -0,0 +1,533 @@ +"""Public, plugin-safe lifecycle API for delegated Hermes subagents. + +This module deliberately exposes immutable contracts, not ``AIAgent`` objects. +It is the supported boundary for plugins that need to supervise fresh child +sessions; plugins must obtain it from ``PluginContext.subagent_lifecycle``. +""" + +from __future__ import annotations + +import contextvars +import dataclasses +import enum +import hashlib +import hmac +import json +import math +import secrets +import threading +import time +from contextlib import contextmanager +from concurrent.futures import Future, TimeoutError +from typing import Any, Callable, Mapping, Optional + + +PUBLIC_CONTRACT_VERSION = 1 +_MAX_GOAL_CHARS = 16_000 +_MAX_CONTEXT_CHARS = 32_000 +_MAX_METADATA_BYTES = 8_192 +_MAX_RESULT_CHARS = 32_000 +_TERMINAL_RETENTION_SECONDS = 3_600 + + +class SubagentLifecycleError(ValueError): + """A request cannot be safely accepted by the public lifecycle API.""" + + +class SubagentState(str, enum.Enum): + PENDING = "PENDING" + STARTING = "STARTING" + RUNNING = "RUNNING" + SUCCEEDED = "SUCCEEDED" + FAILED = "FAILED" + INTERRUPTED = "INTERRUPTED" + CANCEL_REQUESTED = "CANCEL_REQUESTED" + CANCELLED = "CANCELLED" + UNKNOWN = "UNKNOWN" + + +@dataclasses.dataclass(frozen=True) +class SubagentLaunchRequest: + goal: str + context: Optional[str] = None + role: str = "leaf" + model: Optional[str] = None + allowed_toolsets: Optional[tuple[str, ...]] = None + blocked_tools: tuple[str, ...] = () + working_directory: Optional[str] = None + parent_session_id: Optional[str] = None + correlation_id: Optional[str] = None + metadata: Mapping[str, Any] = dataclasses.field(default_factory=dict) + timeout_seconds: Optional[float] = None + + +@dataclasses.dataclass(frozen=True) +class SubagentHandle: + contract_version: int + subagent_id: str + parent_session_id: Optional[str] + correlation_id: Optional[str] + created_at: float + provider: Optional[str] + model: Optional[str] + role: str + depth: int + capability: str + + def to_dict(self) -> dict[str, Any]: + return dataclasses.asdict(self) + + @classmethod + def from_dict(cls, value: Mapping[str, Any]) -> "SubagentHandle": + try: + return cls(**dict(value)) + except (TypeError, ValueError) as exc: + raise SubagentLifecycleError("Malformed subagent handle.") from exc + + +@dataclasses.dataclass(frozen=True) +class SubagentStatus: + handle: SubagentHandle + state: SubagentState + updated_at: float + diagnostic: Optional[str] = None + + +@dataclasses.dataclass(frozen=True) +class SubagentTerminalState: + handle: SubagentHandle + state: SubagentState + completed: bool + timed_out: bool = False + diagnostic: Optional[str] = None + + +@dataclasses.dataclass(frozen=True) +class SubagentCancelResult: + accepted: bool + already_terminal: bool = False + unknown_handle: bool = False + unsupported: bool = False + state: SubagentState = SubagentState.UNKNOWN + + +@dataclasses.dataclass(frozen=True) +class SubagentResult: + handle: SubagentHandle + terminal_state: SubagentState + ready: bool + summary: Optional[str] = None + structured_payload: Optional[Mapping[str, Any]] = None + started_at: Optional[float] = None + completed_at: Optional[float] = None + error_classification: Optional[str] = None + error_message: Optional[str] = None + usage_metadata: Mapping[str, Any] = dataclasses.field(default_factory=dict) + tool_execution_summary: Mapping[str, Any] = dataclasses.field(default_factory=dict) + result_hash: Optional[str] = None + + +@dataclasses.dataclass(frozen=True) +class SubagentReconnectResult: + connected: bool + state: SubagentState + diagnostic: Optional[str] = None + + +@dataclasses.dataclass +class _Record: + handle: SubagentHandle + state: SubagentState + updated_at: float + agent: Any = None + future: Optional[Future] = None + started_at: Optional[float] = None + completed_at: Optional[float] = None + result: Optional[SubagentResult] = None + + +class _Registry: + """Thread-safe terminal-retention registry; never returns live records.""" + + def __init__(self) -> None: + self.lock = threading.RLock() + self.records: dict[str, _Record] = {} + self.correlations: dict[tuple[Optional[str], str], str] = {} + + +_REGISTRY = _Registry() +# Daemon worker pool: a wedged/abandoned child must never block interpreter +# exit at atexit-join time (same rationale as _run_single_child's timeout +# executor and the async-delegation registry pool). +from tools.daemon_pool import DaemonThreadPoolExecutor as _DaemonExecutor + +_EXECUTOR = _DaemonExecutor(max_workers=8, thread_name_prefix="hermes-lifecycle") +_SECRET = secrets.token_bytes(32) +_ACTIVE_PARENT_AGENT: contextvars.ContextVar[Any] = contextvars.ContextVar( + "hermes_subagent_lifecycle_parent", default=None +) + + +@contextmanager +def bind_subagent_parent(parent_agent: Any): + """Bind the host-owned parent for the current agent turn.""" + token = _ACTIVE_PARENT_AGENT.set(parent_agent) + try: + yield + finally: + _ACTIVE_PARENT_AGENT.reset(token) + + +def get_active_subagent_parent() -> Any: + """Return the parent bound to this execution context, if any.""" + return _ACTIVE_PARENT_AGENT.get() + + +class SubagentLifecycleService: + """Stable public service returned by :attr:`PluginContext.subagent_lifecycle`. + + Running children are in-process only. Completed results remain available + until process exit; ``reconnect`` accurately reports that a serialized + handle cannot reconnect after a restart instead of launching work again. + """ + + def __init__(self, parent_agent_resolver: Callable[[], Any]) -> None: + self._parent_agent_resolver = parent_agent_resolver + + def launch(self, request: SubagentLaunchRequest) -> SubagentHandle: + parent = self._parent_agent_resolver() + if parent is None: + raise SubagentLifecycleError( + "No active Hermes parent session is available." + ) + self._validate_request(request, parent) + parent_session_id = str(getattr(parent, "session_id", "") or "") or None + if request.parent_session_id and request.parent_session_id != parent_session_id: + raise SubagentLifecycleError( + "parent_session_id does not match the active session." + ) + correlation_key = (parent_session_id, request.correlation_id or "") + with _REGISTRY.lock: + self._cleanup_locked() + if request.correlation_id and correlation_key in _REGISTRY.correlations: + raise SubagentLifecycleError( + "Duplicate correlation_id for this parent session." + ) + + # Delegate construction remains internal so plugin code never imports + # private delegation helpers or manipulates the active-child registry. + from tools.delegate_tool import ( + _build_child_preserving_parent_tools, + DEFAULT_MAX_ITERATIONS, + ) + + child = _build_child_preserving_parent_tools( + task_index=0, + goal=request.goal, + context=request.context, + toolsets=list(request.allowed_toolsets) + if request.allowed_toolsets + else None, + model=request.model, + max_iterations=DEFAULT_MAX_ITERATIONS, + task_count=1, + parent_agent=parent, + role=request.role, + ) + subagent_id = str(getattr(child, "_subagent_id", "") or "") + if not subagent_id: + raise SubagentLifecycleError("Hermes failed to assign a child identity.") + created = time.time() + handle = SubagentHandle( + PUBLIC_CONTRACT_VERSION, + subagent_id, + parent_session_id, + request.correlation_id, + created, + getattr(child, "provider", None), + getattr(child, "model", None), + getattr(child, "_delegate_role", request.role), + int(getattr(child, "_delegate_depth", 1) or 1), + self._capability(subagent_id, parent_session_id, created), + ) + record = _Record(handle, SubagentState.PENDING, created, agent=child) + with _REGISTRY.lock: + _REGISTRY.records[subagent_id] = record + if request.correlation_id: + _REGISTRY.correlations[correlation_key] = subagent_id + record.future = _EXECUTOR.submit(self._run, record, request.goal, parent) + return handle + + def status(self, handle: SubagentHandle) -> SubagentStatus: + record = self._record(handle) + if record is None: + return SubagentStatus( + handle, SubagentState.UNKNOWN, time.time(), "UNKNOWN_HANDLE" + ) + with _REGISTRY.lock: + return SubagentStatus(record.handle, record.state, record.updated_at) + + def wait( + self, handle: SubagentHandle, *, timeout_seconds: Optional[float] = None + ) -> SubagentTerminalState: + record = self._record(handle) + if record is None: + return SubagentTerminalState( + handle, SubagentState.UNKNOWN, True, diagnostic="UNKNOWN_HANDLE" + ) + future = record.future + if future is not None: + try: + future.result(timeout=timeout_seconds) + except TimeoutError: + return SubagentTerminalState(record.handle, record.state, False, True) + except Exception: + pass + with _REGISTRY.lock: + return SubagentTerminalState( + record.handle, record.state, record.result is not None + ) + + def cancel(self, handle: SubagentHandle, *, reason: str) -> SubagentCancelResult: + record = self._record(handle) + if record is None: + return SubagentCancelResult(False, unknown_handle=True) + with _REGISTRY.lock: + if record.result is not None: + return SubagentCancelResult( + False, already_terminal=True, state=record.state + ) + agent = record.agent + record.state = SubagentState.CANCEL_REQUESTED + record.updated_at = time.time() + if agent is None or not hasattr(agent, "interrupt"): + return SubagentCancelResult( + False, unsupported=True, state=SubagentState.CANCEL_REQUESTED + ) + try: + agent.interrupt(f"Lifecycle cancellation requested: {reason[:500]}") + except Exception: + return SubagentCancelResult( + False, unsupported=True, state=SubagentState.CANCEL_REQUESTED + ) + return SubagentCancelResult(True, state=SubagentState.CANCEL_REQUESTED) + + def result(self, handle: SubagentHandle) -> SubagentResult: + record = self._record(handle) + if record is None: + return SubagentResult( + handle, + SubagentState.UNKNOWN, + False, + error_classification="UNKNOWN_HANDLE", + ) + with _REGISTRY.lock: + if record.result is not None: + return record.result + return SubagentResult( + record.handle, record.state, False, error_classification="NOT_READY" + ) + + def reconnect(self, handle: SubagentHandle) -> SubagentReconnectResult: + record = self._record(handle) + if record is None: + return SubagentReconnectResult( + False, SubagentState.UNKNOWN, "RECONNECT_UNAVAILABLE" + ) + with _REGISTRY.lock: + return SubagentReconnectResult(True, record.state) + + def _record(self, handle: SubagentHandle) -> Optional[_Record]: + if ( + not isinstance(handle, SubagentHandle) + or type(handle.contract_version) is not int + or handle.contract_version != PUBLIC_CONTRACT_VERSION + ): + return None + if ( + not isinstance(handle.subagent_id, str) + or not handle.subagent_id + or ( + handle.parent_session_id is not None + and not isinstance(handle.parent_session_id, str) + ) + or ( + handle.correlation_id is not None + and not isinstance(handle.correlation_id, str) + ) + or isinstance(handle.created_at, bool) + or not isinstance(handle.created_at, (int, float)) + or not math.isfinite(handle.created_at) + or (handle.provider is not None and not isinstance(handle.provider, str)) + or (handle.model is not None and not isinstance(handle.model, str)) + or not isinstance(handle.role, str) + or type(handle.depth) is not int + or not isinstance(handle.capability, str) + ): + return None + if not hmac.compare_digest( + handle.capability, + self._capability( + handle.subagent_id, handle.parent_session_id, handle.created_at + ), + ): + return None + parent = self._parent_agent_resolver() + active_parent_id = str(getattr(parent, "session_id", "") or "") or None + if active_parent_id != handle.parent_session_id: + return None + with _REGISTRY.lock: + return _REGISTRY.records.get(handle.subagent_id) + + @staticmethod + def _cleanup_locked() -> None: + """Retain terminal snapshots for a bounded period, never live work.""" + cutoff = time.time() - _TERMINAL_RETENTION_SECONDS + expired = [ + subagent_id + for subagent_id, record in _REGISTRY.records.items() + if record.result is not None + and record.completed_at is not None + and record.completed_at < cutoff + ] + for subagent_id in expired: + record = _REGISTRY.records.pop(subagent_id) + if record.handle.correlation_id: + _REGISTRY.correlations.pop( + (record.handle.parent_session_id, record.handle.correlation_id), + None, + ) + + def _run(self, record: _Record, goal: str, parent: Any) -> None: + with _REGISTRY.lock: + if record.state is not SubagentState.CANCEL_REQUESTED: + record.state = SubagentState.RUNNING + record.started_at = time.time() + record.updated_at = record.started_at + try: + from tools.delegate_tool import _run_child_lifecycle + + raw = _run_child_lifecycle(0, goal, record.agent, parent) + status = ( + str(raw.get("status", "error")) if isinstance(raw, dict) else "error" + ) + if status == "completed": + state = SubagentState.SUCCEEDED + elif status == "interrupted": + state = ( + SubagentState.CANCELLED + if record.state == SubagentState.CANCEL_REQUESTED + else SubagentState.INTERRUPTED + ) + else: + state = SubagentState.FAILED + summary = raw.get("summary") if isinstance(raw, dict) else None + summary = str(summary)[:_MAX_RESULT_CHARS] if summary is not None else None + error = raw.get("error") if isinstance(raw, dict) else None + result = SubagentResult( + record.handle, + state, + True, + summary=summary, + completed_at=time.time(), + started_at=record.started_at, + error_classification=None + if state == SubagentState.SUCCEEDED + else status.upper(), + error_message=str(error)[:_MAX_RESULT_CHARS] if error else None, + usage_metadata={"api_calls": raw.get("api_calls", 0)} + if isinstance(raw, dict) + else {}, + tool_execution_summary={ + "duration_seconds": raw.get("duration_seconds", 0) + } + if isinstance(raw, dict) + else {}, + ) + except Exception as exc: + result = SubagentResult( + record.handle, + SubagentState.FAILED, + True, + started_at=record.started_at, + completed_at=time.time(), + error_classification=type(exc).__name__, + error_message=str(exc)[:_MAX_RESULT_CHARS], + ) + payload = dataclasses.asdict(result) + payload.pop("result_hash", None) + result = dataclasses.replace( + result, + result_hash=hashlib.sha256( + json.dumps(payload, sort_keys=True, default=str).encode() + ).hexdigest(), + ) + with _REGISTRY.lock: + record.agent = None + record.result = result + record.state = result.terminal_state + record.completed_at = result.completed_at + record.updated_at = result.completed_at or time.time() + + @staticmethod + def _capability( + subagent_id: str, parent_session_id: Optional[str], created_at: float + ) -> str: + value = f"{subagent_id}|{parent_session_id or ''}|{created_at:.6f}".encode() + return hmac.new(_SECRET, value, hashlib.sha256).hexdigest() + + @staticmethod + def _validate_request(request: SubagentLaunchRequest, parent: Any) -> None: + if ( + not isinstance(request, SubagentLaunchRequest) + or not isinstance(request.goal, str) + or not request.goal.strip() + or len(request.goal) > _MAX_GOAL_CHARS + ): + raise SubagentLifecycleError( + "goal must be a non-empty string of at most 16000 characters." + ) + if request.context is not None and ( + not isinstance(request.context, str) + or len(request.context) > _MAX_CONTEXT_CHARS + ): + raise SubagentLifecycleError( + "context must be a string of at most 32000 characters." + ) + if request.role not in {"leaf", "orchestrator"}: + raise SubagentLifecycleError("role must be 'leaf' or 'orchestrator'.") + if request.timeout_seconds is not None: + raise SubagentLifecycleError( + "Per-launch timeout is not supported; configure delegation timeout explicitly." + ) + if request.working_directory is not None: + raise SubagentLifecycleError( + "working_directory is not supported because Hermes delegates use isolated task environments." + ) + if request.blocked_tools: + raise SubagentLifecycleError( + "Per-tool blocking is not supported; use allowed_toolsets. Hermes always blocks unsafe child tools." + ) + try: + metadata_bytes = len( + json.dumps(dict(request.metadata), sort_keys=True).encode() + ) + except (TypeError, ValueError) as exc: + raise SubagentLifecycleError("metadata must be JSON-serializable.") from exc + if metadata_bytes > _MAX_METADATA_BYTES: + raise SubagentLifecycleError("metadata exceeds 8192 bytes.") + if request.allowed_toolsets: + from toolsets import TOOLSETS + + unknown = set(request.allowed_toolsets) - set(TOOLSETS) + if unknown: + raise SubagentLifecycleError( + f"Unknown toolsets: {', '.join(sorted(unknown))}." + ) + enabled = getattr(parent, "enabled_toolsets", None) + if enabled is not None and not set(request.allowed_toolsets).issubset( + set(enabled) + ): + raise SubagentLifecycleError( + "Requested toolsets would broaden parent permissions." + ) diff --git a/agent/system_prompt.py b/agent/system_prompt.py index aab34cb799e1..8b8832ca2807 100644 --- a/agent/system_prompt.py +++ b/agent/system_prompt.py @@ -12,9 +12,11 @@ Three tiers are joined with ``\\n\\n``: * ``stable`` — identity (SOUL.md or DEFAULT_AGENT_IDENTITY), tool guidance, computer-use guidance, nous subscription block, tool-use enforcement guidance + per-model operational guidance, skills prompt, - alibaba model-name workaround, environment hints, platform hints. + alibaba model-name workaround, environment hints, coding guidance, + platform hints. * ``context`` — caller-supplied ``system_message`` plus context files - (AGENTS.md / .cursorrules / etc.) discovered under ``TERMINAL_CWD``. + (AGENTS.md / .cursorrules / etc.) discovered under ``TERMINAL_CWD``, + plus the session's coding-workspace snapshot. * ``volatile`` — memory snapshot, USER.md profile, external memory provider block, timestamp/session/model/provider line. @@ -24,6 +26,7 @@ Pure helpers that read the agent's state. AIAgent keeps thin forwarders. from __future__ import annotations import json +import logging import os from typing import Any, Dict, List, Optional @@ -49,6 +52,8 @@ from agent.runtime_cwd import resolve_context_cwd from hermes_constants import get_hermes_home from utils import is_truthy_value +logger = logging.getLogger(__name__) + def _ra(): """Lazy reference to the ``run_agent`` module. @@ -145,14 +150,14 @@ def _tui_embedded_pane_clarifier(hint: str) -> str: def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) -> Dict[str, str]: - """Assemble the system prompt as three ordered parts. + """Assemble the system prompt as three ordered cache tiers. Returns a dict with three keys: - * ``stable`` — identity, tool guidance, skills prompt, - environment hints, platform hints, model-family operational - guidance. - * ``context`` — context files (AGENTS.md, .cursorrules, etc.) - and caller-supplied system_message. + * ``stable`` — the cross-session-stable prefix, through the coding + operating brief when a workspace snapshot follows. + * ``context`` — the workspace snapshot followed by the remaining + session-stable guidance, context files, and caller-supplied + system_message. * ``volatile`` — memory snapshot, user profile, external memory provider block, timestamp line. @@ -345,25 +350,35 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) stable_parts.append(_env_hints) # Coding posture (base Hermes, any interactive coding surface in a code - # workspace — see agent/coding_context.py). The operating brief + the live - # git/workspace snapshot are built once here and cached for the session; - # the snapshot is never re-probed per turn (that would break the prompt - # cache), so the brief tells the model to re-check git before relying on it. + # workspace — see agent/coding_context.py). Keep the operating brief in + # the cross-session-stable prefix, while placing the live git/workspace + # snapshot behind its own cache boundary. The post-snapshot blocks must + # stay in their historical position after the workspace snapshot. + coding_workspace_parts: List[str] = [] + coding_trailing_parts: List[str] = [] if agent.valid_tool_names: try: - from agent.coding_context import coding_system_blocks + from agent.coding_context import coding_system_prompt_parts - stable_parts.extend( - coding_system_blocks( - platform=agent.platform, - cwd=resolve_context_cwd(), - model=agent.model, - ) + coding_prefix_parts, coding_workspace_parts, coding_trailing_parts = coding_system_prompt_parts( + platform=agent.platform, + cwd=resolve_context_cwd(), + model=agent.model, ) + stable_parts.extend(coding_prefix_parts) except Exception: # Coding-context probing must never block prompt build. pass + # Guidance assembled after the coding posture historically followed the + # workspace snapshot. With no snapshot, the coding tail instead remains + # directly after the coding prefix in the cacheable prefix. + if coding_workspace_parts: + post_workspace_parts: List[str] = [] + else: + stable_parts.extend(coding_trailing_parts) + post_workspace_parts = stable_parts + # Local Python toolchain probe — names python/pip/uv/PEP-668 state when # something is non-default so the model can pick the right install # strategy without discovering by failure. Emits a single line; emits @@ -376,7 +391,7 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) from tools.env_probe import get_environment_probe_line _probe_line = get_environment_probe_line() if _probe_line: - stable_parts.append(_probe_line) + post_workspace_parts.append(_probe_line) except Exception: # Probe failure must never block prompt build. pass @@ -394,7 +409,7 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) except Exception: active_profile = "default" if active_profile == "default": - stable_parts.append( + post_workspace_parts.append( "Active Hermes profile: default. Other profiles (if any) live " "under " + str(get_hermes_home()) + "/profiles//. Each profile has its own " "skills/, plugins/, cron/, and memories/ that affect a different " @@ -403,7 +418,7 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) "you to." ) else: - stable_parts.append( + post_workspace_parts.append( f"Active Hermes profile: {active_profile}. This session reads " f"and writes {get_hermes_home()}/profiles/{active_profile}/. The default " f"profile's data lives at {get_hermes_home()}/skills/, {get_hermes_home()}/plugins/, " @@ -449,11 +464,16 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) if platform_key == "tui" and _effective_hint: _effective_hint = _tui_embedded_pane_clarifier(_effective_hint) if _effective_hint: - stable_parts.append(_effective_hint) + post_workspace_parts.append(_effective_hint) # ── Context tier (cwd-dependent, may change between sessions) ─ context_parts: List[str] = [] + if coding_workspace_parts: + context_parts.extend(coding_workspace_parts) + context_parts.extend(coding_trailing_parts) + context_parts.extend(post_workspace_parts) + # Note: ephemeral_system_prompt is NOT included here. It's injected at # API-call time only so it stays out of the cached/stored system prompt. if system_message is not None: @@ -515,6 +535,8 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None) timestamp_line += f"\nModel: {agent.model}" if agent.provider: timestamp_line += f"\nProvider: {agent.provider}" + if agent.platform: + timestamp_line += f"\nPlatform: {agent.platform}" volatile_parts.append(timestamp_line) return { @@ -541,6 +563,7 @@ def build_system_prompt(agent: Any, system_message: Optional[str] = None) -> str """ parts = build_system_prompt_parts(agent, system_message=system_message) joined = "\n\n".join(p for p in (parts["stable"], parts["context"], parts["volatile"]) if p) + agent._cached_system_prompt_static = parts["stable"] # Surface context-file truncation warnings through the normal agent status # channel so gateway/CLI users see them in chat instead of only in logs. @@ -557,10 +580,65 @@ def invalidate_system_prompt(agent: Any) -> None: so the rebuilt prompt captures any writes from this session. """ agent._cached_system_prompt = None + agent._cached_system_prompt_static = None if agent._memory_store: agent._memory_store.load_from_disk() +def reconstruct_static_prefix( + agent: Any, + system_message: Optional[str] = None, + *, + log_label: str = "restore", +) -> None: + """Reconstruct ``_cached_system_prompt_static`` for a stored prompt. + + The static prefix is not persisted (only the full prompt is), so any + path that adopts a stored/kept ``_cached_system_prompt`` — session + restore, the compression keep-prompt path, or a failover to a cache-on + provider mid-turn (#72626) — must rebuild the stable tier to regain the + two-block ``[static, volatile]`` system layout. + + Safety: the rebuilt stable tier is used ONLY when the stored prompt + literally starts with it (checked here AND re-checked by + ``_apply_system_cache_markers``'s ``startswith`` gate). If any + stable-tier input changed since the prompt was persisted (skills + edited, identity changed), the prefix mismatches, the static stays + None, and requests fall back to the legacy layout with the stored + prompt bytes untouched — never a rewritten prompt. + + A failed reconstruction is memoized per stored prompt + (``_static_rebuild_failed_for``): ``build_system_prompt_parts`` does + real file I/O (SOUL.md, context files, memory), and callers on the + retry-loop hot path must not re-run it every attempt when the inputs + haven't changed. A legitimately changed stored prompt retries once. + """ + if not getattr(agent, "_use_prompt_caching", False): + return + stored = getattr(agent, "_cached_system_prompt", None) + if not isinstance(stored, str) or not stored: + return + existing = getattr(agent, "_cached_system_prompt_static", None) + if isinstance(existing, str) and existing and stored.startswith(existing): + return + if getattr(agent, "_static_rebuild_failed_for", None) == stored: + return + try: + static = build_system_prompt_parts(agent, system_message=system_message)["stable"] + if static and stored.startswith(static): + agent._cached_system_prompt_static = static + agent._static_rebuild_failed_for = None + return + except Exception: + logger.debug( + "static system-prefix reconstruction failed on %s", + log_label, + exc_info=True, + ) + agent._cached_system_prompt_static = None + agent._static_rebuild_failed_for = stored + + def format_tools_for_system_message(agent: Any) -> str: """Format tool definitions for the system message in the trajectory format. diff --git a/agent/title_generator.py b/agent/title_generator.py index 7469a665bfc5..bb44da276ec3 100644 --- a/agent/title_generator.py +++ b/agent/title_generator.py @@ -71,6 +71,27 @@ def _auto_title_enabled() -> bool: return True +def _summarize_user_message(user_message: str) -> str: + """Collapse a slash-skill-expanded turn back to what the user typed. + + A ``/skill`` invocation expands into a message that embeds the whole skill + body, so feeding it to the titler verbatim titles the session after the + *skill's* prose — "Kick off a task in a fresh isolated git worktree" — not + after the user's request. Reuse the canonical scaffolding parser so the + model sees ``/work — fix the title leak`` instead. + """ + if not user_message: + return "" + try: + from agent.skill_commands import describe_skill_invocation + + described = describe_skill_invocation(user_message) + except Exception: + logger.debug("Skill-scaffolding summary failed; titling raw", exc_info=True) + return user_message + return described if described is not None else user_message + + def generate_title( user_message: str, assistant_response: str, @@ -110,7 +131,7 @@ def generate_title( logger.debug("Title runtime validator raised; proceeding", exc_info=True) # Truncate long messages to keep the request small - user_snippet = user_message[:500] if user_message else "" + user_snippet = _summarize_user_message(user_message)[:500] assistant_snippet = assistant_response[:500] if assistant_response else "" language = _title_language() @@ -143,6 +164,11 @@ def generate_title( title = title.strip('"\'') if title.lower().startswith("title:"): title = title[6:].strip() + # A title is one line. A model that ignores "return ONLY the title" and + # answers the prompt instead (a shell transcript, a bulleted plan) would + # otherwise be stored verbatim and truncated mid-command. Keep the first + # non-empty line — the closest thing to a title in that response. + title = next((line.strip() for line in title.splitlines() if line.strip()), "") # Enforce reasonable length if len(title) > 80: title = title[:77] + "..." diff --git a/agent/tool_executor.py b/agent/tool_executor.py index d235de36c03d..688d5720df2e 100644 --- a/agent/tool_executor.py +++ b/agent/tool_executor.py @@ -20,6 +20,7 @@ import os import random import threading import time +from dataclasses import dataclass from typing import Any, Optional from agent.display import ( @@ -31,7 +32,6 @@ from agent.display import ( redact_tool_args_for_display as _redact_tool_args_for_display, _detect_tool_failure, ) -from agent.tool_guardrails import ToolGuardrailDecision from agent.tool_dispatch_helpers import ( _is_destructive_command, _is_multimodal_tool_result, @@ -140,8 +140,8 @@ def _flush_session_db_after_tool_progress( messages: list, *, stage: str, -) -> None: - """Best-effort incremental SessionDB flush for tool-call progress. +) -> bool: + """Flush tool-call progress before projecting it to any UI surface. Tool execution can perform side effects that terminate or restart the current Hermes process before the normal turn-end persistence path runs. @@ -149,9 +149,14 @@ def _flush_session_db_after_tool_progress( transcript survives destructive-but-valid tool calls. """ try: - agent._flush_messages_to_session_db(messages) + persisted = agent._flush_messages_to_session_db(messages) is not False + if not persisted: + agent._incremental_persistence_failed = True + return persisted except Exception as exc: + agent._incremental_persistence_failed = True logger.warning("Incremental tool-call persistence failed after %s: %s", stage, exc) + return False def _ra(): @@ -287,31 +292,63 @@ def _tool_search_scoped_names(agent) -> frozenset: return names -def _apply_tool_request_middleware_for_agent( - agent, - *, - function_name: str, - function_args: dict, - effective_task_id: str, - tool_call_id: str, -) -> tuple[dict, list[dict[str, Any]]]: - try: - from hermes_cli.middleware import apply_tool_request_middleware +@dataclass +class _ManagedToolResult: + result: Any + args: dict[str, Any] + middleware_trace: list[dict[str, Any]] + blocked: bool - result = apply_tool_request_middleware( - function_name, - function_args, - task_id=effective_task_id or "", - session_id=getattr(agent, "session_id", "") or "", - tool_call_id=tool_call_id or "", - turn_id=getattr(agent, "_current_turn_id", "") or "", - api_request_id=getattr(agent, "_current_api_request_id", "") or "", - ) - payload = result.payload if isinstance(result.payload, dict) else function_args - return payload, list(result.trace) - except Exception as exc: - logger.debug("tool_request middleware error: %s", exc) - return function_args, [] + +class _ConcurrentToolAuthorizationGate: + """Serialize policy prompts and exclude their queue from batch deadlines.""" + + def __init__(self) -> None: + self._serialization_lock = threading.Lock() + self._state_lock = threading.Lock() + self._pending = 0 + self._window_started: float | None = None + self._excluded_seconds = 0.0 + + def run(self, callback): + now = time.monotonic() + with self._state_lock: + if self._pending == 0: + self._window_started = now + self._pending += 1 + try: + with self._serialization_lock: + return callback() + finally: + now = time.monotonic() + with self._state_lock: + self._pending -= 1 + if self._pending == 0: + if self._window_started is not None: + self._excluded_seconds += max( + 0.0, now - self._window_started + ) + self._window_started = None + + def excluded_seconds(self) -> float: + """Return completed plus currently active authorization wait time.""" + now = time.monotonic() + with self._state_lock: + excluded = self._excluded_seconds + if self._window_started is not None: + excluded += max(0.0, now - self._window_started) + return excluded + + +def _managed_values( + outcome: _ManagedToolResult, +) -> tuple[Any, dict[str, Any], list[dict[str, Any]], bool]: + return ( + outcome.result, + outcome.args, + outcome.middleware_trace, + outcome.blocked, + ) def _run_agent_tool_execution_middleware( @@ -322,28 +359,271 @@ def _run_agent_tool_execution_middleware( effective_task_id: str, tool_call_id: str, execute, -) -> tuple[Any, dict]: - observed_args = function_args + scope_block: str | None = None, + display_index: int | None = None, + middleware_trace: list[dict[str, Any]] | None = None, + begin_execution=None, + authorization_gate: _ConcurrentToolAuthorizationGate | None = None, +) -> _ManagedToolResult: + """Run Relay rewrites before Hermes policy and dispatch exactly once.""" + from agent import relay_tools + from hermes_cli.middleware import ( + apply_tool_request_middleware, + run_tool_execution_middleware, + ) - def _execute(next_args: dict) -> Any: - nonlocal observed_args - observed_args = next_args if isinstance(next_args, dict) else function_args - return execute(observed_args) + trace = middleware_trace if middleware_trace is not None else [] + state = { + "args": function_args, + "middleware_trace": trace, + "blocked": False, + "dispatched": False, + } + dispatch_lock = threading.Lock() - from hermes_cli.middleware import run_tool_execution_middleware + def _authorized_dispatch(final_args: dict[str, Any]) -> Any: + with dispatch_lock: + if state["dispatched"]: + raise RuntimeError( + "Hermes tool execution callback invoked more than once" + ) + state["dispatched"] = True + state["blocked"] = False + state["args"] = final_args - result = run_tool_execution_middleware( + def _begin() -> None: + _begin_tool_execution( + agent, + function_name=function_name, + function_args=final_args, + effective_task_id=effective_task_id, + tool_call_id=tool_call_id, + display_index=display_index, + ) + + def _advance_start_order(callback=None) -> None: + if begin_execution is None: + if callback is not None: + callback() + return + begin_execution(callback) + + block_message = scope_block + block_error_type = "tool_scope_block" + if block_message is None: + block_error_type = "plugin_block" + + def _resolve_pre_tool_block(): + try: + from hermes_cli.plugins import resolve_pre_tool_block + + return resolve_pre_tool_block( + function_name, + final_args, + task_id=effective_task_id or "", + session_id=getattr(agent, "session_id", "") or "", + tool_call_id=tool_call_id or "", + turn_id=getattr(agent, "_current_turn_id", "") or "", + api_request_id=getattr(agent, "_current_api_request_id", "") + or "", + middleware_trace=list(state["middleware_trace"]), + ) + except Exception: + return None + + block_message = ( + _resolve_pre_tool_block() + if authorization_gate is None + else authorization_gate.run(_resolve_pre_tool_block) + ) + + guardrail_decision = None + if block_message is None: + guardrail_decision = agent._tool_guardrails.before_call( + function_name, final_args + ) + if guardrail_decision.allows_execution: + guardrail_decision = None + + if block_message is not None or guardrail_decision is not None: + _advance_start_order() + state["blocked"] = True + if block_message is not None: + result = json.dumps({"error": block_message}, ensure_ascii=False) + error_type = block_error_type + error_message = block_message + else: + result = agent._guardrail_block_result(guardrail_decision) + error_type = "guardrail_block" + error_message = ( + getattr(guardrail_decision, "message", None) + or "Tool blocked by guardrail policy" + ) + _emit_terminal_post_tool_call( + agent, + function_name=function_name, + function_args=final_args, + result=result, + effective_task_id=effective_task_id, + tool_call_id=tool_call_id, + status="blocked", + error_type=error_type, + error_message=error_message, + middleware_trace=list(state["middleware_trace"]), + ) + return result + + if function_name == "memory": + agent._turns_since_memory = 0 + elif function_name == "skill_manage": + agent._iters_since_skill = 0 + + _advance_start_order(_begin) + return execute(final_args) + + def _hermes_pipeline(relay_args: dict[str, Any]) -> Any: + request_result = apply_tool_request_middleware( + function_name, + relay_args, + skip_relay=True, + task_id=effective_task_id or "", + session_id=getattr(agent, "session_id", "") or "", + tool_call_id=tool_call_id or "", + turn_id=getattr(agent, "_current_turn_id", "") or "", + api_request_id=getattr(agent, "_current_api_request_id", "") or "", + ) + request_args = ( + request_result.payload + if isinstance(request_result.payload, dict) + else relay_args + ) + trace.clear() + trace.extend(request_result.trace) + return run_tool_execution_middleware( + function_name, + request_args, + lambda next_args: _authorized_dispatch( + next_args if isinstance(next_args, dict) else request_args + ), + original_args=function_args, + task_id=effective_task_id or "", + session_id=getattr(agent, "session_id", "") or "", + tool_call_id=tool_call_id or "", + turn_id=getattr(agent, "_current_turn_id", "") or "", + api_request_id=getattr(agent, "_current_api_request_id", "") or "", + ) + + result, _relay_args = relay_tools.execute( function_name, function_args, - _execute, - original_args=function_args, - task_id=effective_task_id or "", - session_id=getattr(agent, "session_id", "") or "", - tool_call_id=tool_call_id or "", - turn_id=getattr(agent, "_current_turn_id", "") or "", - api_request_id=getattr(agent, "_current_api_request_id", "") or "", + _hermes_pipeline, + session_id=str(getattr(agent, "session_id", "") or ""), + metadata={ + "task_id": effective_task_id or "", + "turn_id": getattr(agent, "_current_turn_id", "") or "", + "api_request_id": getattr(agent, "_current_api_request_id", "") or "", + "tool_call_id": tool_call_id or "", + }, ) - return result, observed_args + return _ManagedToolResult( + result=result, + args=state["args"], + middleware_trace=state["middleware_trace"], + blocked=bool(state["blocked"]), + ) + + +def _begin_tool_execution( + agent, + *, + function_name: str, + function_args: dict[str, Any], + effective_task_id: str, + tool_call_id: str, + display_index: int | None, +) -> None: + """Run user-visible and checkpoint preflight on final tool arguments.""" + if not agent.quiet_mode and getattr(agent, "tool_progress_mode", "all") != "off": + display_args = ( + _redact_tool_args_for_display(function_name, function_args) or function_args + ) + args_str = json.dumps(display_args, ensure_ascii=False) + prefix = f"Tool {display_index}" if display_index is not None else "Tool" + if agent.verbose_logging: + print(f" 📞 {prefix}: {function_name}({list(display_args.keys())})") + print( + agent._wrap_verbose( + "Args: ", json.dumps(display_args, indent=2, ensure_ascii=False) + ) + ) + else: + args_preview = ( + args_str[: agent.log_prefix_chars] + "..." + if len(args_str) > agent.log_prefix_chars + else args_str + ) + print( + f" 📞 {prefix}: {function_name}({list(function_args.keys())}) - " + f"{args_preview}" + ) + + agent._current_tool = function_name + agent._touch_activity(f"executing tool: {function_name}") + try: + from tools.environments.base import set_activity_callback + + set_activity_callback(agent._touch_activity) + except Exception: + pass + + if agent.tool_progress_callback: + try: + display_args = ( + _redact_tool_args_for_display(function_name, function_args) + or function_args + ) + preview = _build_tool_preview(function_name, display_args) + agent.tool_progress_callback( + "tool.started", function_name, preview, display_args + ) + except Exception as callback_error: + logging.debug("Tool progress callback error: %s", callback_error) + + if agent.tool_start_callback: + try: + display_args = ( + _redact_tool_args_for_display(function_name, function_args) + or function_args + ) + agent.tool_start_callback( + tool_call_id, function_name, display_args + ) + except Exception as callback_error: + logging.debug("Tool start callback error: %s", callback_error) + + if function_name in {"write_file", "patch"} and agent._checkpoint_mgr.enabled: + try: + _ensure_file_checkpoint( + agent, + function_name, + function_args, + effective_task_id, + ) + except Exception: + pass + + if function_name == "terminal" and agent._checkpoint_mgr.enabled: + try: + command = function_args.get("command", "") + if _is_destructive_command(command): + cwd = function_args.get("workdir") or os.getenv( + "TERMINAL_CWD", os.getcwd() + ) + agent._checkpoint_mgr.ensure_checkpoint( + cwd, f"before terminal: {command[:60]}" + ) + except Exception: + pass def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effective_task_id: str, api_call_count: int = 0, *, finalize: bool = True) -> None: @@ -381,7 +661,9 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe return # ── Parse args + pre-execution bookkeeping ─────────────────────── - parsed_calls = [] # list of (tool_call, function_name, function_args, middleware_trace, block_result, blocked_by_guardrail) + # (tool call, resolved name, parsed args, middleware trace, parse error, + # tool-search scope block) + parsed_calls = [] for tool_call in tool_calls: function_name = tool_call.function.name @@ -397,17 +679,11 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe function_args, [], malformed_args_result, - False, + None, ) ) continue - # Reset nudge counters only for a structurally valid invocation. - if function_name == "memory": - agent._turns_since_memory = 0 - elif function_name == "skill_manage": - agent._iters_since_skill = 0 - # ── Tool Search unwrap ──────────────────────────────────────── # When the model invokes the tool_call bridge, peel it open so # every downstream check (checkpointing, guardrails, plugin @@ -431,170 +707,68 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe _underlying, _underlying_args, _err = _ts.resolve_underlying_call(function_args) if not _err and _underlying: if _underlying in _tool_search_scoped_names(agent): - function_name = _underlying - function_args = _underlying_args + # Probe-validate before unwrapping (ironclaw#5149): + # missing required args return the parameter schema + # instead of dispatching into an opaque failure. + _probe_err = _ts.validate_deferred_call_args(_underlying, _underlying_args) + if _probe_err is not None: + _ts_scope_block = _probe_err + else: + function_name = _underlying + function_args = _underlying_args else: - _ts_scope_block = json.dumps({ - "error": ( - f"'{_underlying}' is not available in this session. " - "Use tool_search to find tools you can call." - ), - }, ensure_ascii=False) + _ts_scope_block = ( + f"'{_underlying}' is not available in this session. " + "Use tool_search to find tools you can call." + ) except Exception: pass - function_args, middleware_trace = _apply_tool_request_middleware_for_agent( - agent, - function_name=function_name, - function_args=function_args, - effective_task_id=effective_task_id, - tool_call_id=getattr(tool_call, "id", "") or "", + parsed_calls.append( + (tool_call, function_name, function_args, [], None, _ts_scope_block) ) - # ── Block evaluation (BEFORE checkpoint preflight) ─────────── - # We must know whether the tool will execute before touching - # checkpoint state (dedup slot, real snapshots). - block_result = None - blocked_by_guardrail = False - if _ts_scope_block is not None: - # Out-of-scope tool_call: reject before hooks/guardrails/dispatch. - block_result = _ts_scope_block - _emit_terminal_post_tool_call( - agent, - function_name=function_name, - function_args=function_args, - result=block_result, - effective_task_id=effective_task_id, - tool_call_id=getattr(tool_call, "id", "") or "", - status="blocked", - error_type="tool_scope_block", - error_message=_ts_scope_block, - middleware_trace=list(middleware_trace), - ) - else: - try: - from hermes_cli.plugins import resolve_pre_tool_block - block_message = resolve_pre_tool_block( - function_name, - function_args, - task_id=effective_task_id or "", - session_id=getattr(agent, "session_id", "") or "", - tool_call_id=getattr(tool_call, "id", "") or "", - turn_id=getattr(agent, "_current_turn_id", "") or "", - api_request_id=getattr(agent, "_current_api_request_id", "") or "", - middleware_trace=list(middleware_trace), - ) - except Exception: - block_message = None - - if block_message is not None: - block_result = json.dumps({"error": block_message}, ensure_ascii=False) - _emit_terminal_post_tool_call( - agent, - function_name=function_name, - function_args=function_args, - result=block_result, - effective_task_id=effective_task_id, - tool_call_id=getattr(tool_call, "id", "") or "", - status="blocked", - error_type="plugin_block", - error_message=block_message, - middleware_trace=list(middleware_trace), - ) - else: - guardrail_decision = agent._tool_guardrails.before_call(function_name, function_args) - if not guardrail_decision.allows_execution: - block_result = agent._guardrail_block_result(guardrail_decision) - blocked_by_guardrail = True - _emit_terminal_post_tool_call( - agent, - function_name=function_name, - function_args=function_args, - result=block_result, - effective_task_id=effective_task_id, - tool_call_id=getattr(tool_call, "id", "") or "", - status="blocked", - error_type="guardrail_block", - error_message=getattr(guardrail_decision, "message", None) or "Tool blocked by guardrail policy", - middleware_trace=list(middleware_trace), - ) - - # ── Checkpoint preflight (only for tools that will execute) ── - if block_result is None: - # Checkpoint for file-mutating tools - if function_name in {"write_file", "patch"} and agent._checkpoint_mgr.enabled: - try: - _ensure_file_checkpoint( - agent, - function_name, - function_args, - effective_task_id, - ) - except Exception: - pass - - # Checkpoint before destructive terminal commands - if function_name == "terminal" and agent._checkpoint_mgr.enabled: - try: - cmd = function_args.get("command", "") - if _is_destructive_command(cmd): - cwd = function_args.get("workdir") or os.getenv("TERMINAL_CWD", os.getcwd()) - agent._checkpoint_mgr.ensure_checkpoint( - cwd, f"before terminal: {cmd[:60]}" - ) - except Exception: - pass - - parsed_calls.append((tool_call, function_name, function_args, middleware_trace, block_result, blocked_by_guardrail)) - # ── Logging / callbacks ────────────────────────────────────────── tool_names_str = ", ".join(name for _, name, _, _, _, _ in parsed_calls) if not agent.quiet_mode and getattr(agent, "tool_progress_mode", "all") != "off": print(f" ⚡ Concurrent: {num_tools} tool calls — {tool_names_str}") - for i, (tc, name, args, middleware_trace, block_result, blocked_by_guardrail) in enumerate(parsed_calls, 1): - display_args = _redact_tool_args_for_display(name, args) or args - args_str = json.dumps(display_args, ensure_ascii=False) - if agent.verbose_logging: - print(f" 📞 Tool {i}: {name}({list(display_args.keys())})") - print(agent._wrap_verbose("Args: ", json.dumps(display_args, indent=2, ensure_ascii=False))) - else: - args_preview = args_str[:agent.log_prefix_chars] + "..." if len(args_str) > agent.log_prefix_chars else args_str - print(f" 📞 Tool {i}: {name}({list(args.keys())}) - {args_preview}") - - for tc, name, args, middleware_trace, block_result, blocked_by_guardrail in parsed_calls: - if block_result is not None: - continue - if agent.tool_progress_callback: - try: - display_args = _redact_tool_args_for_display(name, args) or args - preview = _build_tool_preview(name, display_args) - agent.tool_progress_callback("tool.started", name, preview, display_args) - except Exception as cb_err: - logging.debug(f"Tool progress callback error: {cb_err}") - - for tc, name, args, middleware_trace, block_result, blocked_by_guardrail in parsed_calls: - if block_result is not None: - continue - if agent.tool_start_callback: - try: - display_args = _redact_tool_args_for_display(name, args) or args - agent.tool_start_callback(tc.id, name, display_args) - except Exception as cb_err: - logging.debug(f"Tool start callback error: {cb_err}") # ── Concurrent execution ───────────────────────────────────────── # Each slot holds (function_name, function_args, function_result, duration, error_flag, blocked_flag, middleware_trace) results = [None] * num_tools - for i, (tc, name, args, middleware_trace, block_result, blocked_by_guardrail) in enumerate(parsed_calls): + for i, (tc, name, args, middleware_trace, block_result, _scope_block) in enumerate(parsed_calls): if block_result is not None: results[i] = (name, args, block_result, 0.0, True, True, middleware_trace) + start_condition = threading.Condition() + next_start_order = 0 + authorization_gate = _ConcurrentToolAuthorizationGate() + + def _begin_in_order(order: int, callback=None) -> None: + nonlocal next_start_order + with start_condition: + start_condition.wait_for(lambda: order == next_start_order) + try: + if callback is not None: + callback() + finally: + next_start_order += 1 + start_condition.notify_all() + # Touch activity before launching workers so the gateway knows # we're executing tools (not stuck). agent._current_tool = tool_names_str agent._touch_activity(f"executing {num_tools} tools concurrently: {tool_names_str}") - def _run_tool(index, tool_call, function_name, function_args, middleware_trace): + def _run_tool( + index, + tool_call, + function_name, + function_args, + middleware_trace, + scope_block, + start_order, + ): """Worker function executed in a thread.""" # Register this worker tid so the agent can fan out an interrupt # to it — see AIAgent.interrupt(). Must happen first thing, and @@ -624,18 +798,50 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe # ContextVars are propagated by propagate_context_to_thread() at the # submit site below (GHSA-qg5c-hvr5-hjgr, #13617). start = time.time() + blocked = False + start_advanced = False + + def _advance_start(callback=None) -> None: + nonlocal start_advanced + if start_advanced: + return + try: + _begin_in_order(start_order, callback) + finally: + start_advanced = True + try: try: - result = agent._invoke_tool( - function_name, - function_args, - effective_task_id, - tool_call.id, - messages=messages, - pre_tool_block_checked=True, - skip_tool_request_middleware=True, - tool_request_middleware_trace=list(middleware_trace), + def _execute(next_args: dict[str, Any]) -> Any: + return agent._invoke_tool( + function_name, + next_args, + effective_task_id, + tool_call.id, + messages=messages, + pre_tool_block_checked=True, + skip_tool_request_middleware=True, + skip_tool_execution_middleware=True, + tool_request_middleware_trace=list(middleware_trace), + ) + + managed = _run_agent_tool_execution_middleware( + agent, + function_name=function_name, + function_args=function_args, + effective_task_id=effective_task_id, + tool_call_id=getattr(tool_call, "id", "") or "", + execute=_execute, + scope_block=scope_block, + display_index=index + 1, + middleware_trace=middleware_trace, + begin_execution=_advance_start, + authorization_gate=authorization_gate, ) + result = managed.result + function_args = managed.args + middleware_trace = managed.middleware_trace + blocked = managed.blocked except KeyboardInterrupt: try: agent.interrupt("keyboard interrupt") @@ -652,7 +858,15 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe ) duration = time.time() - start logger.info("tool %s cancelled (%.2fs)", function_name, duration) - results[index] = (function_name, function_args, result, duration, True, False, middleware_trace) + results[index] = ( + function_name, + function_args, + result, + duration, + True, + False, + middleware_trace, + ) return except Exception as tool_error: result = f"Error executing tool '{function_name}': {tool_error}" @@ -663,8 +877,17 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe logger.info("tool %s failed (%.2fs): %s", function_name, duration, result[:200]) else: logger.info("tool %s completed (%.2fs, %d chars)", function_name, duration, len(result)) - results[index] = (function_name, function_args, result, duration, is_error, False, middleware_trace) + results[index] = ( + function_name, + function_args, + result, + duration, + is_error, + blocked, + middleware_trace, + ) finally: + _advance_start() # Tear down worker-tid tracking. Clear any interrupt bit we may # have set so the next task scheduled onto this recycled tid # starts with a clean slate. This MUST be in a finally block @@ -687,9 +910,11 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe try: runnable_calls = [ - (i, tc, name, args) - for i, (tc, name, args, middleware_trace, block_result, blocked_by_guardrail) in enumerate(parsed_calls) - if block_result is None + (i, tc, name, args, scope_block) + for i, (tc, name, args, _trace, parse_error, scope_block) in enumerate( + parsed_calls + ) + if parse_error is None ] futures = [] future_to_index = {} @@ -707,13 +932,22 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe executor = DaemonThreadPoolExecutor(max_workers=max_workers) abandon_executor = False try: - for submit_index, (i, tc, name, args) in enumerate(runnable_calls): + for submit_index, (i, tc, name, args, scope_block) in enumerate( + runnable_calls + ): # Propagate the agent turn's ContextVars (e.g. # _approval_session_key) AND thread-local approval/sudo # callbacks into the worker thread; clears callbacks on exit. try: f = executor.submit( - propagate_context_to_thread(_run_tool), i, tc, name, args, parsed_calls[i][3] + propagate_context_to_thread(_run_tool), + i, + tc, + name, + args, + parsed_calls[i][3], + scope_block, + submit_index, ) except RuntimeError as submit_error: if not _is_interpreter_shutdown_submit_error(submit_error): @@ -724,7 +958,13 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe "skipping %d unsubmitted tool(s)", len(skipped_calls), ) - for skipped_i, _tc, skipped_name, skipped_args in skipped_calls: + for ( + skipped_i, + _tc, + skipped_name, + skipped_args, + _scope_block, + ) in skipped_calls: if results[skipped_i] is None: middleware_trace = parsed_calls[skipped_i][3] result = ( @@ -754,7 +994,10 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe while True: wait_timeout = 5.0 if deadline is not None: - remaining = deadline - time.monotonic() + effective_deadline = ( + deadline + authorization_gate.excluded_seconds() + ) + remaining = effective_deadline - time.monotonic() if remaining <= 0: done, not_done = set(), { f for f in futures if not f.done() @@ -771,7 +1014,11 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe if not not_done: break - if deadline is not None and time.monotonic() >= deadline: + if ( + deadline is not None + and time.monotonic() + >= deadline + authorization_gate.excluded_seconds() + ): abandon_executor = True timed_out_indices = { future_to_index[f] @@ -851,9 +1098,13 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe spinner.stop(f"⚡ {completed}/{num_tools} tools completed in {total_dur:.1f}s total") # ── Post-execution: display per-tool results ───────────────────── - for i, (tc, name, args, middleware_trace, block_result, blocked_by_guardrail) in enumerate(parsed_calls): + for i, (tc, name, args, middleware_trace, _parse_error, _scope_block) in enumerate( + parsed_calls + ): r = results[i] blocked = False + is_error = True + progress_function_name = name # A worker can finish and write results[i] in the window between the # deadline snapshot (timed_out_indices, taken from not_done) and this # loop. Prefer that real result over a fabricated timeout message — the @@ -909,6 +1160,9 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe tool_duration = 0.0 else: function_name, function_args, function_result, tool_duration, is_error, blocked, middleware_trace = r + name = function_name + args = function_args + progress_function_name = function_name if blocked: effect_disposition = "none" @@ -936,43 +1190,15 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe except Exception as _ver_err: logging.debug("file-mutation verifier record failed: %s", _ver_err) - if not blocked and agent.tool_progress_callback: - try: - agent.tool_progress_callback( - "tool.completed", function_name, None, None, - duration=tool_duration, is_error=is_error, - result=function_result, - ) - except Exception as cb_err: - logging.debug(f"Tool progress callback error: {cb_err}") - if agent.verbose_logging: logging.debug(f"Tool {function_name} completed in {tool_duration:.2f}s") logging.debug(f"Tool result ({len(function_result)} chars): {function_result}") - # Print cute message per tool - if agent._should_emit_quiet_tool_messages(): - cute_msg = _get_cute_tool_message_impl(name, args, tool_duration, result=function_result) - agent._safe_print(f" {cute_msg}") - elif not agent.quiet_mode and getattr(agent, "tool_progress_mode", "all") != "off": - _preview_str = _multimodal_text_summary(function_result) - if agent.verbose_logging: - print(f" ✅ Tool {i+1} completed in {tool_duration:.2f}s") - print(agent._wrap_verbose("Result: ", _preview_str)) - else: - response_preview = _preview_str[:agent.log_prefix_chars] + "..." if len(_preview_str) > agent.log_prefix_chars else _preview_str - print(f" ✅ Tool {i+1} completed in {tool_duration:.2f}s - {response_preview}") - agent._current_tool = None - agent._touch_activity(f"tool completed: {name} ({tool_duration:.1f}s)") - - if not blocked and agent.tool_complete_callback: - try: - display_args = _redact_tool_args_for_display(name, args) or args - agent.tool_complete_callback(tc.id, name, display_args, function_result) - except Exception as cb_err: - logging.debug(f"Tool complete callback error: {cb_err}") + _status_suffix = " (error)" if is_error else "" + agent._touch_activity(f"tool completed: {name} ({tool_duration:.1f}s){_status_suffix}") + display_function_result = function_result function_result = maybe_persist_tool_result( content=function_result, tool_name=name, @@ -1007,6 +1233,50 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe ) messages.append(tool_message) risk_metadata = tool_message.get("_tool_output_risk") + if not _flush_session_db_after_tool_progress( + agent, + messages, + stage=f"tool result {name}", + ): + return + + # Every completion surface is downstream of the canonical append. If + # the UI bridge or process dies while projecting one of these events, + # resume can reconstruct the tool result that was already visible. + if not blocked and agent.tool_progress_callback: + try: + agent.tool_progress_callback( + "tool.completed", progress_function_name, None, None, + duration=tool_duration, is_error=is_error, + result=display_function_result, + ) + except Exception as cb_err: + logging.debug(f"Tool progress callback error: {cb_err}") + + # Print cute message per tool + if agent._should_emit_quiet_tool_messages(): + cute_msg = _get_cute_tool_message_impl( + name, args, tool_duration, result=display_function_result, + ) + agent._safe_print(f" {cute_msg}") + elif not agent.quiet_mode and getattr(agent, "tool_progress_mode", "all") != "off": + _preview_str = _multimodal_text_summary(display_function_result) + if agent.verbose_logging: + print(f" ✅ Tool {i+1} completed in {tool_duration:.2f}s") + print(agent._wrap_verbose("Result: ", _preview_str)) + else: + response_preview = _preview_str[:agent.log_prefix_chars] + "..." if len(_preview_str) > agent.log_prefix_chars else _preview_str + print(f" ✅ Tool {i+1} completed in {tool_duration:.2f}s - {response_preview}") + + if not blocked and agent.tool_complete_callback: + try: + display_args = _redact_tool_args_for_display(name, args) or args + agent.tool_complete_callback( + tc.id, name, display_args, display_function_result, + ) + except Exception as cb_err: + logging.debug(f"Tool complete callback error: {cb_err}") + if ( risk_metadata is not None and risk_metadata.get("risk") != "low" @@ -1023,11 +1293,6 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effe ) except Exception as cb_err: logging.debug("Tool output risk callback error: %s", cb_err) - _flush_session_db_after_tool_progress( - agent, - messages, - stage=f"tool result {name}", - ) # ── Per-tool /steer drain ─────────────────────────────────── # Same as the sequential path: drain between each collected @@ -1059,6 +1324,8 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe # Resolve the context-scaled tool-output budget once per turn. _tool_budget = _budget_for_agent(agent) for i, tool_call in enumerate(assistant_message.tool_calls, 1): + if getattr(agent, "_incremental_persistence_failed", False): + return # SAFETY: check interrupt BEFORE starting each tool. # If the user sent "stop" during a previous tool's execution, # do NOT start any more tools -- skip them all immediately. @@ -1074,11 +1341,12 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe skipped_tc.id, effect_disposition="none", )) - _flush_session_db_after_tool_progress( + if not _flush_session_db_after_tool_progress( agent, messages, stage=f"cancelled tool result {skipped_name}", - ) + ): + return break function_name = tool_call.function.name @@ -1094,11 +1362,12 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe tool_call.id, ) ) - _flush_session_db_after_tool_progress( + if not _flush_session_db_after_tool_progress( agent, messages, stage=f"invalid tool arguments {function_name}", - ) + ): + return agent._apply_pending_steer_to_tool_results(messages, 1) continue @@ -1112,8 +1381,25 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe _underlying, _underlying_args, _err = _ts.resolve_underlying_call(function_args) if not _err and _underlying: if _underlying in _tool_search_scoped_names(agent): - function_name = _underlying - function_args = _underlying_args + # Probe-validate before unwrapping (ironclaw#5149): + # missing required args return the parameter schema + # instead of dispatching into an opaque failure. + _probe_err = _ts.validate_deferred_call_args(_underlying, _underlying_args) + if _probe_err is not None: + # This path wraps _block_msg in {"error": ...} — + # flatten the probe payload to one plain string. + try: + _probe = json.loads(_probe_err) + _ts_scope_block = ( + f"{_probe.get('error', '')} Parameters schema: " + f"{json.dumps(_probe.get('parameters', {}), ensure_ascii=False)}. " + f"{_probe.get('hint', '')}" + ).strip() + except Exception: + _ts_scope_block = _probe_err + else: + function_name = _underlying + function_args = _underlying_args else: _ts_scope_block = ( f"'{_underlying}' is not available in this session. " @@ -1122,153 +1408,12 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe except Exception: pass - function_args, middleware_trace = _apply_tool_request_middleware_for_agent( - agent, - function_name=function_name, - function_args=function_args, - effective_task_id=effective_task_id, - tool_call_id=getattr(tool_call, "id", "") or "", - ) - - # Check plugin hooks for a block directive before executing. - _block_msg: Optional[str] = None - _block_error_type = "plugin_block" - if _ts_scope_block is not None: - _block_msg = _ts_scope_block - _block_error_type = "tool_scope_block" - else: - try: - from hermes_cli.plugins import resolve_pre_tool_block - _block_msg = resolve_pre_tool_block( - function_name, - function_args, - task_id=effective_task_id or "", - session_id=getattr(agent, "session_id", "") or "", - tool_call_id=getattr(tool_call, "id", "") or "", - turn_id=getattr(agent, "_current_turn_id", "") or "", - api_request_id=getattr(agent, "_current_api_request_id", "") or "", - middleware_trace=list(middleware_trace), - ) - except Exception: - pass - - _guardrail_block_decision: ToolGuardrailDecision | None = None - if _block_msg is None: - guardrail_decision = agent._tool_guardrails.before_call(function_name, function_args) - if not guardrail_decision.allows_execution: - _guardrail_block_decision = guardrail_decision - - _execution_blocked = _block_msg is not None or _guardrail_block_decision is not None - - if _execution_blocked: - # Tool blocked by plugin or guardrail policy — skip counters, - # callbacks, checkpointing, activity mutation, and real execution. - pass - # Reset nudge counters when the relevant tool is actually used - elif function_name == "memory": - agent._turns_since_memory = 0 - elif function_name == "skill_manage": - agent._iters_since_skill = 0 - - if not agent.quiet_mode and getattr(agent, "tool_progress_mode", "all") != "off": - display_args = _redact_tool_args_for_display(function_name, function_args) or function_args - args_str = json.dumps(display_args, ensure_ascii=False) - if agent.verbose_logging: - print(f" 📞 Tool {i}: {function_name}({list(display_args.keys())})") - print(agent._wrap_verbose("Args: ", json.dumps(display_args, indent=2, ensure_ascii=False))) - else: - args_preview = args_str[:agent.log_prefix_chars] + "..." if len(args_str) > agent.log_prefix_chars else args_str - print(f" 📞 Tool {i}: {function_name}({list(function_args.keys())}) - {args_preview}") - - if not _execution_blocked: - agent._current_tool = function_name - agent._touch_activity(f"executing tool: {function_name}") - - # Set activity callback for long-running tool execution (terminal - # commands, etc.) so the gateway's inactivity monitor doesn't kill - # the agent while a command is running. - if not _execution_blocked: - try: - from tools.environments.base import set_activity_callback - set_activity_callback(agent._touch_activity) - except Exception: - pass - - if not _execution_blocked and agent.tool_progress_callback: - try: - display_args = _redact_tool_args_for_display(function_name, function_args) or function_args - preview = _build_tool_preview(function_name, display_args) - agent.tool_progress_callback("tool.started", function_name, preview, display_args) - except Exception as cb_err: - logging.debug(f"Tool progress callback error: {cb_err}") - - if not _execution_blocked and agent.tool_start_callback: - try: - display_args = _redact_tool_args_for_display(function_name, function_args) or function_args - agent.tool_start_callback(tool_call.id, function_name, display_args) - except Exception as cb_err: - logging.debug(f"Tool start callback error: {cb_err}") - - # Checkpoint: snapshot working dir before file-mutating tools - if not _execution_blocked and function_name in {"write_file", "patch"} and agent._checkpoint_mgr.enabled: - try: - _ensure_file_checkpoint( - agent, - function_name, - function_args, - effective_task_id, - ) - except Exception: - pass # never block tool execution - - # Checkpoint before destructive terminal commands - if not _execution_blocked and function_name == "terminal" and agent._checkpoint_mgr.enabled: - try: - cmd = function_args.get("command", "") - if _is_destructive_command(cmd): - cwd = function_args.get("workdir") or os.getenv("TERMINAL_CWD", os.getcwd()) - agent._checkpoint_mgr.ensure_checkpoint( - cwd, f"before terminal: {cmd[:60]}" - ) - except Exception: - pass # never block tool execution + middleware_trace: list[dict[str, Any]] = [] + _execution_blocked = False tool_start_time = time.time() - if _block_msg is not None: - # Tool blocked by plugin policy — return error without executing. - function_result = json.dumps({"error": _block_msg}, ensure_ascii=False) - tool_duration = 0.0 - _emit_terminal_post_tool_call( - agent, - function_name=function_name, - function_args=function_args, - result=function_result, - effective_task_id=effective_task_id, - tool_call_id=getattr(tool_call, "id", "") or "", - status="blocked", - error_type=_block_error_type, - error_message=_block_msg, - middleware_trace=list(middleware_trace), - ) - elif _guardrail_block_decision is not None: - # Tool blocked by tool-loop guardrail — synthesize exactly one - # tool result for the original tool_call_id without executing. - function_result = agent._guardrail_block_result(_guardrail_block_decision) - tool_duration = 0.0 - _emit_terminal_post_tool_call( - agent, - function_name=function_name, - function_args=function_args, - result=function_result, - effective_task_id=effective_task_id, - tool_call_id=getattr(tool_call, "id", "") or "", - status="blocked", - error_type="guardrail_block", - error_message=getattr(_guardrail_block_decision, "message", None) or "Tool blocked by guardrail policy", - middleware_trace=list(middleware_trace), - ) - elif function_name == "todo": + if function_name == "todo": def _execute(next_args: dict) -> Any: from tools.todo_tool import todo_tool as _todo_tool return _todo_tool( @@ -1276,14 +1421,16 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe merge=next_args.get("merge", False), store=agent._todo_store, ) - function_result, function_args = _run_agent_tool_execution_middleware( + function_result, function_args, middleware_trace, _execution_blocked = _managed_values(_run_agent_tool_execution_middleware( agent, function_name=function_name, function_args=function_args, effective_task_id=effective_task_id, tool_call_id=getattr(tool_call, "id", "") or "", execute=_execute, - ) + scope_block=_ts_scope_block, + display_index=i, + )) tool_duration = time.time() - tool_start_time if agent._should_emit_quiet_tool_messages(): agent._vprint(f" {_get_cute_tool_message_impl('todo', function_args, tool_duration, result=function_result)}") @@ -1305,14 +1452,16 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe db=session_db, current_session_id=agent.session_id, ) - function_result, function_args = _run_agent_tool_execution_middleware( + function_result, function_args, middleware_trace, _execution_blocked = _managed_values(_run_agent_tool_execution_middleware( agent, function_name=function_name, function_args=function_args, effective_task_id=effective_task_id, tool_call_id=getattr(tool_call, "id", "") or "", execute=_execute, - ) + scope_block=_ts_scope_block, + display_index=i, + )) tool_duration = time.time() - tool_start_time if agent._should_emit_quiet_tool_messages(): agent._vprint(f" {_get_cute_tool_message_impl('session_search', function_args, tool_duration, result=function_result)}") @@ -1342,14 +1491,16 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe ), ) return result - function_result, function_args = _run_agent_tool_execution_middleware( + function_result, function_args, middleware_trace, _execution_blocked = _managed_values(_run_agent_tool_execution_middleware( agent, function_name=function_name, function_args=function_args, effective_task_id=effective_task_id, tool_call_id=getattr(tool_call, "id", "") or "", execute=_execute, - ) + scope_block=_ts_scope_block, + display_index=i, + )) tool_duration = time.time() - tool_start_time if agent._should_emit_quiet_tool_messages(): agent._vprint(f" {_get_cute_tool_message_impl('memory', function_args, tool_duration, result=function_result)}") @@ -1359,16 +1510,19 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe return _clarify_tool( question=next_args.get("question", ""), choices=next_args.get("choices"), + multi_select=next_args.get("multi_select", False), callback=agent.clarify_callback, ) - function_result, function_args = _run_agent_tool_execution_middleware( + function_result, function_args, middleware_trace, _execution_blocked = _managed_values(_run_agent_tool_execution_middleware( agent, function_name=function_name, function_args=function_args, effective_task_id=effective_task_id, tool_call_id=getattr(tool_call, "id", "") or "", execute=_execute, - ) + scope_block=_ts_scope_block, + display_index=i, + )) tool_duration = time.time() - tool_start_time if agent._should_emit_quiet_tool_messages(): agent._vprint(f" {_get_cute_tool_message_impl('clarify', function_args, tool_duration, result=function_result)}") @@ -1380,14 +1534,16 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe count=next_args.get("count"), callback=getattr(agent, "read_terminal_callback", None), ) - function_result, function_args = _run_agent_tool_execution_middleware( + function_result, function_args, middleware_trace, _execution_blocked = _managed_values(_run_agent_tool_execution_middleware( agent, function_name=function_name, function_args=function_args, effective_task_id=effective_task_id, tool_call_id=getattr(tool_call, "id", "") or "", execute=_execute, - ) + scope_block=_ts_scope_block, + display_index=i, + )) tool_duration = time.time() - tool_start_time if agent._should_emit_quiet_tool_messages(): agent._vprint(f" {_get_cute_tool_message_impl('read_terminal', function_args, tool_duration, result=function_result)}") @@ -1412,14 +1568,16 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe try: def _execute(next_args: dict) -> Any: return agent._dispatch_delegate_task(next_args) - function_result, function_args = _run_agent_tool_execution_middleware( + function_result, function_args, middleware_trace, _execution_blocked = _managed_values(_run_agent_tool_execution_middleware( agent, function_name=function_name, function_args=function_args, effective_task_id=effective_task_id, tool_call_id=getattr(tool_call, "id", "") or "", execute=_execute, - ) + scope_block=_ts_scope_block, + display_index=i, + )) _delegate_result = function_result finally: agent._delegate_spinner = None @@ -1443,14 +1601,16 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe try: def _execute(next_args: dict) -> Any: return agent.context_compressor.handle_tool_call(function_name, next_args, messages=messages) - function_result, function_args = _run_agent_tool_execution_middleware( + function_result, function_args, middleware_trace, _execution_blocked = _managed_values(_run_agent_tool_execution_middleware( agent, function_name=function_name, function_args=function_args, effective_task_id=effective_task_id, tool_call_id=getattr(tool_call, "id", "") or "", execute=_execute, - ) + scope_block=_ts_scope_block, + display_index=i, + )) _ce_result = function_result except Exception as tool_error: function_result = json.dumps({"error": f"Context engine tool '{function_name}' failed: {tool_error}"}) @@ -1477,14 +1637,16 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe try: def _execute(next_args: dict) -> Any: return agent._memory_manager.handle_tool_call(function_name, next_args) - function_result, function_args = _run_agent_tool_execution_middleware( + function_result, function_args, middleware_trace, _execution_blocked = _managed_values(_run_agent_tool_execution_middleware( agent, function_name=function_name, function_args=function_args, effective_task_id=effective_task_id, tool_call_id=getattr(tool_call, "id", "") or "", execute=_execute, - ) + scope_block=_ts_scope_block, + display_index=i, + )) _mem_result = function_result except Exception as tool_error: function_result = json.dumps({"error": f"Memory tool '{function_name}' failed: {tool_error}"}) @@ -1507,18 +1669,46 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe spinner.start() _spinner_result = None try: - function_result = _ra().handle_function_call( - function_name, function_args, effective_task_id, - tool_call_id=tool_call.id, - session_id=agent.session_id or "", - turn_id=getattr(agent, "_current_turn_id", "") or "", - api_request_id=getattr(agent, "_current_api_request_id", "") or "", - enabled_tools=list(agent.valid_tool_names) if agent.valid_tool_names else None, - skip_pre_tool_call_hook=True, - skip_tool_request_middleware=True, - enabled_toolsets=getattr(agent, "enabled_toolsets", None), - disabled_toolsets=getattr(agent, "disabled_toolsets", None), - tool_request_middleware_trace=list(middleware_trace), + def _execute(next_args: dict) -> Any: + return _ra().handle_function_call( + function_name, + next_args, + effective_task_id, + tool_call_id=tool_call.id, + session_id=agent.session_id or "", + turn_id=getattr(agent, "_current_turn_id", "") or "", + api_request_id=getattr(agent, "_current_api_request_id", "") + or "", + enabled_tools=( + list(agent.valid_tool_names) + if agent.valid_tool_names + else None + ), + skip_pre_tool_call_hook=True, + skip_tool_request_middleware=True, + skip_tool_execution_middleware=True, + tool_request_middleware_trace=list(middleware_trace), + enabled_toolsets=getattr(agent, "enabled_toolsets", None), + disabled_toolsets=getattr(agent, "disabled_toolsets", None), + ) + + ( + function_result, + function_args, + middleware_trace, + _execution_blocked, + ) = _managed_values( + _run_agent_tool_execution_middleware( + agent, + function_name=function_name, + function_args=function_args, + effective_task_id=effective_task_id, + tool_call_id=getattr(tool_call, "id", "") or "", + execute=_execute, + scope_block=_ts_scope_block, + display_index=i, + middleware_trace=middleware_trace, + ) ) _spinner_result = function_result except KeyboardInterrupt: @@ -1549,18 +1739,46 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe agent._vprint(f" {cute_msg}") else: try: - function_result = _ra().handle_function_call( - function_name, function_args, effective_task_id, - tool_call_id=tool_call.id, - session_id=agent.session_id or "", - turn_id=getattr(agent, "_current_turn_id", "") or "", - api_request_id=getattr(agent, "_current_api_request_id", "") or "", - enabled_tools=list(agent.valid_tool_names) if agent.valid_tool_names else None, - skip_pre_tool_call_hook=True, - skip_tool_request_middleware=True, - enabled_toolsets=getattr(agent, "enabled_toolsets", None), - disabled_toolsets=getattr(agent, "disabled_toolsets", None), - tool_request_middleware_trace=list(middleware_trace), + def _execute(next_args: dict) -> Any: + return _ra().handle_function_call( + function_name, + next_args, + effective_task_id, + tool_call_id=tool_call.id, + session_id=agent.session_id or "", + turn_id=getattr(agent, "_current_turn_id", "") or "", + api_request_id=getattr(agent, "_current_api_request_id", "") + or "", + enabled_tools=( + list(agent.valid_tool_names) + if agent.valid_tool_names + else None + ), + skip_pre_tool_call_hook=True, + skip_tool_request_middleware=True, + skip_tool_execution_middleware=True, + tool_request_middleware_trace=list(middleware_trace), + enabled_toolsets=getattr(agent, "enabled_toolsets", None), + disabled_toolsets=getattr(agent, "disabled_toolsets", None), + ) + + ( + function_result, + function_args, + middleware_trace, + _execution_blocked, + ) = _managed_values( + _run_agent_tool_execution_middleware( + agent, + function_name=function_name, + function_args=function_args, + effective_task_id=effective_task_id, + tool_call_id=getattr(tool_call, "id", "") or "", + execute=_execute, + scope_block=_ts_scope_block, + display_index=i, + middleware_trace=middleware_trace, + ) ) except KeyboardInterrupt: _emit_cancelled_terminal_post_tool_call( @@ -1644,31 +1862,16 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe except Exception as _ver_err: logging.debug("file-mutation verifier record failed: %s", _ver_err) - if not _execution_blocked and agent.tool_progress_callback: - try: - agent.tool_progress_callback( - "tool.completed", function_name, None, None, - duration=tool_duration, is_error=_is_error_result, - result=function_result, - ) - except Exception as cb_err: - logging.debug(f"Tool progress callback error: {cb_err}") - agent._current_tool = None - agent._touch_activity(f"tool completed: {function_name} ({tool_duration:.1f}s)") + _status_suffix = " (error)" if _is_error_result else "" + agent._touch_activity(f"tool completed: {function_name} ({tool_duration:.1f}s){_status_suffix}") if agent.verbose_logging: logging.debug(f"Tool {function_name} completed in {tool_duration:.2f}s") _log_result = _multimodal_text_summary(function_result) logging.debug(f"Tool result ({len(_log_result)} chars): {_log_result}") - if not _execution_blocked and agent.tool_complete_callback: - try: - display_args = _redact_tool_args_for_display(function_name, function_args) or function_args - agent.tool_complete_callback(tool_call.id, function_name, display_args, function_result) - except Exception as cb_err: - logging.debug(f"Tool complete callback error: {cb_err}") - + display_function_result = function_result function_result = maybe_persist_tool_result( content=function_result, tool_name=function_name, @@ -1691,6 +1894,40 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe tool_message = make_tool_result_message(function_name, _tool_content, tool_call.id) messages.append(tool_message) risk_metadata = tool_message.get("_tool_output_risk") + if not _flush_session_db_after_tool_progress( + agent, + messages, + stage=f"tool result {function_name}", + ): + return + + # UI completion/progress events are projections of the canonical tool + # row, never a competing in-memory authority. + if not _execution_blocked and agent.tool_progress_callback: + try: + agent.tool_progress_callback( + "tool.completed", function_name, None, None, + duration=tool_duration, is_error=_is_error_result, + result=display_function_result, + ) + except Exception as cb_err: + logging.debug(f"Tool progress callback error: {cb_err}") + + if not _execution_blocked and agent.tool_complete_callback: + try: + display_args = ( + _redact_tool_args_for_display(function_name, function_args) + or function_args + ) + agent.tool_complete_callback( + tool_call.id, + function_name, + display_args, + display_function_result, + ) + except Exception as cb_err: + logging.debug(f"Tool complete callback error: {cb_err}") + if ( risk_metadata is not None and risk_metadata.get("risk") != "low" @@ -1707,11 +1944,6 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe ) except Exception as cb_err: logging.debug("Tool output risk callback error: %s", cb_err) - _flush_session_db_after_tool_progress( - agent, - messages, - stage=f"tool result {function_name}", - ) # ── Per-tool /steer drain ─────────────────────────────────── # Drain pending steer BETWEEN individual tool calls so the @@ -1739,11 +1971,12 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effe skipped_tc.id, effect_disposition="none", )) - _flush_session_db_after_tool_progress( + if not _flush_session_db_after_tool_progress( agent, messages, stage=f"skipped tool result {skipped_name}", - ) + ): + return break if agent.tool_delay > 0 and i < len(assistant_message.tool_calls): @@ -1794,6 +2027,8 @@ def execute_tool_calls_segmented(agent, assistant_message, messages: list, effec segments = _plan_tool_batch_segments(assistant_message.tool_calls, execution_cwd=_exec_cwd) for kind, calls in segments: + if getattr(agent, "_incremental_persistence_failed", False): + return segment_message = SimpleNamespace(tool_calls=list(calls)) if kind == "parallel": execute_tool_calls_concurrent( @@ -1806,6 +2041,9 @@ def execute_tool_calls_segmented(agent, assistant_message, messages: list, effec finalize=False, ) + if getattr(agent, "_incremental_persistence_failed", False): + return + # ── Whole-turn finalize (budget + /steer) ───────────────────────── total_tools = len(assistant_message.tool_calls) if total_tools > 0: diff --git a/agent/tool_guardrails.py b/agent/tool_guardrails.py index f08f1b604786..444ce3739596 100644 --- a/agent/tool_guardrails.py +++ b/agent/tool_guardrails.py @@ -79,6 +79,7 @@ class ToolCallGuardrailConfig: no_progress_block_after: int = 5 idempotent_tools: frozenset[str] = field(default_factory=lambda: IDEMPOTENT_TOOL_NAMES) mutating_tools: frozenset[str] = field(default_factory=lambda: MUTATING_TOOL_NAMES) + loop_caps: "LoopCapConfig" = field(default_factory=lambda: LoopCapConfig()) @classmethod def from_mapping(cls, data: Mapping[str, Any] | None) -> "ToolCallGuardrailConfig": @@ -121,6 +122,54 @@ class ToolCallGuardrailConfig: hard_stop_after.get("idempotent_no_progress", data.get("no_progress_block_after")), defaults.no_progress_block_after, ), + loop_caps=LoopCapConfig.from_mapping(data.get("loop_caps")), + ) + + +# Default session-wide caps, matching Claude Code's v2.1.212 runaway-loop +# Per-turn (per-agent-loop) caps on runaway-prone tool calls. Counts reset at +# the start of every agent loop (reset_for_turn), so the limit is "within a +# single turn" rather than cumulative over the whole session. A single loop +# issuing dozens of web searches or spawning dozens of subagents is already +# pathological, so the defaults are deliberately low. +_DEFAULT_MAX_WEB_SEARCHES_PER_TURN = 50 +_DEFAULT_MAX_SUBAGENTS_PER_TURN = 50 + + +@dataclass(frozen=True) +class LoopCapConfig: + """Per-turn caps on runaway-prone tool calls. + + Inspired by Claude Code v2.1.212 (Week 29, July 2026), which added caps on + WebSearch calls and subagent spawns to stop runaway search / delegation + loops. Here the caps count *within a single agent loop* (one turn): the + counters reset in ``reset_for_turn`` at the start of every + ``run_conversation``, so a legitimate multi-turn session is never starved, + but a single turn that spirals into an unbounded search / delegation loop + is stopped. + + Semantics differ from the per-turn loop *detector* above (which keys on + repeated identical/failing calls): these caps are a hard ceiling on the + total count of a tool within the turn and fire regardless of + ``hard_stop_enabled``. A value of ``0`` disables the cap (unlimited). + """ + + max_web_searches: int = _DEFAULT_MAX_WEB_SEARCHES_PER_TURN + max_subagents: int = _DEFAULT_MAX_SUBAGENTS_PER_TURN + + @classmethod + def from_mapping(cls, data: Mapping[str, Any] | None) -> "LoopCapConfig": + """Build config from the ``tool_loop_guardrails.loop_caps`` section.""" + if not isinstance(data, Mapping): + return cls() + defaults = cls() + return cls( + max_web_searches=_non_negative_int( + data.get("max_web_searches"), defaults.max_web_searches + ), + max_subagents=_non_negative_int( + data.get("max_subagents"), defaults.max_subagents + ), ) @@ -233,6 +282,11 @@ class ToolCallGuardrailController: self._same_tool_failure_counts: dict[str, int] = {} self._no_progress: dict[ToolCallSignature, tuple[str, int]] = {} self._halt_decision: ToolGuardrailDecision | None = None + # Per-turn runaway-loop cap counters. Reset every turn (this method + # runs at the start of each run_conversation), so the caps bound a + # single agent loop rather than accumulating across the session. + self._turn_web_search_count = 0 + self._turn_subagent_count = 0 @property def halt_decision(self) -> ToolGuardrailDecision | None: @@ -240,6 +294,17 @@ class ToolCallGuardrailController: def before_call(self, tool_name: str, args: Mapping[str, Any] | None) -> ToolGuardrailDecision: signature = ToolCallSignature.from_call(tool_name, _coerce_args(args)) + + # ── Per-turn runaway-loop caps ────────────────────────────────── + # These are hard ceilings on how many times a runaway-prone tool may + # be called within a single agent loop (turn). They apply regardless + # of hard_stop_enabled (which only governs the per-turn loop detector). + # We block BEFORE the call runs once the count is already at the cap, + # then increment for an allowed call so the (cap+1)-th is refused. + cap_block = self._check_loop_cap(tool_name, _coerce_args(args), signature) + if cap_block is not None: + return cap_block + if not self.config.hard_stop_enabled: return ToolGuardrailDecision(tool_name=tool_name, signature=signature) @@ -379,6 +444,68 @@ class ToolCallGuardrailController: return False return tool_name in self.config.idempotent_tools + def _check_loop_cap( + self, + tool_name: str, + args: Mapping[str, Any], + signature: ToolCallSignature, + ) -> ToolGuardrailDecision | None: + """Enforce and advance the per-turn runaway-loop counters. + + Returns a ``block`` decision when the cap is already reached, otherwise + increments the relevant counter for the allowed call and returns + ``None``. A cap of 0 disables that limit entirely. Counters reset each + turn via ``reset_for_turn``. + """ + caps = self.config.loop_caps + + if tool_name == "web_search": + cap = caps.max_web_searches + if cap and self._turn_web_search_count >= cap: + decision = ToolGuardrailDecision( + action="block", + code="loop_web_search_cap", + message=( + f"Blocked web_search: this turn has already made {cap} " + "web searches, the per-turn limit. This looks like a " + "runaway search loop. Work with the results you already " + "have and give the user your answer." + ), + tool_name=tool_name, + count=self._turn_web_search_count, + signature=signature, + ) + self._halt_decision = decision + return decision + self._turn_web_search_count += 1 + return None + + if tool_name == "delegate_task": + cap = caps.max_subagents + if not cap: + return None + spawn_count = _subagent_spawn_count(args) + if self._turn_subagent_count >= cap: + decision = ToolGuardrailDecision( + action="block", + code="loop_subagent_cap", + message=( + f"Blocked delegate_task: this turn has already spawned " + f"{self._turn_subagent_count} subagents (limit {cap}). " + "This looks like a runaway delegation loop. Finish the " + "work with the results you have and answer the user." + ), + tool_name=tool_name, + count=self._turn_subagent_count, + signature=signature, + ) + self._halt_decision = decision + return decision + self._turn_subagent_count += spawn_count + return None + + return None + def toolguard_synthetic_result(decision: ToolGuardrailDecision) -> str: """Build a synthetic role=tool content string for a blocked tool call.""" @@ -471,6 +598,32 @@ def _positive_int(value: Any, default: int) -> int: return parsed if parsed >= 1 else default +def _non_negative_int(value: Any, default: int) -> int: + """Parse a session-cap value. 0 is a valid (disable) value; negatives and + junk fall back to the default.""" + if value is None: + return default + try: + parsed = int(value) + except (TypeError, ValueError): + return default + return parsed if parsed >= 0 else default + + +def _subagent_spawn_count(args: Mapping[str, Any]) -> int: + """How many subagents a single delegate_task call spawns. + + delegate_task runs in one of two modes: a batch (``tasks`` is a non-empty + list, one child per item) or a single task (``goal``). Count the batch size + when present, otherwise 1, so the session subagent cap reflects real spawns + rather than delegate_task invocations. + """ + tasks = args.get("tasks") if isinstance(args, Mapping) else None + if isinstance(tasks, list) and tasks: + return len(tasks) + return 1 + + def _sha256(value: str) -> str: # surrogatepass: tool results scraped from the web can carry unpaired # UTF-16 surrogates (e.g. half of a mathematical-bold pair); a strict diff --git a/agent/trace_upload.py b/agent/trace_upload.py index f65547440c7f..404d9be70b13 100644 --- a/agent/trace_upload.py +++ b/agent/trace_upload.py @@ -162,7 +162,7 @@ def build_trace_jsonl( if cwd: r = subprocess.run( ["git", "rev-parse", "--abbrev-ref", "HEAD"], - capture_output=True, text=True, timeout=3, cwd=cwd, + capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=3, cwd=cwd, ) if r.returncode == 0: git_branch = r.stdout.strip() diff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.py index 086883eca1c7..07f76736730a 100644 --- a/agent/transports/chat_completions.py +++ b/agent/transports/chat_completions.py @@ -378,7 +378,6 @@ class ChatCompletionsTransport(ProviderTransport): ephemeral = params.get("ephemeral_max_output_tokens") max_tokens = params.get("max_tokens") anthropic_max_out = params.get("anthropic_max_output") - is_nvidia_nim = params.get("is_nvidia_nim", False) is_kimi = params.get("is_kimi", False) is_tokenhub = params.get("is_tokenhub", False) reasoning_config = _reasoning_config_for_model(model, params.get("reasoning_config")) @@ -436,7 +435,6 @@ class ChatCompletionsTransport(ProviderTransport): extra_body: dict[str, Any] = {} is_openrouter = params.get("is_openrouter", False) - is_nous = params.get("is_nous", False) is_github_models = params.get("is_github_models", False) provider_name = str(params.get("provider_name") or "").strip().lower() base_url = params.get("base_url") diff --git a/agent/transports/codex.py b/agent/transports/codex.py index 5855fcfe9c54..15dd3409e3fc 100644 --- a/agent/transports/codex.py +++ b/agent/transports/codex.py @@ -7,6 +7,7 @@ streaming, or the _run_codex_stream() call path. import hashlib import json +import re from typing import Any, Dict, List, Optional from agent.transports.base import ProviderTransport @@ -27,6 +28,49 @@ def _bounded_prompt_cache_key(value: Any) -> Optional[str]: return f"pck_{digest}" +_EXTENDED_PROMPT_CACHE_MODELS = ( + "gpt-5.5-pro", + "gpt-5.5", + "gpt-5.4", + "gpt-5.2", + "gpt-5.1-codex-max", + "gpt-5.1-codex-mini", + "gpt-5.1-chat-latest", + "gpt-5.1-codex", + "gpt-5.1", + "gpt-5-codex", + "gpt-5", + "gpt-4.1", +) +_EXTENDED_PROMPT_CACHE_MODEL_RE = re.compile( + rf"(?:^|[./:])(?:{'|'.join(re.escape(name) for name in _EXTENDED_PROMPT_CACHE_MODELS)})" + r"(?:-\d{4}-\d{2}-\d{2})?$" +) + + +def _default_prompt_cache_retention_for_request( + model: str, + base_url: Any, +) -> Optional[str]: + """Return ``24h`` for supported models on Amazon Bedrock Mantle.""" + from utils import base_url_hostname + + hostname_parts = base_url_hostname(str(base_url or "")).split(".") + is_bedrock_mantle = ( + len(hostname_parts) == 4 + and hostname_parts[0] == "bedrock-mantle" + and bool(hostname_parts[1]) + and hostname_parts[2:] == ["api", "aws"] + ) + if not is_bedrock_mantle: + return None + + normalized = str(model or "").strip().lower().replace("_", "-") + if _EXTENDED_PROMPT_CACHE_MODEL_RE.search(normalized): + return "24h" + return None + + def _content_cache_key(instructions: str, tools: Optional[List[Dict[str, Any]]]) -> Optional[str]: """Content-address the prompt cache key from the static request prefix. @@ -284,6 +328,13 @@ class ResponsesApiTransport(ProviderTransport): if not is_github_responses and not is_xai_responses and cache_key: kwargs["prompt_cache_key"] = cache_key + cache_retention = _default_prompt_cache_retention_for_request( + model, + params.get("base_url"), + ) + if cache_retention: + kwargs.setdefault("prompt_cache_retention", cache_retention) + if reasoning_enabled and is_xai_responses: from agent.model_metadata import grok_supports_reasoning_effort diff --git a/agent/transports/codex_app_server.py b/agent/transports/codex_app_server.py index 273e44667d6a..c23ff836ed89 100644 --- a/agent/transports/codex_app_server.py +++ b/agent/transports/codex_app_server.py @@ -127,6 +127,10 @@ class CodexAppServerClient: # Codex emits tracing to stderr; default WARN keeps it quiet for users. spawn_env.setdefault("RUST_LOG", "warn") + # Hide the console the codex child would otherwise flash on Windows + # (#56747). Hide-only — stdio pipes stay intact for the app-server wire. + from hermes_cli._subprocess_compat import windows_hide_flags + self._proc = subprocess.Popen( cmd, stdin=subprocess.PIPE, @@ -134,6 +138,7 @@ class CodexAppServerClient: stderr=subprocess.PIPE, bufsize=0, env=spawn_env, + creationflags=windows_hide_flags(), ) self._next_id = 1 self._pending: dict[int, _Pending] = {} @@ -389,7 +394,7 @@ def check_codex_binary( proc = subprocess.run( [codex_bin, "--version"], capture_output=True, - text=True, + text=True, encoding='utf-8', errors='replace', timeout=10, stdin=subprocess.DEVNULL, ) diff --git a/agent/transports/codex_app_server_session.py b/agent/transports/codex_app_server_session.py index 7954ecbf4d52..e2ace753bc80 100644 --- a/agent/transports/codex_app_server_session.py +++ b/agent/transports/codex_app_server_session.py @@ -1054,6 +1054,18 @@ class CodexAppServerSession: ) def _decide_exec_approval(self, params: dict) -> str: + """Decide a Codex exec approval request. + + This is protocol-level routing only — it carries NO Hermes + approval-mode/timeout logic. The Hermes-side resolution happens + upstream: ``agent/codex_runtime.py`` derives + ``auto_approve_exec`` from the canonical + ``tools.approval.is_approval_bypass_active()`` (which reads + ``approvals.mode`` via ``tools.approval._get_approval_mode``), + and ``self._approval_callback`` itself runs the shared approval + gate (mode + ``approvals.timeout``) in ``tools/approval.py``. + Keep it that way — do not re-read approval config here. + """ if self._routing.auto_approve_exec: return "accept" command = params.get("command") or "" @@ -1077,6 +1089,12 @@ class CodexAppServerSession: return "decline" # fail-closed when no callback wired def _decide_apply_patch_approval(self, params: dict) -> str: + """Decide a Codex apply_patch approval request. + + Protocol-level routing only; Hermes approval-mode/timeout + resolution is delegated to ``tools/approval.py`` upstream — see + the docstring on ``_decide_exec_approval``. + """ if self._routing.auto_approve_apply_patch: return "accept" if self._approval_callback is not None: @@ -1231,6 +1249,11 @@ def _approval_choice_to_codex_decision(choice: str) -> str: Codex expects 'accept', 'acceptForSession', 'decline', or 'cancel' (verified against codex-rs/app-server-protocol/src/protocol/v2/item.rs on codex 0.130.0). + + This mapping is Codex-protocol-semantic and intentionally lives here, + NOT in tools/approval.py: the Hermes approval mode/timeout resolution + and the choice itself come from the shared core (tools/approval.py); + only the wire-value translation is local. """ if choice in {"once",}: return "accept" diff --git a/agent/turn_context.py b/agent/turn_context.py index 594518370920..e080d6a5d969 100644 --- a/agent/turn_context.py +++ b/agent/turn_context.py @@ -34,8 +34,11 @@ from typing import Any, Dict, List, Mapping, Optional from agent.conversation_compression import ( IDLE_COMPACTION_STATUS_TEMPLATE, PREFLIGHT_COMPRESSION_STATUS_TEMPLATE, + compression_skipped_due_to_lock, conversation_history_after_compression, + recover_rotated_compression_session, ) +from agent.context_engine import automatic_compaction_status_message from agent.iteration_budget import IterationBudget from agent.memory_manager import build_memory_context_block from agent.model_metadata import ( @@ -333,6 +336,8 @@ def build_turn_context( persist_user_message: Optional[Any], persist_user_timestamp: Optional[float] = None, *, + persist_user_display_kind: Optional[str] = None, + persist_user_display_metadata: Optional[Dict[str, Any]] = None, restore_or_build_system_prompt, install_safe_stdio, sanitize_surrogates, @@ -351,6 +356,13 @@ def build_turn_context( # Guard stdio against OSError from broken pipes (systemd/headless/daemon). install_safe_stdio() + # Recover a session rotated by another path before binding log/turn ids or + # copying client-supplied history. Everything in this turn must consistently + # belong to the canonical child, including observability metadata. + recovered_history = recover_rotated_compression_session(agent) + if recovered_history is not None: + conversation_history = recovered_history + # NOTE: the DB session row is created later, AFTER the system prompt is # restored/built (see _ensure_db_session() below the system-prompt block). # Creating it here — before _cached_system_prompt is populated — inserts a @@ -375,6 +387,7 @@ def build_turn_context( set_runtime_main( getattr(agent, "provider", "") or "", getattr(agent, "model", "") or "", + requested_provider=getattr(agent, "requested_provider", "") or "", base_url=getattr(agent, "base_url", "") or "", api_key=getattr(agent, "api_key", "") or "", api_mode=getattr(agent, "api_mode", "") or "", @@ -425,7 +438,12 @@ def build_turn_context( # Generate unique task_id if not provided to isolate VMs between tasks. effective_task_id = task_id or str(uuid.uuid4()) agent._current_task_id = effective_task_id - turn_id = f"{agent.session_id or 'session'}:{effective_task_id}:{uuid.uuid4().hex[:8]}" + turn_id = str(getattr(agent, "_relay_pending_turn_id", "") or "") + if not turn_id: + turn_id = ( + f"{agent.session_id or 'session'}:{effective_task_id}:{uuid.uuid4().hex[:8]}" + ) + agent._relay_pending_turn_id = None agent._current_turn_id = turn_id agent._current_api_request_id = "" # Tripwire: warn (with both turn ids) when this turn starts before the @@ -526,6 +544,19 @@ def build_turn_context( # Add the current user message after the prompt/session setup has made # close persistence safe. The handoff above preserves any marker already # stamped by an earlier close flush. + # + # A synthesized turn (auto-continue recovery note, delegation completion) + # declares how it should READ in a transcript. Stamp that on the live + # message so the crash persist below writes the row already typed. Typing + # it after the turn instead leaves the row untyped for the whole run — and + # forever if the turn crashes — so the raw system note paints as a user + # bubble. The model still receives role/content unchanged; the api_messages + # build strips both fields from every outgoing copy. + if persist_user_display_kind: + user_msg["display_kind"] = persist_user_display_kind + if persist_user_display_metadata: + user_msg["display_metadata"] = persist_user_display_metadata + messages.append(user_msg) current_turn_user_idx = len(messages) - 1 agent._persist_user_message_idx = current_turn_user_idx @@ -662,11 +693,18 @@ def build_turn_context( f"{_idle_floor:,}", agent.session_id or "none", ) - agent._emit_status( - IDLE_COMPACTION_STATUS_TEMPLATE.format( + _idle_status = automatic_compaction_status_message( + _compressor, + phase="idle", + default_message=IDLE_COMPACTION_STATUS_TEMPLATE.format( idle_seconds=int(_idle_gap), tokens=_idle_tokens - ) + ), + approx_tokens=_idle_tokens, + idle_seconds=int(_idle_gap), + model=agent.model, ) + if _idle_status: + agent._emit_status(_idle_status) _idle_input = messages messages, active_system_prompt = agent._compress_context( messages, system_message, approx_tokens=_idle_tokens, @@ -680,7 +718,7 @@ def build_turn_context( # untouched. if messages is not _idle_input: conversation_history = conversation_history_after_compression( - agent, messages + agent, messages, conversation_history ) # Compaction rebuilt the list, so the index of this turn's # just-appended user message is stale — re-anchor it the @@ -696,6 +734,8 @@ def build_turn_context( # issue #27405 (a few very large messages slipping past the count gate). _preflight_compressed = False _preflight_compression_blocked = False + agent._turn_received_provider_response = False + agent._turn_preflight_display_snapshot = None if agent.compression_enabled and _should_run_preflight_estimate( messages, agent.context_compressor.protect_first_n, @@ -708,6 +748,21 @@ def build_turn_context( tools=agent.tools or None, ) _compressor = agent.context_compressor + # getattr guard: minimal compressor doubles (SimpleNamespace in the + # engine-preflight tests) and plugin context engines lack this + # ContextCompressor-only method — absence means no snapshot, and the + # finalizer's rollback stays disarmed for the turn (display-only). + _snapshot_fn = getattr( + _compressor, "snapshot_preflight_display_tokens", None + ) + if callable(_snapshot_fn): + _snapshot_val = _snapshot_fn() + # Type pin: MagicMock compressors return truthy Mock objects — + # only a real int snapshot may arm the interrupted-turn rollback. + if isinstance(_snapshot_val, int) and not isinstance( + _snapshot_val, bool + ): + agent._turn_preflight_display_snapshot = _snapshot_val _defer_preflight = getattr( _compressor, "should_defer_preflight_to_real_usage", @@ -741,6 +796,8 @@ def build_turn_context( lambda: None, )() + _should_compress_now = False + _compress_block_reason = None if _preflight_deferred: logger.info( "Skipping preflight compression: rough estimate ~%s >= %s, " @@ -756,14 +813,42 @@ def build_turn_context( int(_compression_cooldown.get("remaining_seconds", 0.0)), agent.session_id or "none", ) + if _preflight_tokens >= _compressor.threshold_tokens: + # Context is over threshold but compression is blocked by the + # summary-LLM cooldown — surface a warning (see block below). + _cooldown_secs = _compression_cooldown.get("remaining_seconds", 0.0) + _compress_block_reason = f"cooldown:{_cooldown_secs:.0f}" elif _codex_native_auto: logger.info( "Skipping Hermes preflight compression for codex app-server " "(mode=%s); Hermes will not start thread compaction here.", getattr(agent, "codex_app_server_auto_compaction", "native"), ) - elif _compressor.should_compress(_preflight_tokens): + else: + _should_compress_now = _compressor.should_compress(_preflight_tokens) + if not _should_compress_now: + # Context is over threshold but compression is blocked + # (summary-LLM cooldown or anti-thrashing). Ask should_compress_info + # for the human-readable reason so we can surface a warning below. + # getattr guard: minimal compressor doubles (SimpleNamespace in + # the engine-preflight tests) and older plugin engines lack the + # method — absence means no block reason, no warning. + _info = getattr(_compressor, "should_compress_info", None) + if callable(_info): + try: + _compress_block_reason = _info(_preflight_tokens)[1] + except Exception: + _compress_block_reason = None + if _should_compress_now: _preflight_compressed = True + # Compression is actually running (block cleared / was never + # blocked) — reset the dedup so a future blocked-over-threshold + # turn can warn again. Real session boundary. + # getattr guard: test doubles built via object.__new__ lack the + # method (gateway test-double pitfall) — treat absence as no-op. + _clear_warn = getattr(agent, "_clear_context_overflow_warn", None) + if callable(_clear_warn): + _clear_warn() logger.info( "Preflight compression: ~%s tokens >= %s threshold (model %s, ctx %s)", f"{_preflight_tokens:,}", @@ -771,12 +856,20 @@ def build_turn_context( agent.model, f"{_compressor.context_length:,}", ) - agent._emit_status( - PREFLIGHT_COMPRESSION_STATUS_TEMPLATE.format( + _preflight_status = automatic_compaction_status_message( + _compressor, + phase="preflight", + default_message=PREFLIGHT_COMPRESSION_STATUS_TEMPLATE.format( tokens=_preflight_tokens, threshold=_compressor.threshold_tokens, - ) + ), + approx_tokens=_preflight_tokens, + threshold_tokens=_compressor.threshold_tokens, + context_length=_compressor.context_length, + model=agent.model, ) + if _preflight_status: + agent._emit_status(_preflight_status) # Preflight passes honor the same configured per-turn cap # (compression.max_attempts) as the loop's compression sites; # default 3 preserves the prior hardcoded behavior. @@ -786,10 +879,29 @@ def build_turn_context( for _pass in range(_max_preflight_passes): _orig_len = len(messages) _orig_tokens = _preflight_tokens + _preflight_input = messages messages, active_system_prompt = agent._compress_context( messages, system_message, approx_tokens=_preflight_tokens, task_id=effective_task_id, ) + if ( + messages is _preflight_input + and compression_skipped_due_to_lock(agent) + ): + # #69870 lock-skip: another path holds this session's + # compression lock, so the pass no-oped. That is a + # temporary DEFER, not proof the transcript cannot + # compress — do NOT arm the insufficient-progress + # blocker (the loop's error handlers must keep their + # provider-proven retry budget) and stop preflight + # passes for this turn; the lock winner is shrinking + # the same session concurrently. + logger.info( + "Preflight compression deferred: compression lock " + "held by another path (session %s)", + agent.session_id or "none", + ) + break # Re-estimate now so size-only compression (same row count, # lower token count — e.g. summarising tool outputs) is # recognised as progress instead of being misread as @@ -805,7 +917,7 @@ def build_turn_context( _preflight_compression_blocked = True break # Cannot compress further: neither rows nor tokens moved conversation_history = conversation_history_after_compression( - agent, messages + agent, messages, conversation_history ) agent._empty_content_retries = 0 agent._thinking_prefill_retries = 0 @@ -827,6 +939,100 @@ def build_turn_context( f"{_preflight_tokens:,}", ) break + elif _compress_block_reason: + # Context is already over the compression threshold, but compression + # is blocked (summary LLM cooldown or anti-thrashing). Without a + # signal the session keeps growing until the model silently stops + # answering — the conversation hits the hard provider token limit + # with no explanation. Surface a deduped warning so the user can + # take action (/new or /compress) instead of hitting a silent hang. + agent._warn_context_overflow_blocked( + _compress_block_reason, + _preflight_tokens, + _compressor.threshold_tokens, + ) + else: + # Sub-threshold and unblocked — allow the overflow warning to fire + # again next time the context is over threshold but blocked. + # getattr guard: test doubles built via object.__new__ lack the + # method (gateway test-double pitfall) — treat absence as no-op. + _clear_warn = getattr(agent, "_clear_context_overflow_warn", None) + if callable(_clear_warn): + _clear_warn() + # Engine maintenance only when NO skip-branch fired: a failure + # cooldown, deferred estimate, or codex-native route must keep + # the engine hook un-consulted (#20316 contract — the cooldown + # exists precisely because compression recently failed). + if _compression_cooldown or _preflight_deferred or _codex_native_auto: + _engine_preflight = None + else: + _engine_preflight = getattr( + _compressor, "should_compress_preflight", None + ) + # ── Engine-driven sub-threshold preflight maintenance (#20316) ── + # None of the threshold-path branches fired (not deferred, no + # failure cooldown, not codex-native, and should_compress() said + # the request is under pressure). Context engines that override + # ``should_compress_preflight()`` (e.g. LCM-style incremental + # leaf-chunk compaction) can still request deferred maintenance + # below the token threshold. The default + # ``ContextEngine.should_compress_preflight()`` returns False, so + # the built-in ``ContextCompressor`` path is byte-identical. + # + # Attempt-cap integration: the engine gets exactly ONE + # ``compress()`` pass per turn. It is mutually exclusive with the + # threshold multi-pass loop above (if/elif), so turn-start + # preflight passes stay bounded by the resolved + # ``compression.max_attempts`` cap (floor 1) in every case. + # + # No-op-blocking integration: a sub-threshold engine pass that + # no-ops says nothing about over-threshold compressibility, so it + # must neither set nor clear ``_preflight_compression_blocked`` + # (#64382) — and being in the ``else`` arm it can never run after + # the threshold loop has proven a retry ineffective. + # (resolved above, gated on no skip-branch having fired) + _wants_engine_preflight = False + if callable(_engine_preflight): + try: + _wants_engine_preflight = bool(_engine_preflight(messages)) + except Exception as _preflight_exc: + # A buggy engine must never break an otherwise-healthy + # turn: swallow at debug level and skip maintenance. + logger.debug( + "should_compress_preflight raised %s; skipping " + "engine-driven preflight maintenance", + _preflight_exc, + ) + _wants_engine_preflight = False + if _wants_engine_preflight: + logger.info( + "Engine-driven preflight maintenance: %s requested " + "compress() at ~%s tokens (below %s threshold)", + getattr(_compressor, "name", type(_compressor).__name__), + f"{_preflight_tokens:,}", + f"{getattr(_compressor, 'threshold_tokens', 0):,}", + ) + _engine_input = messages + messages, active_system_prompt = agent._compress_context( + messages, system_message, approx_tokens=_preflight_tokens, + task_id=effective_task_id, + ) + # ``_compress_context`` returns the INPUT list object on every + # skip path (per-session lock held elsewhere, cooldown, + # anti-thrash breaker, codex-native routing) and an engine may + # legitimately no-op. Only re-baseline the flush history and + # re-anchor the user row after a REAL compaction — a skip must + # leave the turn's bookkeeping untouched. + if messages is not _engine_input: + _preflight_compressed = True + conversation_history = conversation_history_after_compression( + agent, messages + ) + agent._empty_content_retries = 0 + agent._thinking_prefill_retries = 0 + agent._last_content_with_tools = None + agent._last_content_tools_all_housekeeping = False + agent._mute_post_response = False if _preflight_compressed: # Compression rebuilt the list (tail messages are fresh compaction @@ -844,7 +1050,7 @@ def build_turn_context( # Plugin hook: pre_llm_call (context injected into user message, not system prompt). plugin_user_context = "" try: - from hermes_cli.plugins import invoke_hook as _invoke_hook + from hermes_cli.lifecycle import invoke_hook as _invoke_hook _pre_results = _invoke_hook( "pre_llm_call", session_id=agent.session_id, @@ -855,6 +1061,7 @@ def build_turn_context( is_first_turn=(not bool(conversation_history)), model=agent.model, platform=getattr(agent, "platform", None) or "", + parent_session_id=getattr(agent, "_parent_session_id", None) or "", sender_id=getattr(agent, "_user_id", None) or "", ) _ctx_parts: list[str] = [] diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.py index 1a7b52ff516c..0f636c1dd241 100644 --- a/agent/turn_finalizer.py +++ b/agent/turn_finalizer.py @@ -201,6 +201,36 @@ def finalize_turn( ) ) + # Preflight can seed the display count before the provider receives the + # request. Roll that estimate back only when an interrupt wins the race + # before any successful provider response. Compaction state remains owned + # by the real-usage/post-compaction path, including its ``-1`` sentinel. + # Guard rules (test-double density on this path is high): + # - snapshot is type-pinned to a real int — MagicMock agents auto-create + # truthy Mock attributes that must never arm the rollback; + # - the received-response flag is pinned to ``is not True`` — its real + # domain is True/False, and only a literal True means a provider + # response completed; + # - the compressor method gets a getattr+callable guard — SimpleNamespace + # compressor doubles and plugin context engines lack it. + _preflight_snapshot = getattr( + agent, "_turn_preflight_display_snapshot", None + ) + if ( + interrupted is True + and isinstance(_preflight_snapshot, int) + and not isinstance(_preflight_snapshot, bool) + and getattr(agent, "_turn_received_provider_response", False) is not True + and getattr(agent, "context_compressor", None) is not None + ): + _rollback_fn = getattr( + agent.context_compressor, + "rollback_interrupted_preflight_display_tokens", + None, + ) + if callable(_rollback_fn): + _rollback_fn(_preflight_snapshot) + # Post-loop cleanup must never lose the response. Trajectory save, # resource teardown, and session persistence all touch fallible # surfaces — file I/O / JSON serialization (_save_trajectory), remote @@ -458,7 +488,7 @@ def finalize_turn( # First hook to return a string wins; None/empty return leaves text unchanged. if final_response and not interrupted: try: - from hermes_cli.plugins import invoke_hook as _invoke_hook + from hermes_cli.lifecycle import invoke_hook as _invoke_hook _transform_results = _invoke_hook( "transform_llm_output", response_text=final_response, @@ -480,7 +510,7 @@ def finalize_turn( # to an external memory system). if final_response and not interrupted: try: - from hermes_cli.plugins import invoke_hook as _invoke_hook + from hermes_cli.lifecycle import invoke_hook as _invoke_hook _invoke_hook( "post_llm_call", session_id=agent.session_id, @@ -495,6 +525,34 @@ def finalize_turn( except Exception as exc: logger.warning("post_llm_call hook failed: %s", exc) + # Context engine observation hook: notify the active engine that this + # turn has finished, with the finalized transcript. Complements the + # per-request select_context() hook (selection before the request; + # observation after the turn). No-op default, fail-open. + try: + from agent.conversation_loop import _notify_context_engine_turn_complete + # Forward the turn's canonical usage when the host has it. The loop + # stashes the most recent API response's usage dict (the same + # canonical buckets fed to ``update_from_response``) on the agent as + # ``_last_turn_usage``. It is ``None`` on turns that never reached a + # provider response (early failure / interrupt), which is exactly the + # contract: real usage when available, ``None`` otherwise. + _turn_usage = getattr(agent, "_last_turn_usage", None) + _notify_context_engine_turn_complete( + agent, + messages, + usage=_turn_usage, + logger=logger, + turn_id=turn_id, + task_id=effective_task_id, + api_call_count=api_call_count, + interrupted=interrupted, + failed=failed, + turn_exit_reason=_turn_exit_reason, + ) + except Exception as exc: + logger.warning("on_turn_complete notification failed: %s", exc) + # Extract reasoning from the CURRENT turn only. Walk backwards # but stop at the user message that started this turn — anything # earlier is from a prior turn and must not leak into the reasoning @@ -611,18 +669,23 @@ def finalize_turn( # Fired at the very end of every run_conversation call. # Plugins can use this for cleanup, flushing buffers, etc. try: - from hermes_cli.plugins import invoke_hook as _invoke_hook + from hermes_cli.lifecycle import invoke_hook as _invoke_hook _invoke_hook( "on_session_end", session_id=agent.session_id, task_id=effective_task_id, turn_id=turn_id, completed=completed, + failed=failed, interrupted=interrupted, + turn_exit_reason=_turn_exit_reason, model=agent.model, platform=getattr(agent, "platform", None) or "", ) except Exception as exc: logger.warning("on_session_end hook failed: %s", exc) + agent._turn_preflight_display_snapshot = None + agent._turn_received_provider_response = False + return result diff --git a/agent/turn_summary.py b/agent/turn_summary.py new file mode 100644 index 000000000000..f4440afb50aa --- /dev/null +++ b/agent/turn_summary.py @@ -0,0 +1,310 @@ +"""Per-turn accounting for the interactive CLI. + +Two display-only pieces live here: + +* :class:`TurnSummaryCollector` — a tiny observer that rides the existing + ``tool_progress_callback`` feed (``tool.completed`` events already carry + the tool name and its raw result) and tallies what a turn actually did. + It holds **no** agent-loop state: the display layer already sees every + tool call, so nothing new is threaded through the conversation loop. +* :func:`format_turn_summary` — a pure formatter that turns a tally plus a + wall-clock duration into one dim line, e.g.:: + + ⋯ 12.4s · edited 2 files +18 -3 · read 4 files · ran 3 commands + + Ported from Claude Code's post-turn accounting line + ("Edited 1 file +6 -2, read 1 file … Worked for 10s"). + +:func:`format_token_flow` is the spinner-side counterpart: a cumulative +token readout appended to the live elapsed timer (``↓ 1.2k tok``). + +Everything in this module is pure/side-effect free apart from the +collector's own counters, which makes it directly unit-testable without a +terminal, an agent, or a network call. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any + +__all__ = [ + "TurnSummaryCollector", + "TurnTally", + "format_turn_summary", + "format_token_flow", + "format_elapsed", +] + + +# Leading glyph for the summary line. Deliberately not an emoji — the line is +# meant to read as terminal chrome, not as agent speech. +SUMMARY_PREFIX = "⋯" + +# A turn that called no tools and finished this fast has nothing worth +# reporting (plain chat reply). Below the threshold the formatter returns "". +_MIN_TOOLLESS_SECONDS = 2.0 + +# Max number of "verb + count" segments rendered before collapsing the rest +# into a "+N more" tail, so a 12-tool turn cannot blow past one line. +_MAX_SEGMENTS = 4 + + +# Tool name -> (verb, singular noun, plural noun). +# +# Verbs are past tense because the line is printed *after* the turn. Tools not +# listed here fall into a generic "called N tools" bucket rather than inventing +# phrasing for plugin/MCP tools whose semantics we don't know. +_VERB_GROUPS: dict[str, tuple[str, str, str]] = { + "write_file": ("edited", "file", "files"), + "patch": ("edited", "file", "files"), + "read_file": ("read", "file", "files"), + "web_extract": ("read", "page", "pages"), + "terminal": ("ran", "command", "commands"), + "execute_code": ("ran", "script", "scripts"), + "search_files": ("searched", "path", "paths"), + "web_search": ("searched the web", "time", "times"), + "session_search": ("searched sessions", "time", "times"), + "browser_navigate": ("browsed", "page", "pages"), + "skill_view": ("read", "skill", "skills"), + "skill_manage": ("updated", "skill", "skills"), + "skills_list": ("listed skills", "time", "times"), + "todo": ("updated", "task list", "task lists"), + "delegate_task": ("delegated", "task", "tasks"), + "memory": ("updated", "memory", "memories"), +} + +# Verb groups that carry file-edit line deltas (+X -Y) when known. +_EDIT_VERB = "edited" + +# Render order: edits first (the thing users most want confirmed), then reads, +# then commands. Anything else follows in first-seen order. +_VERB_PRIORITY: tuple[str, ...] = ("edited", "read", "ran") + +# Tools whose results may report a unified diff we can count lines from. +_DIFF_RESULT_TOOLS = frozenset({"patch"}) + + +@dataclass +class TurnTally: + """What a single turn did, as observed from the tool-progress feed.""" + + # verb -> {noun_plural: count}; keeps insertion order for stable rendering. + verbs: dict[str, dict[str, int]] = field(default_factory=dict) + # Tools with no curated verb, counted together. + other_tools: int = 0 + # Aggregated unified-diff line deltas across edit tools, when reported. + lines_added: int = 0 + lines_removed: int = 0 + # True once at least one edit tool reported a countable diff, so the + # formatter knows the difference between "+0 -0" and "unknown". + has_line_deltas: bool = False + + @property + def total_tools(self) -> int: + counted = sum(sum(nouns.values()) for nouns in self.verbs.values()) + return counted + self.other_tools + + +def _count_diff_lines(diff: str) -> tuple[int, int]: + """Count added/removed lines in unified-diff text. + + File headers (``+++``/``---``) are excluded so a one-line edit does not + read as three additions. + """ + added = removed = 0 + for line in diff.splitlines(): + if line.startswith("+++") or line.startswith("---"): + continue + if line.startswith("+"): + added += 1 + elif line.startswith("-"): + removed += 1 + return added, removed + + +def _extract_line_deltas(tool_name: str, result: Any) -> tuple[int, int] | None: + """Pull (added, removed) from a tool result, or None when unavailable. + + Only tools that already report a diff in their result payload are + inspected — we never shell out to git and never re-read files to + synthesise a delta. + """ + if tool_name not in _DIFF_RESULT_TOOLS: + return None + payload: Any = result + if isinstance(payload, str): + text = payload.strip() + if not text.startswith("{"): + return None + try: + import json + + # strict=False tolerates literal control characters inside strings + # (raw newlines in an embedded diff), which some tool serialisers + # emit. A tally line is never worth failing over formatting. + payload = json.loads(text, strict=False) + except Exception: + return None + if not isinstance(payload, dict): + return None + diff = payload.get("diff") + if not isinstance(diff, str) or not diff.strip(): + return None + added, removed = _count_diff_lines(diff) + # A diff that carries no +/- content lines (e.g. a bare hunk header) tells + # us nothing — report it as unknown rather than rendering a misleading + # "+0 -0" next to a real edit. + if added == 0 and removed == 0: + return None + return added, removed + + +class TurnSummaryCollector: + """Accumulate per-turn tool tallies from the tool-progress feed. + + Wired into the CLI's existing ``_on_tool_progress`` handler: the display + layer already receives every ``tool.completed`` event with the tool name + and raw result, so no agent-loop bookkeeping is added. + """ + + def __init__(self) -> None: + self._tally = TurnTally() + + def begin(self) -> None: + """Start a fresh turn (drops any prior tally).""" + self._tally = TurnTally() + + def record_tool( + self, + tool_name: str | None, + *, + result: Any = None, + is_error: bool = False, + ) -> None: + """Record one completed tool call. + + Failed calls are skipped: a summary claiming "edited 2 files" when one + write was denied would be exactly the over-claim the file-mutation + verifier exists to catch. + """ + if not tool_name or is_error: + return + # Internal/pseudo tools (``_thinking``) are not user-visible work. + if tool_name.startswith("_"): + return + + group = _VERB_GROUPS.get(tool_name) + if group is None: + self._tally.other_tools += 1 + return + + verb, _singular, plural = group + nouns = self._tally.verbs.setdefault(verb, {}) + nouns[plural] = nouns.get(plural, 0) + 1 + + if verb == _EDIT_VERB: + deltas = _extract_line_deltas(tool_name, result) + if deltas is not None: + added, removed = deltas + self._tally.lines_added += added + self._tally.lines_removed += removed + self._tally.has_line_deltas = True + + @property + def tally(self) -> TurnTally: + return self._tally + + def render(self, elapsed_seconds: float) -> str: + """Render this turn's summary line (see :func:`format_turn_summary`).""" + return format_turn_summary(elapsed_seconds, self._tally) + + +def format_elapsed(seconds: float) -> str: + """Format a wall-clock duration compactly (``12.4s`` / ``2m05s``).""" + if seconds < 0: + seconds = 0.0 + if seconds < 60: + return f"{seconds:.1f}s" + minutes, rest = divmod(int(round(seconds)), 60) + return f"{minutes}m{rest:02d}s" + + +def _pluralize(count: int, plural_noun: str) -> str: + """Return ``"1 file"`` / ``"3 files"`` from a plural noun form.""" + if count == 1: + singular = plural_noun + if plural_noun.endswith("ies"): + singular = plural_noun[:-3] + "y" + elif plural_noun.endswith("ses"): + singular = plural_noun[:-2] + elif plural_noun.endswith("s"): + singular = plural_noun[:-1] + return f"1 {singular}" + return f"{count} {plural_noun}" + + +def _ordered_verbs(tally: TurnTally) -> list[str]: + """Verbs in render order: priority verbs first, then first-seen order.""" + seen = list(tally.verbs.keys()) + ranked = [v for v in _VERB_PRIORITY if v in tally.verbs] + ranked += [v for v in seen if v not in _VERB_PRIORITY] + return ranked + + +def format_turn_summary( + elapsed_seconds: float, + tally: TurnTally | None, + *, + max_segments: int = _MAX_SEGMENTS, +) -> str: + """Render the per-turn accounting line, or ``""`` when there's nothing to say. + + Pure function — no config lookups, no terminal access, no I/O. Gating + (``display.turn_summary``, quiet mode, CLI-only) is the caller's job. + """ + if tally is None: + tally = TurnTally() + + segments: list[str] = [] + for verb in _ordered_verbs(tally): + nouns = tally.verbs[verb] + parts = [_pluralize(count, plural) for plural, count in nouns.items() if count] + if not parts: + continue + segment = f"{verb} {', '.join(parts)}" + if verb == _EDIT_VERB and tally.has_line_deltas: + segment += f" +{tally.lines_added} -{tally.lines_removed}" + segments.append(segment) + + if tally.other_tools: + segments.append(f"called {_pluralize(tally.other_tools, 'tools')}") + + if not segments and tally.total_tools == 0 and elapsed_seconds < _MIN_TOOLLESS_SECONDS: + return "" + + if max_segments > 0 and len(segments) > max_segments: + hidden = len(segments) - max_segments + segments = segments[:max_segments] + [f"+{hidden} more"] + + pieces = [format_elapsed(elapsed_seconds)] + segments + return f"{SUMMARY_PREFIX} " + " · ".join(pieces) + + +def format_token_flow(output_tokens: Any, *, arrow: str = "↓") -> str: + """Render cumulative turn tokens for the live spinner (``↓ 1.2k tok``). + + Returns ``""`` for a non-positive count so the spinner shows nothing + rather than a misleading ``↓ 0 tok`` before the first API response lands. + """ + try: + count = int(output_tokens) + except (TypeError, ValueError): + return "" + if count <= 0: + return "" + if count < 1000: + return f"{arrow} {count} tok" + if count < 1_000_000: + return f"{arrow} {count / 1000:.1f}k tok" + return f"{arrow} {count / 1_000_000:.1f}M tok" diff --git a/agent/usage_pricing.py b/agent/usage_pricing.py index 9825e4a27bd5..b7982e46ab05 100644 --- a/agent/usage_pricing.py +++ b/agent/usage_pricing.py @@ -511,15 +511,93 @@ _OFFICIAL_DOCS_PRICING: Dict[tuple[str, str], PricingEntry] = { pricing_version="deepseek-pricing-2026-07", ), # Google Gemini + ( + "google", + "gemini-3.6-flash", + ): PricingEntry( + input_cost_per_million=Decimal("1.50"), + output_cost_per_million=Decimal("7.50"), + cache_read_cost_per_million=Decimal("0.15"), + source="official_docs_snapshot", + source_url="https://ai.google.dev/gemini-api/docs/pricing", + pricing_version="google-pricing-2026-07-28", + ), + ( + "google", + "gemini-3.5-flash", + ): PricingEntry( + input_cost_per_million=Decimal("1.50"), + output_cost_per_million=Decimal("9.00"), + cache_read_cost_per_million=Decimal("0.15"), + source="official_docs_snapshot", + source_url="https://ai.google.dev/pricing", + pricing_version="google-pricing-2026-07-07", + ), + ( + "google", + "gemini-3.5-flash-lite", + ): PricingEntry( + input_cost_per_million=Decimal("0.30"), + output_cost_per_million=Decimal("2.50"), + cache_read_cost_per_million=Decimal("0.03"), + source="official_docs_snapshot", + source_url="https://ai.google.dev/gemini-api/docs/pricing", + pricing_version="google-pricing-2026-07-28", + ), + ( + "google", + "gemini-3.1-pro", + ): PricingEntry( + input_cost_per_million=Decimal("2.00"), + output_cost_per_million=Decimal("12.00"), + cache_read_cost_per_million=Decimal("0.20"), + source="official_docs_snapshot", + source_url="https://ai.google.dev/pricing", + pricing_version="google-pricing-2026-07-07", + ), + ( + "google", + "gemini-3.1-flash-lite", + ): PricingEntry( + input_cost_per_million=Decimal("0.25"), + output_cost_per_million=Decimal("1.50"), + cache_read_cost_per_million=Decimal("0.025"), + source="official_docs_snapshot", + source_url="https://ai.google.dev/pricing", + pricing_version="google-pricing-2026-07-07", + ), + ( + "google", + "gemini-3-pro-preview", + ): PricingEntry( + input_cost_per_million=Decimal("2.00"), + output_cost_per_million=Decimal("12.00"), + cache_read_cost_per_million=Decimal("0.20"), + source="official_docs_snapshot", + source_url="https://ai.google.dev/pricing", + pricing_version="google-pricing-2026-07-07", + ), + ( + "google", + "gemini-3-flash-preview", + ): PricingEntry( + input_cost_per_million=Decimal("0.50"), + output_cost_per_million=Decimal("3.00"), + cache_read_cost_per_million=Decimal("0.05"), + source="official_docs_snapshot", + source_url="https://ai.google.dev/pricing", + pricing_version="google-pricing-2026-07-07", + ), ( "google", "gemini-2.5-pro", ): PricingEntry( input_cost_per_million=Decimal("1.25"), output_cost_per_million=Decimal("10.00"), + cache_read_cost_per_million=Decimal("0.125"), source="official_docs_snapshot", source_url="https://ai.google.dev/pricing", - pricing_version="google-pricing-2026-03-16", + pricing_version="google-pricing-2026-07-07", ), ( "google", @@ -527,9 +605,10 @@ _OFFICIAL_DOCS_PRICING: Dict[tuple[str, str], PricingEntry] = { ): PricingEntry( input_cost_per_million=Decimal("0.15"), output_cost_per_million=Decimal("0.60"), + cache_read_cost_per_million=Decimal("0.015"), source="official_docs_snapshot", source_url="https://ai.google.dev/pricing", - pricing_version="google-pricing-2026-03-16", + pricing_version="google-pricing-2026-07-07", ), ( "google", @@ -537,9 +616,10 @@ _OFFICIAL_DOCS_PRICING: Dict[tuple[str, str], PricingEntry] = { ): PricingEntry( input_cost_per_million=Decimal("0.10"), output_cost_per_million=Decimal("0.40"), + cache_read_cost_per_million=Decimal("0.01"), source="official_docs_snapshot", source_url="https://ai.google.dev/pricing", - pricing_version="google-pricing-2026-03-16", + pricing_version="google-pricing-2026-07-07", ), # AWS Bedrock — pricing per the Bedrock pricing page. # Bedrock charges the same per-token rates as the model provider but @@ -878,6 +958,18 @@ for _base_56 in ("gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"): ] del _base_56 +# The direct Gemini provider currently exposes preview IDs for these two +# models. Keep the official snapshot keyed by both their documented stable +# names and the provider's emitted IDs so a catalog selection is billable. +for _alias, _canonical in { + "gemini-3.1-pro-preview": "gemini-3.1-pro", + "gemini-3.1-flash-lite-preview": "gemini-3.1-flash-lite", +}.items(): + _OFFICIAL_DOCS_PRICING[("google", _alias)] = _OFFICIAL_DOCS_PRICING[ + ("google", _canonical) + ] +del _alias, _canonical + def _to_decimal(value: Any) -> Optional[Decimal]: if value is None: @@ -925,11 +1017,17 @@ def resolve_billing_route( return BillingRoute(provider="openai", model=model.split("/")[-1], base_url=base_url or "", billing_mode="official_docs_snapshot") if provider_name in {"minimax", "minimax-cn"}: return BillingRoute(provider=provider_name, model=model.split("/")[-1], base_url=base_url or "", billing_mode="official_docs_snapshot") - # Vertex AI hosts the same Gemini models as Google AI Studio; price them - # off the gemini official-docs snapshot. Strip the "google/" vendor prefix - # the OpenAI-compat endpoint requires so the pricing key matches. - if provider_name == "vertex" or base_url_host_matches(base_url or "", "aiplatform.googleapis.com"): - return BillingRoute(provider="gemini", model=model.split("/")[-1], base_url=base_url or "", billing_mode="official_docs_snapshot") + # Google AI Studio (Gemini) and Vertex AI host the same Gemini models. + # Price them off the official docs snapshot — the pricing keys are + # keyed on provider='google', so normalize every Google-flavored + # provider name/host onto it. Strip the "google/" vendor prefix the + # Vertex OpenAI-compat endpoint requires so the pricing key matches. + if ( + provider_name in {"google", "gemini", "vertex", "google-gemini", "google-ai-studio", "google-vertex", "vertex-ai"} + or base_url_host_matches(base_url or "", "aiplatform.googleapis.com") + or base_url_host_matches(base_url or "", "generativelanguage.googleapis.com") + ): + return BillingRoute(provider="google", model=model.split("/")[-1], base_url=base_url or "", billing_mode="official_docs_snapshot") if provider_name == "fireworks" or base_url_host_matches(base_url or "", "api.fireworks.ai"): # Fireworks model ids look like accounts/fireworks/models/; # rsplit("/", 1)[-1] yields just which is what the dict keys on. diff --git a/agent/verification_evidence.py b/agent/verification_evidence.py index d66a1534045c..2c8d1f85efa9 100644 --- a/agent/verification_evidence.py +++ b/agent/verification_evidence.py @@ -13,10 +13,11 @@ import shlex import sqlite3 import tempfile import threading +from contextlib import contextmanager from dataclasses import dataclass from datetime import datetime, timedelta, timezone from pathlib import Path -from typing import Any, Optional +from typing import Any, Iterator, Optional from hermes_constants import get_hermes_home @@ -60,16 +61,43 @@ def _db_path() -> Path: def _connect() -> sqlite3.Connection: + from hermes_state import apply_wal_with_fallback + path = _db_path() path.parent.mkdir(parents=True, exist_ok=True) conn = sqlite3.connect(path) - conn.execute("PRAGMA journal_mode=WAL") - conn.execute("PRAGMA busy_timeout=5000") conn.row_factory = sqlite3.Row - _ensure_schema(conn) + try: + apply_wal_with_fallback(conn, db_label="verification_evidence.db") + conn.execute("PRAGMA busy_timeout=5000") + _ensure_schema(conn) + except Exception: + # A PRAGMA/DDL failure after a successful connect() must not leak the + # just-opened connection back to the caller. + conn.close() + raise return conn +@contextmanager +def _transaction() -> Iterator[sqlite3.Connection]: + """Open a connection, commit/rollback on exit, and ALWAYS close it. + + ``sqlite3.Connection.__enter__``/``__exit__`` only commit or roll back the + transaction; they do not close the connection. Using ``with _connect()`` + alone therefore leaks a connection — and its WAL/SHM file descriptors — on + every call, deferring the close to the garbage collector, which over a + long-running process can exhaust ``RLIMIT_NOFILE`` (the cron-ledger sibling + of this bug was #69567 / PR #69594). + """ + conn = _connect() + try: + with conn: + yield conn + finally: + conn.close() + + def _ensure_schema(conn: sqlite3.Connection) -> None: conn.execute( """ @@ -452,7 +480,7 @@ def record_terminal_result( created_at = _utc_now() with _DB_LOCK: - with _connect() as conn: + with _transaction() as conn: cur = conn.execute( """ INSERT INTO verification_events( @@ -518,7 +546,7 @@ def mark_workspace_edited( edited_at = _utc_now() with _DB_LOCK: - with _connect() as conn: + with _transaction() as conn: row = conn.execute( """ SELECT changed_paths_json FROM verification_state @@ -568,7 +596,7 @@ def verification_status( sid = str(session_id or "default") root = str(facts.get("root") or Path(cwd or ".").resolve()) with _DB_LOCK: - with _connect() as conn: + with _transaction() as conn: state = conn.execute( """ SELECT last_event_id, last_edit_at, changed_paths_json diff --git a/apps/bootstrap-installer/package.json b/apps/bootstrap-installer/package.json index ba231432350b..32c3e7f8c3e7 100644 --- a/apps/bootstrap-installer/package.json +++ b/apps/bootstrap-installer/package.json @@ -13,7 +13,7 @@ "tauri:build": "tauri build", "tauri:build:debug": "tauri build --debug", "typecheck": "tsc -p . --noEmit", - "check": "npm run typecheck", + "check": "npm run typecheck && npm run lint", "lint": "eslint src/", "lint:fix": "eslint src/ --fix", "fix": "npm run lint:fix" diff --git a/apps/bootstrap-installer/src-tauri/src/bootstrap.rs b/apps/bootstrap-installer/src-tauri/src/bootstrap.rs index 1d70ec59a611..f78b26134e41 100644 --- a/apps/bootstrap-installer/src-tauri/src/bootstrap.rs +++ b/apps/bootstrap-installer/src-tauri/src/bootstrap.rs @@ -12,11 +12,11 @@ //! 4. Worker iterates stages, calling `install.ps1 -Stage NAME -NonInteractive -Json`. //! 5. On success → `complete`. On any stage failure → `failed`. On cancel → `failed`. -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::sync::Arc; -use std::time::Instant; +use std::time::{Instant, SystemTime, UNIX_EPOCH}; -use anyhow::{anyhow, Result}; +use anyhow::{anyhow, Context, Result}; use serde::{Deserialize, Serialize}; use tauri::{AppHandle, Emitter, State}; use tokio::sync::{mpsc, Mutex}; @@ -260,6 +260,107 @@ pub(crate) fn hermes_is_installed(install_root: &std::path::Path) -> bool { && resolve_hermes_desktop_exe(install_root).is_some() } +fn resolve_marker_commit(install_root: &Path, pin: &Pin) -> Option { + if let Some(commit) = pin + .commit + .as_ref() + .filter(|commit| !commit.trim().is_empty()) + { + return Some(commit.clone()); + } + + let output = std::process::Command::new("git") + .args(["rev-parse", "HEAD"]) + .current_dir(install_root) + .output() + .ok()?; + if !output.status.success() { + return None; + } + + let commit = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if commit.is_empty() { + None + } else { + Some(commit) + } +} + +fn write_bootstrap_complete_marker(install_root: &Path, pin: &Pin) -> Result { + use std::io::Write; + + let marker_path = crate::paths::likely_bootstrap_marker(install_root); + if let Some(parent) = marker_path.parent() { + std::fs::create_dir_all(parent).with_context(|| { + format!( + "could not create bootstrap marker directory {}", + parent.display() + ) + })?; + } + + let completed_at_unix = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|duration| duration.as_secs()) + .unwrap_or_default(); + let marker = serde_json::json!({ + "schemaVersion": 1, + "pinnedCommit": resolve_marker_commit(install_root, pin), + "pinnedBranch": pin.branch.clone(), + "completedAtUnix": completed_at_unix, + }); + let mut body = serde_json::to_vec_pretty(&marker)?; + body.push(b'\n'); + + // Atomic publish (temp sibling + flush + rename), matching Electron's + // writeFileAtomic(). hermes_is_installed() only checks existence, so a + // partial direct write would incorrectly enable the launcher fast path. + let tmp_path = install_root.join(".hermes-bootstrap-complete.tmp"); + { + let mut file = std::fs::File::create(&tmp_path).with_context(|| { + format!( + "could not create temp bootstrap marker {}", + tmp_path.display() + ) + })?; + file.write_all(&body).with_context(|| { + format!( + "could not write temp bootstrap marker {}", + tmp_path.display() + ) + })?; + file.sync_all().with_context(|| { + format!( + "could not flush temp bootstrap marker {}", + tmp_path.display() + ) + })?; + } + // Windows rename fails if the destination already exists; drop any prior + // marker first so a re-run can still publish a fresh payload. + if marker_path.exists() { + std::fs::remove_file(&marker_path).with_context(|| { + format!( + "could not replace existing bootstrap marker {}", + marker_path.display() + ) + })?; + } + if let Err(err) = std::fs::rename(&tmp_path, &marker_path) { + let _ = std::fs::remove_file(&tmp_path); + return Err(err).with_context(|| { + format!( + "could not publish bootstrap marker {} → {}", + tmp_path.display(), + marker_path.display() + ) + }); + } + + tracing::info!(path = %marker_path.display(), "bootstrap marker written"); + Ok(marker) +} + /// Spawn the already-built desktop app, detached. Returns Err if no built app /// exists or the spawn fails, so the caller can fall back to showing the /// installer UI. @@ -644,6 +745,23 @@ async fn run_bootstrap( .unwrap_or_else(|| crate::paths::hermes_home().to_string_lossy().into_owned()); let install_root = PathBuf::from(&hermes_home).join("hermes-agent"); + // Marker publish is terminal for this run: a write failure must emit Failed + // so the UI leaves the progress state (it does not poll get_bootstrap_status). + let marker = match write_bootstrap_complete_marker(&install_root, &pin) { + Ok(marker) => marker, + Err(err) => { + let msg = format!("write bootstrap marker failed: {err:#}"); + emit_event( + &app, + BootstrapEvent::Failed { + stage: None, + error: msg.clone(), + }, + ); + return Err(anyhow!(msg)); + } + }; + // Copy ourselves to HERMES_HOME/hermes-setup.exe so the desktop app can // re-invoke us with `--update` and shortcuts have a stable target. This is // a one-shot install concern; an `--update` re-invocation no-ops because @@ -660,10 +778,7 @@ async fn run_bootstrap( &app, BootstrapEvent::Complete { install_root: install_root.to_string_lossy().into_owned(), - marker: Some(serde_json::json!({ - "pinnedCommit": pin.commit, - "pinnedBranch": pin.branch, - })), + marker: Some(marker), }, ); @@ -903,4 +1018,103 @@ mod tests { ); let _ = std::fs::remove_dir_all(&root); } + + #[test] + fn bootstrap_complete_marker_uses_desktop_compatible_schema() { + let root = unique_tmp_dir("marker-schema"); + let pin = Pin { + commit: Some("abcdef1234567890".to_string()), + branch: Some("main".to_string()), + }; + + let marker = + write_bootstrap_complete_marker(&root, &pin).expect("marker write should succeed"); + let marker_path = root.join(".hermes-bootstrap-complete"); + let from_disk: serde_json::Value = + serde_json::from_slice(&std::fs::read(&marker_path).unwrap()).unwrap(); + + assert_eq!(marker, from_disk); + assert_eq!(from_disk["schemaVersion"], 1); + assert_eq!(from_disk["pinnedCommit"], "abcdef1234567890"); + assert_eq!(from_disk["pinnedBranch"], "main"); + assert!( + from_disk["completedAtUnix"].as_u64().is_some(), + "marker must carry a completion timestamp" + ); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn bootstrap_complete_marker_is_published_atomically() { + let root = unique_tmp_dir("marker-atomic"); + make_release_tree(&root); + let pin = Pin { + commit: Some("abcdef1234567890".to_string()), + branch: Some("main".to_string()), + }; + + write_bootstrap_complete_marker(&root, &pin).expect("marker write should succeed"); + + let marker_path = root.join(".hermes-bootstrap-complete"); + let tmp_path = root.join(".hermes-bootstrap-complete.tmp"); + assert!( + marker_path.is_file(), + "final marker must exist after atomic publish" + ); + assert!( + !tmp_path.exists(), + "temp sibling must not remain after atomic publish" + ); + assert!( + hermes_is_installed(&root), + "atomically published marker must enable the installer fast path" + ); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn hermes_is_installed_treats_marker_existence_as_sufficient() { + // Documents why write_bootstrap_complete_marker must publish atomically: + // the launcher predicate only checks existence, so a partial/corrupt + // final marker would still enable the fast path. + let root = unique_tmp_dir("marker-existence-only"); + make_release_tree(&root); + std::fs::write(root.join(".hermes-bootstrap-complete"), b"").unwrap(); + + assert!( + hermes_is_installed(&root), + "empty/partial marker content still counts as installed" + ); + let _ = std::fs::remove_dir_all(&root); + } + + #[test] + fn marker_write_failure_leaves_no_final_marker() { + // install_root is a regular file → create_dir_all on its path fails + // before any marker bytes are published under the final name. + let base = unique_tmp_dir("marker-fail"); + let not_a_dir = base.join("not-a-dir"); + std::fs::write(¬_a_dir, b"not a directory").unwrap(); + let pin = Pin { + commit: Some("abcdef1234567890".to_string()), + branch: Some("main".to_string()), + }; + + let err = write_bootstrap_complete_marker(¬_a_dir, &pin) + .expect_err("marker write against a non-directory root must fail"); + let msg = format!("{err:#}"); + assert!( + msg.contains("bootstrap marker"), + "error should mention the marker path: {msg}" + ); + assert!( + !not_a_dir.join(".hermes-bootstrap-complete").exists(), + "failed write must not leave a final marker that enables the fast path" + ); + assert!( + !not_a_dir.join(".hermes-bootstrap-complete.tmp").exists(), + "failed write must not leave a temp marker sibling either" + ); + let _ = std::fs::remove_dir_all(&base); + } } diff --git a/apps/bootstrap-installer/src-tauri/src/paths.rs b/apps/bootstrap-installer/src-tauri/src/paths.rs index 7c64c91cf6ef..0eec8ccd319d 100644 --- a/apps/bootstrap-installer/src-tauri/src/paths.rs +++ b/apps/bootstrap-installer/src-tauri/src/paths.rs @@ -149,8 +149,8 @@ fn repair_macos_installer_helper(path: &Path) { #[cfg(not(target_os = "macos"))] fn repair_macos_installer_helper(_path: &Path) {} -/// Where install.ps1 writes the bootstrap-complete marker (existence-only file -/// the Electron app also checks). Per main.ts: +/// Where the bootstrap-complete marker lives (existence-only for the Rust +/// installer fast path; JSON schema-checked by the Electron app). Per main.ts: /// const BOOTSTRAP_COMPLETE_MARKER = path.join(ACTIVE_HERMES_ROOT, '.hermes-bootstrap-complete') /// We don't always know ACTIVE_HERMES_ROOT until install.ps1 reports it, so /// this is a probe helper, not a definitive path. diff --git a/apps/desktop/DESIGN.md b/apps/desktop/DESIGN.md index 53075c5d49bb..dae529dca902 100644 --- a/apps/desktop/DESIGN.md +++ b/apps/desktop/DESIGN.md @@ -117,20 +117,31 @@ that sit inside a heading/sentence; replaces `h-auto px-0 py-0`), `micro` (status-stack/table-footers), and the icon family `icon` / `icon-xs` / `icon-sm` / `icon-lg` / `icon-titlebar`. -**Icon-only buttons must have a tooltip.** Every button with an `icon*` size -carries no visible text label, so it must be wrapped in `` -with a descriptive label (matching the button's `aria-label`). Never use the -native HTML `title=` attribute — it's unstyled, delayed (~500ms OS default), -and visually inconsistent with the instant themed `Tip`. An enforcement test -(`src/components/ui/__tests__/no-native-title.test.ts`) fails on any ` - {onRemove && ( + <> + +
- )} -
-
+ {onRemove && ( + + )} + +
+ {lightboxSrc && ( + + )} + ) } diff --git a/apps/desktop/src/app/chat/composer/composer-utils.test.ts b/apps/desktop/src/app/chat/composer/composer-utils.test.ts index 4df8463ba2de..062b25677385 100644 --- a/apps/desktop/src/app/chat/composer/composer-utils.test.ts +++ b/apps/desktop/src/app/chat/composer/composer-utils.test.ts @@ -2,12 +2,14 @@ import type { Unstable_TriggerItem } from '@assistant-ui/core' import { describe, expect, it } from 'vitest' import { + acceptsTriggerCompletion, isPendingDraftPersistCurrent, type PendingDraftPersist, pickPlaceholder, slashArgStage, slashChipKindForItem, - slashCommandToken + slashCommandToken, + type TriggerAcceptInput } from './composer-utils' const item = (group: string): Unstable_TriggerItem => @@ -39,6 +41,53 @@ describe('slashChipKindForItem', () => { }) }) +describe('acceptsTriggerCompletion', () => { + const press = (key: string, overrides: Partial = {}) => + acceptsTriggerCompletion({ + activeExplicit: false, + freeTextArgStage: false, + key, + kind: '/', + query: 'personality alic', + ...overrides + }) + + it('accepts on Enter / Tab / Space for a finite option list', () => { + expect(press('Enter')).toBe(true) + expect(press('Tab')).toBe(true) + expect(press(' ')).toBe(true) + }) + + it('ignores keys that are neither navigation nor acceptance', () => { + expect(press('a')).toBe(false) + expect(press('Escape')).toBe(false) + }) + + it('lets an `@` mention take a literal space', () => { + expect(press(' ', { kind: '@', query: 'src/comp' })).toBe(false) + expect(press('Enter', { kind: '@', query: 'src/comp' })).toBe(true) + }) + + it('types a space on a bare `/ ` instead of accepting', () => { + expect(press(' ', { query: '' })).toBe(false) + }) + + // The `/goal ` class: the popover may be live over free-form text, so + // the keys that mean something else in prose must keep meaning it. + it('sends the prose rather than the unchosen first row', () => { + expect(press('Enter', { freeTextArgStage: true, query: 'goal ship the redesign' })).toBe(false) + expect(press(' ', { freeTextArgStage: true, query: 'goal ship the' })).toBe(false) + }) + + it('accepts on Enter once the user has arrowed to a row deliberately', () => { + expect(press('Enter', { activeExplicit: true, freeTextArgStage: true, query: 'goal stat' })).toBe(true) + }) + + it('keeps Tab as the explicit accept even over free text', () => { + expect(press('Tab', { freeTextArgStage: true, query: 'goal stat' })).toBe(true) + }) +}) + describe('pickPlaceholder', () => { it('returns a member of the pool', () => { const pool = ['a', 'b', 'c'] as const diff --git a/apps/desktop/src/app/chat/composer/composer-utils.ts b/apps/desktop/src/app/chat/composer/composer-utils.ts index 7939be35b6b6..21e3c1ac4a12 100644 --- a/apps/desktop/src/app/chat/composer/composer-utils.ts +++ b/apps/desktop/src/app/chat/composer/composer-utils.ts @@ -4,6 +4,8 @@ import type { SlashChipKind } from '@/components/assistant-ui/directive-text' import type { ComposerAttachment } from '@/store/composer' import { setSessionPickerOpen } from '@/store/session' +import type { TriggerState } from './text-utils' + export const COMPOSER_STACK_BREAKPOINT_PX = 320 // Above the stack breakpoint but still cramped: the model pill sheds its label @@ -50,12 +52,57 @@ export function slashChipKindForItem(item: Unstable_TriggerItem): SlashChipKind return 'command' } +/** True for a skill completion — the only kind offered mid-message. */ +export const isSkillItem = (item: Unstable_TriggerItem) => slashChipKindForItem(item) === 'skill' + /** A `/` query is at its arg stage once it's past the command name. */ export const slashArgStage = (query: string) => query.includes(' ') /** The `/command` token of a slash query (`personality x` → `/personality`). */ export const slashCommandToken = (query: string) => `/${query.split(/\s+/, 1)[0]?.toLowerCase() ?? ''}` +export interface TriggerAcceptInput { + /** The user moved the highlight themselves (arrow keys) rather than + * inheriting the list's default first row. */ + activeExplicit: boolean + /** The trigger is a slash command whose argument is arbitrary prose. */ + freeTextArgStage: boolean + key: string + kind: TriggerState['kind'] + query: string +} + +/** + * Whether a keypress accepts the highlighted completion while the popover is + * open. Tab is always an accept — it has no other meaning in the composer. + * + * Enter and Space are conditional, because both mean something else while a + * free-text argument is being written (`/goal ship the redesign`). Space types + * a space, and Enter sends the message; letting either take the popover's + * pre-highlighted row would swap the prose the user is mid-sentence on for a + * subcommand they never chose. Enter still accepts once the user has arrowed + * to a row deliberately, so the highlight never lies about what Enter will do. + */ +export function acceptsTriggerCompletion({ + activeExplicit, + freeTextArgStage, + key, + kind, + query +}: TriggerAcceptInput): boolean { + if (key === 'Tab') { + return true + } + + if (key === 'Enter') { + return !freeTextArgStage || activeExplicit + } + + // Space is slash-only (an `@` mention takes a literal space) and gated to a + // non-empty query so a bare `/ ` still types a space. + return key === ' ' && kind === '/' && Boolean(query.trim()) && !freeTextArgStage +} + export interface QueueEditState { attachments: ComposerAttachment[] draft: string diff --git a/apps/desktop/src/app/chat/composer/contrib.ts b/apps/desktop/src/app/chat/composer/contrib.ts index 893f5174c200..94d19457a58f 100644 --- a/apps/desktop/src/app/chat/composer/contrib.ts +++ b/apps/desktop/src/app/chat/composer/contrib.ts @@ -3,13 +3,16 @@ * through the SAME registry schema as every other surface (statusbar, titlebar, * panes, layouts): * - * render areas (`render`): composer.top — banner strip above the input - * composer.bottom — row below the input grid - * composer.leading — inline after the "+" menu - * composer.actions — inline before the model pill + * render areas (`render`): composer.top — banner strip above the input + * composer.bottom — row below the input grid + * composer.underside — floating strip BELOW the + * whole composer (no chrome) + * composer.leading — inline after the "+" menu + * composer.actions — inline before the model pill * - * data kinds (`data`): composer.middleware (ComposerMiddleware) - * composer.attachments (ComposerAttachmentProvider) + * data kinds (`data`): composer.middleware (ComposerMiddleware) + * composer.attachments (ComposerAttachmentProvider) + * composer.microActions (ComposerMicroActionProvider) * * Core keeps ownership of the transcript, input, and submit engine — these * seams AUGMENT the composer, they never replace it. Middleware runs as an @@ -17,17 +20,23 @@ * draft, pass it through, or cancel the send by returning null. */ +import { useMemo } from 'react' + import { useContributions } from '@/contrib/react/use-contributions' import { registry } from '@/contrib/registry' +import type { TodoItem } from '@/lib/todos' import type { ComposerAttachment } from '@/store/composer' +import type { ComposerAction } from '@/store/composer-actions' export const COMPOSER_AREAS = { top: 'composer.top', bottom: 'composer.bottom', + underside: 'composer.underside', leading: 'composer.leading', actions: 'composer.actions', middleware: 'composer.middleware', - attachments: 'composer.attachments' + attachments: 'composer.attachments', + microActions: 'composer.microActions' } as const export interface ComposerDraft { @@ -92,3 +101,39 @@ export function useComposerAttachmentProviders(): Array ({ key: `${c.source ?? 'core'}:${c.id}`, ...(c.data as ComposerAttachmentProvider) })) .filter(p => Boolean(p.label && p.run)) } + +/** + * Payload of a `composer.microActions` data contribution — the pill strip at + * the top of the composer's overlay lane. + * + * `resolve` is called with the live session context and returns the badges to + * show right now, or `[]` for "nothing from me". Returning a list rather than + * a static badge is what lets a provider be conditional ("only while idle", + * "only with unfinished tasks") without a reactive `when()`, which the + * registry deliberately doesn't offer. + */ +export interface ComposerMicroActionProvider { + resolve: (ctx: ComposerMicroActionContext) => ComposerAction[] +} + +/** What a micro-action provider gets to branch on. Deliberately small: every + * field here is a standing compatibility promise to the plugins using it. */ +export interface ComposerMicroActionContext { + /** A turn is currently running in this session. */ + busy: boolean + sessionId: string + /** Live todo list for the session (empty when there is none). */ + todos: readonly TodoItem[] +} + +/** Micro-action providers, memoised against the registry's own stable + * snapshot — the strip re-resolves on every composer render, so a fresh array + * here would defeat that. */ +export function useComposerMicroActionProviders(): ComposerMicroActionProvider[] { + const contributions = useContributions(COMPOSER_AREAS.microActions) + + return useMemo( + () => contributions.map(c => c.data as ComposerMicroActionProvider).filter(p => typeof p?.resolve === 'function'), + [contributions] + ) +} diff --git a/apps/desktop/src/app/chat/composer/controls.test.tsx b/apps/desktop/src/app/chat/composer/controls.test.tsx index a2186622690f..8a84be8ea477 100644 --- a/apps/desktop/src/app/chat/composer/controls.test.tsx +++ b/apps/desktop/src/app/chat/composer/controls.test.tsx @@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { ChatBarState } from '@/app/chat/composer/types' import { I18nProvider } from '@/i18n' +import { applyWakeStartResult, applyWakeStatus, resetWakeWordState } from '@/store/wake-word' import { ComposerControls } from './controls' @@ -65,15 +66,74 @@ describe('ComposerControls shortcut tooltips', () => { await expectShortcutTooltip('Send', '↵') }) - it('shows Ctrl+Enter for Steer', async () => { + it('shows Enter for Steer', async () => { renderControls({ busy: true, busyAction: 'steer' }) - await expectShortcutTooltip('Steer the current run', 'Ctrl+↵') + await expectShortcutTooltip('Steer the current run', '↵') }) - it('shows Enter for Queue', async () => { + it('shows Ctrl+Enter for Queue', async () => { renderControls({ busy: true, busyAction: 'queue' }) - await expectShortcutTooltip('Queue message', '↵') + await expectShortcutTooltip('Queue message', 'Ctrl+↵') + }) +}) + +describe('wake-word ear visibility', () => { + afterEach(() => { + resetWakeWordState() + }) + + it('stays mounted during a busy agent turn', () => { + applyWakeStatus({ available: true, enabled: true, listening: true, phrase: 'hey hermes' }) + renderControls({ busy: true, busyAction: 'stop' }) + + expect(screen.getByLabelText('Wake word: "hey hermes" — listening')).toBeTruthy() + }) + + it('stays mounted (enabled in config) even when a start was refused', () => { + applyWakeStatus({ available: true, enabled: true, listening: false, phrase: 'hey hermes' }) + // Transient refusal marks available false but enabled keeps it mounted. + applyWakeStartResult({ hint: 'mic busy', reason: 'unavailable', started: false }) + renderControls() + + expect(screen.getByLabelText('Wake word: "hey hermes" — off')).toBeTruthy() + }) + + it('stays visible (never hides) even when unavailable and not enabled', () => { + applyWakeStatus({ available: false, enabled: false, listening: false, phrase: 'hey hermes' }) + renderControls() + + // The ear ALWAYS shows so the user can click to enable; a failed start + // surfaces its reason in the tooltip rather than hiding the control. + expect(screen.getByLabelText('Wake word: "hey hermes" — off')).toBeTruthy() + }) + + it('surfaces the backend refusal reason in the tooltip, still visible', () => { + applyWakeStatus({ available: false, enabled: false, listening: false, phrase: 'hey hermes' }) + applyWakeStartResult({ hint: 'run `hermes tools` (Voice section)', reason: 'unavailable', started: false }) + renderControls() + + const ear = screen.getByLabelText('Wake word: "hey hermes" — off') + expect(ear).toBeTruthy() + }) + + it('shows a disabled paused ear inside the voice-conversation pill', () => { + applyWakeStatus({ available: true, enabled: true, listening: true, phrase: 'hey hermes' }) + renderControls({ + conversation: { + active: true, + level: 0, + muted: false, + onEnd: vi.fn(), + onStart: vi.fn(), + onStopTurn: vi.fn(), + onToggleMute: vi.fn(), + status: 'listening' + } + }) + + const ear = screen.getByLabelText('Wake word: "hey hermes" — paused during voice chat') + expect((ear as HTMLButtonElement).disabled).toBe(true) }) }) diff --git a/apps/desktop/src/app/chat/composer/controls.tsx b/apps/desktop/src/app/chat/composer/controls.tsx index 432e0a6ead47..06a3869894fe 100644 --- a/apps/desktop/src/app/chat/composer/controls.tsx +++ b/apps/desktop/src/app/chat/composer/controls.tsx @@ -1,10 +1,24 @@ +import { useStore } from '@nanostores/react' + import { Button } from '@/components/ui/button' import { Codicon } from '@/components/ui/codicon' import { Tip, TipKeybindLabel } from '@/components/ui/tooltip' import { useI18n } from '@/i18n' import { triggerHaptic } from '@/lib/haptics' -import { AudioLines, iconSize, Layers3, Loader2, Square, SteeringWheel, Volume2, VolumeX } from '@/lib/icons' +import { + AudioLines, + Ear, + EarOff, + iconSize, + Layers3, + Loader2, + Square, + SteeringWheel, + Volume2, + VolumeX +} from '@/lib/icons' import { cn } from '@/lib/utils' +import { $wakeWord, toggleWakeWord } from '@/store/wake-word' import type { ConversationStatus } from './hooks/use-voice-conversation' import { ModelPill } from './model-pill' @@ -80,8 +94,9 @@ export function ComposerControls({ + {busyAction === 'steer' ? ( - }> + }> + + ) +} + function DictationButton({ disabled, state, diff --git a/apps/desktop/src/app/chat/composer/enter-submit-dom-race.test.tsx b/apps/desktop/src/app/chat/composer/enter-submit-dom-race.test.tsx index ff01bf6fd377..ad35b20faa33 100644 --- a/apps/desktop/src/app/chat/composer/enter-submit-dom-race.test.tsx +++ b/apps/desktop/src/app/chat/composer/enter-submit-dom-race.test.tsx @@ -29,7 +29,8 @@ function Harness({ onSubmit, onQueue, onCancel, - onDrain + onDrain, + onSendNow }: { busy?: boolean disabled?: boolean @@ -38,6 +39,7 @@ function Harness({ onQueue: (text: string) => void onCancel: () => void onDrain: () => void + onSendNow?: (id: string) => void }) { const editorRef = useRef(null) const draftRef = useRef('') @@ -103,6 +105,12 @@ function Harness({ } if (busy && !hasLivePayload) { + const head = queued[0] + + if (head) { + onSendNow?.(head) + } + return } @@ -167,13 +175,14 @@ describe('composer Enter submit — live DOM vs stale composer state (#39630)', expect(onCancel).not.toHaveBeenCalled() }) - it('treats an empty Enter while busy as a no-op (never an accidental Stop)', async () => { + it('treats an empty Enter while busy with nothing queued as a no-op (never an accidental Stop)', async () => { const onCancel = vi.fn() const onSubmit = vi.fn() const onQueue = vi.fn() + const onSendNow = vi.fn() const { getByTestId } = render( - + ) const editor = getByTestId('editor') @@ -186,6 +195,35 @@ describe('composer Enter submit — live DOM vs stale composer state (#39630)', expect(onCancel).not.toHaveBeenCalled() expect(onSubmit).not.toHaveBeenCalled() expect(onQueue).not.toHaveBeenCalled() + expect(onSendNow).not.toHaveBeenCalled() + }) + + it('double-send: an empty Enter while busy with a queued turn sends that turn now', async () => { + const onCancel = vi.fn() + const onSendNow = vi.fn() + + const { getByTestId } = render( + + ) + + const editor = getByTestId('editor') + + await act(async () => { + editor.textContent = '' + fireEvent.keyDown(editor, { key: 'Enter' }) + }) + + // Head of the queue, and NOT a bare cancel — send-now promotes + interrupts. + expect(onSendNow).toHaveBeenCalledWith('queued-1') + expect(onCancel).not.toHaveBeenCalled() }) it('drains the next queued prompt on Enter when idle with a truly empty editor', async () => { diff --git a/apps/desktop/src/app/chat/composer/focus.test.ts b/apps/desktop/src/app/chat/composer/focus.test.ts new file mode 100644 index 000000000000..bc92932bb8fe --- /dev/null +++ b/apps/desktop/src/app/chat/composer/focus.test.ts @@ -0,0 +1,218 @@ +import { afterEach, describe, expect, it } from 'vitest' + +import { + blurComposerInput, + getActiveComposer, + markActiveComposer, + onComposerFocusRequest, + releaseActiveComposer, + requestComposerFocus +} from './focus' +import { RICH_INPUT_SLOT } from './rich-editor' + +/** + * Inactive tabs keep their composer mounted, so an unscoped lookup can blur a + * background input and leave the one the user is typing in focused. + */ + +/** A composer input inside its own pane layer, hidden or not. */ +function mountInput(hidden = false) { + const layer = document.createElement('div') + const input = document.createElement('div') + input.dataset.slot = RICH_INPUT_SLOT + input.tabIndex = 0 + layer.toggleAttribute('data-pane-hidden', hidden) + layer.append(input) + document.body.append(layer) + + return input +} + +/** A chat surface stamp — the same `data-composer-target` ChatView hangs. */ +function mountSurface(target: string, hidden = false) { + const layer = document.createElement('div') + layer.toggleAttribute('data-pane-hidden', hidden) + const surface = document.createElement('div') + surface.dataset.composerTarget = target + layer.append(surface) + document.body.append(layer) + + return surface +} + +afterEach(() => { + document.body.innerHTML = '' + // `activeTarget` is module-level — a case that leaves a stale claim behind + // would otherwise decide the next one. + markActiveComposer('main') +}) + +describe('blurComposerInput', () => { + it('blurs the foreground composer while a hidden tab matches first', () => { + const background = mountInput(true) + const foreground = mountInput() + + foreground.focus() + blurComposerInput() + + expect(document.activeElement).not.toBe(foreground) + expect(document.activeElement).not.toBe(background) + }) + + it('leaves focus alone when the composer does not hold it', () => { + const outside = document.createElement('button') + document.body.append(outside) + mountInput() + + outside.focus() + blurComposerInput() + + expect(document.activeElement).toBe(outside) + }) +}) + +/** + * `markActiveComposer` has four call sites and, unguarded, no counterpart: an + * unmounting or keep-alive-buried composer left `activeTarget` pointing at + * itself, so every `'active'`-routed request was delivered to a target with no + * on-screen subscriber. Type-to-focus preventDefaults the keystroke BEFORE the + * request, so a dead target swallows the character and focuses nothing. + */ +describe('releaseActiveComposer', () => { + it('falls back to the main composer when the claimant releases', () => { + const root = document.createElement('div') + root.dataset.slot = 'aui_edit-composer-root' + document.body.append(root) + + markActiveComposer('edit') + expect(getActiveComposer()).toBe('edit') + + root.remove() + releaseActiveComposer('edit') + + expect(getActiveComposer()).toBe('main') + }) + + it('leaves the key with the live claimant when a stale composer releases late', () => { + markActiveComposer('edit') + markActiveComposer('tile:abc') + + releaseActiveComposer('edit') + + expect(getActiveComposer()).toBe('tile:abc') + }) + + it('prefers the visible chat surface over a hard main default', () => { + const root = document.createElement('div') + root.dataset.slot = 'aui_edit-composer-root' + document.body.append(root) + mountSurface('tile:visible') + markActiveComposer('edit') + + root.remove() + releaseActiveComposer('edit') + + expect(getActiveComposer()).toBe('tile:visible') + }) + + it('routes an active-target request to the main composer once the edit composer closes', async () => { + // Mirrors the per-composer filter in use-composer-draft / user-edit-composer: + // a composer ignores any request not addressed to its own target. + const mainComposerSaw: string[] = [] + + const off = onComposerFocusRequest(({ target }) => { + if (target === 'main') { + mainComposerSaw.push(target) + } + }) + + const root = document.createElement('div') + root.dataset.slot = 'aui_edit-composer-root' + document.body.append(root) + markActiveComposer('edit') + root.remove() + releaseActiveComposer('edit') + requestComposerFocus('active') + + // `dispatch` defers to a macrotask so click/keydown handlers settle first. + await new Promise(resolve => window.setTimeout(resolve, 0)) + off() + + expect(mainComposerSaw).toEqual(['main']) + }) +}) + +describe('resolveActive / keep-alive tab heal', () => { + it('heals type-to-focus onto the visible main tab when a tile is buried', async () => { + // Repro for the reported main-tab miss: user typed in a session tile, then + // clicked the main/workspace tab without focusing its input. The tile stays + // mounted under data-pane-hidden, so activeTarget still reads tile:… and + // every type-to-focus request is dropped by the visible main composer. + mountSurface('tile:buried', true) + mountSurface('main') + markActiveComposer('tile:buried') + + expect(getActiveComposer()).toBe('main') + + const mainSaw: string[] = [] + const tileSaw: string[] = [] + + const off = onComposerFocusRequest(({ target }) => { + if (target === 'main') { + mainSaw.push(target) + } + + if (target === 'tile:buried') { + tileSaw.push(target) + } + }) + + requestComposerFocus('active', { typeChar: 'h' }) + await new Promise(resolve => window.setTimeout(resolve, 0)) + off() + + expect(mainSaw).toEqual(['main']) + expect(tileSaw).toEqual([]) + // Cache stays honest so dict/insert/Esc path all agree thereafter. + expect(getActiveComposer()).toBe('main') + }) + + it('keeps a live tile claim while that tile is the visible surface', () => { + mountSurface('main', true) + mountSurface('tile:front') + markActiveComposer('tile:front') + + expect(getActiveComposer()).toBe('tile:front') + }) + + it('heals an edit claim once the edit root is gone (no release site needed)', async () => { + mountSurface('main') + markActiveComposer('edit') + // No edit root in the document → claim is dead. getActiveComposer heals. + expect(getActiveComposer()).toBe('main') + + const mainSaw: string[] = [] + + const off = onComposerFocusRequest(({ target }) => { + if (target === 'main') { + mainSaw.push(target) + } + }) + + requestComposerFocus('active', { typeChar: 'a' }) + await new Promise(resolve => window.setTimeout(resolve, 0)) + off() + + expect(mainSaw).toEqual(['main']) + }) + + it('holds an edit claim while the edit composer root is mounted', () => { + const root = document.createElement('div') + root.dataset.slot = 'aui_edit-composer-root' + document.body.append(root) + mountSurface('main') + markActiveComposer('edit') + + expect(getActiveComposer()).toBe('edit') + }) +}) diff --git a/apps/desktop/src/app/chat/composer/focus.ts b/apps/desktop/src/app/chat/composer/focus.ts index a470edfcd958..3302d0310787 100644 --- a/apps/desktop/src/app/chat/composer/focus.ts +++ b/apps/desktop/src/app/chat/composer/focus.ts @@ -10,6 +10,8 @@ * steal focus from the composer effect. */ +import { queryVisible } from '@/components/pane-shell/pane-visibility' + import type { InlineRefInput } from './inline-refs' import { RICH_INPUT_SLOT } from './rich-editor' @@ -41,6 +43,21 @@ const INSERT_REFS_EVENT = 'hermes:composer-insert-refs' const SUBMIT_EVENT = 'hermes:composer-submit' const VOICE_TOGGLE_EVENT = 'hermes:composer-voice-toggle' +/** Inline edit composer root — mounted only while a user bubble is being edited. */ +const EDIT_COMPOSER_ROOT = '[data-slot="aui_edit-composer-root"]' + +/** Attribute-safe selector fragment. jsdom (vitest) does not ship `CSS.escape`. */ +const cssEscape = (value: string): string => { + if (typeof CSS !== 'undefined' && typeof CSS.escape === 'function') { + return CSS.escape(value) + } + + // Our targets are `'main'` / `'edit'` / `'tile:'` — alphanumerics plus `:` + // and `-`. Escape anything outside that set so a weird id cannot break the + // attribute selector. + return value.replace(/[^a-zA-Z0-9_:-]/g, ch => `\\${ch}`) +} + interface SubmitDetail { target: ComposerTarget text: string @@ -48,7 +65,76 @@ interface SubmitDetail { let activeTarget: ComposerTarget = 'main' -const resolve = (target: ComposerTarget | 'active') => (target === 'active' ? activeTarget : target) +/** + * The chat surface currently on screen (`data-composer-target` hung off each + * ChatView). Inactive tabs stay mounted with `data-pane-hidden`, so this uses + * the same visibility policy as every other document-wide surface lookup. + */ +const visibleChatTarget = (): ComposerTarget | null => { + if (typeof document === 'undefined') { + return null + } + + const surface = queryVisible('[data-composer-target]') + const target = surface?.dataset.composerTarget + + return target ? (target as ComposerTarget) : null +} + +/** True when `target` still has a live, on-screen subscriber. */ +const targetIsReachable = (target: ComposerTarget): boolean => { + if (typeof document === 'undefined') { + return true + } + + // The edit composer is an in-thread overlay, not a chat surface — it never + // stamps `data-composer-target`. While its root is mounted it still owns the + // bus; once it tears down the claim is dead. + if (target === 'edit') { + return Boolean(document.querySelector(EDIT_COMPOSER_ROOT)) + } + + // Exact match on a VISIBLE surface. Background keep-alive tabs carry the same + // `data-composer-target` but sit under `data-pane-hidden`, so queryVisible + // filters them out. + if (queryVisible(`[data-composer-target="${cssEscape(target)}"]`)) { + return true + } + + // A different chat surface is on screen → this claim is buried or gone. + // (A claim with zero stamped surfaces yet — first paint, pure-unit tests — + // keeps the marked key until the DOM contradicts it.) + if (queryVisible('[data-composer-target]')) { + return false + } + + return true +} + +/** + * The composer `'active'` should route to right now. + * + * The cached claim (`activeTarget`) wins while its surface is still on screen. + * Tab stacks keep inactive panes mounted, so focusing a tile then clicking the + * main tab leaves `activeTarget` pointing at a buried composer — with no + * subscriber on the visible surface, every type-to-focus keystroke is + * preventDefault'd and dropped. Heal to the visible chat surface (or main) + * whenever the claim is off-screen or gone, and keep the cache honest so Esc / + * voice / soft `/` agree with the keyboard path. + */ +const resolveActive = (): ComposerTarget => { + if (targetIsReachable(activeTarget)) { + return activeTarget + } + + const visible = visibleChatTarget() ?? 'main' + + activeTarget = visible + + return visible +} + +const resolve = (target: ComposerTarget | 'active') => (target === 'active' ? resolveActive() : target) const dispatch = (name: string, detail: T) => { if (typeof window === 'undefined') { @@ -80,9 +166,33 @@ export const markActiveComposer = (target: ComposerTarget) => { activeTarget = target } +/** Hand the routing key back when a composer unmounts, so `'active'` can never + * resolve to a composer that no longer has a subscriber — such a request is + * dispatched and then dropped by every mounted composer's target filter, and + * nothing re-marks the active composer on its own. + * + * Guarded on identity: a composer unmounting AFTER another one claimed the key + * (closing a background tile, a deferred edit-close cleanup) must not steal it + * from the live claimant. Falls through to {@link resolveActive} when the + * caller's surface is buried rather than gone, so closing on a tab switch that + * already re-fronted another chat surfaces there immediately. */ +export const releaseActiveComposer = (target: ComposerTarget) => { + if (activeTarget !== target) { + return + } + + // Prefer the visible chat surface over a hard `'main'` default — releasing a + // closed tile while another tile is fronted should land there, not the + // (possibly buried) workspace tab. + activeTarget = visibleChatTarget() ?? 'main' +} + /** The composer that last held focus — the target `'active'` resolves to. - * Used by broadcast listeners (voice, Esc-to-stop) to act on exactly one. */ -export const getActiveComposer = (): ComposerTarget => activeTarget + * Used by broadcast listeners (voice, Esc-to-stop) to act on exactly one. + * Heals a stale claim the same way {@link requestComposerFocus} does, so Esc + * and type-to-focus never disagree after a tab switch left the bus pointing at + * a keep-alive-mounted background composer. */ +export const getActiveComposer = (): ComposerTarget => resolveActive() export const requestComposerFocus = ( target: ComposerTarget | 'active' = 'active', @@ -175,9 +285,11 @@ export const focusComposerInput = (el: HTMLElement | null) => { window.setTimeout(focus, 0) } -/** Drop focus from the main composer input (status-stack chrome, sidebar, etc.). */ +/** Drop focus from the main composer input (status-stack chrome, sidebar, etc.). + * Skips inactive tabs — they stay mounted, so an unscoped lookup can land on a + * background composer and leave the visible one focused. */ export const blurComposerInput = () => { - const el = document.querySelector(`[data-slot="${RICH_INPUT_SLOT}"]`) as HTMLElement | null + const el = queryVisible(`[data-slot="${RICH_INPUT_SLOT}"]`) if (el && document.activeElement === el) { el.blur() diff --git a/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.ts b/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.ts index 949b8f1020c2..aa657ca8291c 100644 --- a/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.ts +++ b/apps/desktop/src/app/chat/composer/hooks/use-auto-speak-replies.ts @@ -4,10 +4,11 @@ import { useEffect, useRef } from 'react' import { playSpeechText } from '@/lib/voice-playback' import { ownsAmbientCue } from '@/store/ambient' import { notifyError } from '@/store/notifications' -import { $messages } from '@/store/session' import { $voicePlayback } from '@/store/voice-playback' import { $autoSpeakReplies } from '@/store/voice-prefs' +import { useComposerScope } from '../scope' + interface AutoSpeakReply { id: string pending: boolean @@ -40,6 +41,9 @@ export function useAutoSpeakReplies({ sessionId }: UseAutoSpeakReplies) { const enabled = useStore($autoSpeakReplies) + // Wake on THIS composer's transcript: a tile subscribed to the primary's + // would never fire on its own replies (and would fire on someone else's). + const { $messages } = useComposerScope() const latest = useRef({ conversationActive, failureLabel, markSpoken, pendingReply }) latest.current = { conversationActive, failureLabel, markSpoken, pendingReply } @@ -83,5 +87,5 @@ export function useAutoSpeakReplies({ const stops = [$messages.subscribe(speakLatest), $voicePlayback.listen(speakLatest)] return () => stops.forEach(f => f()) - }, [enabled, sessionId]) + }, [$messages, enabled, sessionId]) } diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.test.tsx new file mode 100644 index 000000000000..7707c8ae7537 --- /dev/null +++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.test.tsx @@ -0,0 +1,177 @@ +import { act, cleanup, render } from '@testing-library/react' +import { useLayoutEffect } from 'react' +import { afterEach, describe, expect, it, vi } from 'vitest' + +import { type ComposerAttachment, mainComposerScope, stashSessionDraft } from '@/store/composer' + +import type { QueueEditState } from '../composer-utils' +import { type ComposerTarget, getActiveComposer, markActiveComposer } from '../focus' +import { type ComposerScope, ComposerScopeProvider, MAIN_COMPOSER_SCOPE } from '../scope' + +import { useComposerDraft } from './use-composer-draft' + +const mockComposerApi = { setText: vi.fn() } + +vi.mock('@assistant-ui/react', () => ({ + useAui: () => ({ composer: () => mockComposerApi }), + useAuiState: (selector: (state: { composer: { text: string } }) => unknown) => selector({ composer: { text: '' } }), + useComposerRuntime: () => ({ + getState: () => ({ text: '' }), + subscribe: () => () => undefined + }) +})) + +interface ProbeHarnessProps { + activeQueueSessionKey: string | null + onLayoutSnapshot: (attachments: ComposerAttachment[]) => void + sessionId: string +} + +function ProbeHarness({ activeQueueSessionKey, onLayoutSnapshot, sessionId }: ProbeHarnessProps) { + useComposerDraft({ + activeQueueSessionKey, + focusKey: null, + inputDisabled: false, + queueEditRef: { current: null as QueueEditState | null }, + sessionId + }) + + // useLayoutEffect fires synchronously right after the DOM commit, BEFORE + // the hook's per-thread scope-swap useEffect (a passive effect) has a + // chance to swap attachmentScope.$attachments over to the new session. A + // synchronous read here — the same read ChatBar's `attachments` prop + // performs at render time — observes the OUTGOING session's attachments. + useLayoutEffect(() => { + onLayoutSnapshot(mainComposerScope.$attachments.get()) + }) + + return null +} + +describe('useComposerDraft — attachment scope stays coherent with the committed session on switch (#59305)', () => { + afterEach(() => { + cleanup() + mainComposerScope.clear() + }) + + it('clears the outgoing session attachments by the layout phase right after switching sessions', () => { + const attachmentA: ComposerAttachment = { id: 'url-A', kind: 'url', label: 'A' } + stashSessionDraft('session-A', 'hi from A', [attachmentA]) + + const snapshots: ComposerAttachment[][] = [] + + const { rerender } = render( + snapshots.push(s)} sessionId="session-A" /> + ) + + // Mount loads session A's stashed attachment into the (module-level) main + // scope — confirms the fixture actually seeded the leak precondition. + expect(mainComposerScope.$attachments.get()).toEqual([attachmentA]) + + snapshots.length = 0 // drop the initial-mount snapshot; only the switch matters + + act(() => { + rerender( + snapshots.push(s)} + sessionId="session-B" + /> + ) + }) + + // By the layout phase the scope must already be B's (empty) — a submit + // fired the instant B renders must never ship session A's attachment. + expect(snapshots[0]).toEqual([]) + }) +}) + +describe('useComposerDraft — rehydrate diagnostic log stays redacted', () => { + afterEach(() => { + cleanup() + mainComposerScope.clear() + vi.restoreAllMocks() + }) + + it('logs counts/kinds/scope on restore but never the raw url, refText, or label', () => { + const secretUrl = 'https://secret.example.com/private-workspace-path' + + const attachment: ComposerAttachment = { + id: 'url-secret', + kind: 'url', + label: 'do-not-leak-label', + refText: `@url:${secretUrl}` + } + + stashSessionDraft('session-secret', '', [attachment]) + + const debugSpy = vi.spyOn(console, 'debug').mockImplementation(() => undefined) + + render( + undefined} + sessionId="session-secret" + /> + ) + + const rehydrateCalls = debugSpy.mock.calls.filter(call => call[0] === '[composer-rehydrate]') + expect(rehydrateCalls.length).toBeGreaterThan(0) + + const serialized = JSON.stringify(rehydrateCalls) + expect(serialized).not.toContain(secretUrl) + expect(serialized).not.toContain(attachment.label) + expect(serialized).not.toContain(attachment.refText) + + expect(rehydrateCalls[0]?.[1]).toMatchObject({ + attachmentCount: 1, + attachmentKinds: ['url'], + scope: 'session-secret' + }) + }) +}) + +describe('useComposerDraft — a closing composer hands the focus-bus key back', () => { + afterEach(() => { + cleanup() + mainComposerScope.clear() + markActiveComposer('main') + }) + + function renderScoped(target: ComposerTarget) { + const scope: ComposerScope = { ...MAIN_COMPOSER_SCOPE, target } + + return render( + + undefined} + sessionId="session-tile" + /> + + ) + } + + it('stops `active` resolving to a session tile once the tile unmounts', () => { + const { unmount } = renderScoped('tile:abc') + + // Mounting claims the bus for this tile — the leak precondition. + expect(getActiveComposer()).toBe('tile:abc') + + unmount() + + expect(getActiveComposer()).toBe('main') + }) + + it('leaves the key alone when another composer claimed it before this one unmounted', () => { + const { unmount } = renderScoped('tile:abc') + expect(getActiveComposer()).toBe('tile:abc') + + // The user clicks into a second tile, which claims the bus. + markActiveComposer('tile:other') + + unmount() + + expect(getActiveComposer()).toBe('tile:other') + }) +}) diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts index 11dc9534df0f..d981d6435d8b 100644 --- a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts +++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts @@ -1,5 +1,5 @@ import { useAui, useAuiState, useComposerRuntime } from '@assistant-ui/react' -import { type RefObject, useCallback, useEffect, useRef, useState } from 'react' +import { type RefObject, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react' import { SLASH_COMMAND_RE } from '@/lib/chat-runtime' import { type ComposerAttachment, stashSessionDraft, takeSessionDraft } from '@/store/composer' @@ -17,10 +17,11 @@ import { markActiveComposer, onComposerFocusRequest, onComposerInsertRefsRequest, - onComposerInsertRequest + onComposerInsertRequest, + releaseActiveComposer } from '../focus' import { type InlineRefInput, insertInlineRefsIntoEditor } from '../inline-refs' -import { composerPlainText, placeCaretEnd, renderComposerContents } from '../rich-editor' +import { composerPlainText, placeCaretEnd, REF_RE, renderComposerContents } from '../rich-editor' import { useComposerScope } from '../scope' import type { ChatBarProps } from '../types' @@ -153,6 +154,15 @@ export function useComposerDraft({ } }, [focusInput, focusKey, focusRequestId, inputDisabled]) + // The mirror of the `markActiveComposer` above: give the key back when this + // composer goes away (a session tile closing, a pane unmounting). Covers both + // claim sites for this composer — `focusInput` here and ChatBar's `onFocus` — + // since they mark the same scope target. Without it `'active'` keeps + // resolving to a dead tile and every routed focus/insert request is dropped. + // (Heal-to-visible in focus.ts covers the keep-alive-tab case where the pane + // stays mounted behind the front tab; this covers true unmounts.) + useEffect(() => () => releaseActiveComposer(target), [target]) + useEffect(() => { if (inputDisabled) { return undefined @@ -189,6 +199,21 @@ export function useComposerDraft({ stashSessionDraft(scope, text, attachments) const loadIntoComposer = (text: string, attachments: ComposerAttachment[]) => { + // Diagnostic breadcrumb for #59305-class reports: identifies WHAT kind of + // state got restored into the composer (session switch, queue-edit + // restore, history browse) without logging any raw content. REF_RE has the + // global flag — testing against a throwaway clone avoids mutating the + // shared instance's lastIndex, which would otherwise corrupt this check on + // the next call. + if (attachments.length > 0 || new RegExp(REF_RE.source, REF_RE.flags).test(text)) { + console.debug('[composer-rehydrate]', { + attachmentCount: attachments.length, + attachmentKinds: attachments.map(a => a.kind), + hasTextRefs: new RegExp(REF_RE.source, REF_RE.flags).test(text), + scope: activeQueueSessionKeyRef.current + }) + } + attachmentScope.$attachments.set(cloneAttachments(attachments)) paintDraft(text, false) } @@ -231,6 +256,7 @@ export function useComposerDraft({ // source otherwise), and (3) schedule the debounced per-session stash. // Browsing history / editing a queued prompt suppress the stash so recalled // text never clobbers the draft. + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) useEffect(() => { const sync = () => { const text = composerRuntime.getState().text @@ -318,7 +344,17 @@ export function useComposerDraft({ // Per-thread draft swap — the composer's only session coupling. Lifecycle // never clears composer state; this effect alone stashes on leave, restores // on enter. Keyed writes are idempotent, so no skip-sentinel. - useEffect(() => { + // + // MUST be a layout effect, not a passive one: it swaps attachmentScope's + // module-level $attachments atom, and a passive effect fires only after the + // browser paints the new session's view — leaving a window where the DOM + // already shows session B while $attachments (and therefore ChatBar's + // `attachments` prop) still holds session A's chips. A submit fired in that + // window (e.g. a fast session switch immediately followed by Enter) would + // ship A's attachments into B's turn (#59305). useLayoutEffect closes the + // window by running before paint. + + useLayoutEffect(() => { // A pending debounce timer from the outgoing session is now stale — its // scope was correct when scheduled, but the authoritative stash below // (and the cleanup on the way out) already covers that text. Letting it @@ -344,6 +380,7 @@ export function useComposerDraft({ // pagehide is load-bearing: React skips effect cleanups on reload, so Cmd+R // inside the debounce/rAF window would drop trailing keystrokes without this. + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) useEffect(() => { const flushPendingDraftPersist = () => { const scope = draftScopeRef.current @@ -381,6 +418,7 @@ export function useComposerDraft({ requestMainFocus, sessionIdRef, setComposerText, - stashAt + stashAt, + syncDraftFromEditor } } diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.ts index 318802bbab80..859e70456c91 100644 --- a/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.ts +++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.ts @@ -1,10 +1,15 @@ import { useAuiState } from '@assistant-ui/react' import { type RefObject, useCallback, useEffect, useRef, useState } from 'react' +import { + chatSurfaceRoot, + clearSurfaceVar, + COMPOSER_HEIGHT_VAR, + COMPOSER_SURFACE_HEIGHT_VAR, + setSurfaceVar +} from '@/app/chat/surface-vars' import { useMediaQuery } from '@/hooks/use-media-query' import { useResizeObserver } from '@/hooks/use-resize-observer' -import { $composerPoppedOut } from '@/store/composer-popout' -import { isSecondaryWindow } from '@/store/windows' import { COMPOSER_COMPACT_PILL_PX, COMPOSER_SINGLE_LINE_MAX_PX, COMPOSER_STACK_BREAKPOINT_PX } from '../composer-utils' @@ -76,6 +81,11 @@ export function useComposerMetrics({ composerRef, composerSurfaceRef, editorRef, const lastBucketedSurfaceHeightRef = useRef(0) const lastTightRef = useRef(null) const lastCompactPillRef = useRef(null) + // Mirrored into a ref so `syncComposerMetrics` stays referentially stable — + // it's the shared ResizeObserver's handler, and a new identity every render + // would re-register the observation. + const poppedOutRef = useRef(poppedOut) + poppedOutRef.current = poppedOut const syncComposerMetrics = useCallback(() => { const composer = composerRef.current @@ -86,21 +96,20 @@ export function useComposerMetrics({ composerRef, composerSurfaceRef, editorRef, // Floating composer is out of the thread's flow — it must not reserve any // bottom clearance. Zero the measured vars so the thread reclaims the space. - // (Read globals here so the callback stays stable; mirror the popoutAllowed - // gate since secondary windows are forced docked.) - if ($composerPoppedOut.get() && !isSecondaryWindow()) { - const root = document.documentElement + // Read through a ref so the callback stays stable, and read THIS surface's + // own state: pop-out is per layout zone, so a float in the left split must + // not zero the right split's clearance. + if (poppedOutRef.current) { lastBucketedHeightRef.current = 0 lastBucketedSurfaceHeightRef.current = 0 - root.style.setProperty('--composer-measured-height', '0px') - root.style.setProperty('--composer-surface-measured-height', '0px') + setSurfaceVar(composer, COMPOSER_HEIGHT_VAR, '0px') + setSurfaceVar(composer, COMPOSER_SURFACE_HEIGHT_VAR, '0px') return } const { height, width } = composer.getBoundingClientRect() const surfaceHeight = composerSurfaceRef.current?.getBoundingClientRect().height - const root = document.documentElement if (width > 0) { const nextTight = width < COMPOSER_STACK_BREAKPOINT_PX @@ -135,7 +144,7 @@ export function useComposerMetrics({ composerRef, composerSurfaceRef, editorRef, if (bucket !== lastBucketedHeightRef.current) { lastBucketedHeightRef.current = bucket - root.style.setProperty('--composer-measured-height', `${bucket}px`) + setSurfaceVar(composer, COMPOSER_HEIGHT_VAR, `${bucket}px`) } } @@ -144,7 +153,7 @@ export function useComposerMetrics({ composerRef, composerSurfaceRef, editorRef, if (bucket !== lastBucketedSurfaceHeightRef.current) { lastBucketedSurfaceHeightRef.current = bucket - root.style.setProperty('--composer-surface-measured-height', `${bucket}px`) + setSurfaceVar(composer, COMPOSER_SURFACE_HEIGHT_VAR, `${bucket}px`) } } }, [composerRef, composerSurfaceRef, editorRef]) @@ -160,12 +169,18 @@ export function useComposerMetrics({ composerRef, composerSurfaceRef, editorRef, }, [poppedOut, syncComposerMetrics]) useEffect(() => { + // Resolve the owning surface while the composer is still attached; the + // unmount cleanup runs after React detached the node, where closest() + // can no longer find [data-chat-surface] and would clear the document + // root instead of this surface (same class of bug as the status stack's + // stale-clearance leak). + const root = chatSurfaceRoot(composerRef.current) + return () => { - const root = document.documentElement - root.style.removeProperty('--composer-measured-height') - root.style.removeProperty('--composer-surface-measured-height') + clearSurfaceVar(root, COMPOSER_HEIGHT_VAR) + clearSurfaceVar(root, COMPOSER_SURFACE_HEIGHT_VAR) } - }, []) + }, [composerRef]) // Pill compacts on real width (tile/pane), OR when stacked for any reason // (viewport-narrow / wrapped) so the controls row never over-runs. diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-placeholder.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-placeholder.ts index 0c2e4b61927c..8d1bf8c1ee56 100644 --- a/apps/desktop/src/app/chat/composer/hooks/use-composer-placeholder.ts +++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-placeholder.ts @@ -29,6 +29,7 @@ export function useComposerPlaceholder({ disabled, reconnecting, sessionId }: Us const prevSessionIdRef = useRef(sessionId) + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) useEffect(() => { const prev = prevSessionIdRef.current prevSessionIdRef.current = sessionId diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-popout.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-popout.ts index 518aa3658a56..b326025bb95d 100644 --- a/apps/desktop/src/app/chat/composer/hooks/use-composer-popout.ts +++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-popout.ts @@ -1,18 +1,20 @@ import { useStore } from '@nanostores/react' -import { type RefObject, useCallback, useEffect } from 'react' +import { type RefObject, useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react' +import { usePaneGroup, usePaneVisible } from '@/components/pane-shell/pane-visibility' +import { useResizeObserver } from '@/hooks/use-resize-observer' import { triggerHaptic } from '@/lib/haptics' import { - $composerPopoutPosition, - $composerPoppedOut, + $composerPopoutZone, + clampPopoutPosition, + getComposerPopoutZone, + popoutBoundsElement, + type PopoutPosition, readPopoutBounds, - setComposerPopoutPosition, setComposerPoppedOut } from '@/store/composer-popout' import { isSecondaryWindow } from '@/store/windows' -import { useComposerScope } from '../scope' - import { useComposerPopoutGestures } from './use-popout-drag' interface UseComposerPopoutOptions { @@ -20,32 +22,122 @@ interface UseComposerPopoutOptions { } /** - * Pop-out engine: the docked↔floating state (a shared, persisted atom), the - * dock/float/toggle actions, the drag gestures, and the on-screen re-clamp. - * Secondary windows (the tiny Ctrl+Shift+N window, subagent watch windows) can't - * pop out — a floating composer makes no sense there and would yank the main - * window's composer out via the shared atom. + * This surface's on-screen placement, derived from its zone's drag intent. + * + * A zone stores one intent for its whole tab stack — drag the box in any tab and + * it moves in all of them — but each surface owns a different rect, so the + * intent is clamped per surface. Clamping into the store instead would have + * every keep-alive-mounted tab overwrite the others with a position bounded by + * ITS geometry, last writer winning: that's how a drag in one tab used to get + * lost in another. + * + * Re-placing is skipped while this surface drags (the gesture already clamped + * against this rect) and while it's an inactive tab (still mounted, so a live + * drag would otherwise force a reflow per background tab per frame). + */ +function usePopoutPlacement( + composerRef: RefObject, + groupId: string, + intent: PopoutPosition, + dragging: boolean, + poppedOut: boolean +): PopoutPosition { + const [placement, setPlacement] = useState(intent) + const visible = usePaneVisible() + // Re-place while this surface is the visible tab and isn't itself dragging. + const live = poppedOut && visible && !dragging + + // Resolved before the shared ResizeObserver below registers (hook order puts + // this layout effect first), so the observer always has this surface's own + // bounds element rather than a document-wide first match. + const boundsRef = useRef(null) + + useLayoutEffect(() => { + boundsRef.current = popoutBoundsElement(composerRef.current) + }) + + const reclamp = useCallback(() => { + const el = composerRef.current + + if (!el) { + return + } + + const size = { height: el.offsetHeight, width: el.offsetWidth } + const next = clampPopoutPosition(getComposerPopoutZone(groupId).position, size, readPopoutBounds(el)) + + // Bail on an unchanged placement: a sash drag resizes the surface every + // frame, and a fresh object each time re-renders the whole composer. + setPlacement(prev => (prev.bottom === next.bottom && prev.right === next.right ? prev : next)) + }, [composerRef, groupId]) + + // The surface resizing (sash drag, sidebar open, tab split) re-places the box + // against its new rect; the composer resizing (a growing draft) re-places it + // against its new height. + useResizeObserver( + useCallback(() => { + if (live) { + reclamp() + } + }, [live, reclamp]), + composerRef, + boundsRef + ) + + // useLayoutEffect, not useEffect: a tab revealed after the box was dragged in + // another one must not paint a frame at its stale placement before catching + // up. Runs before paint, and no-ops for hidden tabs (`live`). + useLayoutEffect(() => { + if (!live) { + return undefined + } + + reclamp() + // A second pass after layout settles (sidebar widths, fonts): anyone + // restored out of bounds is pulled back even if the first measure was + // premature. + const raf = requestAnimationFrame(reclamp) + window.addEventListener('resize', reclamp) + + return () => { + cancelAnimationFrame(raf) + window.removeEventListener('resize', reclamp) + } + }, [intent, live, reclamp]) + + return dragging ? intent : placement +} + +/** + * Pop-out engine: the docked↔floating state, the dock/float/toggle actions, the + * drag gestures, and this surface's placement. + * + * State is scoped to the surface's layout ZONE (its tab stack): tabs in the same + * zone share one float, so switching tabs keeps the box exactly where you put + * it, while a split zone beside them keeps its own — popping out on the left + * doesn't fling a composer out of the right. + * + * Secondary windows (the tiny Ctrl+Shift+N window, subagent watch windows) stay + * docked: a floating composer makes no sense in a scratch window. */ export function useComposerPopout({ composerRef }: UseComposerPopoutOptions) { - // The floating composer is a window-level singleton: only the main scope - // (not tiles) in a primary window may pop out. - const scope = useComposerScope() - const popoutAllowed = !isSecondaryWindow() && scope.popoutAllowed - const poppedOut = useStore($composerPoppedOut) && popoutAllowed - const popoutPosition = useStore($composerPopoutPosition) + const popoutAllowed = !isSecondaryWindow() + const groupId = usePaneGroup() + const zone = useStore(useMemo(() => $composerPopoutZone(groupId), [groupId])) + const poppedOut = zone.poppedOut && popoutAllowed const handleComposerPopOut = useCallback(() => { triggerHaptic('open') - setComposerPoppedOut(true) - }, []) + setComposerPoppedOut(groupId, true) + }, [groupId]) const handleComposerDock = useCallback(() => { triggerHaptic('success') - setComposerPoppedOut(false) - }, []) + setComposerPoppedOut(groupId, false) + }, [groupId]) // Double-click the grab area toggles dock/float. Undocking restores the last - // position (the persisted atom is never cleared on dock). + // position (a zone's stored position is never cleared on dock). const handleComposerToggle = useCallback(() => { poppedOut ? handleComposerDock() : handleComposerPopOut() }, [handleComposerDock, handleComposerPopOut, poppedOut]) @@ -56,39 +148,14 @@ export function useComposerPopout({ composerRef }: UseComposerPopoutOptions) { onPointerDown: onComposerGesturePointerDown } = useComposerPopoutGestures({ composerRef, + groupId, onDock: handleComposerDock, onPopOut: handleComposerPopOut, poppedOut, - position: popoutPosition + position: zone.position }) - // Keep the floating box on-screen: re-clamp (with the real measured size + - // thread bounds) when it pops out and on every window resize — so a position - // persisted on a bigger/other monitor, a shrunk window, or now-wider sidebar - // can never strand it. The rAF pass re-clamps after layout settles (sidebar - // widths, fonts), so anyone loading in out of bounds is pulled back + saved - // even if the first measure was premature. - useEffect(() => { - if (!poppedOut) { - return undefined - } - - const reclamp = (persist: boolean) => { - const el = composerRef.current - const size = el ? { height: el.offsetHeight, width: el.offsetWidth } : undefined - setComposerPopoutPosition($composerPopoutPosition.get(), { area: readPopoutBounds(el), persist, size }) - } - - reclamp(true) - const raf = requestAnimationFrame(() => reclamp(true)) - const onResize = () => reclamp(false) - window.addEventListener('resize', onResize) - - return () => { - cancelAnimationFrame(raf) - window.removeEventListener('resize', onResize) - } - }, [composerRef, poppedOut]) + const popoutPosition = usePopoutPlacement(composerRef, groupId, zone.position, dragging, poppedOut) return { dockProximity, diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts index 4e813f548aef..e1bb5442fef0 100644 --- a/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts +++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-queue.ts @@ -106,7 +106,9 @@ export function useComposerQueue({ entryId: entry.id, sessionKey: activeQueueSessionKey }) - loadIntoComposer(entry.text, entry.attachments) + // Edit what the panel SHOWS. A queued `/skill` entry's text is the + // expanded skill body — never drop that into the composer. + loadIntoComposer(entry.displayText ?? entry.text, entry.attachments) triggerHaptic('selection') focusInput() } @@ -135,7 +137,7 @@ export function useComposerQueue({ if (next) { setQueueEditSnapshot({ ...queueEdit, entryId: next.id }) - loadIntoComposer(next.text, next.attachments) + loadIntoComposer(next.displayText ?? next.text, next.attachments) } else { setQueueEditSnapshot(null) loadIntoComposer(queueEdit.draft, queueEdit.attachments) @@ -213,6 +215,7 @@ export function useComposerQueue({ const accepted = await Promise.resolve( onSubmit(entry.text, { attachments: entry.attachments, + ...(entry.displayText ? { displayText: entry.displayText } : {}), fromQueue: true, sessionId: drainRuntimeSessionId, storedSessionId: drainQueueSessionKey @@ -322,6 +325,7 @@ export function useComposerQueue({ // never churns, so a change there is a real session switch and must NOT // migrate; only the runtime-derived key (queueSessionKey falsy → key is // sessionId) churns on a backend bounce/resume of the same conversation. + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) useEffect(() => { const prev = prevQueueKeyRef.current prevQueueKeyRef.current = activeQueueSessionKey diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx index c2a6bc6d7993..dd83d04f0c0f 100644 --- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx +++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx @@ -1,17 +1,25 @@ import { act, cleanup, renderHook, waitFor } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' +import { $clarifyRequests } from '@/store/clarify' import type { ComposerAttachment } from '@/store/composer' +import { $gateway } from '@/store/gateway' import { useComposerSubmit } from './use-composer-submit' interface SubmitHarnessOptions { attachments?: ComposerAttachment[] busy?: boolean + compacting?: boolean text?: string } -function renderSubmitHook({ attachments = [], busy = false, text = '' }: SubmitHarnessOptions = {}) { +function renderSubmitHook({ + attachments = [], + busy = false, + compacting = false, + text = '' +}: SubmitHarnessOptions = {}) { const draftRef = { current: text } const editor = document.createElement('div') editor.dataset.slot = 'composer-rich-input' @@ -33,6 +41,7 @@ function renderSubmitHook({ attachments = [], busy = false, text = '' }: SubmitH activeQueueSessionKeyRef: { current: 'stored-session' }, attachments, busy, + compacting, clearDraft, disabled: false, draftRef, @@ -79,6 +88,23 @@ describe('useComposerSubmit busy-turn routing', () => { expect(onSubmit).not.toHaveBeenCalled() }) + it('queues a plain-text follow-up while the active turn is compacting', () => { + const { hook, onCancel, onSteer, onSubmit, queueCurrentDraft } = renderSubmitHook({ + busy: true, + compacting: true, + text: 'wait for the summary' + }) + + act(() => { + hook.result.current.submitDraft() + }) + + expect(queueCurrentDraft).toHaveBeenCalledTimes(1) + expect(onSteer).not.toHaveBeenCalled() + expect(onSubmit).not.toHaveBeenCalled() + expect(onCancel).not.toHaveBeenCalled() + }) + it('runs slash commands immediately while busy', async () => { const { clearDraft, hook, onCancel, onSteer, onSubmit, queueCurrentDraft } = renderSubmitHook({ busy: true, @@ -89,7 +115,9 @@ describe('useComposerSubmit busy-turn routing', () => { hook.result.current.submitDraft() }) - await waitFor(() => expect(onSubmit).toHaveBeenCalledWith('/compress preserve context')) + await waitFor(() => + expect(onSubmit).toHaveBeenCalledWith('/compress preserve context', { composerScope: 'stored-session' }) + ) expect(clearDraft).toHaveBeenCalledTimes(1) expect(onSteer).not.toHaveBeenCalled() expect(queueCurrentDraft).not.toHaveBeenCalled() @@ -135,9 +163,103 @@ describe('useComposerSubmit busy-turn routing', () => { hook.result.current.submitDraft() }) - await waitFor(() => expect(onSubmit).toHaveBeenCalledWith('ordinary question', { attachments: [] })) + await waitFor(() => + expect(onSubmit).toHaveBeenCalledWith('ordinary question', { + attachments: [], + composerScope: 'stored-session' + }) + ) expect(onSteer).not.toHaveBeenCalled() expect(queueCurrentDraft).not.toHaveBeenCalled() expect(onCancel).not.toHaveBeenCalled() }) + + it('threads the loaded composer scope through onSubmit for the #59305 submit-time guard', async () => { + const { hook, onSubmit } = renderSubmitHook({ text: 'hello' }) + + act(() => { + hook.result.current.submitDraft() + }) + + await waitFor(() => + expect(onSubmit).toHaveBeenCalledWith('hello', expect.objectContaining({ composerScope: 'stored-session' })) + ) + }) +}) + +describe('useComposerSubmit with a clarify parked on the session', () => { + const gatewayRequest = vi.fn(async () => ({ ok: true })) + + const parkClarify = (sessionId: string) => { + $clarifyRequests.set({ + [sessionId]: { requestId: `req-${sessionId}`, question: 'which one?', choices: ['a', 'b'], sessionId } + }) + $gateway.set({ request: gatewayRequest } as unknown as ReturnType) + } + + afterEach(() => { + cleanup() + gatewayRequest.mockClear() + $clarifyRequests.set({}) + $gateway.set(null) + vi.restoreAllMocks() + }) + + it('skips the question and still sends the typed message on an idle session', async () => { + parkClarify('runtime-session') + const { hook, onSubmit } = renderSubmitHook({ text: 'actually do this instead' }) + + act(() => { + hook.result.current.submitDraft() + }) + + await waitFor(() => + expect(gatewayRequest).toHaveBeenCalledWith('clarify.respond', { + request_id: 'req-runtime-session', + answer: '' + }) + ) + await waitFor(() => + expect(onSubmit).toHaveBeenCalledWith('actually do this instead', expect.objectContaining({ attachments: [] })) + ) + expect($clarifyRequests.get()['runtime-session']).toBeUndefined() + }) + + it('skips the question before steering a busy turn', async () => { + parkClarify('runtime-session') + const { hook, onSteer } = renderSubmitHook({ busy: true, text: 'change course' }) + + act(() => { + hook.result.current.submitDraft() + }) + + await waitFor(() => expect(onSteer).toHaveBeenCalledWith('change course')) + expect(gatewayRequest).toHaveBeenCalledWith('clarify.respond', { request_id: 'req-runtime-session', answer: '' }) + }) + + it('leaves the question alone for an empty Enter (Stop, not an answer)', () => { + parkClarify('runtime-session') + const { hook, onCancel } = renderSubmitHook({ busy: true }) + + act(() => { + hook.result.current.submitDraft() + }) + + expect(gatewayRequest).not.toHaveBeenCalled() + expect($clarifyRequests.get()['runtime-session']).toBeDefined() + expect(onCancel).toHaveBeenCalledTimes(1) + }) + + it("leaves another session's question alone", async () => { + parkClarify('other-session') + const { hook, onSubmit } = renderSubmitHook({ text: 'unrelated message' }) + + act(() => { + hook.result.current.submitDraft() + }) + + await waitFor(() => expect(onSubmit).toHaveBeenCalled()) + expect(gatewayRequest).not.toHaveBeenCalled() + expect($clarifyRequests.get()['other-session']).toBeDefined() + }) }) diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts index be053ddac82d..9d34ddfca3f1 100644 --- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts +++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts @@ -2,12 +2,14 @@ import { type RefObject, useEffect, useRef } from 'react' import { SLASH_COMMAND_RE } from '@/lib/chat-runtime' import { triggerHaptic } from '@/lib/haptics' +import { hasClarifyRequest, skipClarifyRequest } from '@/store/clarify' import { clearSessionDraft, type ComposerAttachment } from '@/store/composer' import { resetBrowseState } from '@/store/composer-input-history' import { enqueueQueuedPrompt, type QueuedPromptEntry } from '@/store/composer-queue' import { cloneAttachments, type QueueEditState } from '../composer-utils' import { onComposerSubmitRequest } from '../focus' +import { pathifyRefs } from '../path-refs' import { composerPlainText } from '../rich-editor' import { useComposerScope } from '../scope' import type { ChatBarProps } from '../types' @@ -17,6 +19,7 @@ interface UseComposerSubmitArgs { activeQueueSessionKeyRef: RefObject attachments: ComposerAttachment[] busy: boolean + compacting: boolean clearDraft: () => void disabled: boolean draftRef: RefObject @@ -51,6 +54,7 @@ export function useComposerSubmit({ activeQueueSessionKeyRef, attachments, busy, + compacting, clearDraft, disabled, draftRef, @@ -87,7 +91,11 @@ export function useComposerSubmit({ stashAt(submittedScope, text, submittedAttachments) } - void Promise.resolve(attachments ? onSubmit(text, { attachments }) : onSubmit(text)) + void Promise.resolve( + attachments + ? onSubmit(text, { attachments, composerScope: submittedScope }) + : onSubmit(text, { composerScope: submittedScope }) + ) .then(accepted => void (accepted === false ? restore() : clearSessionDraft(submittedScope))) .catch(restore) } @@ -132,9 +140,27 @@ export function useComposerSubmit({ } } - const text = draftRef.current + // A path that never got its committing space (`@apps/desktop/` left by a Tab + // descend, then Enter) is still the reference the user picked — promote it + // on the way out so it attaches instead of submitting as inert text. + const text = pathifyRefs(draftRef.current) const payloadPresent = text.trim().length > 0 || attachments.length > 0 + // A clarify card parked on this session owns the turn: the agent is blocked + // inside its tool batch waiting on `clarify.respond`, so a follow-up routed + // through steer/queue sits undelivered until the clarify's own timeout + // (default 5 min) — the message looks sent and nothing happens. Typing a + // real message instead of picking an option IS the answer "none of these": + // skip the question so the tool returns, then route the words normally. + // + // Fire-and-forget, not awaited: the skip clears the card synchronously and + // both RPCs ride the same socket in call order, so the gateway resolves the + // clarify before it sees the follow-up. Awaiting first would leave the draft + // live for a tick — long enough for a second Enter to send it twice. + if (payloadPresent && !queueEdit && hasClarifyRequest(sessionId)) { + void skipClarifyRequest(sessionId) + } + if (queueEdit) { exitQueuedEdit('save') } else if (busy) { @@ -149,7 +175,7 @@ export function useComposerSubmit({ triggerHaptic('submit') clearDraft() dispatchSubmit(text) - } else if (!attachments.length && text.trim()) { + } else if (!compacting && !attachments.length && text.trim()) { // Cursor-style stop-and-correct: interrupt the live turn and redirect // it with this text. redirect() preserves the shown reasoning/work; if // the turn already ended, steerDraft re-queues so nothing is lost. diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.test.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.test.ts new file mode 100644 index 000000000000..a778262d370f --- /dev/null +++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.test.ts @@ -0,0 +1,225 @@ +import type { Unstable_TriggerAdapter, Unstable_TriggerItem } from '@assistant-ui/core' +import { act, renderHook } from '@testing-library/react' +import { createRef } from 'react' +import { describe, expect, it, vi } from 'vitest' + +import { composerPlainText, renderComposerContents, RICH_INPUT_SLOT } from '../rich-editor' + +import { useComposerTrigger } from './use-composer-trigger' + +/** A live contentEditable seeded with `text`, caret parked at the end. */ +function mountEditor(text: string) { + const editor = document.createElement('div') + editor.dataset.slot = RICH_INPUT_SLOT + editor.contentEditable = 'true' + document.body.append(editor) + renderComposerContents(editor, text) + + const range = document.createRange() + range.selectNodeContents(editor) + range.collapse(false) + const selection = window.getSelection()! + selection.removeAllRanges() + selection.addRange(range) + + return editor +} + +const item = (command: string, group = 'Skills'): Unstable_TriggerItem => ({ + id: command, + type: 'slash', + label: command.slice(1), + metadata: { command, display: command, meta: '', group, action: '', rawText: command } +}) + +function mountTrigger(editor: HTMLDivElement, items: Unstable_TriggerItem[]) { + const editorRef = createRef() as { current: HTMLDivElement | null } + editorRef.current = editor + + const draftRef = { current: composerPlainText(editor) } + + const adapter: Unstable_TriggerAdapter = { + categories: () => [], + categoryItems: () => [], + search: () => items + } + + const setComposerText = vi.fn() + + const hook = renderHook(() => + useComposerTrigger({ + at: { adapter: null, loading: false }, + draftRef, + editorRef, + requestMainFocus: vi.fn(), + setComposerText, + slash: { adapter, loading: false } + }) + ) + + return { draftRef, hook, setComposerText } +} + +describe('useComposerTrigger — slash anywhere in the prompt', () => { + it('opens the completion list for a slash typed mid-message', () => { + const editor = mountEditor('please run /cle') + const { hook } = mountTrigger(editor, [item('/clean')]) + + act(() => hook.result.current.refreshTrigger()) + + expect(hook.result.current.trigger).toMatchObject({ kind: '/', inline: true, query: 'cle' }) + expect(hook.result.current.triggerItems).toHaveLength(1) + }) + + it('inserts the picked skill inline and keeps the surrounding prose intact', () => { + const editor = mountEditor('please run /cle') + const { hook } = mountTrigger(editor, [item('/clean')]) + + act(() => hook.result.current.refreshTrigger()) + act(() => hook.result.current.replaceTriggerWithChip(item('/clean'))) + + // The `/cle` the user typed is replaced by the full command; "please run" + // in front of it survives untouched. + expect(composerPlainText(editor)).toBe('please run /clean ') + }) + + it('offers only skills mid-message, not app commands', () => { + // `/model` and `/new` act on the app — meaningless as a reference in prose. + const editor = mountEditor('please run /') + const { hook } = mountTrigger(editor, [item('/clean'), item('/model', 'Commands'), item('/new', 'Commands')]) + + act(() => hook.result.current.refreshTrigger()) + + expect(hook.result.current.triggerItems.map(i => i.label)).toEqual(['clean']) + }) + + it('still offers the full command set at the start of the prompt', () => { + const editor = mountEditor('/') + const { hook } = mountTrigger(editor, [item('/clean'), item('/model', 'Commands')]) + + act(() => hook.result.current.refreshTrigger()) + + expect(hook.result.current.triggerItems.map(i => i.label)).toEqual(['clean', 'model']) + }) + + it('still opens the list for a slash at the start of the prompt', () => { + const editor = mountEditor('/cle') + const { hook } = mountTrigger(editor, [item('/clean')]) + + act(() => hook.result.current.refreshTrigger()) + + expect(hook.result.current.trigger).toMatchObject({ kind: '/', query: 'cle' }) + expect(hook.result.current.trigger?.inline).toBeUndefined() + }) + + it('leaves a mid-message file path alone', () => { + const editor = mountEditor('open src/foo/bar') + const { hook } = mountTrigger(editor, [item('/clean')]) + + act(() => hook.result.current.refreshTrigger()) + + expect(hook.result.current.trigger).toBeNull() + }) + + it('opens the list for a second slash after a leading command', () => { + // `/work /cle`: the command regex's argument tail would otherwise swallow + // `/cle` as an argument to `/work`, and a no-arg command suppresses the + // popover — so every slash after the first went dead. + const editor = mountEditor('/work /cle') + const { hook } = mountTrigger(editor, [item('/clean')]) + + act(() => hook.result.current.refreshTrigger()) + + expect(hook.result.current.trigger).toMatchObject({ kind: '/', inline: true, query: 'cle' }) + expect(hook.result.current.triggerItems).toHaveLength(1) + }) + + it('inserts the second command without disturbing the first', () => { + const editor = mountEditor('/work rewrite the composer /cle') + const { hook } = mountTrigger(editor, [item('/clean')]) + + act(() => hook.result.current.refreshTrigger()) + act(() => hook.result.current.replaceTriggerWithChip(item('/clean'))) + + expect(composerPlainText(editor)).toBe('/work rewrite the composer /clean ') + }) +}) + +describe('useComposerTrigger — free-text slash arguments', () => { + it('keeps a picked /goal command as editable text while retaining subcommand completion', () => { + const editor = mountEditor('/go') + const goal = item('/goal', 'Commands') + const { hook } = mountTrigger(editor, [goal]) + + act(() => hook.result.current.refreshTrigger()) + act(() => hook.result.current.replaceTriggerWithChip(goal)) + + expect(composerPlainText(editor)).toBe('/goal ') + expect(editor.querySelector('[data-slash-kind]')).toBeNull() + expect(hook.result.current.trigger).not.toBeNull() + }) + + it('does not seal a multi-word /goal into a chip when the option list runs empty', () => { + const editor = mountEditor('/goal finish the full prompt') + const { hook } = mountTrigger(editor, []) + + act(() => hook.result.current.refreshTrigger()) + + expect(hook.result.current.slashFreeTextArgStage).toBe(true) + expect(hook.result.current.commitTypedSlashDirective()).toBe(false) + expect(composerPlainText(editor)).toBe('/goal finish the full prompt') + expect(editor.querySelector('[data-slash-kind]')).toBeNull() + }) + + it('treats the default highlight as a suggestion until the user arrows to a row', () => { + const editor = mountEditor('/goal stat') + const { hook } = mountTrigger(editor, [item('/goal status', 'Options')]) + + act(() => hook.result.current.refreshTrigger()) + expect(hook.result.current.triggerActiveExplicit).toBe(false) + + act(() => hook.result.current.moveTriggerActive(1)) + expect(hook.result.current.triggerActiveExplicit).toBe(true) + }) + + it('drops a deliberate selection once the query moves on', () => { + const editor = mountEditor('/goal stat') + const { hook } = mountTrigger(editor, [item('/goal status', 'Options')]) + + act(() => hook.result.current.refreshTrigger()) + act(() => hook.result.current.moveTriggerActive(1)) + + renderComposerContents(editor, '/goal start the migration') + act(() => hook.result.current.refreshTrigger()) + + expect(hook.result.current.triggerActiveExplicit).toBe(false) + }) + + it('keeps a multi-word /resume search typeable instead of firing the picker action', () => { + // The session list always ends in a "Browse all sessions…" action row, so + // an accept here doesn't insert a chip — it empties the composer and opens + // the overlay, taking the half-typed query with it. + const editor = mountEditor('/resume my new') + const { hook } = mountTrigger(editor, [item('/resume', 'Sessions')]) + + act(() => hook.result.current.refreshTrigger()) + + expect(hook.result.current.slashFreeTextArgStage).toBe(true) + expect(hook.result.current.commitTypedSlashDirective()).toBe(false) + expect(composerPlainText(editor)).toBe('/resume my new') + }) + + it('still commits a fully typed finite option as one directive chip', () => { + const editor = mountEditor('/personality creative') + const { hook } = mountTrigger(editor, []) + + act(() => hook.result.current.refreshTrigger()) + + expect(hook.result.current.slashFreeTextArgStage).toBe(false) + act(() => { + expect(hook.result.current.commitTypedSlashDirective()).toBe(true) + }) + expect(composerPlainText(editor)).toBe('/personality creative ') + expect(editor.querySelector('[data-slash-kind]')?.getAttribute('data-ref-text')).toBe('/personality creative') + }) +}) diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.ts index 20abc03309f5..ea968fb36437 100644 --- a/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.ts +++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-trigger.ts @@ -2,9 +2,15 @@ import type { Unstable_TriggerAdapter, Unstable_TriggerItem } from '@assistant-u import { type MutableRefObject, type RefObject, useCallback, useEffect, useRef, useState } from 'react' import { hermesDirectiveFormatter } from '@/components/assistant-ui/directive-text' -import { desktopSlashCommandTakesArgs } from '@/lib/desktop-slash-commands' +import { desktopSlashCommandArgumentMode } from '@/lib/desktop-slash-commands' -import { COMPLETION_ACTIONS, slashArgStage, slashChipKindForItem, slashCommandToken } from '../composer-utils' +import { + COMPLETION_ACTIONS, + isSkillItem, + slashArgStage, + slashChipKindForItem, + slashCommandToken +} from '../composer-utils' import { composerPlainText, placeCaretEnd, @@ -47,6 +53,11 @@ export function useComposerTrigger({ }: UseComposerTriggerOptions) { const [trigger, setTrigger] = useState(null) const [triggerActive, setTriggerActive] = useState(0) + // The list highlights its first row on open, which is a suggestion rather + // than a choice. This records that the user moved the highlight themselves, + // which is what lets Enter accept a completion in a free-text argument stage + // without stealing prose from everyone who never touched the arrows. + const [triggerActiveExplicit, setTriggerActiveExplicit] = useState(false) const [triggerItems, setTriggerItems] = useState([]) // Set synchronously in keydown when the open trigger popover consumes a // navigation/control key (Arrow/Enter/Tab/Escape). The subsequent keyup must @@ -57,6 +68,11 @@ export function useComposerTrigger({ // re-rendered and the handler closure sees the post-keydown state. const triggerKeyConsumedRef = useRef(false) + const resetTriggerActive = useCallback(() => { + setTriggerActive(0) + setTriggerActiveExplicit(false) + }, []) + const refreshTrigger = useCallback(() => { const editor = editorRef.current @@ -74,7 +90,7 @@ export function useComposerTrigger({ if (!rawText.includes('@') && !rawText.includes('/')) { if (trigger) { setTrigger(null) - setTriggerActive(0) + resetTriggerActive() } return @@ -83,11 +99,16 @@ export function useComposerTrigger({ const before = textBeforeCaret(editor) const found = detectTrigger(before ?? composerPlainText(editor)) - // The arg-stage popover is only useful for commands with an options screen. - // For a no-arg command it would dead-end on "No matches", so drop it — the - // directive is already complete. + // A text-only command has no completion screen once its prose begins. Mixed + // commands such as /goal stay live so their finite subcommands can still be + // suggested, while arbitrary goal text remains valid. + const argumentMode = + found?.kind === '/' && slashArgStage(found.query) + ? desktopSlashCommandArgumentMode(slashCommandToken(found.query)) + : null + const detected = - found?.kind === '/' && slashArgStage(found.query) && !desktopSlashCommandTakesArgs(slashCommandToken(found.query)) + found?.kind === '/' && slashArgStage(found.query) && argumentMode !== 'options' && argumentMode !== 'mixed' ? null : found @@ -98,9 +119,9 @@ export function useComposerTrigger({ // caret move (mouseup) or a stray refresh — must preserve the user's // current selection instead of snapping back to the first item. if (detected?.kind !== trigger?.kind || detected?.query !== trigger?.query) { - setTriggerActive(0) + resetTriggerActive() } - }, [editorRef, trigger]) + }, [editorRef, resetTriggerActive, trigger]) const triggerAdapter: Unstable_TriggerAdapter | null = trigger?.kind === '@' ? at.adapter : trigger?.kind === '/' ? slash.adapter : null @@ -112,7 +133,13 @@ export function useComposerTrigger({ return } - setTriggerItems(triggerAdapter.search(trigger.query)) + const items = triggerAdapter.search(trigger.query) + + // Mid-message only offers SKILLS. A built-in like `/model` or `/new` acts + // on the app, so it's meaningless as a reference inside prose — only a + // skill reads as "handle this part with X". Filtering here rather than in + // the fetcher keeps one completion source for both shapes. + setTriggerItems(trigger.inline ? items.filter(isSkillItem) : items) }, [trigger, triggerAdapter]) const triggerLoading = trigger?.kind === '@' ? at.loading : trigger?.kind === '/' ? slash.loading : false @@ -122,10 +149,23 @@ export function useComposerTrigger({ // Space/Tab — neither should dead-end on a popover. const argStageEmpty = trigger?.kind === '/' && slashArgStage(trigger.query) && !triggerLoading && !triggerItems.length + const slashArgumentMode = + trigger?.kind === '/' && slashArgStage(trigger.query) + ? desktopSlashCommandArgumentMode(slashCommandToken(trigger.query)) + : null + + const slashFreeTextArgStage = slashArgumentMode === 'mixed' || slashArgumentMode === 'text' + const closeTrigger = () => { setTrigger(null) setTriggerItems([]) - setTriggerActive(0) + resetTriggerActive() + } + + /** Step the highlight, marking it as the user's own deliberate pick. */ + const moveTriggerActive = (delta: number) => { + setTriggerActiveExplicit(true) + setTriggerActive(idx => (idx + delta + triggerItems.length) % triggerItems.length) } useEffect(() => { @@ -136,9 +176,16 @@ export function useComposerTrigger({ // the completion list is empty because the arg is already fully typed (the // backend completer drops exact matches). Reuses the chip path via a // synthetic item whose serialized form is the verbatim text. - const commitTypedSlashDirective = () => { + const commitTypedSlashDirective = (): boolean => { if (trigger?.kind !== '/') { - return + return false + } + + // Free prose must stay ordinary contentEditable text. This guard also + // protects against a stale completion result reaching the keydown path + // before refreshTrigger has caught up with the latest DOM input. + if (desktopSlashCommandArgumentMode(slashCommandToken(trigger.query)) !== 'options') { + return false } const text = `/${trigger.query.trimEnd()}` @@ -156,9 +203,11 @@ export function useComposerTrigger({ rawText: text } }) + + return true } - const replaceTriggerWithChip = (item: Unstable_TriggerItem) => { + const replaceTriggerWithChip = (item: Unstable_TriggerItem, options?: { descend?: boolean }) => { const editor = editorRef.current if (!editor || !trigger) { @@ -188,20 +237,48 @@ export function useComposerTrigger({ const serialized = hermesDirectiveFormatter.serialize(item) const starter = serialized.endsWith(':') + // Tab on a folder walks INTO it instead of committing it: re-type the + // token as the bare path so the next `complete.path` lists that folder's + // children, exactly as typing the path by hand would. Enter still commits + // the folder itself — the two intents are distinct, so the keys are too. + // Only `@` folders descend; a slash command's arg list has no hierarchy. + const descendInto = + options?.descend && trigger.kind === '@' && item.type === 'folder' + ? String((item.metadata as { insertId?: unknown } | undefined)?.insertId ?? '') + : '' + + if (descendInto) { + const path = descendInto.endsWith('/') ? descendInto : `${descendInto}/` + const current = composerPlainText(editor) + const prefix = current.slice(0, Math.max(0, current.length - trigger.tokenLength)) + + renderComposerContents(editor, `${prefix}@${path}`) + placeCaretEnd(editor) + draftRef.current = composerPlainText(editor) + setComposerText(draftRef.current) + requestMainFocus() + window.setTimeout(refreshTrigger, 0) + + return + } + // Picking a bare arg-taking command (e.g. `/personality`) shouldn't commit // it — expand to its options step so the popover shows the inline list, just // as typing `/personality ` by hand would. A serialized value with a space is - // already an arg pick (`/personality alice`), so it commits normally. + // already an arg pick (`/personality alice`), so it commits normally. An + // inline (mid-message) pick never expands: it's a reference inside prose, so + // there's no command invocation for the args to belong to. const command = (item.metadata as { command?: string } | undefined)?.command ?? '' - const expandsToArgs = trigger.kind === '/' && !serialized.includes(' ') && desktopSlashCommandTakesArgs(command) + const argumentMode = desktopSlashCommandArgumentMode(command) + const expandsToArgs = trigger.kind === '/' && !trigger.inline && !serialized.includes(' ') && argumentMode !== null const text = starter || serialized.endsWith(' ') ? serialized : `${serialized} ` const directive = !starter && serialized.match(/^@([^:]+):(.+)$/) // No pill while expanding — the bare command stays plain text until an arg // is picked, at which point a single pill is emitted for the full command. const slashKind = !expandsToArgs && trigger.kind === '/' ? slashChipKindForItem(item) : null - const keepTriggerOpen = starter || expandsToArgs + const keepTriggerOpen = starter || (expandsToArgs && argumentMode !== 'text') const finish = () => { draftRef.current = composerPlainText(editor) @@ -266,15 +343,47 @@ export function useComposerTrigger({ finish() } + /** Backspace inside an `@` path drops the last segment (`a/b/` → `a/`) + * instead of one character. Descending is one Tab per level, so climbing + * back out should cost one key too rather than a held delete. Returns + * false when the caret isn't in a path, so keydown falls through. */ + const ascendTriggerPath = () => { + const editor = editorRef.current + + if (!editor || trigger?.kind !== '@' || !trigger.query.includes('/')) { + return false + } + + // Trailing slash means we're listing a folder's children: drop that + // folder. Otherwise a partial segment is typed — drop just that. + const trimmed = trigger.query.replace(/\/$/, '') + const parent = trimmed.slice(0, trimmed.lastIndexOf('/') + 1) + + const current = composerPlainText(editor) + const prefix = current.slice(0, Math.max(0, current.length - trigger.tokenLength)) + + renderComposerContents(editor, `${prefix}@${parent}`) + placeCaretEnd(editor) + draftRef.current = composerPlainText(editor) + setComposerText(draftRef.current) + window.setTimeout(refreshTrigger, 0) + + return true + } + return { argStageEmpty, + ascendTriggerPath, closeTrigger, commitTypedSlashDirective, + moveTriggerActive, refreshTrigger, replaceTriggerWithChip, setTriggerActive, + slashFreeTextArgStage, trigger, triggerActive, + triggerActiveExplicit, triggerItems, triggerKeyConsumedRef, triggerLoading diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-undo.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-undo.test.tsx new file mode 100644 index 000000000000..bbffc396ecb6 --- /dev/null +++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-undo.test.tsx @@ -0,0 +1,193 @@ +import { render } from '@testing-library/react' +import { createRef, type RefObject } from 'react' +import { describe, expect, it, vi } from 'vitest' + +import { useComposerUndo } from './use-composer-undo' + +/** Mount the hook against a real contentEditable, exposing its API. */ +function mountUndo(editorRef: RefObject, onSync: () => string) { + const api: { current: ReturnType | null } = { current: null } + + const Harness = () => { + // Assigned during render on purpose: the tests drive the API imperatively + // right after mount, and this is a harness, not app state. + api.current = useComposerUndo({ editorRef, syncDraftFromEditor: onSync }) + + return null + } + + const view = render() + + return { api, view } +} + +function makeEditor(text: string) { + const editor = document.createElement('div') + editor.contentEditable = 'true' + // jsdom only focuses a contentEditable div when it's explicitly focusable; + // the real editor is reachable via the composer's focus bus. + editor.tabIndex = 0 + editor.append(document.createTextNode(text)) + document.body.append(editor) + + const ref = createRef() as RefObject + ref.current = editor + + return { editor, ref } +} + +const caretAtEnd = (editor: HTMLElement) => { + const range = document.createRange() + const selection = window.getSelection()! + range.selectNodeContents(editor) + range.collapse(false) + selection.removeAllRanges() + selection.addRange(range) +} + +describe('useComposerUndo', () => { + it('restores the pre-edit text, which is what a paste destroyed', () => { + const { editor, ref } = makeEditor('before') + caretAtEnd(editor) + + const { api, view } = mountUndo(ref, () => editor.textContent || '') + + // Bank, then simulate the Range-based paste that Chromium never records. + api.current!.recordUndoPoint() + editor.append(document.createTextNode(' PASTED')) + expect(editor.textContent).toBe('before PASTED') + + api.current!.undo() + expect(editor.textContent).toBe('before') + + api.current!.redo() + expect(editor.textContent).toBe('before PASTED') + + view.unmount() + editor.remove() + }) + + it('withUndoPoint banks only when the edit actually ran', () => { + const { editor, ref } = makeEditor('text') + caretAtEnd(editor) + + const { api, view } = mountUndo(ref, () => editor.textContent || '') + + // A guard that declines must not consume an undo slot. + expect(api.current!.withUndoPoint(() => false)).toBe(false) + expect(api.current!.undo()).toBe(false) + + expect( + api.current!.withUndoPoint(() => { + editor.append(document.createTextNode('!')) + + return true + }) + ).toBe(true) + + api.current!.undo() + expect(editor.textContent).toBe('text') + + view.unmount() + editor.remove() + }) + + it('claims a native historyUndo aimed at the focused editor', () => { + const { editor, ref } = makeEditor('kept') + editor.focus() + caretAtEnd(editor) + + const { api, view } = mountUndo(ref, () => editor.textContent || '') + + api.current!.recordUndoPoint() + editor.append(document.createTextNode(' extra')) + + // What Electron's Edit menu `{ role: 'undo' }` produces. + const event = new InputEvent('beforeinput', { bubbles: true, cancelable: true, inputType: 'historyUndo' }) + editor.dispatchEvent(event) + + expect(event.defaultPrevented).toBe(true) + expect(editor.textContent).toBe('kept') + + view.unmount() + editor.remove() + }) + + it('ignores a historyUndo while another editor holds focus', () => { + const { editor, ref } = makeEditor('mine') + const { editor: other } = makeEditor('theirs') + + other.focus() + + const { api, view } = mountUndo(ref, () => editor.textContent || '') + + api.current!.recordUndoPoint() + editor.append(document.createTextNode(' changed')) + + const event = new InputEvent('beforeinput', { bubbles: true, cancelable: true, inputType: 'historyUndo' }) + other.dispatchEvent(event) + + // Not ours to claim — the other surface keeps its native behavior. + expect(event.defaultPrevented).toBe(false) + expect(editor.textContent).toBe('mine changed') + + view.unmount() + editor.remove() + other.remove() + }) + + it('keeps two mounted composers independent', () => { + const { editor: main, ref: mainRef } = makeEditor('main') + const { editor: edit, ref: editRef } = makeEditor('edit') + + const mainUndo = mountUndo(mainRef, () => main.textContent || '') + const editUndo = mountUndo(editRef, () => edit.textContent || '') + + mainUndo.api.current!.recordUndoPoint() + main.append(document.createTextNode(' typed')) + + // Undoing in the edit composer must not touch the main composer's text. + editUndo.api.current!.undo() + expect(main.textContent).toBe('main typed') + + mainUndo.api.current!.undo() + expect(main.textContent).toBe('main') + expect(edit.textContent).toBe('edit') + + mainUndo.view.unmount() + editUndo.view.unmount() + main.remove() + edit.remove() + }) + + it('reset drops history so undo cannot cross a draft swap', () => { + const { editor, ref } = makeEditor('session A') + caretAtEnd(editor) + + const { api, view } = mountUndo(ref, () => editor.textContent || '') + + api.current!.recordUndoPoint() + editor.append(document.createTextNode(' edited')) + api.current!.resetUndoHistory() + + expect(api.current!.undo()).toBe(false) + expect(editor.textContent).toBe('session A edited') + + view.unmount() + editor.remove() + }) + + it('is inert when the editor ref is empty', () => { + const ref = createRef() as RefObject + const sync = vi.fn(() => '') + + const { api, view } = mountUndo(ref, sync) + + api.current!.recordUndoPoint() + + expect(api.current!.undo()).toBe(false) + expect(sync).not.toHaveBeenCalled() + + view.unmount() + }) +}) diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-undo.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-undo.ts new file mode 100644 index 000000000000..72f891f6dac0 --- /dev/null +++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-undo.ts @@ -0,0 +1,119 @@ +import { type RefObject, useCallback, useEffect, useMemo } from 'react' + +import { caretOffsetInEditor, composerPlainText, placeCaretAtOffset, renderComposerContents } from '../rich-editor' +import { type ComposerSnapshot, createComposerUndoHistory } from '../undo-history' + +interface UseComposerUndoArgs { + editorRef: RefObject + /** Push a restored snapshot back into draftRef + composer state. */ + syncDraftFromEditor: () => string +} + +/** + * Undo/redo for the rich composer. + * + * The editor mutates its DOM through `Range` to dodge Chromium's O(n²) editing + * pipeline (#45812), which also dodges Chromium's undo stack — so a paste was + * invisible to ⌘Z and the keystroke undid whatever edit came before it instead. + * We own the stack outright rather than half of it: every edit path records the + * pre-edit state here, and the editor claims ⌘Z / ⌘⇧Z itself. + */ +export function useComposerUndo({ editorRef, syncDraftFromEditor }: UseComposerUndoArgs) { + const history = useMemo(() => createComposerUndoHistory(), []) + + const snapshot = useCallback((): ComposerSnapshot => { + const editor = editorRef.current + + if (!editor) { + return { caret: 0, text: '' } + } + + return { caret: caretOffsetInEditor(editor), text: composerPlainText(editor) } + }, [editorRef]) + + /** Bank the current state before mutating the editor. `coalesce` marks a + * keystroke, so a run of typing collapses into one undo step. */ + const recordUndoPoint = useCallback( + (options?: { coalesce?: boolean }) => { + if (editorRef.current) { + history.record(snapshot(), options) + } + }, + [editorRef, history, snapshot] + ) + + const applySnapshot = useCallback( + (next: ComposerSnapshot | null) => { + const editor = editorRef.current + + if (!next || !editor) { + return false + } + + renderComposerContents(editor, next.text) + placeCaretAtOffset(editor, next.caret) + syncDraftFromEditor() + + return true + }, + [editorRef, syncDraftFromEditor] + ) + + /** Run a conditional edit, banking its pre-edit state only if it actually + * ran. The snapshot has to be taken first (the edit destroys the state we'd + * be saving), but recording unconditionally would clear the redo stack on + * every Backspace that falls through to the native path. */ + const withUndoPoint = useCallback( + (edit: () => boolean) => { + const before = snapshot() + const ran = edit() + + if (ran) { + history.record(before) + } + + return ran + }, + [history, snapshot] + ) + + const undo = useCallback(() => applySnapshot(history.undo(snapshot())), [applySnapshot, history, snapshot]) + const redo = useCallback(() => applySnapshot(history.redo(snapshot())), [applySnapshot, history, snapshot]) + + // A session/draft swap makes prior history meaningless — undoing into another + // conversation's text is worse than having no history at all. + const resetUndoHistory = useCallback(() => history.reset(), [history]) + + // Electron's Edit menu ships `{ role: 'undo' }`, whose accelerator the macOS + // menu bar consumes before the web contents sees the keystroke (the same + // hazard main.ts documents for ⌘W). It fires the native editing command, + // which knows nothing about our stack. Claim it at the document level while + // the composer holds focus, so the menu item and the keystroke agree. + useEffect(() => { + const onBeforeInput = (event: Event) => { + const inputType = (event as InputEvent).inputType + + if (inputType !== 'historyUndo' && inputType !== 'historyRedo') { + return + } + + if (document.activeElement !== editorRef.current) { + return + } + + event.preventDefault() + + if (inputType === 'historyUndo') { + undo() + } else { + redo() + } + } + + document.addEventListener('beforeinput', onBeforeInput, true) + + return () => document.removeEventListener('beforeinput', onBeforeInput, true) + }, [editorRef, redo, undo]) + + return { recordUndoPoint, redo, resetUndoHistory, undo, withUndoPoint } +} diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts index 5ce92171d3f1..49e0ba5ce7fe 100644 --- a/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts +++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts @@ -1,15 +1,19 @@ +import { useStore } from '@nanostores/react' import { useCallback, useEffect, useRef, useState } from 'react' import { useI18n } from '@/i18n' -import { chatMessageText } from '@/lib/chat-messages' +import { chatMessageText, collectUnspokenTurnSpeech } from '@/lib/chat-messages' import { triggerHaptic } from '@/lib/haptics' +import { $voiceConversationStartRequest, takeVoiceConversationStart } from '@/store/composer' import { resetBrowseState } from '@/store/composer-input-history' -import { notifyError } from '@/store/notifications' -import { $messages } from '@/store/session' -import { $autoSpeakReplies, setAutoSpeakReplies } from '@/store/voice-prefs' +import { $gateway } from '@/store/gateway' +import { notify, notifyError } from '@/store/notifications' +import { $autoSpeakReplies, $voiceStopPhrase, setAutoSpeakReplies } from '@/store/voice-prefs' +import { resumeWakeAfterVoice } from '@/store/wake-word' import type { ComposerTarget } from '../focus' import { onComposerVoiceToggleRequest } from '../focus' +import { useComposerScope } from '../scope' import type { ChatBarProps } from '../types' import { useAutoSpeakReplies } from './use-auto-speak-replies' @@ -23,6 +27,9 @@ interface UseComposerVoiceArgs { focusInput: () => void insertText: (text: string) => void maxRecordingSeconds: number + /** Interrupt the in-flight agent turn (Stop-button seam) — fired when the + * user speaks over the model while it is still generating. */ + onInterrupt?: () => Promise | void onSubmit: ChatBarProps['onSubmit'] onTranscribeAudio: ChatBarProps['onTranscribeAudio'] sessionId: string | null | undefined @@ -44,14 +51,18 @@ export function useComposerVoice({ focusInput, insertText, maxRecordingSeconds, + onInterrupt, onSubmit, onTranscribeAudio, sessionId, target }: UseComposerVoiceArgs) { const { t } = useI18n() + // A tile's composer speaks ITS transcript, not the primary chat's. + const { $messages } = useComposerScope() const [voiceConversationActive, setVoiceConversationActive] = useState(false) const lastSpokenIdRef = useRef(null) + const voiceStartRequest = useStore($voiceConversationStartRequest) const { dictate, voiceActivityState, voiceStatus } = useVoiceRecorder({ focusInput, @@ -60,6 +71,7 @@ export function useComposerVoice({ onTranscribeAudio }) + /** Auto-speak selector: the latest unspoken reply only — a backlog collapses to the newest. */ const pendingResponse = () => { const messages = $messages.get() const last = messages.findLast(m => m.role === 'assistant' && !m.hidden) @@ -81,6 +93,13 @@ export function useComposerVoice({ } } + /** + * Voice-conversation selector: every unspoken assistant bubble of the turn, + * in order — narration interims AND the final answer, not just whichever + * bubble happens to be last. See `collectUnspokenTurnSpeech`. + */ + const pendingTurnResponse = () => collectUnspokenTurnSpeech($messages.get(), lastSpokenIdRef.current) + const consumePendingResponse = () => { const messages = $messages.get() const last = messages.findLast(m => m.role === 'assistant' && !m.hidden) @@ -101,14 +120,34 @@ export function useComposerVoice({ await onSubmit(text) } + const wakePausedRef = useRef(false) + // Resolves once the in-flight wake.pause round-trip completes (mic released by + // the wake listener). The conversation awaits this before opening its own mic + // so the two never contend for the device — on Windows especially, opening the + // capture device while the wake listener still holds it makes getUserMedia + // fail and the conversation never starts listening. + const wakePauseBarrierRef = useRef | null>(null) + const conversation = useVoiceConversation({ busy, consumePendingResponse, enabled: voiceConversationActive, onFatalError: () => setVoiceConversationActive(false), + // Speaking over the model mid-generation interrupts the in-flight turn — + // the same seam as the Stop button — so the interjection becomes the next + // turn instead of waiting behind a reply the user already rejected. + onInterrupt, + // A spoken stop command ("stop", "never mind", "goodbye", …) ends the + // hands-free conversation. Flipping the flag is the authoritative off + // switch — the enabled=false prop + effect below drive conversation.end() + // teardown (mic close, wake re-arm). + onStopWord: () => setVoiceConversationActive(false), onSubmit: submitVoiceTurn, onTranscribeAudio, - pendingResponse + pendingResponse: pendingTurnResponse, + // Before the conversation opens the mic, wait for any in-flight wake.pause + // to finish releasing the capture device (see wakePauseBarrierRef). + beforeMicOpen: () => wakePauseBarrierRef.current ?? undefined }) // The `composer.voice` hotkey (Ctrl+B) toggles the conversation. Starting @@ -132,6 +171,73 @@ export function useComposerVoice({ [target, toggleVoiceConversation] ) + useEffect(() => { + if (target === 'main' && !disabled && takeVoiceConversationStart(voiceStartRequest) && !voiceConversationActive) { + setVoiceConversationActive(true) + } + }, [disabled, target, voiceConversationActive, voiceStartRequest]) + + const resumeWakeIfPaused = useCallback(() => { + if (!wakePausedRef.current) { + return + } + + wakePausedRef.current = false + wakePauseBarrierRef.current = null + // Reconcile, don't just resume: the wake word is a persistent setting, so + // ending a voice chat must re-arm the listener whenever config says + // enabled — including when the raw resume loses the mic-release race. + void resumeWakeAfterVoice() + }, []) + + // The ref is a request token (did WE issue wake.pause?), not an atom mirror — + // it guards resumeWakeIfPaused from resuming a detector another surface owns. + const pauseWakeForVoice = useCallback(() => { + wakePausedRef.current = true + + const barrier = (async () => { + try { + await $gateway.get()?.request('wake.pause', {}) + } catch { + // No wake listener / older backend — nothing held the mic. + } + })() + + wakePauseBarrierRef.current = barrier + + return barrier + }, []) + + useEffect(() => { + if (voiceConversationActive) { + pauseWakeForVoice() + } else { + resumeWakeIfPaused() + } + }, [pauseWakeForVoice, resumeWakeIfPaused, voiceConversationActive]) + + // 'Say "stop" to end the voice chat.' notice when the conversation starts. + // Phrase comes from voice.stop_phrases (first entry) so a custom phrase + // renders correctly; a null phrase (stop_phrases: []) shows no notice. + useEffect(() => { + if (!voiceConversationActive) { + return + } + + const phrase = $voiceStopPhrase.get() + + if (phrase) { + notify({ + id: 'voice-stop-hint', + kind: 'info', + icon: 'mic', + message: t.notifications.voice.sayStopToEnd(phrase) + }) + } + }, [t, voiceConversationActive]) + + useEffect(() => resumeWakeIfPaused, [resumeWakeIfPaused]) + // Explicit start/end for the on-screen conversation controls (the hotkey uses // the gated toggle above). const startConversation = useCallback(() => setVoiceConversationActive(true), []) diff --git a/apps/desktop/src/app/chat/composer/hooks/use-live-completion-adapter.ts b/apps/desktop/src/app/chat/composer/hooks/use-live-completion-adapter.ts index 6da699b602a1..d35c78ea7b3f 100644 --- a/apps/desktop/src/app/chat/composer/hooks/use-live-completion-adapter.ts +++ b/apps/desktop/src/app/chat/composer/hooks/use-live-completion-adapter.ts @@ -25,9 +25,18 @@ export function useLiveCompletionAdapter(options: { enabled: boolean debounceMs?: number fetcher: (query: string) => Promise + /** True when `fetcher` will answer this query from cache. Such a query skips + * both the debounce and the loading state — the debounce exists to avoid a + * request per keystroke, and a spinner over an answer we already hold reads + * as latency the user isn't actually paying. */ + isCached?: (query: string) => boolean + /** Bump to declare the held answer stale. Without it a popover left open on + * an unchanged query would keep serving what it fetched before the source + * changed, because the adapter de-dupes on the query alone. */ + epoch?: number toItem: (entry: CompletionEntry, index: number) => Unstable_TriggerItem }): { adapter: Unstable_TriggerAdapter; loading: boolean } { - const { enabled, debounceMs = 60, fetcher, toItem } = options + const { enabled, debounceMs = 60, epoch = 0, fetcher, isCached, toItem } = options const [state, setState] = useState<{ query: string; items: Unstable_TriggerItem[] }>({ query: EMPTY_QUERY, @@ -49,6 +58,7 @@ export function useLiveCompletionAdapter(options: { useEffect(() => () => cancelTimer(), [cancelTimer]) + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) useEffect(() => { if (enabled) { return @@ -61,6 +71,16 @@ export function useLiveCompletionAdapter(options: { setState({ query: EMPTY_QUERY, items: [] }) }, [cancelTimer, enabled]) + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) + useEffect(() => { + // Invalidate by forgetting which query the held items answer, so the next + // search() re-fetches. The items themselves stay until the new answer + // lands — an open popover must not blink empty on a background refresh. + // On mount this is already the state, so the first run is a no-op. + pendingQueryRef.current = null + setState(current => (current.query === EMPTY_QUERY ? current : { ...current, query: EMPTY_QUERY })) + }, [epoch]) + const scheduleFetch = useCallback( (query: string) => { if (!enabled) { @@ -74,9 +94,13 @@ export function useLiveCompletionAdapter(options: { pendingQueryRef.current = query cancelTimer() const token = ++tokenRef.current - setLoading(true) + const cached = isCached?.(query) ?? false - timerRef.current = window.setTimeout(() => { + if (!cached) { + setLoading(true) + } + + const run = () => { timerRef.current = null fetcher(query) @@ -102,9 +126,13 @@ export function useLiveCompletionAdapter(options: { setLoading(false) } }) - }, debounceMs) + } + + // A cached answer resolves in a microtask, so debouncing it would only + // add a frame of empty popover on every keystroke. + cached ? run() : (timerRef.current = window.setTimeout(run, debounceMs)) }, - [cancelTimer, debounceMs, enabled, fetcher, toItem] + [cancelTimer, debounceMs, enabled, fetcher, isCached, toItem] ) const adapter = useMemo( diff --git a/apps/desktop/src/app/chat/composer/hooks/use-micro-actions.ts b/apps/desktop/src/app/chat/composer/hooks/use-micro-actions.ts new file mode 100644 index 000000000000..a8da94f04116 --- /dev/null +++ b/apps/desktop/src/app/chat/composer/hooks/use-micro-actions.ts @@ -0,0 +1,47 @@ +import { useEffect } from 'react' + +import { useSessionSlice } from '@/lib/use-session-slice' +import { setComposerActions } from '@/store/composer-actions' +import { $todosBySession } from '@/store/todos' + +import { type ComposerMicroActionContext, useComposerMicroActionProviders } from '../contrib' + +/** + * Resolve every registered micro-action provider for this session and publish + * the result to `$composerActionsBySession`, which the pill strip renders. + * + * Core registers nothing, so the strip stays empty until something contributes + * to `composer.microActions`. Providers are pure functions of the session + * context and the set is recomputed rather than mutated, so there are no + * ordering games between registrars and a provider that stops returning a + * badge withdraws it. One that throws is skipped, so a broken plugin loses + * only its own badge. + */ +export function useComposerMicroActions(sessionId: null | string, busy: boolean) { + const todos = useSessionSlice($todosBySession, sessionId) + const providers = useComposerMicroActionProviders() + + useEffect(() => { + if (!sessionId) { + return + } + + const ctx: ComposerMicroActionContext = { busy, sessionId, todos } + + setComposerActions( + sessionId, + providers.flatMap(provider => { + try { + return provider.resolve(ctx) ?? [] + } catch { + return [] + } + }) + ) + }, [busy, providers, sessionId, todos]) + + // Withdraw on unmount / session switch ONLY. Clearing in the resolve effect's + // cleanup would publish an empty set before every republish — two store + // writes and two stack re-renders for what is usually a no-op. + useEffect(() => (sessionId ? () => setComposerActions(sessionId, []) : undefined), [sessionId]) +} diff --git a/apps/desktop/src/app/chat/composer/hooks/use-popout-drag.ts b/apps/desktop/src/app/chat/composer/hooks/use-popout-drag.ts index 0b71507bfd1a..4af646040436 100644 --- a/apps/desktop/src/app/chat/composer/hooks/use-popout-drag.ts +++ b/apps/desktop/src/app/chat/composer/hooks/use-popout-drag.ts @@ -3,6 +3,7 @@ import { type PointerEvent as ReactPointerEvent, type RefObject, useCallback, us import { POPOUT_ESTIMATED_HEIGHT, POPOUT_WIDTH_REM, + type PopoutBounds, type PopoutPosition, type PopoutSize, readPopoutBounds, @@ -35,6 +36,8 @@ interface PressState { interface ComposerPopoutGesturesOptions { composerRef: RefObject + /** Layout zone this composer belongs to — the scope its float is stored under. */ + groupId: string onDock: () => void onPopOut: () => void poppedOut: boolean @@ -46,7 +49,15 @@ function gestureTargetOk(target: EventTarget | null) { return false } - return !target.closest('button, a, input, textarea, select, [role="menuitem"], [data-radix-popper-content-wrapper]') + // `composer-no-drag`: chrome that lives inside the composer root but isn't + // part of the draggable frame — the floating pill strips. The pills are + // `button`s and already excluded, but the strip's own box (the gaps between + // pills) isn't, so without this a press landing between two badges still + // drags. The strips are `w-fit`, so this costs the grab band only the width + // of the badges themselves. + return !target.closest( + 'button, a, input, textarea, select, [role="menuitem"], [data-radix-popper-content-wrapper], [data-slot="composer-no-drag"]' + ) } /** Floating composer's 5px outer frame — grab here to drag without long-press. */ @@ -67,10 +78,17 @@ function isFloatDragPlatform(target: EventTarget | null) { } /** 0 (far) → 1 (inside the dock zone). Drives both the dock glow and the - * release-to-dock test (which fires at proximity 1). */ -function dockProximityOf(rect: DOMRect) { - const horizontalDist = Math.abs(rect.left + rect.width / 2 - window.innerWidth / 2) - const verticalGap = window.innerHeight - DOCK_ZONE_BOTTOM_PX - rect.bottom + * release-to-dock test (which fires at proximity 1). + * + * Measured against THIS surface's area, not the window: the dock target is the + * docked composer, which sits at the bottom-center of its own chat surface. In + * a split (or any layout where the chat isn't the full window) the viewport's + * bottom-center is somewhere else entirely, so dragging onto the real dock + * never registered. */ +function dockProximityOf(rect: DOMRect, area?: PopoutBounds) { + const a = area ?? { bottom: window.innerHeight, left: 0, right: window.innerWidth, top: 0 } + const horizontalDist = Math.abs(rect.left + rect.width / 2 - (a.left + a.right) / 2) + const verticalGap = a.bottom - DOCK_ZONE_BOTTOM_PX - rect.bottom const v = verticalGap <= 0 ? 1 : Math.max(0, 1 - verticalGap / DOCK_VERTICAL_FALLOFF_PX) @@ -109,6 +127,7 @@ function popoutPositionUnderPointer( */ export function useComposerPopoutGestures({ composerRef, + groupId, onDock, onPopOut, poppedOut, @@ -142,7 +161,12 @@ export function useComposerPopoutGestures({ const beginFloatDrag = useCallback( (state: PressState, clientX: number, clientY: number, next: PopoutPosition, size?: PopoutSize) => { clearTimer() - const clamped = setComposerPopoutPosition(next, { area: readPopoutBounds(composerRef.current), size }) + + const clamped = setComposerPopoutPosition(groupId, next, { + area: readPopoutBounds(composerRef.current), + size + }) + liveRef.current = clamped state.mode = 'float' @@ -154,7 +178,7 @@ export function useComposerPopoutGestures({ setDragging(true) }, - [clearTimer, composerRef] + [clearTimer, composerRef, groupId] ) const peelOffFromDock = useCallback( @@ -231,6 +255,7 @@ export function useComposerPopoutGestures({ [clearTimer, poppedOut] ) + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) useEffect(() => { // Coalesce drag updates to one per frame — pointermove can fire several times // between paints on high-Hz mice, and each update re-renders + clamps. @@ -254,17 +279,19 @@ export function useComposerPopoutGestures({ const composer = composerRef.current const size = composer ? { height: composer.offsetHeight, width: composer.offsetWidth } : undefined + const area = readPopoutBounds(composer) liveRef.current = setComposerPopoutPosition( + groupId, { bottom: state.startBottom - (pending.y - state.startY), right: state.startRight - (pending.x - state.startX) }, - { area: readPopoutBounds(composer), size } + { area, size } ) if (composer) { - setDockProximity(dockProximityOf(composer.getBoundingClientRect())) + setDockProximity(dockProximityOf(composer.getBoundingClientRect(), area)) } } @@ -316,13 +343,14 @@ export function useComposerPopoutGestures({ if (state.armed && state.mode === 'float') { const composer = composerRef.current const rect = composer?.getBoundingClientRect() + const area = readPopoutBounds(composer) - if (rect && dockProximityOf(rect) >= 1) { + if (rect && dockProximityOf(rect, area) >= 1) { onDock() } else { // Persist the resting position once, on release — never per move. const size = composer ? { height: composer.offsetHeight, width: composer.offsetWidth } : undefined - setComposerPopoutPosition(liveRef.current, { area: readPopoutBounds(composer), persist: true, size }) + setComposerPopoutPosition(groupId, liveRef.current, { area, persist: true, size }) } } @@ -339,7 +367,7 @@ export function useComposerPopoutGestures({ window.removeEventListener('pointerup', handleUp) window.removeEventListener('pointercancel', handleUp) } - }, [composerRef, onDock, peelOffFromDock, resetGesture]) + }, [composerRef, groupId, onDock, peelOffFromDock, resetGesture]) useEffect(() => clearTimer, [clearTimer]) diff --git a/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.test.tsx new file mode 100644 index 000000000000..a1e87ca53f26 --- /dev/null +++ b/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.test.tsx @@ -0,0 +1,157 @@ +import type { Unstable_TriggerItem } from '@assistant-ui/core' +import { act, cleanup, render } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' + +import type { HermesGateway } from '@/hermes' +import { queryClient } from '@/lib/query-client' +import { invalidateSlashCompletions } from '@/lib/slash-completion-cache' + +import { isSkillItem } from '../composer-utils' + +import { useSlashCompletions } from './use-slash-completions' + +const CATALOG = { + categories: [{ name: 'Session', pairs: [['/new', 'Start a new session']] }], + pairs: [ + ['/new', 'Start a new session'], + ['/work', 'Kick off a task in a fresh worktree'] + ] +} + +// A catalog shaped like a real install: a couple of skills the user lives in, +// a bundled one they have never opened, and one of their own they haven't +// either. +const RANKED_CATALOG = { + categories: [{ name: 'Session', pairs: [['/new', 'Start a new session']] }], + pairs: [ + ['/new', 'Start a new session'], + ['/docx', 'Edit Word documents'], + ['/research', 'Look it up before answering'], + ['/research-paper-writing', 'Write an academic paper'], + ['/work', 'Kick off a task in a fresh worktree'] + ], + skills: { + '/docx': { usage: 0, origin: 'local' }, + '/research': { usage: 60, origin: 'local' }, + '/research-paper-writing': { usage: 0, origin: 'bundled' }, + '/work': { usage: 172, origin: 'local' } + } +} + +const commandsOf = (items: readonly Unstable_TriggerItem[]) => + items.map(item => (item.metadata as { command?: string })?.command) + +function harness(gateway: HermesGateway) { + const api: { search?: (query: string) => readonly Unstable_TriggerItem[] } = {} + + function Probe() { + const { adapter } = useSlashCompletions({ gateway }) + api.search = adapter.search + + return null + } + + render() + + return api as { search: (query: string) => readonly Unstable_TriggerItem[] } +} + +/** Drive the adapter until its async fetch has settled into `search`'s result. */ +async function completions(api: { search: (query: string) => readonly Unstable_TriggerItem[] }, query: string) { + await act(async () => { + api.search(query) + await Promise.resolve() + }) + + // The debounce is skipped only for cached queries; give the timer a beat. + await act(async () => { + await new Promise(resolve => setTimeout(resolve, 120)) + }) + + return api.search(query) +} + +afterEach(() => { + cleanup() + queryClient.clear() +}) + +describe('useSlashCompletions', () => { + it('serves the bare-slash catalog from cache instead of re-requesting it', async () => { + const request = vi.fn().mockResolvedValue(CATALOG) + const api = harness({ request } as unknown as HermesGateway) + + await completions(api, '') + expect(request).toHaveBeenCalledTimes(1) + + // Reopening `/` must not hit the gateway again. + queryClient.setQueryData(['unrelated'], 1) + await completions(api, '') + expect(request).toHaveBeenCalledTimes(1) + + // …until something that changes the command set invalidates it. + await act(async () => invalidateSlashCompletions()) + await completions(api, '') + expect(request).toHaveBeenCalledTimes(2) + }) + + it('offers skill commands on a bare slash, not just built-ins', async () => { + const request = vi.fn().mockResolvedValue(CATALOG) + const api = harness({ request } as unknown as HermesGateway) + + const items = await completions(api, '') + const work = items.find(item => (item.metadata as { command?: string })?.command === '/work') + + expect((work?.metadata as { group?: string })?.group).toBe('Skills') + }) + + // A `/` typed mid-message is a reference dropped into prose, so the trigger + // filters the list to skills (use-composer-trigger). A bare mid-message `/` + // resolves to the same empty query as an opening `/`, so that filter runs + // over the catalog — which listed no skill-group rows at all, leaving the + // inline popover empty. Asserted through isSkillItem, the real predicate. + it('leaves only skills for a mid-message slash', async () => { + const request = vi.fn().mockResolvedValue(CATALOG) + const api = harness({ request } as unknown as HermesGateway) + + const inline = (await completions(api, '')).filter(isSkillItem) + + expect(inline.map(item => (item.metadata as { command?: string })?.command)).toEqual(['/work']) + }) + + // An alphabetical `/` menu buries the skills someone runs daily under the + // ones that shipped with Hermes and were never opened. + it('orders skills by use and hides never-used built-ins on a bare slash', async () => { + const request = vi.fn().mockResolvedValue(RANKED_CATALOG) + const api = harness({ request } as unknown as HermesGateway) + + const skills = commandsOf((await completions(api, '')).filter(isSkillItem)) + + expect(skills).toEqual(['/work', '/research', '/docx']) + }) + + // Typing is a search, and a search that hides a match is broken — the + // never-used built-in still shows, just below the one she actually uses. + it('ranks a typed query by use without hiding anything', async () => { + const request = vi.fn().mockImplementation((method: string) => + Promise.resolve( + method === 'commands.catalog' + ? RANKED_CATALOG + : { + items: [ + { text: '/research-paper-writing', display: '/research-paper-writing', meta: 'Write a paper' }, + { text: '/research', display: '/research', meta: 'Look it up' } + ] + } + ) + ) + + const api = harness({ request } as unknown as HermesGateway) + + // Warm the catalog first: the popover always opens on a bare `/` before a + // query is typed, which is where the usage map comes from. + await completions(api, '') + + expect(commandsOf(await completions(api, 'research'))).toEqual(['/research', '/research-paper-writing']) + }) +}) diff --git a/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.ts b/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.ts index bf6e5006beae..32f0038fe2e5 100644 --- a/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.ts +++ b/apps/desktop/src/app/chat/composer/hooks/use-slash-completions.ts @@ -1,4 +1,5 @@ import type { Unstable_TriggerAdapter, Unstable_TriggerItem } from '@assistant-ui/core' +import { useStore } from '@nanostores/react' import { useCallback } from 'react' import type { HermesGateway } from '@/hermes' @@ -10,8 +11,15 @@ import { type DesktopThemeCommandOption, filterDesktopCommandsCatalog, isDesktopSlashExtensionCommand, - isDesktopSlashSuggestion + isDesktopSlashSuggestion, + rankSkillCommands } from '@/lib/desktop-slash-commands' +import { + $slashCompletionsEpoch, + cachedSlashCompletion, + hasCachedSlashCompletion, + peekCachedSlashCompletion +} from '@/lib/slash-completion-cache' import { normalize } from '@/lib/text' import { $sessions } from '@/store/session' @@ -63,6 +71,7 @@ export function useSlashCompletions(options: { } { const { gateway, skinThemes, activeSkin } = options const enabled = Boolean(gateway) + const epoch = useStore($slashCompletionsEpoch) const fetcher = useCallback( async (query: string): Promise => { @@ -133,14 +142,16 @@ export function useSlashCompletions(options: { try { if (!query) { - const catalog = filterDesktopCommandsCatalog(await gateway.request('commands.catalog')) + const catalog = filterDesktopCommandsCatalog( + await cachedSlashCompletion('catalog', () => gateway.request('commands.catalog')) + ) // Prefer the categorized layout so the popover renders section headers // (Session, Tools & Skills, ...). Fall back to the flat list when the // backend didn't categorize. const sections = catalog.categories?.length ? catalog.categories : [{ name: '', pairs: catalog.pairs ?? [] }] - const items = sections.flatMap(section => + const items = sections.flatMap(section => section.pairs.map(([command, meta]) => ({ text: command, display: command, @@ -149,12 +160,32 @@ export function useSlashCompletions(options: { })) ) + // Skill commands reach us only through the flat `pairs` list — the + // backend categorizes registry commands but appends skills + // uncategorized, so the categorized layout alone drops every skill + // from the bare `/` list even though typing `/wo` offers them. + // Re-add the leftovers under one Skills header (which also gives them + // the skill pill accent and makes them offerable mid-message). + const categorized = new Set(items.map(item => item.text.toLowerCase())) + const skillRows: CompletionEntry[] = [] + + for (const [command, meta] of catalog.pairs ?? []) { + if (!categorized.has(command.toLowerCase()) && isDesktopSlashExtensionCommand(command)) { + skillRows.push({ text: command, display: command, group: 'Skills', meta }) + } + } + + // Browsing, not searching: rank the skills the user actually reaches + // for to the top and drop never-used built-ins entirely. Typing a + // query takes the other branch, where nothing is hidden. + items.push(...rankSkillCommands(skillRows, catalog.skills, { pruneUnusedBuiltins: true })) + return { items, query } } - const result = await gateway.request<{ items?: CompletionEntry[]; replace_from?: number }>('complete.slash', { - text - }) + const result = await cachedSlashCompletion(`slash:${text.toLowerCase()}`, () => + gateway.request<{ items?: CompletionEntry[]; replace_from?: number }>('complete.slash', { text }) + ) // Arg-completion items (replace_from > 1) carry just the arg stub — // e.g. complete.slash returns `{text: "alice"}` for `/personality alic` @@ -191,9 +222,27 @@ export function useSlashCompletions(options: { // Skills (stable within a group, preserving backend relevance order). const groupOrder = ['Commands', 'Skills', 'Options'] - const items = isArgCompletion - ? decorated - : [...decorated].sort((a, b) => groupOrder.indexOf(a.group) - groupOrder.indexOf(b.group)) + if (isArgCompletion) { + return { items: decorated, query } + } + + // Rank the matched skills by use — `/re` should lead with the /research + // the user lives in, not the /research-paper-writing they've never + // opened. Nothing is pruned here: a typed query is a search, and a + // search that hides a match is broken. Usage rides along on the catalog + // response, which the popover has already fetched by the time anyone + // types; if it somehow hasn't, order falls back to the backend's. + const catalogSkills = peekCachedSlashCompletion('catalog')?.skills + + const ranked = [ + ...decorated.filter(item => item.group !== 'Skills'), + ...rankSkillCommands( + decorated.filter(item => item.group === 'Skills'), + catalogSkills + ) + ] + + const items = [...ranked].sort((a, b) => groupOrder.indexOf(a.group) - groupOrder.indexOf(b.group)) return { items, query } } catch { @@ -231,5 +280,21 @@ export function useSlashCompletions(options: { } }, []) - return useLiveCompletionAdapter({ enabled, fetcher, toItem }) + // Mirrors the fetcher's branching: the `/skin` and `/resume` arg stages are + // answered from client-side state, so they never wait on the network; every + // other query is served from the completion cache when it's still warm. + const isCached = useCallback( + (query: string) => { + const text = `/${query}` + + if ((skinThemes && /^\/skin\s+/is.test(text)) || /^\/(?:resume|sessions|switch)\s+/is.test(text)) { + return true + } + + return hasCachedSlashCompletion(query ? `slash:${text.toLowerCase()}` : 'catalog') + }, + [skinThemes] + ) + + return useLiveCompletionAdapter({ enabled, epoch, fetcher, isCached, toItem }) } diff --git a/apps/desktop/src/app/chat/composer/hooks/use-status-presence.ts b/apps/desktop/src/app/chat/composer/hooks/use-status-presence.ts index c6b9af53b737..b4655ffd50cb 100644 --- a/apps/desktop/src/app/chat/composer/hooks/use-status-presence.ts +++ b/apps/desktop/src/app/chat/composer/hooks/use-status-presence.ts @@ -1,26 +1,37 @@ import { useSyncExternalStore } from 'react' +import { $composerActionsBySession } from '@/store/composer-actions' import { $statusItemsBySession } from '@/store/composer-status' import { $previewStatusBySession } from '@/store/preview-status' +/** Structural view of the three per-session feeds — they hold different item + * types, and all this hook needs from each is "does this key have rows". */ +interface PresenceFeed { + get(): Record + listen(listener: () => void): () => void +} + +const FEEDS: PresenceFeed[] = [$statusItemsBySession, $composerActionsBySession, $previewStatusBySession] + const subscribe = (onChange: () => void) => { - const offItems = $statusItemsBySession.listen(onChange) - const offPreviews = $previewStatusBySession.listen(onChange) + const offs = FEEDS.map(feed => feed.listen(onChange)) return () => { - offItems() - offPreviews() + for (const off of offs) { + off() + } } } /** - * Whether a session has any status items or previews, as a coarse *edge*: the - * boolean only flips when the stack appears/disappears. ChatBar uses it to - * toggle a styling data-attr — subscribing to the whole `$statusItemsBySession` - * (a `computed` that rebuilds the entire map) / `$previewStatusBySession` maps - * re-rendered the ~1.4k ChatBar on every per-item mutation (a subagent tick, a - * 5s background poll) and on churn in OTHER sessions. The boolean snapshot bails - * out of all of that, re-rendering only on the actual show/hide transition. + * Whether a session has any status items, micro actions, or previews, as a + * coarse *edge*: the boolean only flips when the stack appears/disappears. + * ChatBar uses it to toggle a styling data-attr — subscribing to the whole + * `$statusItemsBySession` (a `computed` that rebuilds the entire map) / + * `$previewStatusBySession` maps re-rendered the ~1.4k ChatBar on every + * per-item mutation (a subagent tick, a 5s background poll) and on churn in + * OTHER sessions. The boolean snapshot bails out of all of that, re-rendering + * only on the actual show/hide transition. */ export function useSessionStatusPresence(sessionId: string | null): boolean { return useSyncExternalStore(subscribe, () => { @@ -28,9 +39,6 @@ export function useSessionStatusPresence(sessionId: string | null): boolean { return false } - return ( - ($statusItemsBySession.get()[sessionId]?.length ?? 0) > 0 || - ($previewStatusBySession.get()[sessionId]?.length ?? 0) > 0 - ) + return FEEDS.some(feed => (feed.get()[sessionId]?.length ?? 0) > 0) }) } diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.test.tsx new file mode 100644 index 000000000000..1e43ef8b1863 --- /dev/null +++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.test.tsx @@ -0,0 +1,266 @@ +import { act, cleanup, renderHook, waitFor } from '@testing-library/react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import type { BargeMonitorCallbacks } from '@/lib/voice-barge-in' + +import type { MicRecording } from './use-mic-recorder' +import { useVoiceConversation } from './use-voice-conversation' + +// The full-duplex contract: the barge monitor is live across the WHOLE agent +// turn — generation (thinking) and playback (speaking) — so speaking over the +// model interrupts it mid-generation instead of the mic being deaf until TTS +// starts (the Windows report: interruption "never works" because the deaf +// window covered generation, and playback bleed made the old monitor's +// trigger unreachable). + +const monitorCalls: BargeMonitorCallbacks[] = [] +const stopMonitor = vi.fn() + +vi.mock('@/lib/voice-barge-in', () => ({ + monitorSpeechDuringPlayback: (callbacks: BargeMonitorCallbacks) => { + monitorCalls.push(callbacks) + + return stopMonitor + } +})) + +const markVoicePlaybackInterrupted = vi.fn() +const stopVoicePlayback = vi.fn() + +vi.mock('@/lib/voice-playback', () => ({ + markVoicePlaybackInterrupted: () => markVoicePlaybackInterrupted(), + playSpeechText: vi.fn(async () => true), + startSpeechStream: vi.fn(async () => null), + stopVoicePlayback: () => stopVoicePlayback() +})) + +vi.mock('@/lib/thinking-sound', () => ({ + startThinkingSound: vi.fn(), + stopThinkingSound: vi.fn() +})) + +const micHandle = { + cancel: vi.fn(), + start: vi.fn(async () => undefined), + stop: vi.fn<() => Promise>(async () => null) +} + +vi.mock('./use-mic-recorder', () => ({ + useMicRecorder: () => ({ handle: micHandle, level: 0, recording: false }) +})) + +vi.mock('@/i18n', () => ({ + useI18n: () => ({ + t: { + notifications: { + voice: { + configureSpeechToText: 'configure STT', + couldNotStartSession: 'could not start', + microphoneFailed: 'mic failed', + playbackFailed: 'playback failed', + transcriptionFailed: 'transcription failed', + unavailable: 'unavailable' + } + } + } + }) +})) + +vi.mock('@/store/notifications', () => ({ + notify: vi.fn(), + notifyError: vi.fn() +})) + +interface HookProps { + busy: boolean +} + +function renderConversation(overrides: { onInterrupt?: () => void; transcript?: string } = {}) { + const onInterrupt = overrides.onInterrupt ?? vi.fn() + + // Mirrors the real app: submitting a turn makes the agent busy. + const onBusyChange: { current: (busy: boolean) => void } = { current: () => undefined } + + const onSubmit = vi.fn(async () => { + onBusyChange.current(true) + }) + + const onStopWord = vi.fn() + + // First transcription is the turn that starts the conversation; subsequent + // ones are barge captures (the overridable transcript). + let transcriptions = 0 + + const onTranscribeAudio = vi.fn(async () => + transcriptions++ === 0 ? 'kick off the task' : (overrides.transcript ?? 'and another thing') + ) + + const hook = renderHook( + ({ busy }: HookProps) => + useVoiceConversation({ + busy, + consumePendingResponse: vi.fn(), + enabled: true, + onInterrupt, + onStopWord, + onSubmit, + onTranscribeAudio, + pendingResponse: () => null + }), + { initialProps: { busy: false } } + ) + + onBusyChange.current = busy => hook.rerender({ busy }) + + return { hook, onInterrupt, onStopWord, onSubmit, onTranscribeAudio } +} + +/** Drive the hook into the generation phase (turn submitted, model working). */ +async function enterThinking(hook: ReturnType['hook']) { + await act(async () => { + await hook.result.current.start() + }) + await waitFor(() => expect(hook.result.current.status).toBe('listening')) + + micHandle.stop.mockResolvedValueOnce({ + audio: new Blob(['q'], { type: 'audio/webm' }), + durationMs: 900, + heardSpeech: true + }) + + await act(async () => { + hook.result.current.stopTurn() + }) + await waitFor(() => expect(hook.result.current.status).toBe('thinking')) +} + +describe('useVoiceConversation full-duplex barge-in', () => { + beforeEach(() => { + monitorCalls.length = 0 + vi.clearAllMocks() + micHandle.start.mockResolvedValue(undefined) + micHandle.stop.mockResolvedValue(null) + }) + + afterEach(cleanup) + + it('arms the barge monitor during generation (before any reply audio exists)', async () => { + const { hook } = renderConversation() + + await act(async () => { + await hook.result.current.start() + }) + await enterThinking(hook) + + await waitFor(() => expect(hook.result.current.status).toBe('thinking')) + // busy=true + thinking → the full-duplex monitor must be live. + await waitFor(() => expect(monitorCalls.length).toBeGreaterThan(0)) + }) + + it('interrupts the in-flight turn when speech trips mid-generation', async () => { + const { hook, onInterrupt } = renderConversation() + + await act(async () => { + await hook.result.current.start() + }) + await enterThinking(hook) + await waitFor(() => expect(monitorCalls.length).toBeGreaterThan(0)) + + act(() => { + monitorCalls.at(-1)?.onSpeech() + }) + + expect(onInterrupt).toHaveBeenCalledTimes(1) + expect(markVoicePlaybackInterrupted).toHaveBeenCalled() + expect(stopVoicePlayback).toHaveBeenCalled() + }) + + it('submits the captured interruption once the interrupt settles (busy clears)', async () => { + const { hook, onSubmit } = renderConversation({ transcript: 'no, do it differently' }) + + await act(async () => { + await hook.result.current.start() + }) + await enterThinking(hook) + await waitFor(() => expect(monitorCalls.length).toBeGreaterThan(0)) + + const monitor = monitorCalls.at(-1) + + act(() => { + monitor?.onSpeech() + }) + + // Interrupt lands → the turn ends → busy flips false. + hook.rerender({ busy: false }) + + await act(async () => { + monitor?.onUtterance?.(new Blob(['x'], { type: 'audio/webm' })) + }) + + await waitFor(() => expect(onSubmit).toHaveBeenCalledWith('no, do it differently')) + }) + + it('does not interrupt when speech trips during playback (turn already done)', async () => { + const { hook, onInterrupt } = renderConversation() + + await act(async () => { + await hook.result.current.start() + }) + await enterThinking(hook) + await waitFor(() => expect(monitorCalls.length).toBeGreaterThan(0)) + + // Turn finished; playback phase. + hook.rerender({ busy: false }) + + act(() => { + monitorCalls.at(-1)?.onSpeech() + }) + + expect(onInterrupt).not.toHaveBeenCalled() + expect(stopVoicePlayback).toHaveBeenCalled() + }) + + it('a spoken stop command in the barge capture ends the conversation instead of submitting', async () => { + const { hook, onStopWord, onSubmit } = renderConversation({ transcript: 'stop' }) + + await act(async () => { + await hook.result.current.start() + }) + await enterThinking(hook) + await waitFor(() => expect(monitorCalls.length).toBeGreaterThan(0)) + + const monitor = monitorCalls.at(-1) + + act(() => { + monitor?.onSpeech() + }) + hook.rerender({ busy: false }) + + await act(async () => { + monitor?.onUtterance?.(new Blob(['s'], { type: 'audio/webm' })) + }) + + await waitFor(() => expect(onStopWord).toHaveBeenCalledTimes(1)) + // Only the kickoff turn was submitted — the "stop" capture never was. + expect(onSubmit).toHaveBeenCalledTimes(1) + expect(onSubmit).not.toHaveBeenCalledWith('stop') + }) + + it('re-arms a single monitor per turn (idempotent ensure)', async () => { + const { hook } = renderConversation() + + await act(async () => { + await hook.result.current.start() + }) + await enterThinking(hook) + await waitFor(() => expect(monitorCalls.length).toBeGreaterThan(0)) + + const armed = monitorCalls.length + + // Effect re-runs (busy toggles, status changes) must not open more mics. + hook.rerender({ busy: true }) + hook.rerender({ busy: true }) + + expect(monitorCalls.length).toBe(armed) + }) +}) diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts index 2ec43c83c0b8..94fb912ff1c1 100644 --- a/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts +++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-conversation.ts @@ -1,6 +1,7 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { useI18n } from '@/i18n' +import { startThinkingSound, stopThinkingSound } from '@/lib/thinking-sound' import { monitorSpeechDuringPlayback } from '@/lib/voice-barge-in' import { markVoicePlaybackInterrupted, @@ -9,7 +10,9 @@ import { startSpeechStream, stopVoicePlayback } from '@/lib/voice-playback' +import { isVoiceStopCommand } from '@/lib/voice-stop-word' import { notify, notifyError } from '@/store/notifications' +import { $voicePlayback } from '@/store/voice-playback' import { useMicRecorder } from './use-mic-recorder' @@ -25,20 +28,34 @@ interface VoiceConversationOptions { busy: boolean enabled: boolean onFatalError?: () => void + /** Interrupt the in-flight agent turn (the same seam as the Stop button). + * Fired when the user speaks while the model is still generating. */ + onInterrupt?: () => Promise | void + onStopWord?: () => void onSubmit: (text: string) => Promise | void onTranscribeAudio?: (audio: Blob) => Promise pendingResponse: () => PendingVoiceResponse | null consumePendingResponse: () => void + /** Awaited right before the mic is opened. Used to let the wake-word listener + * fully release the capture device first, so the two never contend. */ + beforeMicOpen?: () => Promise | void } +/** How long a barge-triggered interrupt may take to settle before we submit + * the captured utterance anyway. */ +const INTERRUPT_SETTLE_TIMEOUT_MS = 5_000 + export function useVoiceConversation({ busy, enabled, onFatalError, + onInterrupt, + onStopWord, onSubmit, onTranscribeAudio, pendingResponse, - consumePendingResponse + consumePendingResponse, + beforeMicOpen }: VoiceConversationOptions) { const { t } = useI18n() const voiceCopy = t.notifications.voice @@ -54,24 +71,49 @@ export function useVoiceConversation({ const speechSessionRef = useRef(null) const stopBargeMonitorRef = useRef<(() => void) | null>(null) const bargeCapturePendingRef = useRef(false) + const bargedRef = useRef(false) + const speechStartSequenceRef = useRef(0) const enabledRef = useRef(enabled) const mutedRef = useRef(muted) const busyRef = useRef(busy) const statusRef = useRef('idle') const wasEnabledRef = useRef(enabled) + const onStopWordRef = useRef(onStopWord) + const onInterruptRef = useRef(onInterrupt) + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) + useEffect(() => { + onInterruptRef.current = onInterrupt + }, [onInterrupt]) + + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) + useEffect(() => { + onStopWordRef.current = onStopWord + }, [onStopWord]) + + const beforeMicOpenRef = useRef(beforeMicOpen) + + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) + useEffect(() => { + beforeMicOpenRef.current = beforeMicOpen + }, [beforeMicOpen]) + + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) useEffect(() => { enabledRef.current = enabled }, [enabled]) + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) useEffect(() => { mutedRef.current = muted }, [muted]) + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) useEffect(() => { busyRef.current = busy }, [busy]) + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) useEffect(() => { statusRef.current = status }, [status]) @@ -87,6 +129,7 @@ export function useVoiceConversation({ stopBargeMonitorRef.current?.() stopBargeMonitorRef.current = null bargeCapturePendingRef.current = false + bargedRef.current = false speechSessionRef.current = null responseIdRef.current = null spokenSourceLengthRef.current = 0 @@ -128,6 +171,18 @@ export function useVoiceConversation({ return } + // A spoken "stop" (or "never mind", "goodbye", …) ends the + // conversation instead of being submitted as a turn. Only whole- + // utterance stop commands match, so "stop the container" still goes + // through as a real request. + if (isVoiceStopCommand(transcript)) { + dropSpeechSession() + setStatus('idle') + onStopWordRef.current?.() + + return + } + awaitingSpokenResponseRef.current = true dropSpeechSession() await onSubmit(transcript) @@ -163,6 +218,20 @@ export function useVoiceConversation({ return } + // Let the wake-word listener fully release the capture device before we + // open ours — opening the mic while wake still holds it makes getUserMedia + // fail (the "clicked voice but it never starts listening" bug). + try { + await beforeMicOpenRef.current?.() + } catch { + // A pause failure shouldn't block the user's explicit start. + } + + // enabled/muted/busy or an interleaved turn may have changed while we waited. + if (!enabledRef.current || mutedRef.current || busyRef.current || statusRef.current !== 'idle') { + return + } + try { // VAD tuning mirrors `tools.voice_mode` defaults so the browser loop matches the CLI. await handle.start({ @@ -177,6 +246,12 @@ export function useVoiceConversation({ onSilence: () => void handleTurn() }) setStatus('listening') + // Clear any prior turn-timeout before arming a fresh one. Each listen + // cycle reassigns turnTimeoutRef; without clearing first, a stale 60s + // timer from an earlier cycle survives and later fires handleTurn() in + // the middle of a new listen, cutting it short (or, after enough idle + // re-listens, wedging the loop into a state it doesn't re-arm from). + clearTurnTimeout() turnTimeoutRef.current = window.setTimeout(() => void handleTurn(), 60_000) } catch (error) { notifyError(error, voiceCopy.couldNotStartSession) @@ -207,7 +282,15 @@ export function useVoiceConversation({ dropSpeechSession() - if (enabledRef.current) { + // If stopVoicePlayback() was called externally (Stop button, end), the + // voice-playback sequence has advanced past what we captured at speech + // start — don't auto-start the next sentence, the user chose to stop. + const stoppedByUser = + speechStartSequenceRef.current > 0 && $voicePlayback.get().sequence > speechStartSequenceRef.current + + speechStartSequenceRef.current = 0 + + if (enabledRef.current && !stoppedByUser) { pendingStartRef.current = true } @@ -248,6 +331,25 @@ export function useVoiceConversation({ return } + // A spoken stop command while barging means "stop everything" — the + // turn/playback was already cut at trip time; now end the conversation + // instead of submitting "stop" as a new prompt. + if (isVoiceStopCommand(transcript)) { + dropSpeechSession() + setStatus('idle') + onStopWordRef.current?.() + + return + } + + // A generation-phase barge interrupted the in-flight turn; the submit + // path refuses while `busy`, so wait for the interrupt to settle. + const deadline = Date.now() + INTERRUPT_SETTLE_TIMEOUT_MS + + while (busyRef.current && Date.now() < deadline) { + await new Promise(resolve => window.setTimeout(resolve, 100)) + } + awaitingSpokenResponseRef.current = true dropSpeechSession() consumePendingResponse() @@ -261,24 +363,46 @@ export function useVoiceConversation({ [consumePendingResponse, onSubmit, onTranscribeAudio, voiceCopy.transcriptionFailed] ) - /** Barge-in monitor wiring shared by the live and fallback speech paths. */ - const openBargeMonitor = useCallback( - (onBarge: () => void) => - monitorSpeechDuringPlayback({ - onSpeech: () => { - bargeCapturePendingRef.current = true - onBarge() - markVoicePlaybackInterrupted() - stopVoicePlayback() - }, - onUtterance: audio => { - bargeCapturePendingRef.current = false - stopBargeMonitorRef.current = null - void submitCapturedUtterance(audio) + /** + * Full-duplex barge-in monitor for the WHOLE agent turn: armed at submit, + * live through generation (thinking) AND playback (speaking). + * + * - generation phase (`busy`): speech interrupts the in-flight turn via + * `onInterrupt` — the same seam as the Stop button — and cuts any TTS that + * managed to start, so the stale reply never speaks. + * - playback phase: speech cuts playback and the captured interruption is + * transcribed and submitted as the next turn. + * + * Idempotent — one monitor owns the mic per turn; re-arming while one is + * live is a no-op (the live/fallback speech paths and the turn-drive effect + * all call this). + */ + const ensureBargeMonitor = useCallback(() => { + if (stopBargeMonitorRef.current) { + return + } + + stopBargeMonitorRef.current = monitorSpeechDuringPlayback({ + isPlaying: () => $voicePlayback.get().status === 'speaking', + onSpeech: () => { + bargeCapturePendingRef.current = true + bargedRef.current = true + markVoicePlaybackInterrupted() + stopVoicePlayback() + + if (busyRef.current) { + // Mid-generation: stop the in-flight turn so the captured utterance + // becomes the next one instead of queueing behind a stale reply. + void onInterruptRef.current?.() } - }), - [submitCapturedUtterance] - ) + }, + onUtterance: audio => { + bargeCapturePendingRef.current = false + stopBargeMonitorRef.current = null + void submitCapturedUtterance(audio) + } + }) + }, [submitCapturedUtterance]) /** Push any new reply text into the live session; finish when complete. */ const feedSpeechSession = useCallback( @@ -330,26 +454,25 @@ export function useVoiceConversation({ return } - let barged = false + // The full-duplex monitor is normally already live (armed at submit); + // this is a safety net for read-aloud-style entries into the loop. + ensureBargeMonitor() - stopBargeMonitorRef.current?.() - stopBargeMonitorRef.current = openBargeMonitor(() => { - barged = true - }) + speechStartSequenceRef.current = $voicePlayback.get().sequence void playSpeechText(response.text, { source: 'voice-conversation' }) .catch(error => notifyError(error, voiceCopy.playbackFailed)) .finally(() => { if (responseIdRef.current === responseId) { awaitingSpokenResponseRef.current = false - settleAfterSpeech(barged) + settleAfterSpeech(bargedRef.current) } }) } poll() }, - [openBargeMonitor, pendingResponse, settleAfterSpeech, voiceCopy.playbackFailed] + [ensureBargeMonitor, pendingResponse, settleAfterSpeech, voiceCopy.playbackFailed] ) /** @@ -361,17 +484,14 @@ export function useVoiceConversation({ (responseId: string) => { responseIdRef.current = responseId spokenSourceLengthRef.current = 0 + speechStartSequenceRef.current = $voicePlayback.get().sequence setStatus('speaking') - let barged = false - // VAD barge-in: the user talking over the reply cuts playback, drops // the not-yet-spoken remainder, AND keeps capturing — the interruption // is transcribed from its first syllable instead of losing the opening - // words to a mic re-open. - stopBargeMonitorRef.current = openBargeMonitor(() => { - barged = true - }) + // words to a mic re-open. Usually already live (armed at submit). + ensureBargeMonitor() void (async () => { const session = await startSpeechStream({ source: 'voice-conversation' }) @@ -414,10 +534,10 @@ export function useVoiceConversation({ } awaitingSpokenResponseRef.current = false - settleAfterSpeech(barged) + settleAfterSpeech(bargedRef.current) })() }, - [awaitFallbackSpeech, feedSpeechSession, openBargeMonitor, settleAfterSpeech] + [awaitFallbackSpeech, ensureBargeMonitor, feedSpeechSession, settleAfterSpeech] ) const start = useCallback(async () => { @@ -505,15 +625,39 @@ export function useVoiceConversation({ return () => window.removeEventListener('keydown', onKeyDown, { capture: true }) }, [enabled, stopTurn]) + // Ambient "thinking" sound: while the agent works (status 'thinking') no + // audio flows, which reads as dead air mid-conversation. Calm bubble blips + // fill the gap; they stop the INSTANT speech starts, the mic re-arms, or the + // conversation ends. Gated by voice.thinking_sound + the shared sound mute. + useEffect(() => { + if (enabled && !muted && status === 'thinking') { + startThinkingSound() + + return stopThinkingSound + } + + stopThinkingSound() + + return undefined + }, [enabled, muted, status]) + // Drive the loop: when a voice-submitted reply appears, open a live speech // session (which feeds itself from then on). Otherwise start listening when // idle between turns. + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) useEffect(() => { if (!enabled || muted) { return } if (awaitingSpokenResponseRef.current && status !== 'speaking') { + // Generation phase: the turn is in flight but no reply audio exists + // yet. Keep the mic live so speech can interrupt the model mid- + // generation (full-duplex) instead of going deaf until playback. + if (status === 'thinking' && (busy || bargeCapturePendingRef.current)) { + ensureBargeMonitor() + } + const response = pendingResponse() if (response) { @@ -522,8 +666,9 @@ export function useVoiceConversation({ return } - if (!busy && status === 'thinking') { - // Turn finished without any speakable reply (tool-only, error). + if (!busy && status === 'thinking' && !bargeCapturePendingRef.current) { + // Turn finished without any speakable reply (tool-only, error). A + // live barge capture owns the loop instead — it submits or resumes. awaitingSpokenResponseRef.current = false dropSpeechSession() pendingStartRef.current = true @@ -540,8 +685,9 @@ export function useVoiceConversation({ if (pendingStartRef.current) { void startListening() } - }, [busy, enabled, muted, openLiveSpeech, pendingResponse, startListening, status]) + }, [busy, enabled, muted, ensureBargeMonitor, openLiveSpeech, pendingResponse, startListening, status]) + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) useEffect(() => { if (enabled && !wasEnabledRef.current) { void start() diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsx index d06f3d79c31d..cfb5e751889e 100644 --- a/apps/desktop/src/app/chat/composer/index.tsx +++ b/apps/desktop/src/app/chat/composer/index.tsx @@ -1,8 +1,8 @@ import { ComposerPrimitive } from '@assistant-ui/react' import { useStore } from '@nanostores/react' -import { type ClipboardEvent, type FormEvent, type KeyboardEvent, useCallback, useEffect, useRef } from 'react' +import { type ClipboardEvent, type FormEvent, type KeyboardEvent, useCallback, useEffect, useMemo, useRef } from 'react' -import { composerFill, composerSurfaceGlass } from '@/components/chat/composer-dock' +import { composerFill, composerFloatingStrip, composerSurfaceGlass } from '@/components/chat/composer-dock' import { Button } from '@/components/ui/button' import { Slot as ContribSlot } from '@/contrib/react/slot' import { useI18n } from '@/i18n' @@ -11,6 +11,8 @@ import { sanitizeComposerInput } from '@/lib/composer-input-sanitize' import { DATA_IMAGE_URL_RE } from '@/lib/embedded-images' import { triggerHaptic } from '@/lib/haptics' import { cn } from '@/lib/utils' +import { interceptsTypedVoiceStop } from '@/lib/voice-stop-word' +import { sessionCompacting } from '@/store/compaction' import { browseBackward, browseForward, deriveUserHistory, isBrowsingHistory } from '@/store/composer-input-history' import { POPOUT_WIDTH_REM } from '@/store/composer-popout' import { parkQueuedPrompts, removeQueuedPrompt, unparkQueuedPrompts } from '@/store/composer-queue' @@ -21,7 +23,12 @@ import { $autoSpeakReplies } from '@/store/voice-prefs' import { useTheme } from '@/themes' import { AttachmentList } from './attachments' -import { COMPOSER_FADE_BACKGROUND, type QueueEditState, slashArgStage } from './composer-utils' +import { + acceptsTriggerCompletion, + COMPOSER_FADE_BACKGROUND, + type QueueEditState, + slashArgStage +} from './composer-utils' import { ContextMenu } from './context-menu' import { COMPOSER_AREAS, runComposerMiddleware } from './contrib' import { ComposerControls } from './controls' @@ -39,16 +46,19 @@ import { useComposerPopout } from './hooks/use-composer-popout' import { useComposerQueue } from './hooks/use-composer-queue' import { useComposerSubmit } from './hooks/use-composer-submit' import { useComposerTrigger } from './hooks/use-composer-trigger' +import { useComposerUndo } from './hooks/use-composer-undo' import { useComposerUrlDialog } from './hooks/use-composer-url-dialog' import { useComposerVoice } from './hooks/use-composer-voice' +import { useComposerMicroActions } from './hooks/use-micro-actions' import { useSlashCompletions } from './hooks/use-slash-completions' import { useSessionStatusPresence } from './hooks/use-status-presence' +import { chipTypedPathOnSpace, pathifyRefs } from './path-refs' import { QueuePanel } from './queue-panel' import { composerPlainText, deleteChipBeforeCaret, deleteSelectionInEditor, - insertPlainTextAtCaret, + insertComposerContentsAtCaret, normalizeComposerEditorDom, RICH_INPUT_SLOT } from './rich-editor' @@ -58,7 +68,9 @@ import { CodingStatusRow } from './status-stack/coding-row' import { extractClipboardImageBlobs } from './text-utils' import { ComposerTriggerPopover } from './trigger-popover' import type { ChatBarProps } from './types' +import { isRedoShortcut, isUndoShortcut } from './undo-history' import { UrlDialog } from './url-dialog' +import { chipTypedUrlOnSpace, linkifyUrls } from './url-refs' import { VoiceActivity, VoicePlaybackActivity } from './voice-activity' export function ChatBar({ @@ -84,11 +96,32 @@ export function ChatBar({ onSubmit: onSubmitProp, onTranscribeAudio }: ChatBarProps) { + // Typed stop phrase during an active voice conversation ends it — same + // semantics as SAYING "stop" (voice-stop-word.ts) or clicking the pill's + // end control. Populated after useComposerVoice below (the submit wrapper + // is created first); render-time assignment keeps the ref current. + const voiceStopRef = useRef<{ active: boolean; end: () => void }>({ active: false, end: () => {} }) + // Every send (typed, queued, voice) passes through the contributed // middleware chain first — rewrite / pass-through / cancel. Empty chain = // exact pass-through, so surfaces without contributions are byte-identical. const onSubmit = useCallback( async (value, options) => { + // Bare stop phrase typed while the voice conversation is live: end the + // conversation (mic off, pill dismissed) instead of sending "stop" to + // the agent. Spoken transcripts are already stop-checked inside + // use-voice-conversation, so this only catches typed/queued sends. + // Outside a voice conversation, typed "stop" is a normal message. + const voiceStop = voiceStopRef.current + + if (interceptsTypedVoiceStop(voiceStop.active, value, options?.attachments?.length ?? 0)) { + voiceStop.end() + + // Consumed (not rejected): report accepted so the submit engine + // clears the draft instead of restoring "stop" into the composer. + return true + } + const draft = await runComposerMiddleware({ text: value, attachments: options?.attachments }) if (!draft) { @@ -104,6 +137,7 @@ export function ChatBar({ // focus-bus key, and awaiting-input edge. Main scope = the legacy globals. const scope = useComposerScope() const attachments = useStore(scope.attachments.$attachments) + const compacting = useStore(useMemo(() => sessionCompacting(sessionId ?? null), [sessionId])) const scrolledUp = useStore($threadScrolledUp) const autoSpeak = useStore($autoSpeakReplies) // The turn is parked on the user (clarify / approval / sudo / secret). Esc must @@ -122,6 +156,10 @@ export function ChatBar({ // every per-item status mutation or other sessions' churn (see the hook). const statusPresent = useSessionStatusPresence(statusSessionId) + // Publishes contributed micro actions for this session; the status stack + // renders them as the pill strip at the top of the overlay lane. + useComposerMicroActions(statusSessionId, busy) + const composerRef = useRef(null) const composerSurfaceRef = useRef(null) @@ -170,9 +208,24 @@ export function ChatBar({ requestMainFocus, sessionIdRef, setComposerText, - stashAt + stashAt, + syncDraftFromEditor } = useComposerDraft({ activeQueueSessionKey, focusKey, inputDisabled, queueEditRef, sessionId }) + // Undo/redo. The rich editor bypasses Chromium's editing pipeline for speed, + // which also bypasses its undo stack — so we own the stack and every edit + // path below banks its pre-edit state through `recordUndoPoint`. + const { recordUndoPoint, redo, resetUndoHistory, undo, withUndoPoint } = useComposerUndo({ + editorRef, + syncDraftFromEditor + }) + + // Prior history belongs to the draft that just left — undoing into another + // conversation's text is worse than having none. + useEffect(() => { + resetUndoHistory() + }, [activeQueueSessionKey, resetUndoHistory]) + // "Add URL" dialog — open/value state, autofocus, and submit (host onAddUrl or // an @url: directive into the draft). const { openUrlDialog, setUrlOpen, setUrlValue, submitUrl, urlInputRef, urlOpen, urlValue } = useComposerUrlDialog({ @@ -230,11 +283,15 @@ export function ChatBar({ // Steer only makes sense mid-turn, text-only (the gateway can't carry images // into a tool result) and never for a slash command (those execute inline). - const canSteer = busy && !!onSteer && attachments.length === 0 && isSteerableText + const canSteer = busy && !compacting && !!onSteer && attachments.length === 0 && isSteerableText // While busy: text redirects the live turn (Cursor-style stop-and-correct), // attachments queue for the next turn, an empty composer stops. - const busyAction: 'steer' | 'queue' | 'stop' = canSteer ? 'steer' : hasComposerPayload ? 'queue' : 'stop' + const busyAction: 'steer' | 'queue' | 'stop' = canSteer + ? 'steer' + : compacting || hasComposerPayload + ? 'queue' + : 'stop' // The submit engine — the orchestration seam where draft + queue meet. Owns // the submit decision tree, the send-with-restore primitive, and steer. @@ -243,6 +300,7 @@ export function ChatBar({ activeQueueSessionKeyRef, attachments, busy, + compacting, clearDraft, disabled, draftRef, @@ -274,13 +332,17 @@ export function ChatBar({ // this API; keyup uses triggerKeyConsumedRef to skip its refresh. const { argStageEmpty, + ascendTriggerPath, closeTrigger, commitTypedSlashDirective, + moveTriggerActive, refreshTrigger, replaceTriggerWithChip, setTriggerActive, + slashFreeTextArgStage, trigger, triggerActive, + triggerActiveExplicit, triggerItems, triggerKeyConsumedRef, triggerLoading @@ -349,6 +411,23 @@ export function ChatBar({ scheduleFlushEditorToDraft(event.currentTarget) } + // Native typing/deleting mutates the DOM through Chromium's editing pipeline, + // whose undo stack we've taken over — so bank the pre-edit state here, before + // the change lands. `beforeinput` is the only hook that still sees the old + // text. Consecutive keystrokes coalesce into one entry, so ⌘Z steps back by a + // burst rather than a character. + const handleEditorBeforeInput = (event: FormEvent) => { + const inputType = (event.nativeEvent as InputEvent).inputType + + // Undo/redo are ours (handled in useComposerUndo + keydown), and IME preedit + // is not a committed edit — compositionend is where that text becomes real. + if (inputType === 'historyUndo' || inputType === 'historyRedo' || composingRef.current) { + return + } + + recordUndoPoint({ coalesce: inputType === 'insertText' || inputType === 'deleteContentBackward' }) + } + const handlePaste = (event: ClipboardEvent) => { const imageBlobs = extractClipboardImageBlobs(event.clipboardData) @@ -395,7 +474,12 @@ export function ChatBar({ } event.preventDefault() - insertPlainTextAtCaret(event.currentTarget, pastedText) + + // Links in the paste land as `@url:` chips rather than a wall of URL text — + // the same reference the "Add URL" dialog inserts, parsed in place so a link + // mid-sentence keeps its position. Bare `@path` tokens promote the same way. + recordUndoPoint() + insertComposerContentsAtCaret(event.currentTarget, pathifyRefs(linkifyUrls(pastedText))) scheduleFlushEditorToDraft(event.currentTarget) } @@ -409,6 +493,23 @@ export function ChatBar({ return } + // Undo/redo before anything else — we own the stack (see useComposerUndo), + // so these never reach Chromium's native history, which has no record of + // the Range-based edits the rich editor makes. + if (isUndoShortcut(event.nativeEvent)) { + event.preventDefault() + undo() + + return + } + + if (isRedoShortcut(event.nativeEvent)) { + event.preventDefault() + redo() + + return + } + // Plain Backspace right after a directive chip: remove the chip + its // auto-inserted trailing space as one unit, so deleting a directive never // leaves an orphaned space. (Modified backspaces stay native.) @@ -417,7 +518,7 @@ export function ChatBar({ !event.metaKey && !event.ctrlKey && !event.altKey && - deleteChipBeforeCaret(event.currentTarget) + withUndoPoint(() => deleteChipBeforeCaret(event.currentTarget)) ) { event.preventDefault() flushEditorToDraft(event.currentTarget) @@ -427,7 +528,29 @@ export function ChatBar({ // Non-collapsed Backspace/Delete: native selection-delete is ~O(n²) on large // drafts (Ctrl+A → Delete froze ~1.3s). Collapsed carets fall through. - if ((event.key === 'Backspace' || event.key === 'Delete') && deleteSelectionInEditor(event.currentTarget)) { + if ( + (event.key === 'Backspace' || event.key === 'Delete') && + withUndoPoint(() => deleteSelectionInEditor(event.currentTarget)) + ) { + event.preventDefault() + flushEditorToDraft(event.currentTarget) + + return + } + + // A typed link finished with a space chips like a pasted one — the space + // itself rides along inside the insert. + if (withUndoPoint(() => chipTypedUrlOnSpace(event))) { + event.preventDefault() + flushEditorToDraft(event.currentTarget) + + return + } + + // Same for a bare `@path` — a hand-typed or Tab-descended path chips into + // the `@file:`/`@folder:` ref it means, instead of submitting as plain text + // the backend never resolves. + if (withUndoPoint(() => chipTypedPathOnSpace(event))) { event.preventDefault() flushEditorToDraft(event.currentTarget) @@ -450,7 +573,7 @@ export function ChatBar({ if (event.key === 'ArrowDown') { event.preventDefault() triggerKeyConsumedRef.current = true - setTriggerActive(idx => (idx + 1) % triggerItems.length) + moveTriggerActive(1) return } @@ -458,18 +581,21 @@ export function ChatBar({ if (event.key === 'ArrowUp') { event.preventDefault() triggerKeyConsumedRef.current = true - setTriggerActive(idx => (idx - 1 + triggerItems.length) % triggerItems.length) + moveTriggerActive(-1) return } - // Enter / Tab / Space all accept the highlighted item: a no-arg command - // commits its directive chip, an arg-taking command expands to its - // options step, and an arg option commits the full `/cmd arg` chip. Space - // is slash-only (an `@` mention takes a literal space) and gated to a - // non-empty query so a bare `/ ` still types a space. - const acceptOnSpace = event.key === ' ' && trigger.kind === '/' && Boolean(trigger.query.trim()) - const accept = event.key === 'Enter' || event.key === 'Tab' || acceptOnSpace + // Accepting the highlighted item: a no-arg command commits its directive + // chip, an arg-taking command expands to its options step, and an arg + // option commits the full `/cmd arg` chip. + const accept = acceptsTriggerCompletion({ + activeExplicit: triggerActiveExplicit, + freeTextArgStage: slashFreeTextArgStage, + key: event.key, + kind: trigger.kind, + query: trigger.query + }) if (accept) { event.preventDefault() @@ -477,12 +603,24 @@ export function ChatBar({ const item = triggerItems[triggerActive] if (item) { - replaceTriggerWithChip(item) + // Tab means "go deeper" on a folder; Enter means "I want this one". + // Everything else treats them alike. + replaceTriggerWithChip(item, { descend: event.key === 'Tab' }) } return } + // Backspace climbs out of an `@` path one segment at a time, mirroring + // Tab's one-key descent. Only when the caret sits at the end of the + // token — mid-token editing keeps normal character deletion. + if (event.key === 'Backspace' && !event.metaKey && !event.altKey && ascendTriggerPath()) { + event.preventDefault() + triggerKeyConsumedRef.current = true + + return + } + if (event.key === 'Escape') { event.preventDefault() triggerKeyConsumedRef.current = true @@ -503,11 +641,12 @@ export function ChatBar({ slashArgStage(trigger.query) && trigger.query.trim() ) { - event.preventDefault() - triggerKeyConsumedRef.current = true - commitTypedSlashDirective() + if (commitTypedSlashDirective()) { + event.preventDefault() + triggerKeyConsumedRef.current = true - return + return + } } // ArrowUp/ArrowDown navigate, in priority order: the queue (edit entries in @@ -544,7 +683,7 @@ export function ChatBar({ // $messages is read imperatively (not subscribed) so the composer // doesn't re-render on every streaming delta flush. - const history = deriveUserHistory(scope.readMessages(), chatMessageText) + const history = deriveUserHistory(scope.$messages.get(), chatMessageText) const entry = browseBackward(sessionId, currentDraft, history) if (entry !== null) { @@ -569,7 +708,7 @@ export function ChatBar({ event.preventDefault() triggerKeyConsumedRef.current = true - const history = deriveUserHistory(scope.readMessages(), chatMessageText) + const history = deriveUserHistory(scope.$messages.get(), chatMessageText) const result = browseForward(sessionId, history) if (result !== null) { @@ -580,14 +719,22 @@ export function ChatBar({ return } - // Cmd/Ctrl+Enter is reserved for steering the live run — never a send. - // Steer when there's a steerable draft, otherwise swallow it so it can't - // surprise-send. (Plain Enter still queues while busy / sends when idle.) + // Cmd/Ctrl+Enter queues a follow-up while a turn runs. Plain Enter steers + // a text-only draft, so both live-turn actions stay reachable by keyboard. if (event.key === 'Enter' && (event.metaKey || event.ctrlKey) && !event.shiftKey) { event.preventDefault() - if (canSteer) { - steerDraft() + if (busy && !disabled) { + // As with plain Enter, source the just-typed content from the DOM so a + // fast keypress cannot queue a stale draft. + const editorText = editorRef.current ? composerPlainText(editorRef.current) : draftRef.current + + if (editorText !== draftRef.current) { + draftRef.current = editorText + setComposerText(editorText) + } + + queueDraft() } return @@ -615,12 +762,21 @@ export function ChatBar({ return } - // Empty Enter while busy is a no-op — interrupting is explicit (Stop/Esc), - // never a stray Enter after sending. With a payload, submitDraft queues it. - // Gate on the live DOM payload (not the render-lagged composer state) so a - // message typed fast / via IME while busy still reaches submitDraft() and - // gets queued instead of being mistaken for an empty Enter. + // Empty Enter while busy. With prompts queued this is the double-send: + // the first Enter put the words in the queue, a second sends them now + // (promote + interrupt + drain on settle), mirroring the idle empty-Enter + // drain above. With nothing queued it stays a no-op — interrupting is + // explicit (Stop/Esc), never a stray Enter after sending. Gate on the live + // DOM payload (not the render-lagged composer state) so a message typed + // fast / via IME while busy still reaches submitDraft() and gets queued + // instead of being mistaken for an empty Enter. if (busy && !hasLivePayload) { + const head = queuedPrompts.find(entry => entry.id !== queueEdit?.entryId) + + if (head) { + sendQueuedNow(head.id) + } + return } @@ -700,12 +856,19 @@ export function ChatBar({ focusInput, insertText, maxRecordingSeconds, + // Voice barge-in mid-generation halts the run like the Stop button. + onInterrupt: haltRun, onSubmit, onTranscribeAudio, sessionId, target: scope.target }) + // Keep the typed-stop interceptor (see onSubmit above) in sync with the + // live conversation state. Render-time ref assignment, same pattern as + // dispatchSubmitRef — no effect needed for a plain mirror. + voiceStopRef.current = { active: voiceConversationActive, end: endConversation } + const contextMenu = ( window.setTimeout(closeTrigger, 80)} onCompositionEnd={event => { composingRef.current = false @@ -946,7 +1110,14 @@ export function ChatBar({ className={cn('pointer-events-auto absolute inset-0', dragging ? 'cursor-grabbing' : 'cursor-grab')} data-dragging={dragging ? '' : undefined} data-slot="composer-drag-region" - onDoubleClick={handleComposerToggle} + onDoubleClick={event => { + // The pill strips paint above this region; a double-click that + // lands on one must not float the composer. onPointerDown goes + // through gestureTargetOk, but this handler doesn't. + if (!(event.target as Element).closest('[data-slot="composer-no-drag"]')) { + handleComposerToggle() + } + }} /> )}
@@ -1038,6 +1209,17 @@ export function ChatBar({
+ {/* Underside: a floating strip BELOW the whole composer surface. + Chrome-free by design — contributions bring their own pill/skin, + like the micro-action strip above. In flow (the root is + bottom-anchored, so this grows the composer upward and stays on + screen) but OUTSIDE the surface, so it escapes the surface's + clipping, border, and scroll fade. Shares the micro-action + strip's grid so the two bracket the composer on one vertical + line. Renders nothing until something contributes. */} +
+ +
diff --git a/apps/desktop/src/app/chat/composer/inline-refs.ts b/apps/desktop/src/app/chat/composer/inline-refs.ts index 5fd62f4cc94a..5e282f6a040a 100644 --- a/apps/desktop/src/app/chat/composer/inline-refs.ts +++ b/apps/desktop/src/app/chat/composer/inline-refs.ts @@ -4,7 +4,13 @@ import { contextPath } from '@/lib/chat-runtime' import type { DroppedFile } from '../hooks/use-composer-actions' -import { composerPlainText, normalizeComposerEditorDom, placeCaretEnd, refChipElement } from './rich-editor' +import { + composerPlainText, + normalizeComposerEditorDom, + placeCaretEnd, + refChipElement, + RICH_INPUT_SLOT +} from './rich-editor' /** A chip to insert: a raw `@kind:value` string, or a typed value + display label. */ export type InlineRefInput = string | { kind: string; label?: string; value: string } @@ -92,7 +98,12 @@ function plainTextInRange(editor: HTMLDivElement, range: Range, edge: 'after' | slice.setStart(range.endContainer, range.endOffset) } + // Carry the editor's slot marker: composerPlainText appends a trailing "\n" + // to any other block element, so a bare
made `beforeText` always look + // like it ended in whitespace and the separating space was never inserted — + // a chip dropped after a word came out glued to it (`review@file:...`). const container = document.createElement('div') + container.dataset.slot = RICH_INPUT_SLOT container.appendChild(slice.cloneContents()) return composerPlainText(container) diff --git a/apps/desktop/src/app/chat/composer/model-pill.tsx b/apps/desktop/src/app/chat/composer/model-pill.tsx index b5a6e976805b..2a26db4094c9 100644 --- a/apps/desktop/src/app/chat/composer/model-pill.tsx +++ b/apps/desktop/src/app/chat/composer/model-pill.tsx @@ -11,7 +11,7 @@ import { useI18n } from '@/i18n' import { ChevronDown } from '@/lib/icons' import { formatModelStatusLabel } from '@/lib/model-status-label' import { cn } from '@/lib/utils' -import { $currentModelSource, setModelPickerOpen } from '@/store/session' +import { $currentModelSource, $defaultReasoningEffort, setModelPickerOpen } from '@/store/session' import type { ChatBarState } from './types' @@ -48,6 +48,7 @@ export function ModelPill({ const fastMode = useStore(view.$fast) const reasoningEffort = useStore(view.$reasoningEffort) const modelSource = useStore($currentModelSource) + const defaultEffort = useStore($defaultReasoningEffort) const runtimeId = useStore(view.$runtimeId) const [open, setOpen] = useState(false) @@ -68,7 +69,9 @@ export function ModelPill({ ) : ( <> {currentModel.trim() ? ( - {formatModelStatusLabel(currentModel, { fastMode, reasoningEffort })} + + {formatModelStatusLabel(currentModel, { defaultEffort, fastMode, reasoningEffort })} + ) : ( )} diff --git a/apps/desktop/src/app/chat/composer/path-refs.test.ts b/apps/desktop/src/app/chat/composer/path-refs.test.ts new file mode 100644 index 000000000000..da7cf1dc6f15 --- /dev/null +++ b/apps/desktop/src/app/chat/composer/path-refs.test.ts @@ -0,0 +1,103 @@ +import type { KeyboardEvent } from 'react' +import { describe, expect, it } from 'vitest' + +import { chipTypedPathOnSpace, pathifyRefs } from './path-refs' +import { composerPlainText, RICH_INPUT_SLOT } from './rich-editor' + +/** + * Tab-descending into a folder from the `@` popover leaves a bare + * `@apps/desktop/` in the editor. That is not a reference — the backend's + * REFERENCE_PATTERN only matches `@kind:value` — so it used to submit as plain + * text and silently attach nothing. + */ + +/** An editor holding `text` with a collapsed caret at its end, plus the space + * keydown the composer would hand `chipTypedPathOnSpace`. */ +const spaceOn = (text: string) => { + const editor = document.createElement('div') + editor.dataset.slot = RICH_INPUT_SLOT + editor.textContent = text + document.body.append(editor) + + const selection = window.getSelection()! + const range = document.createRange() + + range.setStart(editor.firstChild!, text.length) + range.collapse(true) + selection.removeAllRanges() + selection.addRange(range) + + return { editor, event: { currentTarget: editor, key: ' ' } as KeyboardEvent } +} + +describe('pathifyRefs', () => { + it('promotes a Tab-descended folder token', () => { + expect(pathifyRefs('look at @apps/desktop/')).toBe('look at @folder:`apps/desktop`') + }) + + it('promotes a typed file path', () => { + expect(pathifyRefs('read @src/main.ts please')).toBe('read @file:`src/main.ts` please') + }) + + it('promotes every bare path in one message', () => { + expect(pathifyRefs('@apps/desktop/ and @src/main.ts')).toBe('@folder:`apps/desktop` and @file:`src/main.ts`') + }) + + it('leaves an already-typed directive alone', () => { + const text = 'look at @folder:`apps/desktop` ok' + + expect(pathifyRefs(text)).toBe(text) + }) + + it('leaves a handle alone', () => { + expect(pathifyRefs('cc @teknium1 on this')).toBe('cc @teknium1 on this') + }) + + it('leaves simple refs alone', () => { + expect(pathifyRefs('check @diff and @staged')).toBe('check @diff and @staged') + }) + + it('leaves an email alone', () => { + expect(pathifyRefs('mail me at brooklyn@nous.dev/x')).toBe('mail me at brooklyn@nous.dev/x') + }) + + it('is a no-op without an @', () => { + expect(pathifyRefs('nothing here')).toBe('nothing here') + }) +}) + +describe('chipTypedPathOnSpace', () => { + it('chips a Tab-descended folder token into a real @folder: chip', () => { + const { editor, event } = spaceOn('look at @apps/desktop/') + + expect(chipTypedPathOnSpace(event)).toBe(true) + + const chip = editor.querySelector('[data-ref-text]') + + expect(chip?.getAttribute('data-ref-kind')).toBe('folder') + expect(chip?.getAttribute('data-ref-id')).toBe('apps/desktop') + expect(chip?.textContent).toContain('desktop') + expect(composerPlainText(editor)).toBe('look at @folder:`apps/desktop` ') + }) + + it('chips a typed file path', () => { + const { editor, event } = spaceOn('read @src/main.ts') + + expect(chipTypedPathOnSpace(event)).toBe(true) + expect(editor.querySelector('[data-ref-kind="file"]')).not.toBeNull() + expect(composerPlainText(editor)).toBe('read @file:`src/main.ts` ') + }) + + it('leaves a handle alone', () => { + const { editor, event } = spaceOn('cc @teknium1') + + expect(chipTypedPathOnSpace(event)).toBe(false) + expect(editor.querySelector('[data-ref-text]')).toBeNull() + }) + + it('leaves an already-typed ref alone', () => { + const { event } = spaceOn('look at @folder:`apps/desktop`') + + expect(chipTypedPathOnSpace(event)).toBe(false) + }) +}) diff --git a/apps/desktop/src/app/chat/composer/path-refs.ts b/apps/desktop/src/app/chat/composer/path-refs.ts new file mode 100644 index 000000000000..c326727afa21 --- /dev/null +++ b/apps/desktop/src/app/chat/composer/path-refs.ts @@ -0,0 +1,103 @@ +/** + * Bare-path recognition for the composer. Walking into a folder from the `@` + * popover (Tab) re-types the token as a bare `@apps/desktop/` so the next + * `complete.path` lists that folder's children. That's right while typing, but + * a bare token is not a reference: `REFERENCE_PATTERN` only matches + * `@kind:value`, so a draft sent with one attaches nothing and renders as + * plain text instead of a chip. + * + * So the bare token is promoted to its typed form on the way out — the same + * shape `url-refs.ts` uses for bare links. + */ +import type { KeyboardEvent } from 'react' + +import { quoteRefValue, REF_RE, refChipElement, replaceBeforeCaret } from './rich-editor' +import { textBeforeCaret } from './text-utils' + +// A `/` is required, exactly like URL_RE requires an explicit scheme: `@teknium1` +// and `@diff` are a handle and a simple ref, not paths, and guessing wrong turns +// someone's name into a file reference. A separator is the cheap signal that the +// user meant a path. The token also can't start with a `:` kind prefix — that is +// already a typed ref and REF_RE owns it. +const BARE_PATH_RE = /(? { + const start = match.index ?? 0 + + return { end: start + match[0].length, start } + }) + + let out = '' + let cursor = 0 + + for (const match of text.matchAll(BARE_PATH_RE)) { + const start = match.index ?? 0 + const ref = barePathRef(match[1] || '') + + if (!ref || fenced.some(span => start >= span.start && start < span.end)) { + continue + } + + out += `${text.slice(cursor, start)}${ref}` + cursor = start + match[0].length + } + + return out + text.slice(cursor) +} + +/** A plain space finishing a typed `@path` commits it as a chip, so a hand-typed + * path chips the same way a picked one does. Returns whether it ran, so a + * keydown handler can fall through on anything else. */ +export function chipTypedPathOnSpace(event: KeyboardEvent) { + if (event.key !== ' ' || event.metaKey || event.ctrlKey || event.altKey) { + return false + } + + const editor = event.currentTarget + + // Runs on every space, so bail on the cheap native read before paying for the + // caret range walk (same guard shape as the trigger detector). + if (!editor.textContent?.includes('@')) { + return false + } + + const before = textBeforeCaret(editor) + const match = before ? TYPED_BARE_PATH_RE.exec(before) : null + const token = match?.[0] + const ref = match?.[1] ? barePathRef(match[1]) : null + + if (!token || !ref) { + return false + } + + const directive = ref.match(/^@([^:]+):(.+)$/) + + if (!directive) { + return false + } + + const fragment = document.createDocumentFragment() + + fragment.append(refChipElement(directive[1], directive[2]), document.createTextNode(' ')) + + return replaceBeforeCaret(editor, token.length, fragment) +} diff --git a/apps/desktop/src/app/chat/composer/queue-panel.tsx b/apps/desktop/src/app/chat/composer/queue-panel.tsx index 6bb04ec23c4e..2f5612efd13c 100644 --- a/apps/desktop/src/app/chat/composer/queue-panel.tsx +++ b/apps/desktop/src/app/chat/composer/queue-panel.tsx @@ -4,7 +4,7 @@ import { Button } from '@/components/ui/button' import { Codicon } from '@/components/ui/codicon' import { Tip } from '@/components/ui/tooltip' import { type Translations, useI18n } from '@/i18n' -import { ArrowUp, iconSize, Pencil, Trash2 } from '@/lib/icons' +import { CornerDownLeft, iconSize, Pencil, Trash2 } from '@/lib/icons' import { cn } from '@/lib/utils' import type { QueuedPromptEntry } from '@/store/composer-queue' @@ -22,7 +22,7 @@ interface QueuePanelProps { } const entryPreview = (entry: QueuedPromptEntry, c: Translations['composer']) => - entry.text.trim() || (entry.attachments.length > 0 ? c.attachmentOnly : c.emptyTurn) + (entry.displayText ?? entry.text).trim() || (entry.attachments.length > 0 ? c.attachmentOnly : c.emptyTurn) export function QueuePanel({ busy, @@ -103,7 +103,7 @@ export function QueuePanel({ type="button" variant="ghost" > - + diff --git a/apps/desktop/src/app/chat/composer/rich-editor.test.ts b/apps/desktop/src/app/chat/composer/rich-editor.test.ts index 12e3e9613eff..842765388ff8 100644 --- a/apps/desktop/src/app/chat/composer/rich-editor.test.ts +++ b/apps/desktop/src/app/chat/composer/rich-editor.test.ts @@ -4,10 +4,11 @@ import { insertInlineRefsIntoEditor } from './inline-refs' import { composerPlainText, deleteSelectionInEditor, - insertPlainTextAtCaret, + insertComposerContentsAtCaret, normalizeComposerEditorDom, refChipElement, renderComposerContents, + replaceBeforeCaret, RICH_INPUT_SLOT } from './rich-editor' @@ -70,16 +71,40 @@ describe('insertInlineRefsIntoEditor', () => { expect(editor.querySelector(':scope > div')).toBeNull() expect(composerPlainText(editor)).toBe('@file:`src/foo.ts` ') }) + + it('separates a chip from the word the caret sits after', () => { + const editor = document.createElement('div') + editor.dataset.slot = RICH_INPUT_SLOT + editor.append(document.createTextNode('review')) + document.body.append(editor) + caretIn(editor) + + expect(insertInlineRefsIntoEditor(editor, ['@file:`src/a.ts`'])).toBe('review @file:`src/a.ts` ') + + editor.remove() + }) + + it('does not double the space when one is already there', () => { + const editor = document.createElement('div') + editor.dataset.slot = RICH_INPUT_SLOT + editor.append(document.createTextNode('review ')) + document.body.append(editor) + caretIn(editor) + + expect(insertInlineRefsIntoEditor(editor, ['@file:`src/a.ts`'])).toBe('review @file:`src/a.ts` ') + + editor.remove() + }) }) -describe('insertPlainTextAtCaret', () => { +describe('insertComposerContentsAtCaret', () => { it('inserts multiline text as text nodes + br', () => { const editor = document.createElement('div') editor.dataset.slot = RICH_INPUT_SLOT document.body.append(editor) caretIn(editor) - insertPlainTextAtCaret(editor, 'one\ntwo\nthree') + insertComposerContentsAtCaret(editor, 'one\ntwo\nthree') expect(editor.querySelectorAll('br').length).toBe(2) expect(composerPlainText(editor)).toBe('one\ntwo\nthree') @@ -102,12 +127,76 @@ describe('insertPlainTextAtCaret', () => { selection.removeAllRanges() selection.addRange(range) - insertPlainTextAtCaret(editor, 'cd') + insertComposerContentsAtCaret(editor, 'cd') expect(composerPlainText(editor)).toBe('abcdef') editor.remove() }) + + it('lands directives in the text as chips', () => { + const editor = document.createElement('div') + editor.dataset.slot = RICH_INPUT_SLOT + document.body.append(editor) + caretIn(editor) + + insertComposerContentsAtCaret(editor, 'read @url:`https://example.dev/a` now') + + expect(editor.querySelectorAll('[data-ref-kind="url"]').length).toBe(1) + expect(composerPlainText(editor)).toBe('read @url:`https://example.dev/a` now') + + editor.remove() + }) +}) + +describe('replaceBeforeCaret', () => { + it('swaps the token before the caret and leaves the caret after the insert', () => { + const editor = document.createElement('div') + editor.dataset.slot = RICH_INPUT_SLOT + editor.textContent = 'see foo' + document.body.append(editor) + + const text = editor.firstChild! + const selection = window.getSelection()! + const range = document.createRange() + + range.setStart(text, 7) + range.collapse(true) + selection.removeAllRanges() + selection.addRange(range) + + const fragment = document.createDocumentFragment() + fragment.append(refChipElement('file', '`src/foo.ts`'), document.createTextNode(' ')) + + expect(replaceBeforeCaret(editor, 3, fragment)).toBe(true) + expect(composerPlainText(editor)).toBe('see @file:`src/foo.ts` ') + expect(selection.getRangeAt(0).collapsed).toBe(true) + + editor.remove() + }) + + it('leaves the editor alone when the caret has no room for the token', () => { + const editor = document.createElement('div') + editor.dataset.slot = RICH_INPUT_SLOT + editor.textContent = 'hi' + document.body.append(editor) + + const selection = window.getSelection()! + const range = document.createRange() + + range.setStart(editor.firstChild!, 2) + range.collapse(true) + selection.removeAllRanges() + selection.addRange(range) + + const fragment = document.createDocumentFragment() + fragment.append(document.createTextNode('x')) + + expect(replaceBeforeCaret(editor, 20, fragment)).toBe(false) + expect(composerPlainText(editor)).toBe('hi') + + editor.remove() + }) }) describe('deleteSelectionInEditor', () => { diff --git a/apps/desktop/src/app/chat/composer/rich-editor.ts b/apps/desktop/src/app/chat/composer/rich-editor.ts index 71491b87496d..7bf770eda17e 100644 --- a/apps/desktop/src/app/chat/composer/rich-editor.ts +++ b/apps/desktop/src/app/chat/composer/rich-editor.ts @@ -11,6 +11,7 @@ import { directiveIconElement, directiveIconSvg, formatRefValue, + refChipLabel, slashChipClass, type SlashChipKind, slashIconElement @@ -34,10 +35,6 @@ export function unquoteRef(raw: string) { return quoted ? raw.slice(1, -1) : raw.replace(/[,.;!?]+$/, '') } -export function refLabel(id: string) { - return id.split(/[\\/]/).filter(Boolean).pop() || id -} - /** Always-quote variant of formatRefValue — chips need a fence even for safe values. */ export function quoteRefValue(value: string) { if (!value.includes('`')) { @@ -59,7 +56,9 @@ export function refChipHtml(kind: string, rawValue: string, displayLabel?: strin const id = unquoteRef(rawValue) const text = `@${kind}:${quoteRefValue(id)}` - return `${directiveIconSvg(kind)}${escapeHtml(displayLabel || refLabel(id))}` + const label = displayLabel || refChipLabel(kind, id) + + return `${directiveIconSvg(kind)}${escapeHtml(label)}` } export function refChipElement(kind: string, rawValue: string, displayLabel?: string) { @@ -69,12 +68,13 @@ export function refChipElement(kind: string, rawValue: string, displayLabel?: st const label = document.createElement('span') chip.contentEditable = 'false' + chip.title = id chip.dataset.refText = text chip.dataset.refId = id chip.dataset.refKind = kind chip.className = DIRECTIVE_CHIP_CLASS label.className = 'truncate' - label.textContent = displayLabel || refLabel(id) + label.textContent = displayLabel || refChipLabel(kind, id) chip.append(directiveIconElement(kind), label) return chip @@ -144,14 +144,15 @@ function composerSelectionRange(editor: HTMLElement) { return { range, selection } } -/** Insert plain text at the caret (replacing any selection). Pastes use this - * instead of `execCommand('insertText')` — Chromium's editing pipeline is - * ~O(n²) on large multiline blobs. */ -export function insertPlainTextAtCaret(editor: HTMLElement, text: string) { +/** Insert text at the caret (replacing any selection), with any `@kind:value` + * directives in it landing as chips. Pastes use this instead of + * `execCommand('insertText')` — Chromium's editing pipeline is ~O(n²) on large + * multiline blobs. */ +export function insertComposerContentsAtCaret(editor: HTMLElement, text: string) { const hit = composerSelectionRange(editor) const fragment = document.createDocumentFragment() - appendTextWithBreaks(fragment, text) + appendComposerContents(fragment, text) const tail = fragment.lastChild @@ -172,6 +173,41 @@ export function insertPlainTextAtCaret(editor: HTMLElement, text: string) { } } +/** Swap the `length` characters immediately before a collapsed caret for + * `fragment`, leaving the caret after it. Returns whether it ran — a caret that + * isn't inside a text node holding the whole token is left alone. */ +export function replaceBeforeCaret(editor: HTMLElement, length: number, fragment: DocumentFragment) { + const hit = composerSelectionRange(editor) + + if (!hit?.range.collapsed) { + return false + } + + const { startContainer, startOffset } = hit.range + + if (startContainer.nodeType !== Node.TEXT_NODE || startOffset < length) { + return false + } + + const range = document.createRange() + const tail = fragment.lastChild + + range.setStart(startContainer, startOffset - length) + range.setEnd(startContainer, startOffset) + range.deleteContents() + range.insertNode(fragment) + + if (tail) { + range.setStartAfter(tail) + } + + range.collapse(true) + hit.selection.removeAllRanges() + hit.selection.addRange(range) + + return true +} + /** Backspace at a collapsed caret immediately after a chip: delete the chip AND * the single trailing space we auto-insert after it, atomically — so removing a * directive never strands an orphaned space (the contenteditable-driven cleanup @@ -296,6 +332,106 @@ export function placeCaretEnd(element: HTMLElement) { selection?.addRange(range) } +/** The caret's offset in `composerPlainText` coordinates, so it can be restored + * after the editor is re-rendered from text (undo/redo). A chip counts as its + * whole `@kind:value` text — the same units the snapshot measures. */ +export function caretOffsetInEditor(editor: HTMLElement): number { + const selection = window.getSelection() + const range = selection?.rangeCount ? selection.getRangeAt(0) : null + + if (!range || !editor.contains(range.commonAncestorContainer)) { + return composerPlainText(editor).length + } + + const before = range.cloneRange() + before.selectNodeContents(editor) + before.setEnd(range.startContainer, range.startOffset) + + // The scratch container must carry the editor's slot marker: composerPlainText + // appends a trailing "\n" to any other block element, which would inflate + // every offset by one and land the restored caret a character late. + const container = document.createElement('div') + container.dataset.slot = RICH_INPUT_SLOT + container.append(before.cloneContents()) + + return composerPlainText(container).length +} + +/** Place the caret `offset` characters into the editor, in the same + * `composerPlainText` coordinates `caretOffsetInEditor` reports. Lands after a + * chip it would otherwise split, since a chip is a single atomic unit. */ +export function placeCaretAtOffset(editor: HTMLElement, offset: number) { + const selection = window.getSelection() + + if (!selection) { + return + } + + let remaining = offset + + const walk = (node: Node): Range | null => { + for (const child of Array.from(node.childNodes)) { + if (child.nodeType === Node.TEXT_NODE) { + const length = (child.textContent || '').length + + if (remaining <= length) { + const range = document.createRange() + range.setStart(child, remaining) + range.collapse(true) + + return range + } + + remaining -= length + + continue + } + + if (child.nodeType !== Node.ELEMENT_NODE) { + continue + } + + const el = child as HTMLElement + + // Chips and
are atomic: consume their serialized length whole. + if (el.dataset.refText || el.tagName === 'BR') { + const length = el.dataset.refText ? el.dataset.refText.length : 1 + + if (remaining < length) { + const range = document.createRange() + range.setStartBefore(el) + range.collapse(true) + + return range + } + + remaining -= length + + continue + } + + const hit = walk(el) + + if (hit) { + return hit + } + } + + return null + } + + const range = walk(editor) + + if (range) { + selection.removeAllRanges() + selection.addRange(range) + + return + } + + placeCaretEnd(editor) +} + /** Nothing but a break / whitespace (recursively) — i.e. no real text or chip. */ function isBlankNode(node: ChildNode | null): boolean { if (!node) { diff --git a/apps/desktop/src/app/chat/composer/scope.tsx b/apps/desktop/src/app/chat/composer/scope.tsx index 67581a39e30d..e7e7aff880ef 100644 --- a/apps/desktop/src/app/chat/composer/scope.tsx +++ b/apps/desktop/src/app/chat/composer/scope.tsx @@ -23,20 +23,18 @@ export interface ComposerScope { /** This scope's "turn parked on user input" edge — gates Esc-to-stop. */ $awaitingInput: ReadableAtom attachments: ComposerAttachmentScope - /** Only the main scope may pop out (the floating composer is a singleton). */ - popoutAllowed: boolean - /** Imperative read of this scope's transcript (input-history browse) — - * never subscribed, so streaming stays out of the composer's renders. */ - readMessages: () => ChatMessage[] + /** This scope's transcript. Read it imperatively (input-history browse) to + * keep streaming out of the composer's renders; subscribe only off-render + * (auto-speak) where the reply edge is the whole point. */ + $messages: ReadableAtom /** Focus-bus routing key (`'main'` | `'tile:'`). */ target: ComposerTarget } export const MAIN_COMPOSER_SCOPE: ComposerScope = { $awaitingInput: $activeSessionAwaitingInput, + $messages, attachments: mainComposerScope, - popoutAllowed: true, - readMessages: () => $messages.get(), target: 'main' } diff --git a/apps/desktop/src/app/chat/composer/status-stack/action-badges.tsx b/apps/desktop/src/app/chat/composer/status-stack/action-badges.tsx new file mode 100644 index 000000000000..9493bff12596 --- /dev/null +++ b/apps/desktop/src/app/chat/composer/status-stack/action-badges.tsx @@ -0,0 +1,78 @@ +import { memo, useState } from 'react' + +import { Codicon } from '@/components/ui/codicon' +import { cn } from '@/lib/utils' +import type { ComposerAction } from '@/store/composer-actions' +import { notifyError } from '@/store/notifications' + +/** + * Floating pill — the treatment the thread's jump/approval button uses for a + * control that sits over scrolling content: full radius, hairline border, the + * shared composer fill behind a blur so thread text never bleeds through. + * Sized against the composer's own control height so a row of pills lines up + * with the chrome it floats above. + * + * NEVER `pointer-events-none`, not even when disabled. The pop-out drag region + * is an `absolute` sibling behind these pills, so a pill that stops taking + * pointer events hands the hit test straight to it — and a dead-looking badge + * becomes a grab handle that floats the composer. + */ +const PILL = cn( + 'inline-flex h-(--composer-control-size) max-w-56 shrink-0 cursor-pointer items-center gap-1.5 rounded-full px-2.5', + 'border border-border/65 bg-(--composer-fill) backdrop-blur-[0.75rem] [-webkit-backdrop-filter:blur(0.75rem)]', + 'text-xs font-normal text-(--ui-text-secondary) transition-colors', + 'hover:bg-(--chrome-action-hover) hover:text-foreground', + 'disabled:cursor-default disabled:opacity-50 disabled:hover:bg-(--composer-fill)', + 'focus-visible:outline-none focus-visible:ring-[0.1875rem] focus-visible:ring-ring/50' +) + +/** + * The micro-action pills. Layout-free on purpose — the composer owns the strip + * (`composerFloatingStrip`), this owns only the pills, so the strip above the + * surface and the `composer.underside` strip below it can't drift apart. + */ +export const ActionBadges = memo(function ActionBadges({ + actions, + sessionId +}: { + actions: ComposerAction[] + sessionId: string +}) { + // A pill can kick off async work (a gateway call, a submit). Track which one + // is in flight so it can spin and lock instead of double-firing. + const [runningId, setRunningId] = useState(null) + + const run = async (action: ComposerAction) => { + if (runningId) { + return + } + + setRunningId(action.id) + + try { + await action.run(sessionId) + } catch (error) { + notifyError(error, action.label) + } finally { + setRunningId(null) + } + } + + return actions.map(action => { + const running = runningId === action.id + const glyph = running ? 'loading' : action.icon + + return ( + + ) + }) +}) diff --git a/apps/desktop/src/app/chat/composer/status-stack/coding-row.tsx b/apps/desktop/src/app/chat/composer/status-stack/coding-row.tsx index aee735e4aea4..14cb89d3ddcd 100644 --- a/apps/desktop/src/app/chat/composer/status-stack/coding-row.tsx +++ b/apps/desktop/src/app/chat/composer/status-stack/coding-row.tsx @@ -3,17 +3,16 @@ import { memo, useEffect, useRef, useState } from 'react' import { WorktreeDialog } from '@/app/chat/sidebar/projects/worktree-dialog' import { StatusRow } from '@/components/chat/status-row' +import { + type ActionItemSpec, + ActionsContextMenu, + ActionsMenu, + type MenuKit, + renderActionItem +} from '@/components/ui/actions-menu' import { Button } from '@/components/ui/button' import { Codicon } from '@/components/ui/codicon' import { DiffCount } from '@/components/ui/diff-count' -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuLabel, - DropdownMenuSeparator, - DropdownMenuTrigger -} from '@/components/ui/dropdown-menu' import type { HermesGitBranch } from '@/global' import { useI18n } from '@/i18n' import { $repoStatus, $repoWorktrees } from '@/store/coding-status' @@ -91,6 +90,7 @@ export const CodingStatusRow = memo(function CodingStatusRow({ const worktreeReq = useStore($newWorktreeRequest) const lastWorktreeReqRef = useRef(worktreeReq) + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) useEffect(() => { if (worktreeReq === lastWorktreeReqRef.current) { return @@ -152,34 +152,87 @@ export const CodingStatusRow = memo(function CodingStatusRow({ // they're the only change (otherwise +/- tells the story). const untrackedOnly = !hasLineDelta && status.untracked > 0 + // The branch actions, rendered identically by the kebab dropdown and the + // row's right-click menu so the two never drift. `onBranchOff` gates the + // whole menu (omitted = remote backend), matching the kebab. + const renderBranchItems = (kit: MenuKit) => { + const branchItems: ActionItemSpec[] = branchTargets.map(target => ({ + key: target.base ?? '__head__', + label: {target.label}, + onSelect: () => startBranch(target.base) + })) + + const worktreeItems: ActionItemSpec[] = otherWorktrees.map(worktree => ({ + key: worktree.path, + label: {worktree.branch}, + onSelect: () => onOpenWorktree?.(worktree.path) + })) + + return ( + <> + {s.newBranch} + {branchItems.map(item => renderActionItem(kit, item))} + {switchTarget && + renderActionItem(kit, { + key: '__switch__', + label: {s.switchTo(switchTarget)}, + onSelect: () => void switchToBranch(switchTarget) + })} + + {s.worktrees} + {worktreeItems.map(item => renderActionItem(kit, item))} + {/* Create a fresh worktree off the current HEAD (the generic "spin up a + worktree here", mirroring the sidebar's + button). */} + {renderActionItem(kit, { + key: '__start__', + label: {p.startWork}, + onSelect: () => startBranch(undefined) + })} + {onConvertBranch && + renderActionItem(kit, { + key: '__convert__', + label: {p.convertBranch}, + onSelect: () => startBranch(undefined) + })} + + ) + } + return ( <> - } - onActivate={onOpen} - > -
- - {branchLabel} - + + } + onActivate={onOpen} + > +
+ + {branchLabel} + - {/* Branch actions kebab — same pattern as the session/worktree rows. - ALWAYS laid out; only its opacity flips on hover/focus/open, so - revealing it never reflows the row (no layout shift). pointer-events - follow opacity so the invisible trigger isn't clickable at rest. */} - {onBranchOff && ( - - + {/* Branch actions kebab — same pattern as the session/worktree rows. + ALWAYS laid out; only its opacity flips on hover/focus/open, so + revealing it never reflows the row (no layout shift). pointer-events + follow opacity so the invisible trigger isn't clickable at rest. */} + {onBranchOff && ( + - - {/* The row sits at the bottom of the screen (above the composer), - so the menu opens upward. */} - - {s.newBranch} - {branchTargets.map(target => ( - startBranch(target.base)}> - {target.label} - - ))} + + )} +
- {switchTarget && ( - void switchToBranch(switchTarget)}> - {s.switchTo(switchTarget)} - - )} - - - {s.worktrees} - {otherWorktrees.map(worktree => ( - onOpenWorktree?.(worktree.path)}> - {worktree.branch} - - ))} - {/* Create a fresh worktree off the current HEAD (the generic - "spin up a worktree here", mirroring the sidebar's + button). */} - startBranch(undefined)}> - {p.startWork} - - {/* Create a fresh worktree off the current HEAD (the generic - "spin up a worktree here", mirroring the sidebar's + button). */} - {onConvertBranch && ( - startBranch(undefined)}> - {p.convertBranch} - - )} - - + {(status.ahead > 0 || status.behind > 0) && ( + + {status.ahead > 0 && ( + + ↑ + {status.ahead} + + )} + {status.behind > 0 && ( + + ↓ + {status.behind} + + )} + )} -
- {(status.ahead > 0 || status.behind > 0) && ( - - {status.ahead > 0 && ( - - ↑ - {status.ahead} - - )} - {status.behind > 0 && ( - - ↓ - {status.behind} - - )} - - )} - - {hasLineDelta ? ( - - ) : untrackedOnly ? ( - - {s.changed(status.untracked)} - - ) : null} -
+ {hasLineDelta ? ( + + ) : untrackedOnly ? ( + + {s.changed(status.untracked)} + + ) : null} + + {resolvedRepoPath && onOpenWorktree && ( ({ + detail, + status, + title, + updatedAt: Date.now() +}) + +function renderStack(sessionId: null | string = SID) { + return render( + + + + + + ) +} + +describe('ComposerStatusStack goal indicator', () => { + beforeEach(() => { + $goalsBySession.set({}) + }) + + afterEach(() => { + cleanup() + $goalsBySession.set({}) + }) + + it('renders nothing when the session has no goal', () => { + const view = renderStack() + + expect(view.container.firstChild).toBeNull() + }) + + it('shows an active goal with its title', () => { + $goalsBySession.set({ [SID]: goal('active') }) + + renderStack() + + expect(screen.getByText('Goal active')).toBeTruthy() + expect(screen.getByText('ship the feature')).toBeTruthy() + }) + + it('labels a paused goal as paused', () => { + $goalsBySession.set({ [SID]: goal('paused') }) + + renderStack() + + expect(screen.getByText('Goal paused')).toBeTruthy() + expect(screen.getByText('ship the feature')).toBeTruthy() + }) + + it('shows the continuation detail line for an active goal', () => { + $goalsBySession.set({ [SID]: goal('active', 'ship it', 'Continuing toward goal (3/20)') }) + + renderStack() + + expect(screen.getByText('Continuing toward goal (3/20)')).toBeTruthy() + }) + + it('scopes the indicator to the goal-owning session', () => { + $goalsBySession.set({ 'other-session': goal('active') }) + + const view = renderStack() + + expect(view.container.firstChild).toBeNull() + }) +}) diff --git a/apps/desktop/src/app/chat/composer/status-stack/index.tsx b/apps/desktop/src/app/chat/composer/status-stack/index.tsx index 739080be8b85..6d526a8dcf65 100644 --- a/apps/desktop/src/app/chat/composer/status-stack/index.tsx +++ b/apps/desktop/src/app/chat/composer/status-stack/index.tsx @@ -3,16 +3,19 @@ import { type ReactNode, useEffect, useLayoutEffect, useMemo, useRef } from 'rea import { useNavigate } from 'react-router-dom' import { blurComposerInput } from '@/app/chat/composer/focus' +import { chatSurfaceRoot, clearSurfaceVar, setSurfaceVar, STATUS_STACK_VAR } from '@/app/chat/surface-vars' import { AGENTS_ROUTE } from '@/app/routes' import { BillingBanner } from '@/components/billing-banner' -import { composerDockCard } from '@/components/chat/composer-dock' +import { composerDockCard, composerFloatingStrip } from '@/components/chat/composer-dock' import { StatusSection } from '@/components/chat/status-section' import { Button } from '@/components/ui/button' import { Codicon } from '@/components/ui/codicon' import { Tip, TipKeybindLabel } from '@/components/ui/tooltip' import { type Translations, useI18n } from '@/i18n' +import { useSessionSlice } from '@/lib/use-session-slice' import { cn } from '@/lib/utils' import { $billingBlock } from '@/store/billing-block' +import { $composerActionsBySession } from '@/store/composer-actions' import { $statusItemsBySession, type ComposerStatusItem, @@ -22,10 +25,12 @@ import { type StatusGroup, stopBackgroundProcess } from '@/store/composer-status' +import { refreshSessionGoal } from '@/store/goals' import { $previewStatusBySession, dismissPreviewArtifact } from '@/store/preview-status' import { $threadScrolledUp } from '@/store/thread-scroll' import { openSessionInNewWindow } from '@/store/windows' +import { ActionBadges } from './action-badges' import { PreviewStatusRow } from './preview-row' import { StatusItemRow } from './status-row' @@ -41,12 +46,25 @@ const isLocalhostPreview = (target: string): boolean => /\b(?:localhost|127\.0\. // Real codicons per group (no sparkles): a checklist for todos, the agent glyph // for subagents, a background process glyph for background tasks. const GROUP_ICON: Record = { + goal: 'target', todo: 'checklist', subagent: 'agent', background: 'server-process' } const groupLabel = (group: StatusGroup, s: Translations['statusStack']) => { + if (group.type === 'goal') { + const status = group.items[0]?.goalStatus + + return status === 'paused' + ? s.goalPaused + : status === 'waiting' + ? s.goalWaiting + : status === 'done' + ? s.goalDone + : s.goalActive + } + if (group.type === 'todo') { return s.todos(group.items.filter(i => i.todoStatus === 'completed').length, group.items.length) } @@ -69,23 +87,26 @@ interface ComposerStatusStackProps { export function ComposerStatusStack({ queue, sessionId }: ComposerStatusStackProps) { const { t } = useI18n() const navigate = useNavigate() - const itemsBySession = useStore($statusItemsBySession) - const previewsBySession = useStore($previewStatusBySession) + // Subscribe to THIS session's slice only. Both maps churn on other + // sessions' activity (subagent ticks, background polls, preview updates in + // any tile); a whole-map `useStore` re-rendered every mounted stack — one + // per open tile — on all of it. The per-key arrays are referentially stable + // across unrelated writes, so the slice hook bails out unless OUR session's + // items actually changed. + const items = useSessionSlice($statusItemsBySession, sessionId) + const previews = useSessionSlice($previewStatusBySession, sessionId) + const actions = useSessionSlice($composerActionsBySession, sessionId) const scrolledUp = useStore($threadScrolledUp) const billing = useStore($billingBlock) - const groups = useMemo( - () => groupStatusItems(sessionId ? (itemsBySession[sessionId] ?? []) : []), - [itemsBySession, sessionId] - ) - - const previews = sessionId ? (previewsBySession[sessionId] ?? []) : [] + const groups = useMemo(() => groupStatusItems(items), [items]) // Seed from the registry on session open; event-driven refreshes (terminal / // process tool completions) live in use-message-stream. useEffect(() => { if (sessionId) { void refreshBackgroundProcesses(sessionId) + void refreshSessionGoal(sessionId) } }, [sessionId]) @@ -133,6 +154,10 @@ export function ComposerStatusStack({ queue, sessionId }: ComposerStatusStackPro sections.push({ key: 'billing', node: }) } + // Micro actions ride at the top of the stack — the one block you press + // rather than read. Rendered OUTSIDE the card (see `actionStrip`) so the + // pills float; a blocked account still gets the billing wall above them. + for (const group of groups) { sections.push({ key: group.type, @@ -153,7 +178,7 @@ export function ComposerStatusStack({ queue, sessionId }: ComposerStatusStackPro
) : undefined } - defaultCollapsed={group.type !== 'todo'} + defaultCollapsed={group.type !== 'todo' && group.type !== 'goal'} icon={} label={groupLabel(group, t.statusStack)} > @@ -190,23 +215,34 @@ export function ComposerStatusStack({ queue, sessionId }: ComposerStatusStackPro sections.push({ key: 'queue', node: queue }) } - const visible = sections.length > 0 + // Micro actions are the TOP-MOST thing in the whole overlay lane — above the + // status card, above the billing wall, above everything. They're the only + // rows up here you press instead of read, so nothing may ever stack on top + // of them. Rendered outside the card (below) so the pills float. + const actionStrip = actions.length > 0 && sessionId ? : null + + const visible = sections.length > 0 || Boolean(actionStrip) const stackRef = useRef(null) // The stack is out of flow (overlays the thread), so the composer's measured // height never sees it. Publish our own measured height — bucketed like the // composer's, to avoid style invalidation churn — so the thread's // last-message clearance can add it and the stack never hides messages. + // Scoped to THIS surface: tiles render their own stack (see surface-vars.ts). useLayoutEffect(() => { - const root = document.documentElement const el = stackRef.current if (!visible || !el) { - root.style.removeProperty('--status-stack-measured-height') - return } + // Resolve the owning surface NOW, while the node is attached. The cleanup + // below runs after the stack collapsed and React removed the div, so + // closest() from the detached node misses [data-chat-surface] and would + // clear the document root instead — leaving the stale height on the + // surface, which keeps inflating the thread's bottom clearance until the + // next publish. + const root = chatSurfaceRoot(el) let last = -1 const sync = () => { @@ -214,7 +250,7 @@ export function ComposerStatusStack({ queue, sessionId }: ComposerStatusStackPro if (bucket !== last) { last = bucket - root.style.setProperty('--status-stack-measured-height', `${bucket}px`) + setSurfaceVar(el, STATUS_STACK_VAR, `${bucket}px`) } } @@ -224,7 +260,7 @@ export function ComposerStatusStack({ queue, sessionId }: ComposerStatusStackPro return () => { observer.disconnect() - root.style.removeProperty('--status-stack-measured-height') + clearSurfaceVar(root, STATUS_STACK_VAR) } }, [visible]) @@ -237,29 +273,52 @@ export function ComposerStatusStack({ queue, sessionId }: ComposerStatusStackPro // Sits in the overlay lane above the composer. The composer root has pt-2 // before the actual surface; translate by that amount so the stack returns // to its original attachment point without intruding into the repo strip. - className="absolute inset-x-0 bottom-full z-3 max-h-[40vh] translate-y-2 overflow-y-auto" + // pl matches the surface's own left edge: `inset-x-0` resolves against the + // root's PADDING box, while the surface and the underside strip sit in its + // CONTENT box, so without it the lane hangs 5px further left than both. + className="absolute inset-x-0 bottom-full z-3 flex max-h-[40vh] flex-col translate-y-2 pl-[0.3125rem]" onPointerDownCapture={() => blurComposerInput()} ref={stackRef} > - {/* The card paints the shared --composer-fill (rest / scrolled / focused - all match the composer surface by construction); on scroll we only - ghost the CONTENT — element opacity on the card would kill the blur. - Rounded top, square bottom; the bottom border is TRANSPARENT — the - composer surface's visible top border (which sits at a higher z) is the - single shared seam, so the two read as one fused capsule. */} -
+ {actionStrip} +
+ )} + {/* Everything else scrolls under them. */} +
+ {/* The card paints the shared --composer-fill (rest / scrolled / focused + all match the composer surface by construction); on scroll we only + ghost the CONTENT — element opacity on the card would kill the blur. + Rounded top, square bottom; the bottom border is TRANSPARENT — the + composer surface's visible top border (which sits at a higher z) is the + single shared seam, so the two read as one fused capsule. */} + {sections.length > 0 && ( +
+ {sections.map(section => ( +
{section.node}
+ ))} +
)} - > - {sections.map(section => ( -
{section.node}
- ))}
) diff --git a/apps/desktop/src/app/chat/composer/status-stack/preview-row.tsx b/apps/desktop/src/app/chat/composer/status-stack/preview-row.tsx index cf721d2ae936..dc40c31de2e2 100644 --- a/apps/desktop/src/app/chat/composer/status-stack/preview-row.tsx +++ b/apps/desktop/src/app/chat/composer/status-stack/preview-row.tsx @@ -11,7 +11,7 @@ import { cn } from '@/lib/utils' import { PREVIEW_PANE_ID } from '@/store/layout' import { notifyError } from '@/store/notifications' import { $paneOpen } from '@/store/panes' -import { $previewTarget, dismissPreviewTarget, setCurrentSessionPreviewTarget } from '@/store/preview' +import { $previewTabSources, closePreviewForSource, openPreview } from '@/store/preview' import { type PreviewArtifact } from '@/store/preview-status' interface PreviewStatusRowProps { @@ -22,10 +22,10 @@ interface PreviewStatusRowProps { /** One detected artifact, single line, always visible: filename + open + close. */ export const PreviewStatusRow = memo(function PreviewStatusRow({ item, onDismiss }: PreviewStatusRowProps) { const { t } = useI18n() - const activePreview = useStore($previewTarget) + const openSources = useStore($previewTabSources) const previewPaneOpen = useStore($paneOpen(PREVIEW_PANE_ID)) const [opening, setOpening] = useState(false) - const isOpen = activePreview?.source === item.target && previewPaneOpen + const isOpen = openSources.includes(item.target) && previewPaneOpen const resolveTarget = async () => { const target = await normalizeOrLocalPreviewTarget(item.target, item.cwd || undefined) @@ -43,7 +43,7 @@ export const PreviewStatusRow = memo(function PreviewStatusRow({ item, onDismiss } if (isOpen) { - dismissPreviewTarget() + closePreviewForSource(item.target) return } @@ -51,7 +51,7 @@ export const PreviewStatusRow = memo(function PreviewStatusRow({ item, onDismiss setOpening(true) try { - setCurrentSessionPreviewTarget(await resolveTarget(), 'tool-result', item.target) + openPreview(await resolveTarget(), 'tool-result') } catch (error) { notifyError(error, t.preview.unavailable) } finally { diff --git a/apps/desktop/src/app/chat/composer/status-stack/status-row.tsx b/apps/desktop/src/app/chat/composer/status-stack/status-row.tsx index 6857be46ccfe..2c43743c40c5 100644 --- a/apps/desktop/src/app/chat/composer/status-stack/status-row.tsx +++ b/apps/desktop/src/app/chat/composer/status-stack/status-row.tsx @@ -25,6 +25,24 @@ const TODO_GLYPHS: Record, { icon // Left slot: braille spinner while running, otherwise a small status dot // (green = done, red = failed) so the slot is always filled and rows align. function leadingGlyph(item: ComposerStatusItem, s: Translations['statusStack']): ReactNode { + if (item.type === 'goal') { + if (item.goalStatus === 'paused') { + return + } + + if (item.goalStatus === 'done') { + return + } + + return ( + + ) + } + if (item.todoStatus === 'pending') { return ( )} + {item.type === 'goal' && item.currentTool && ( + + {item.currentTool} + + )} {failed && typeof item.exitCode === 'number' && item.exitCode !== 0 && ( {s.exit(item.exitCode)} diff --git a/apps/desktop/src/app/chat/composer/status-stack/surface-var-lifecycle.test.tsx b/apps/desktop/src/app/chat/composer/status-stack/surface-var-lifecycle.test.tsx new file mode 100644 index 000000000000..a01563aedc34 --- /dev/null +++ b/apps/desktop/src/app/chat/composer/status-stack/surface-var-lifecycle.test.tsx @@ -0,0 +1,94 @@ +import { act, cleanup, render } from '@testing-library/react' +import { MemoryRouter } from 'react-router-dom' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { STATUS_STACK_VAR } from '@/app/chat/surface-vars' +import { I18nProvider } from '@/i18n' +import { $goalsBySession, type SessionGoal } from '@/store/goals' + +import { ComposerStatusStack } from './index' + +// The stack measures itself into a surface var — jsdom has no ResizeObserver. +class ResizeObserverStub { + observe() {} + unobserve() {} + disconnect() {} +} + +vi.stubGlobal('ResizeObserver', ResizeObserverStub) + +const SID = 'sess-height-1' + +const goal = (): SessionGoal => ({ status: 'active', title: 'ship the feature', updatedAt: Date.now() }) + +/** + * Regression: when the stack collapses (its last item finishes), React removes + * the stack div BEFORE the layout-effect cleanup runs. Resolving the surface + * from the ref at cleanup time then walks a DETACHED node, misses + * [data-chat-surface], and clears the document root instead — the stale height + * stays on the surface and keeps inflating the thread's bottom clearance + * (`--thread-last-message-clearance`) until the next publish. The effect must + * capture its surface root while the node is still attached. + */ +describe('ComposerStatusStack surface-var lifecycle', () => { + beforeEach(() => { + $goalsBySession.set({}) + }) + + afterEach(() => { + cleanup() + $goalsBySession.set({}) + document.documentElement.style.removeProperty(STATUS_STACK_VAR) + }) + + function renderOnSurface() { + const surface = document.createElement('div') + surface.setAttribute('data-chat-surface', '') + document.body.append(surface) + + const view = render( + + + + + , + { container: surface } + ) + + return { surface, view } + } + + it('publishes its measured height onto the owning surface while visible', () => { + $goalsBySession.set({ [SID]: goal() }) + + const { surface } = renderOnSurface() + + // jsdom measures 0 — the value is irrelevant, the target element is not. + expect(surface.style.getPropertyValue(STATUS_STACK_VAR)).toBe('0px') + expect(document.documentElement.style.getPropertyValue(STATUS_STACK_VAR)).toBe('') + }) + + it('clears the surface var when the stack collapses to nothing', () => { + $goalsBySession.set({ [SID]: goal() }) + + const { surface } = renderOnSurface() + expect(surface.style.getPropertyValue(STATUS_STACK_VAR)).toBe('0px') + + // Last status item goes away → the component renders null and React + // detaches the stack div before the cleanup runs. + act(() => $goalsBySession.set({})) + + expect(surface.style.getPropertyValue(STATUS_STACK_VAR)).toBe('') + }) + + it('clears the surface var on unmount', () => { + $goalsBySession.set({ [SID]: goal() }) + + const { surface, view } = renderOnSurface() + expect(surface.style.getPropertyValue(STATUS_STACK_VAR)).toBe('0px') + + view.unmount() + + expect(surface.style.getPropertyValue(STATUS_STACK_VAR)).toBe('') + }) +}) diff --git a/apps/desktop/src/app/chat/composer/text-utils.test.ts b/apps/desktop/src/app/chat/composer/text-utils.test.ts index 6c6a20780f64..2a350593f45c 100644 --- a/apps/desktop/src/app/chat/composer/text-utils.test.ts +++ b/apps/desktop/src/app/chat/composer/text-utils.test.ts @@ -44,14 +44,58 @@ describe('detectTrigger', () => { it('does not treat file-style paths as slash triggers', () => { expect(detectTrigger('src/foo/bar')).toBeNull() expect(detectTrigger('/path/to/file')).toBeNull() + // Mid-message paths stay excluded too: a path keeps going past the command + // token, so the trailing-anchored inline trigger never matches it. + expect(detectTrigger('check src/foo/bar')).toBeNull() + expect(detectTrigger('look at /usr/local/bin')).toBeNull() + expect(detectTrigger('and/or')).toBeNull() }) - it('does not trigger slash popover mid-message', () => { - expect(detectTrigger('hello /')).toBeNull() - expect(detectTrigger('hello /skill')).toBeNull() + it('keeps the at-mention live while walking into subfolders', () => { + // A `/` inside the query is path navigation, not the end of the token — + // the popover has to stay open so the next directory level can load. + expect(detectTrigger('@./')).toEqual({ kind: '@', query: './', tokenLength: 3 }) + expect(detectTrigger('@./src')).toEqual({ kind: '@', query: './src', tokenLength: 6 }) + expect(detectTrigger('@~/Desktop/')).toEqual({ kind: '@', query: '~/Desktop/', tokenLength: 11 }) + expect(detectTrigger('@/usr/local')).toEqual({ kind: '@', query: '/usr/local', tokenLength: 11 }) + expect(detectTrigger('@apps/desktop/src')).toEqual({ + kind: '@', + query: 'apps/desktop/src', + tokenLength: 17 + }) + }) + + it('keeps the at-mention live for a typed ref kind with a path', () => { + expect(detectTrigger('@file:src/main.tsx')).toEqual({ + kind: '@', + query: 'file:src/main.tsx', + tokenLength: 18 + }) + expect(detectTrigger('@folder:apps/')).toEqual({ kind: '@', query: 'folder:apps/', tokenLength: 13 }) + }) + + it('still ends the at-mention token at whitespace', () => { + // The token is whitespace-delimited; a path doesn't change that. + expect(detectTrigger('@./src and more')).toBeNull() + expect(detectTrigger('look at @apps/desktop')).toEqual({ + kind: '@', + query: 'apps/desktop', + tokenLength: 13 + }) + }) + + it('treats a mid-message slash as an inline reference', () => { + // Skills have to be reachable anywhere in a prompt, not just at position 0. + expect(detectTrigger('hello /')).toEqual({ kind: '/', inline: true, query: '', tokenLength: 1 }) + expect(detectTrigger('hello /clean')).toEqual({ kind: '/', inline: true, query: 'clean', tokenLength: 6 }) + expect(detectTrigger('text\n/skill')).toEqual({ kind: '/', inline: true, query: 'skill', tokenLength: 6 }) + }) + + it('does not carry arg completion into an inline slash reference', () => { + // Only a position-0 slash is a real invocation, so `/personality alic` + // mid-message is prose — the trigger ends at the command token. expect(detectTrigger('hello there /personality alic')).toBeNull() - expect(detectTrigger('text\n/skill')).toBeNull() - expect(detectTrigger('multi word message /')).toBeNull() + expect(detectTrigger('run /tools enable foo')).toBeNull() }) it('still anchors at-mention triggers strictly at the token edge', () => { diff --git a/apps/desktop/src/app/chat/composer/text-utils.ts b/apps/desktop/src/app/chat/composer/text-utils.ts index b9b6adc07f1e..bf91f1db6a44 100644 --- a/apps/desktop/src/app/chat/composer/text-utils.ts +++ b/apps/desktop/src/app/chat/composer/text-utils.ts @@ -1,22 +1,44 @@ import { DATA_IMAGE_URL_RE, dataUrlToBlob } from '@/lib/embedded-images' export interface TriggerState { + /** True for a `/` typed mid-message — an inline skill/command reference in + * prose rather than a command invocation. Arg completion doesn't apply. */ + inline?: boolean kind: '@' | '/' query: string tokenLength: number } // `@` triggers stop at the first whitespace — `@file:path` and `@diff` are -// single tokens. `/` triggers keep going so the popover stays live while the -// user types args (`/personality alic` → arg completer suggests `alice`). -// Restricting the slash command name to `[a-zA-Z][\w-]*` avoids matching file -// paths like `src/foo/bar`. +// single tokens, and a path is part of that token: `@./src/`, `@~/Desktop/`, +// and `@file:src/foo` all have to keep the popover live while the user walks +// into subdirectories. Excluding `/` from the query class would end the token +// at the first separator, which is exactly the "can't browse into a folder" +// bug. Restricting the slash command name to `[a-zA-Z][\w-]*` avoids +// matching file paths like `src/foo/bar`. // -// Slash commands only execute at the beginning of a message, so the `/` -// trigger is anchored strictly at position 0 — not after whitespace — to -// avoid opening the popover mid-message (e.g. `hello /`). -const AT_TRIGGER_RE = /(?:^|[\s])(@)([^\s@/]*)$/ -const SLASH_TRIGGER_RE = /^(\/)((?:[a-zA-Z][\w-]*(?:\s+\S*)*)?)$/ +// `/` triggers fire in two shapes, because a slash means two different things +// depending on where it sits: +// +// - At position 0 it's a COMMAND invocation the app executes (SLASH_COMMAND_RE +// is `^`-anchored, and so is the backend's). The popover stays live past the +// command name so arg completion works (`/personality alic` → `alice`). +// - After whitespace it's an inline REFERENCE the user is dropping into prose +// ("clean this up with /clean"). The text submits as an ordinary message, so +// there are no args to complete — the trigger is a single token that ends at +// the next space, exactly like `@`. +// +// Only the FIRST slash can be an invocation, so the inline shape is tested +// first: the command regex's argument tail (`(?:\s+\S*)*`) happily swallows a +// later `/skill` as if it were an argument, which killed completion for every +// slash after a leading command (`/work /cle` → nothing). +// +// The inline shape is what makes skills reachable anywhere in a prompt. Both +// shapes need the trailing `$`: detection runs against the text BEFORE the +// caret, so the match must end where the user is typing. +const AT_TRIGGER_RE = /(?:^|[\s])(@)([^\s@]*)$/ +const SLASH_COMMAND_TRIGGER_RE = /^(\/)((?:[a-zA-Z][\w-]*(?:\s+\S*)*)?)$/ +const SLASH_INLINE_TRIGGER_RE = /[\s](\/)([a-zA-Z][\w-]*)?$/ /** Stable key for paste dedupe — `items` and `files` often mirror the same image as different objects. */ export function blobDedupeKey(blob: Blob): string { @@ -107,10 +129,22 @@ export function textBeforeCaret(editor: HTMLDivElement): string | null { } export function detectTrigger(textBefore: string): TriggerState | null { - const slash = SLASH_TRIGGER_RE.exec(textBefore) + // An inline `/skill` is a reference dropped into prose, so it carries no args + // and the whole match is the token the chip replaces. Checked before the + // anchored command shape so a second slash isn't mistaken for the first + // command's argument. + const inline = SLASH_INLINE_TRIGGER_RE.exec(textBefore) - if (slash) { - return { kind: '/', query: slash[2], tokenLength: 1 + slash[2].length } + if (inline) { + const query = inline[2] ?? '' + + return { inline: true, kind: '/', query, tokenLength: 1 + query.length } + } + + const command = SLASH_COMMAND_TRIGGER_RE.exec(textBefore) + + if (command) { + return { kind: '/', query: command[2], tokenLength: 1 + command[2].length } } const at = AT_TRIGGER_RE.exec(textBefore) diff --git a/apps/desktop/src/app/chat/composer/undo-history.test.ts b/apps/desktop/src/app/chat/composer/undo-history.test.ts new file mode 100644 index 000000000000..5ce477a8020e --- /dev/null +++ b/apps/desktop/src/app/chat/composer/undo-history.test.ts @@ -0,0 +1,245 @@ +import { beforeEach, describe, expect, it } from 'vitest' + +import { + caretOffsetInEditor, + composerPlainText, + placeCaretAtOffset, + refChipElement, + renderComposerContents, + RICH_INPUT_SLOT +} from './rich-editor' +import { createComposerUndoHistory, isRedoShortcut, isUndoShortcut } from './undo-history' + +const key = (over: Partial = {}) => + ({ altKey: false, ctrlKey: false, key: 'z', metaKey: false, shiftKey: false, ...over }) as KeyboardEvent + +describe('undo/redo shortcut recognition', () => { + it('claims Cmd+Z and Ctrl+Z as undo, but not with Shift or Alt', () => { + expect(isUndoShortcut(key({ metaKey: true }))).toBe(true) + expect(isUndoShortcut(key({ ctrlKey: true }))).toBe(true) + expect(isUndoShortcut(key({ metaKey: true, shiftKey: true }))).toBe(false) + expect(isUndoShortcut(key({ altKey: true, metaKey: true }))).toBe(false) + expect(isUndoShortcut(key({ key: 'a', metaKey: true }))).toBe(false) + expect(isUndoShortcut(key())).toBe(false) + }) + + it('claims Cmd+Shift+Z everywhere and Ctrl+Y as redo', () => { + expect(isRedoShortcut(key({ metaKey: true, shiftKey: true }))).toBe(true) + expect(isRedoShortcut(key({ ctrlKey: true, shiftKey: true }))).toBe(true) + expect(isRedoShortcut(key({ ctrlKey: true, key: 'y' }))).toBe(true) + expect(isRedoShortcut(key({ metaKey: true }))).toBe(false) + expect(isRedoShortcut(key({ altKey: true, ctrlKey: true, key: 'y' }))).toBe(false) + }) + + it('never treats one keystroke as both undo and redo', () => { + const chords = [ + key({ metaKey: true }), + key({ ctrlKey: true }), + key({ metaKey: true, shiftKey: true }), + key({ ctrlKey: true, shiftKey: true }), + key({ ctrlKey: true, key: 'y' }) + ] + + for (const chord of chords) { + expect(isUndoShortcut(chord) && isRedoShortcut(chord)).toBe(false) + } + }) +}) + +describe('composer undo history', () => { + const snap = (text: string, caret = text.length) => ({ caret, text }) + + it('steps back through discrete edits, newest first', () => { + const history = createComposerUndoHistory() + + history.record(snap('')) + history.record(snap('a')) + history.record(snap('ab')) + + expect(history.undo(snap('abc'))?.text).toBe('ab') + expect(history.undo(snap('ab'))?.text).toBe('a') + expect(history.undo(snap('a'))?.text).toBe('') + expect(history.undo(snap(''))).toBeNull() + }) + + it('redoes back to the state undo left, and stops at the newest', () => { + const history = createComposerUndoHistory() + + history.record(snap('before')) + + const undone = history.undo(snap('before + pasted')) + + expect(undone?.text).toBe('before') + expect(history.redo(snap('before'))?.text).toBe('before + pasted') + expect(history.redo(snap('before + pasted'))).toBeNull() + }) + + it('restores the caret along with the text', () => { + const history = createComposerUndoHistory() + + history.record({ caret: 3, text: 'hello world' }) + + expect(history.undo({ caret: 0, text: 'changed' })).toEqual({ caret: 3, text: 'hello world' }) + }) + + it('collapses a run of typing into one entry, so undo steps back by a burst', () => { + let now = 1_000 + const history = createComposerUndoHistory(200, () => now) + + history.record(snap(''), { coalesce: true }) + now += 50 + history.record(snap('h'), { coalesce: true }) + now += 50 + history.record(snap('he'), { coalesce: true }) + + // One burst → one entry, back to the state before the burst started. + expect(history.undo(snap('hel'))?.text).toBe('') + expect(history.undo(snap(''))).toBeNull() + }) + + it('starts a new entry once the typing pause exceeds the coalesce window', () => { + let now = 1_000 + const history = createComposerUndoHistory(200, () => now) + + history.record(snap(''), { coalesce: true }) + now += 5_000 + history.record(snap('word one'), { coalesce: true }) + + expect(history.undo(snap('word one two'))?.text).toBe('word one') + expect(history.undo(snap('word one'))?.text).toBe('') + }) + + it('does not coalesce a paste into the typing burst that preceded it', () => { + let now = 1_000 + const history = createComposerUndoHistory(200, () => now) + + history.record(snap(''), { coalesce: true }) + now += 20 + // A paste is a discrete edit — no coalesce flag. + history.record(snap('typed ')) + + expect(history.undo(snap('typed PASTED'))?.text).toBe('typed ') + expect(history.undo(snap('typed '))?.text).toBe('') + }) + + it('drops the redo stack once a new edit lands', () => { + const history = createComposerUndoHistory() + + history.record(snap('one')) + history.undo(snap('one two')) + history.record(snap('one')) + + expect(history.redo(snap('one three'))).toBeNull() + }) + + it('ignores a no-op edit so undo never looks stuck for a press', () => { + const history = createComposerUndoHistory() + + history.record(snap('same')) + history.record(snap('same')) + + expect(history.undo(snap('same'))?.text).toBe('same') + expect(history.undo(snap('same'))).toBeNull() + }) + + it('bounds the stack, discarding the oldest entries', () => { + const history = createComposerUndoHistory(3) + + for (const text of ['a', 'b', 'c', 'd', 'e']) { + history.record(snap(text)) + } + + expect(history.undo(snap('f'))?.text).toBe('e') + expect(history.undo(snap('e'))?.text).toBe('d') + expect(history.undo(snap('d'))?.text).toBe('c') + expect(history.undo(snap('c'))).toBeNull() + }) + + it('reset clears both directions', () => { + const history = createComposerUndoHistory() + + history.record(snap('a')) + history.undo(snap('ab')) + history.reset() + + expect(history.undo(snap('ab'))).toBeNull() + expect(history.redo(snap('ab'))).toBeNull() + }) +}) + +describe('caret offsets in composerPlainText coordinates', () => { + let editor: HTMLDivElement + + beforeEach(() => { + editor = document.createElement('div') + editor.dataset.slot = RICH_INPUT_SLOT + document.body.append(editor) + }) + + const caretAfter = (node: Node, offset: number) => { + const range = document.createRange() + const selection = window.getSelection()! + range.setStart(node, offset) + range.collapse(true) + selection.removeAllRanges() + selection.addRange(range) + } + + it('round-trips a caret in plain text', () => { + renderComposerContents(editor, 'hello world') + placeCaretAtOffset(editor, 5) + + expect(caretOffsetInEditor(editor)).toBe(5) + }) + + it('counts a chip as its whole @kind:value text', () => { + editor.append( + document.createTextNode('see '), + refChipElement('file', '`src/a.ts`'), + document.createTextNode(' now') + ) + + const chipText = '@file:`src/a.ts`' + // Caret at the very end = everything before it. + placeCaretAtOffset(editor, composerPlainText(editor).length) + + expect(caretOffsetInEditor(editor)).toBe(4 + chipText.length + 4) + }) + + it('lands the caret before a chip rather than splitting it', () => { + editor.append(document.createTextNode('a '), refChipElement('file', '`x.ts`')) + + // An offset that falls midway through the chip's serialized text. + placeCaretAtOffset(editor, 2 + 3) + + expect(caretOffsetInEditor(editor)).toBe(2) + }) + + it('counts a line break as one character', () => { + renderComposerContents(editor, 'one\ntwo') + placeCaretAtOffset(editor, 5) + + expect(caretOffsetInEditor(editor)).toBe(5) + expect(composerPlainText(editor)).toBe('one\ntwo') + }) + + it('clamps past-the-end offsets to the end instead of throwing', () => { + renderComposerContents(editor, 'short') + placeCaretAtOffset(editor, 999) + + expect(caretOffsetInEditor(editor)).toBe(5) + }) + + it('reports the end when the selection is outside the editor', () => { + renderComposerContents(editor, 'hello') + + const outside = document.createElement('div') + outside.textContent = 'elsewhere' + document.body.append(outside) + caretAfter(outside.firstChild!, 3) + + expect(caretOffsetInEditor(editor)).toBe(5) + + outside.remove() + }) +}) diff --git a/apps/desktop/src/app/chat/composer/undo-history.ts b/apps/desktop/src/app/chat/composer/undo-history.ts new file mode 100644 index 000000000000..62bed71be835 --- /dev/null +++ b/apps/desktop/src/app/chat/composer/undo-history.ts @@ -0,0 +1,126 @@ +/** + * The composer's own undo stack. + * + * The rich editor mutates its DOM through `Range` rather than the browser's + * editing commands — `execCommand('insertText')` is ~O(n²) on large multiline + * blobs and froze the composer for seconds on a big paste (#45812). The cost of + * that bypass is that those mutations never reach Chromium's undo stack, so + * ⌘Z skipped straight past a paste and undid whatever came *before* it, leaving + * the pasted text stranded. + * + * Owning the whole stack is the only coherent fix: a half-owned one interleaves + * our snapshots with Chromium's own typing entries and undoes them out of order. + * So every composer edit — typed or programmatic — records here, and the editor + * intercepts ⌘Z / ⌘⇧Z instead of letting the native command run. + * + * Snapshots are plain text + a caret offset, not DOM: the editor already + * round-trips losslessly through `composerPlainText`/`renderComposerContents`, + * so text is the smallest thing that fully restores a state. + */ + +export interface ComposerSnapshot { + caret: number + text: string +} + +/** Consecutive typing inside this window collapses into one undo entry, so ⌘Z + * steps back by a burst the way a native editor does — not one character. */ +const COALESCE_WINDOW_MS = 600 + +const DEFAULT_LIMIT = 200 + +export interface ComposerUndoHistory { + /** Drop all history and start over from `snapshot`'s state (session swap). */ + reset: () => void + /** Redo one step. `current` is the live state, banked for a subsequent undo. */ + redo: (current: ComposerSnapshot) => ComposerSnapshot | null + /** Bank the state that existed *before* an edit. `coalesce` merges this into + * the previous entry when it lands inside the typing window. */ + record: (previous: ComposerSnapshot, options?: { coalesce?: boolean }) => void + /** Undo one step. `current` is the live state, banked for a subsequent redo. */ + undo: (current: ComposerSnapshot) => ComposerSnapshot | null +} + +export function createComposerUndoHistory( + limit = DEFAULT_LIMIT, + now: () => number = () => Date.now() +): ComposerUndoHistory { + let past: ComposerSnapshot[] = [] + let future: ComposerSnapshot[] = [] + let lastRecordedAt = 0 + let lastWasCoalescable = false + + const record: ComposerUndoHistory['record'] = (previous, options) => { + const coalesce = options?.coalesce ?? false + const at = now() + const merges = coalesce && lastWasCoalescable && past.length > 0 && at - lastRecordedAt < COALESCE_WINDOW_MS + + lastRecordedAt = at + lastWasCoalescable = coalesce + // A fresh edit invalidates anything the user had redone past. + future = [] + + // Merging keeps the OLDER snapshot — the entry already holds the state from + // the start of the burst, which is what ⌘Z should step back to. + if (merges) { + return + } + + // A no-op edit (same text) would make ⌘Z look broken for one press. + if (past[past.length - 1]?.text === previous.text) { + return + } + + past.push(previous) + + if (past.length > limit) { + past = past.slice(past.length - limit) + } + } + + const step = (from: ComposerSnapshot[], to: ComposerSnapshot[], current: ComposerSnapshot) => { + const next = from.pop() + + if (!next) { + return null + } + + to.push(current) + // Any traversal ends the typing burst, so the next keystroke opens a new entry. + lastWasCoalescable = false + + return next + } + + return { + record, + redo: current => step(future, past, current), + reset: () => { + past = [] + future = [] + lastRecordedAt = 0 + lastWasCoalescable = false + }, + undo: current => step(past, future, current) + } +} + +/** True for the keystroke that means "undo" (⌘Z / Ctrl+Z, without Shift). */ +export function isUndoShortcut(event: Pick) { + return (event.metaKey || event.ctrlKey) && !event.altKey && !event.shiftKey && event.key.toLowerCase() === 'z' +} + +/** True for "redo" — ⌘⇧Z everywhere, plus Ctrl+Y on Windows/Linux. */ +export function isRedoShortcut(event: Pick) { + if (event.altKey) { + return false + } + + const key = event.key.toLowerCase() + + if ((event.metaKey || event.ctrlKey) && event.shiftKey && key === 'z') { + return true + } + + return event.ctrlKey && !event.metaKey && !event.shiftKey && key === 'y' +} diff --git a/apps/desktop/src/app/chat/composer/url-refs.test.ts b/apps/desktop/src/app/chat/composer/url-refs.test.ts new file mode 100644 index 000000000000..febbd533ce43 --- /dev/null +++ b/apps/desktop/src/app/chat/composer/url-refs.test.ts @@ -0,0 +1,98 @@ +import type { KeyboardEvent } from 'react' +import { describe, expect, it } from 'vitest' + +import { composerPlainText, RICH_INPUT_SLOT } from './rich-editor' +import { chipTypedUrlOnSpace, linkifyUrls } from './url-refs' + +/** An editor holding `text` with a collapsed caret at `caret`, plus the space + * keydown the composer would hand `chipTypedUrlOnSpace`. */ +const spaceOn = (text: string, caret: number) => { + const editor = document.createElement('div') + editor.dataset.slot = RICH_INPUT_SLOT + editor.textContent = text + document.body.append(editor) + + const selection = window.getSelection()! + const range = document.createRange() + + range.setStart(editor.firstChild!, caret) + range.collapse(true) + selection.removeAllRanges() + selection.addRange(range) + + return { editor, event: { currentTarget: editor, key: ' ' } as KeyboardEvent } +} + +describe('linkifyUrls', () => { + it('rewrites a bare link as a url directive', () => { + expect(linkifyUrls('https://example.dev/a/b')).toBe('@url:`https://example.dev/a/b`') + }) + + it('keeps the link in place mid-sentence and leaves its punctuation behind', () => { + expect(linkifyUrls('read https://example.dev/a. then stop')).toBe('read @url:`https://example.dev/a`. then stop') + }) + + it('keeps balanced parens but drops the one that closed the sentence', () => { + expect(linkifyUrls('(see https://en.wikipedia.org/wiki/A_(b))')).toBe( + '(see @url:`https://en.wikipedia.org/wiki/A_(b)`)' + ) + }) + + it('rewrites every link in a multi-link paste', () => { + expect(linkifyUrls('http://a.dev and https://b.dev')).toBe('@url:`http://a.dev` and @url:`https://b.dev`') + }) + + it('leaves a link that is already a directive alone', () => { + expect(linkifyUrls('@url:`https://example.dev`')).toBe('@url:`https://example.dev`') + }) + + it('leaves text without a scheme alone', () => { + expect(linkifyUrls('example.dev/a and src/foo.ts')).toBe('example.dev/a and src/foo.ts') + }) +}) + +describe('chipTypedUrlOnSpace', () => { + it('chips a link typed right before the caret and adds the space', () => { + const { editor, event } = spaceOn('see https://example.dev/a', 25) + + expect(chipTypedUrlOnSpace(event)).toBe(true) + expect(composerPlainText(editor)).toBe('see @url:`https://example.dev/a` ') + + editor.remove() + }) + + it('keeps sentence punctuation outside the chip', () => { + const { editor, event } = spaceOn('https://example.dev.', 20) + + expect(chipTypedUrlOnSpace(event)).toBe(true) + expect(composerPlainText(editor)).toBe('@url:`https://example.dev`. ') + + editor.remove() + }) + + it('ignores a caret that is not sitting on a link', () => { + const { editor, event } = spaceOn('https://example.dev is nice', 27) + + expect(chipTypedUrlOnSpace(event)).toBe(false) + expect(composerPlainText(editor)).toBe('https://example.dev is nice') + + editor.remove() + }) + + it('ignores a scheme with no host yet', () => { + const { editor, event } = spaceOn('https://', 8) + + expect(chipTypedUrlOnSpace(event)).toBe(false) + + editor.remove() + }) + + it('leaves a modified space alone', () => { + const { editor, event } = spaceOn('https://example.dev', 19) + + expect(chipTypedUrlOnSpace({ ...event, altKey: true })).toBe(false) + expect(composerPlainText(editor)).toBe('https://example.dev') + + editor.remove() + }) +}) diff --git a/apps/desktop/src/app/chat/composer/url-refs.ts b/apps/desktop/src/app/chat/composer/url-refs.ts new file mode 100644 index 000000000000..580abdc1c6fb --- /dev/null +++ b/apps/desktop/src/app/chat/composer/url-refs.ts @@ -0,0 +1,103 @@ +/** + * Bare-link recognition for the composer. A link the user pastes or types is the + * same thing the "+ → Add URL" dialog inserts, so it becomes an `@url:` + * directive: a chip that truncates instead of a wall of URL text, and a + * reference the gateway resolves. + */ +import type { KeyboardEvent } from 'react' + +import { quoteRefValue, REF_RE, refChipElement, replaceBeforeCaret } from './rich-editor' +import { textBeforeCaret } from './text-utils' + +// An explicit scheme only — `example.com` bare is too easy to hit by accident +// (a filename, a version, a sentence). Brackets and quotes fence a URL in prose; +// parens don't, so they stay in and an unbalanced tail is trimmed below. +const URL_RE = /https?:\/\/[^\s<>[\]{}"'`]+/gi +const TYPED_URL_RE = /(?:^|\s)(https?:\/\/[^\s<>[\]{}"'`]+)$/i + +/** A URL at the end of a sentence carries the punctuation that ended it. */ +function splitUrlTail(raw: string) { + let url = raw.replace(/[,.;:!?]+$/, '') + + while (url.endsWith(')') && url.split(')').length > url.split('(').length) { + url = url.slice(0, -1) + } + + return { trailing: raw.slice(url.length), url } +} + +/** A URL needs a host past the scheme to be worth chipping. */ +const hasHost = (url: string) => /^https?:\/\/[^/\s]/i.test(url) + +/** Rewrite bare links in `text` as `@url:` directives, leaving links that are + * already part of a directive alone. Returns `text` unchanged when there are + * none. */ +export function linkifyUrls(text: string) { + REF_RE.lastIndex = 0 + + const fenced = Array.from(text.matchAll(REF_RE)).map(match => { + const start = match.index ?? 0 + + return { end: start + match[0].length, start } + }) + + let out = '' + let cursor = 0 + + for (const match of text.matchAll(URL_RE)) { + const start = match.index ?? 0 + const { url } = splitUrlTail(match[0]) + + if (!hasHost(url) || fenced.some(span => start >= span.start && start < span.end)) { + continue + } + + out += `${text.slice(cursor, start)}@url:${quoteRefValue(url)}` + cursor = start + url.length + } + + return out + text.slice(cursor) +} + +/** A plain space finishing a typed link commits it as a chip (followed by + * whatever punctuation ended it, then the space). Returns whether it ran, so a + * keydown handler can fall through on anything else. */ +export function chipTypedUrlOnSpace(event: KeyboardEvent) { + if (event.key !== ' ' || event.metaKey || event.ctrlKey || event.altKey) { + return false + } + + const editor = event.currentTarget + + // Runs on every space, so bail on the cheap native read before paying for the + // caret range walk (same guard shape as the trigger detector). + if (!editor.textContent?.includes('://')) { + return false + } + + const before = textBeforeCaret(editor) + const match = before ? TYPED_URL_RE.exec(before) : null + const token = match?.[1] + + if (!token) { + return false + } + + const { trailing, url } = splitUrlTail(token) + + if (!hasHost(url)) { + return false + } + + const fragment = document.createDocumentFragment() + + fragment.append(refChipElement('url', quoteRefValue(url))) + + if (trailing) { + fragment.append(document.createTextNode(trailing)) + } + + fragment.append(document.createTextNode(' ')) + + return replaceBeforeCaret(editor, token.length, fragment) +} diff --git a/apps/desktop/src/app/chat/hooks/use-file-drop-zone.ts b/apps/desktop/src/app/chat/hooks/use-file-drop-zone.ts index 42e4554b992e..186c226b84ac 100644 --- a/apps/desktop/src/app/chat/hooks/use-file-drop-zone.ts +++ b/apps/desktop/src/app/chat/hooks/use-file-drop-zone.ts @@ -44,6 +44,7 @@ export function useFileDropZone({ enabled = true, onDropFiles }: FileDropZoneOpt // DnD can't be cancelled at the OS level, so we drop the overlay and arm a // guard that swallows the trailing drop instead. Top escape layer + capture // stop so it doesn't also fire a handler behind the drag (see drag-session). + // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment) useEffect(() => { if (dragKind === null) { return diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsx index bd18be0c4834..40a8922d453f 100644 --- a/apps/desktop/src/app/chat/index.tsx +++ b/apps/desktop/src/app/chat/index.tsx @@ -1,14 +1,16 @@ import { type AppendMessage, AssistantRuntimeProvider, type ThreadMessage } from '@assistant-ui/react' import { useStore } from '@nanostores/react' import { useQuery } from '@tanstack/react-query' +import type { ReadableAtom } from 'nanostores' import type * as React from 'react' -import { Suspense, useCallback, useEffect, useMemo } from 'react' +import { Suspense, useCallback, useEffect, useMemo, useState } from 'react' import { useLocation } from 'react-router-dom' import type { SubmitTextOptions } from '@/app/session/hooks/use-prompt-actions/utils' import { Thread } from '@/components/assistant-ui/thread' import { Backdrop } from '@/components/Backdrop' import { COMPOSER_HEART_CONFIG, HeartField } from '@/components/chat/vibe-hearts' +import { usePaneVisible } from '@/components/pane-shell/pane-visibility' import { $sessionTileDragging, $sessionTileEdgeHover } from '@/components/pane-shell/tree/store' import { PromptOverlays } from '@/components/prompt-overlays' import { Button } from '@/components/ui/button' @@ -42,7 +44,7 @@ import { import { isSecondaryWindow, isWatchWindow } from '@/store/windows' import type { ModelOptionsResponse } from '@/types/hermes' -import { routeSessionId } from '../routes' +import { primaryRouteSelectedSessionId, routeSessionId } from '../routes' import { titlebarHeaderBaseClass, titlebarHeaderShadowClass, titlebarHeaderTitleClass } from '../shell/titlebar' import { ChatDropOverlay } from './chat-drop-overlay' @@ -69,7 +71,7 @@ interface ChatViewProps extends Omit, 'onSubmit'> { onCancel: () => Promise | void onAddContextRef: (refText: string, label?: string, detail?: string) => void onAddUrl: (url: string) => void - onBranchInNewChat: (messageId: string) => void + onBranchInNewChat?: (messageId: string) => void maxVoiceRecordingSeconds?: number onAttachImageBlob: (blob: Blob) => Promise | boolean | void onAttachDroppedItems: (candidates: DroppedFile[]) => Promise | boolean | void @@ -174,6 +176,30 @@ interface ChatRuntimeBoundaryProps { const NO_MESSAGES: ChatMessage[] = [] +/** + * The view's $messages, live only while this surface is the VISIBLE tab. + * + * Keep-alive keeps every ever-active tab MOUNTED (tree-group.tsx), so without + * this gate a hidden tab re-renders its entire thread on every streaming + * delta flush (~30×/s) — five busy tabs quintuple the per-token render cost + * and the app crawls. Hidden tabs freeze their transcript instead (status + * dots stay live through the separate status atoms) and catch up in one + * commit on reveal — the subscribe fires immediately with the current value. + */ +function useMessagesWhileVisible($messages: ReadableAtom): ChatMessage[] { + const visible = usePaneVisible() + const [messages, setMessages] = useState(() => $messages.get()) + + // nanostores types the listener value ReadonlyIfObject; the store publishes + // a fresh array per flush, so the cast is safe and avoids a per-token clone. + useEffect( + () => (visible ? $messages.subscribe(value => setMessages(value as ChatMessage[])) : undefined), + [$messages, visible] + ) + + return messages +} + /** * Owns the $messages subscription and the assistant-ui external-store runtime. * @@ -193,7 +219,7 @@ function ChatRuntimeBoundary({ onThreadMessagesChange, suppressMessages }: ChatRuntimeBoundaryProps) { - const storeMessages = useStore(useSessionView().$messages) + const storeMessages = useMessagesWhileVisible(useSessionView().$messages) const messages = suppressMessages ? NO_MESSAGES : storeMessages const runtimeMessageRepository = useRuntimeMessageRepository(messages) @@ -285,11 +311,18 @@ export function ChatView({ const resumeExhaustedSessionId = useStore($resumeExhaustedSessionId) // Durable composer/queue scope (lineage root) so auto-compression tip rotation - // does not wipe an in-progress draft or orphan /queue entries. - const queueSessionKey = useMemo( - () => resolveComposerSessionKey(selectedSessionId, sessions), - [selectedSessionId, sessions] - ) + // does not wipe an in-progress draft or orphan /queue entries. For the + // primary view, the route is authoritative over the store selection — the + // latter can be momentarily null/stale mid-switch, which used to leak into + // the composer's scope key (#59305). A tile has no route, so it always uses + // its own selection directly. + const queueSessionKey = useMemo(() => { + const effectiveSelectedSessionId = isPrimary + ? primaryRouteSelectedSessionId(location.pathname, selectedSessionId) + : selectedSessionId + + return resolveComposerSessionKey(effectiveSelectedSessionId, sessions) + }, [isPrimary, location.pathname, selectedSessionId, sessions]) // When the tip row arrives after compression, migrate any tip-keyed stash onto // the durable lineage key before the composer remounts onto that key. @@ -437,6 +470,7 @@ export function ChatView({ 'relative isolate flex h-full min-w-0 flex-col overflow-hidden bg-(--ui-chat-surface-background)', className )} + data-chat-surface="" data-composer-target={composerScope.target} data-session-anchor={sessionAnchor} > diff --git a/apps/desktop/src/app/chat/pane-mirror.ts b/apps/desktop/src/app/chat/pane-mirror.ts index b78189593693..03a6e167891c 100644 --- a/apps/desktop/src/app/chat/pane-mirror.ts +++ b/apps/desktop/src/app/chat/pane-mirror.ts @@ -31,9 +31,10 @@ export interface PaneMirror { before?: (tile: T) => null | string | undefined minWidth: string title: (key: string) => string - /** Lead-dot color for the tile's tab (e.g. a session's project color). Re-read - * on every `also` change, so pass the color source in `also` to keep it live. */ - accent?: (key: string) => string | undefined + /** Custom lead NODE for the tile's tab (rendered before the label). A live, + * self-subscribing component (e.g. a session's status dot) so the strip needn't + * re-sync on status/color change — only `title` drives re-registration. */ + tabLead?: (key: string) => ReactNode render: (key: string) => ReactNode /** Wrap the tile's TAB (domain context menu — session verbs). */ tabWrap?: (key: string, tab: ReactElement) => ReactNode @@ -52,7 +53,7 @@ export interface PaneMirror { /** Build a `watch*` fn: syncs once, then re-syncs on every source/also change. * Module-level state lives in the returned closure, so call it once per app. */ export function paneMirror(cfg: PaneMirror): () => void { - const registered = new Map void; title: string; accent?: string }>() + const registered = new Map void; title: string }>() const paneId = (key: string) => `${cfg.prefix}:${key}` const sync = () => { @@ -62,11 +63,10 @@ export function paneMirror(cfg: PaneMirror): () => void { for (const tile of tiles) { const key = cfg.key(tile) const title = cfg.title(key) - const accent = cfg.accent?.(key) const current = registered.get(key) - // register() replaces same-id in place — safe for live title/accent refreshes. - if (current && current.title === title && current.accent === accent) { + // register() replaces same-id in place — safe for live title refreshes. + if (current && current.title === title) { continue } @@ -75,7 +75,7 @@ export function paneMirror(cfg: PaneMirror): () => void { area: 'panes', title, data: { - accent, + tabLead: cfg.tabLead ? () => cfg.tabLead!(key) : undefined, dock: { before: cfg.before?.(tile), pane: cfg.anchor?.(tile) ?? 'workspace', @@ -92,7 +92,7 @@ export function paneMirror(cfg: PaneMirror): () => void { render: () => cfg.render(key) }) - registered.set(key, { dispose, title, accent }) + registered.set(key, { dispose, title }) if (!current) { registerPaneCloser(paneId(key), () => cfg.close(key)) diff --git a/apps/desktop/src/app/chat/right-rail/preview-artifact.test.tsx b/apps/desktop/src/app/chat/right-rail/preview-artifact.test.tsx new file mode 100644 index 000000000000..5b1a84e20988 --- /dev/null +++ b/apps/desktop/src/app/chat/right-rail/preview-artifact.test.tsx @@ -0,0 +1,112 @@ +import { act, cleanup, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it } from 'vitest' + +import { $artifactRegistry, $artifactVersionSelection, artifactPreviewTarget, upsertArtifact } from '@/store/artifacts' + +import { ArtifactPreview } from './preview-artifact' + +function register(title: string, kind: 'code' | 'html' | 'svg', content: string) { + const result = upsertArtifact('session-1', { kind, language: kind === 'code' ? 'python' : kind, title }, content) + + if (!result) { + throw new Error('artifact did not register') + } + + return result +} + +async function renderArtifact(artifactId: string) { + const record = $artifactRegistry.get()['session-1']!.find(item => item.id === artifactId)! + + await act(async () => { + render() + }) +} + +describe('ArtifactPreview', () => { + afterEach(() => { + cleanup() + $artifactRegistry.set({}) + $artifactVersionSelection.set({}) + }) + + it('renders html in a scripts-only sandboxed frame the parent app is unreachable from', async () => { + const { artifactId } = register('Dashboard', 'html', '

Hi

') + await renderArtifact(artifactId) + + const frame = screen.getByTitle('Dashboard') as HTMLIFrameElement + + expect(frame.getAttribute('sandbox')).toBe('allow-scripts') + expect(frame.srcdoc).toContain('

Hi

') + // No allow-same-origin: scripts inside cannot reach the renderer's origin. + expect(frame.getAttribute('sandbox')).not.toContain('same-origin') + }) + + it('strips scripts out of svg before it renders inline', async () => { + const { artifactId } = register( + 'Logo', + 'svg', + '' + ) + + await renderArtifact(artifactId) + + expect(document.querySelector('svg')).not.toBeNull() + expect(document.querySelector('svg script')).toBeNull() + }) + + it('offers only the source view for code, which has nothing to render', async () => { + const { artifactId } = register('Solver', 'code', 'print("hi")') + await renderArtifact(artifactId) + + expect(screen.queryByRole('button', { name: /rendered/i })).toBeNull() + }) + + it('shows the version stepper once an artifact has history, and follows the selection', async () => { + register('Dashboard', 'html', '

v1

') + const { artifactId } = register('Dashboard', 'html', '

v2

') + await renderArtifact(artifactId) + + expect(screen.getByText('v2 of 2')).toBeTruthy() + expect((screen.getByTitle('Dashboard') as HTMLIFrameElement).srcdoc).toContain('v2') + + await act(async () => { + $artifactVersionSelection.set({ [artifactId]: 0 }) + }) + + expect(screen.getByText('v1 of 2')).toBeTruthy() + expect((screen.getByTitle('Dashboard') as HTMLIFrameElement).srcdoc).toContain('v1') + }) + + it('hides the stepper for a single-version artifact', async () => { + const { artifactId } = register('Dashboard', 'html', '

only

') + await renderArtifact(artifactId) + + expect(screen.queryByText('v1 of 1')).toBeNull() + }) + + it('picks up a new version in an already-open tab', async () => { + const { artifactId } = register('Dashboard', 'html', '

v1

') + await renderArtifact(artifactId) + + await act(async () => { + register('Dashboard', 'html', '

v2

') + }) + + expect((screen.getByTitle('Dashboard') as HTMLIFrameElement).srcdoc).toContain('v2') + }) + + it('falls back to an empty state when the registry no longer has the artifact', async () => { + const { artifactId } = register('Dashboard', 'html', '

gone

') + const record = $artifactRegistry.get()['session-1']!.find(item => item.id === artifactId)! + const target = artifactPreviewTarget(record) + + $artifactRegistry.set({}) + + await act(async () => { + render() + }) + + expect(screen.queryByTitle('Dashboard')).toBeNull() + }) +}) diff --git a/apps/desktop/src/app/chat/right-rail/preview-artifact.tsx b/apps/desktop/src/app/chat/right-rail/preview-artifact.tsx new file mode 100644 index 000000000000..07d60393a8e4 --- /dev/null +++ b/apps/desktop/src/app/chat/right-rail/preview-artifact.tsx @@ -0,0 +1,263 @@ +import { useStore } from '@nanostores/react' +import DOMPurify from 'dompurify' +import { useEffect, useMemo, useState } from 'react' + +import { CopyButton } from '@/components/ui/copy-button' +import { Tip } from '@/components/ui/tooltip' +import { useI18n } from '@/i18n' +import { artifactDownloadName, type ArtifactKind } from '@/lib/artifact-detect' +import { downloadTextFile } from '@/lib/download-text' +import { ChevronLeft, ChevronRight, Download, ExternalLink } from '@/lib/icons' +import { $artifactRegistry, $artifactVersionSelection, findArtifact, selectArtifactVersion } from '@/store/artifacts' +import { notifyError } from '@/store/notifications' +import type { PreviewTarget } from '@/store/preview' + +import { PreviewEmptyState, PreviewModeSwitcher, type PreviewViewMode, SourceView } from './preview-file' + +const MIME_BY_KIND = { code: 'text/plain', html: 'text/html', svg: 'image/svg+xml' } as const + +// Shiki has no `svg` grammar; code artifacts keep their detected fence language. +const SOURCE_LANGUAGE_BY_KIND: Record = { + code: undefined, + html: 'html', + svg: 'xml' +} + +const HEADER_BUTTON_CLASS = + 'flex items-center gap-1 rounded-md px-1.5 text-[0.625rem] font-bold text-muted-foreground transition-colors hover:bg-accent hover:text-foreground disabled:pointer-events-none disabled:opacity-40' + +/** Wrap an HTML fragment in a minimal document shell; full documents pass + * through untouched. Keeps generated fragments (no /) rendering + * with sane defaults instead of quirks-mode soup. */ +function composeArtifactHtml(content: string): string { + if (/]|', + '', + '', + content, + '' + ].join('\n') +} + +/** Write the composed document to a real temp file through the existing + * buffer-save IPC, then hand it to the OS browser. A blob/data URL can't + * cross into the OS default browser, so a file on disk is the honest path. */ +async function openHtmlInBrowser(content: string): Promise { + const bridge = window.hermesDesktop + + if (!bridge?.saveImageBuffer || !bridge.openExternal) { + throw new Error('Desktop bridge unavailable') + } + + const bytes = new TextEncoder().encode(composeArtifactHtml(content)) + const path = await bridge.saveImageBuffer(bytes, '.html') + + if (!path) { + throw new Error('Could not write artifact file') + } + + const fileUrl = `file://${path.startsWith('/') ? '' : '/'}${path.replace(/\\/g, '/')}` + + if (bridge.openPreviewInBrowser) { + await bridge.openPreviewInBrowser(fileUrl) + + return + } + + await bridge.openExternal(fileUrl) +} + +/** + * Live view for renderable artifact content. + * + * HTML runs in an `