diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8c15cb696a..00abe5ec24 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,6 +26,10 @@ on: push: branches: [main, preview, dev] paths: + - "Dockerfile" + - "compose.yaml" + - ".dockerignore" + - "docker/**" - "src/**" - "bin/**" - "tests/**" @@ -180,6 +184,10 @@ jobs: # start the workflow so the aggregate check exists, while these # paths decide whether the expensive test jobs need to run. ci: + - 'Dockerfile' + - 'compose.yaml' + - '.dockerignore' + - 'docker/**' - 'src/**' - 'bin/**' - 'tests/**' @@ -423,6 +431,7 @@ jobs: run: | bun x tsc --noEmit bun x tsc --noEmit -p tests/tsconfig.doctor-service-memory-contract.json + bun x tsc --ignoreConfig --noEmit --strict --target ESNext --module ESNext --moduleResolution bundler --types bun-types --skipLibCheck scripts/ci/docker-smoke.ts - name: GUI tests run: cd gui && bun test --isolate tests @@ -908,6 +917,26 @@ jobs: bun run scripts/keyring-smoke.ts ' + # Exercise the source-build Compose contract, including real volume reuse. + # Host fixtures cannot prove image construction or container recreation. + docker-smoke: + name: docker smoke + needs: changes + if: github.event_name != 'pull_request' || needs.changes.outputs.ci == 'true' + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: Checkout + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7 + with: + persist-credentials: false + + - name: Setup project Bun + uses: ./.github/actions/setup-project-bun + + - name: Build, start, and recreate the container + run: bun scripts/ci/docker-smoke.ts + npm-global-smoke: name: npm-global ${{ matrix.os }} needs: changes @@ -986,7 +1015,7 @@ jobs: # direct dependencies only, so a failing `select-windows-runner` would # otherwise reach this gate as nothing at all while its dependents report # `skipped` — which the gate is required to read as a deliberate skip. - needs: [changes, select-windows-runner, test, storage-policy, api-usage, gates, platform-macos, macos-control, platform-windows, keyring-smoke, npm-global-smoke] + needs: [changes, select-windows-runner, test, storage-policy, api-usage, gates, platform-macos, macos-control, platform-windows, keyring-smoke, docker-smoke, npm-global-smoke] runs-on: ubuntu-latest timeout-minutes: 5 steps: diff --git a/Dockerfile b/Dockerfile index 1ed000743d..5987bfa991 100644 --- a/Dockerfile +++ b/Dockerfile @@ -25,7 +25,10 @@ RUN cd gui && bun run build FROM ${BUN_IMAGE} AS runtime WORKDIR /home/bun/app +# Docker supervises this foreground process; retain routed state on stop/recreate. +# This uses the existing service lifecycle mode and does not install a service manager. ENV NODE_ENV=production \ + OCX_SERVICE=1 \ OPENCODEX_HOME=/home/bun/.opencodex \ CODEX_HOME=/home/bun/.codex \ OCX_API_TOKEN_FILE=/home/bun/.opencodex/service-api-token diff --git a/devlog/_fin/260907_axis1_bugfixes/000_plan.md b/devlog/_fin/260907_axis1_bugfixes/000_plan.md new file mode 100644 index 0000000000..ad0da69270 --- /dev/null +++ b/devlog/_fin/260907_axis1_bugfixes/000_plan.md @@ -0,0 +1,24 @@ +# Axis 1: measured bug fixes and failure diagnostics + +Completed: see [031_delivery_record.md](031_delivery_record.md) for merged commits, final CI, attribution and deferrals. + +Archetype: satisfy existing contracts. Trigger: owner assigned axis 1 (#3809, #3464, #3661). Goal: deliver reviewable fixes through a manual PR chain and merge the verified scope. Non-goals: new account/retry policy, auth defaults, multipart recovery, releases, native stacks, sibling edits. Stop: merged feasible scope plus explicit unresolved dispositions. Escalation: defer a policy-dependent or unreproducible slice; reclaim a worker slice after two failed packets. Evidence: this unit plus ignored `.tmp/axis1/` and `.codexclaw` receipts. Resources: task-owned worktree/branches and GitHub repository access; Astra high leaves within host capacity; no caller-specified token or wall-clock budget. + +Baseline: origin/dev 137d6a727; source PR #3809 at 4a1012359a522ddd6d7ff77203c9e5f3632d605c. Assigned 5cc8 checkout has pre-existing changes and remains untouched. Code lives in /tmp/ocx-axis1-20260907. + +## Cycle map +1. wp0: docs-only scope, source audit and dependency roadmap; no runtime changes. +2. wp1: bounded quota, version-guidance and recovery-diagnostic changes; independent source/security review and structural checks. Runtime verification deferred explicitly to wp2. +3. wp2: publish ordinary PR chain, run final cumulative hosted CI, resolve findings, admin merge bottom-up and verify dev ancestry. Lower CI only if final CI fails. + +## Delivery contract +The owner explicitly requests a manual delivery chain even where units are independent: quota -> CLI guidance -> recovery reasons, with each layer carrying its own tests and credit. This order is an integration order, not a fabricated runtime dependency. No native registration. Lower commits carry [skip ci] to defer duplicate workflow runs; final head does not. Skipped lower runs are never called passing. No local tests/typecheck/build suites and no hook-triggered suites; task pushes use --no-verify. Hosted ci.yml on the final head must cover all changed runtime/tests; lower-level runs are diagnostic only after final failure. Merge with --admin under the explicit owner exception; preserve original commits/trailers with merge commits, retarget each child to dev, and check integration trees against final evidence. Concurrent dev changes require fresh combined verification. + +## Work boundaries +- Quota: src/providers/quota.ts, src/oauth/anthropic-routing.ts, src/oauth/health.ts, src/server/responses/core.ts, src/images/loop.ts, src/web-search/loop.ts, focused quota tests/layout, provider documentation. +- CLI: src/cli/version-skew.ts and relevant status/doctor consumers, tests/cli/cli-version-skew.test.ts, troubleshooting documentation. No service restart or repair behavior changes. +- Recovery: src/server/responses/agent-task-recovery.ts, agent-task-recovery-cache.ts, src/lib/bounded-body.ts and existing focused tests, Responses error projection if needed, recovery documentation. No expanded admission/retry. +- Main owns shared core.ts integration and test-layout files. Workers must not touch each other's paths or git index. + +## Verification and acceptance +No local suite commands are executed. Source mapping, git diff --check and documentation structural checks are local evidence only. Hosted Cross-platform CI at final head provides runtime/typecheck/privacy and affected platform proof; inspect jobs for skipped coverage. Build completion is provisional until that run and independent audit succeed. Original PR author(s) must be named in commit Co-authored-by trailers, sourced from original commits/API; report authors may also be acknowledged accurately. Source-of-truth sync uses relevant existing structure and docs-site pages. diff --git a/devlog/_fin/260907_axis1_bugfixes/010_roadmap.md b/devlog/_fin/260907_axis1_bugfixes/010_roadmap.md new file mode 100644 index 0000000000..75e07478c0 --- /dev/null +++ b/devlog/_fin/260907_axis1_bugfixes/010_roadmap.md @@ -0,0 +1,3 @@ +# wp0: scope roadmap + +Read current source, prior issue disposition and PR #3809 before choosing changes. Independent Astra high reviewers map each bounded issue. Confirm existing launcher behavior and bounded recovery reasons are already in dev; plan only residual fixes. Record exact file boundaries and acceptance scenarios in 020. Success: all three slices have verifiable requirements, main-owned shared files, original author anchors and explicit policy exclusions. Local evidence is documentation and source inspection; no runtime claim. diff --git a/devlog/_fin/260907_axis1_bugfixes/011_audit.md b/devlog/_fin/260907_axis1_bugfixes/011_audit.md new file mode 100644 index 0000000000..cc1cb1d51e --- /dev/null +++ b/devlog/_fin/260907_axis1_bugfixes/011_audit.md @@ -0,0 +1,5 @@ +# wp0 audit disposition + +Independent Astra high reviewer Hooke: VERDICT: GO-WITH-FIXES (blockers=1). Shared-flight failure propagation was the blocker. Accepted: 000/020 now assign cache and bounded-body ownership and define shared typed outcomes, success-only cache, caller-local cancellation and capacity semantics. Source scouts independently identified and confirmed these requirements. Fixed stale CLI test path. Windows runtime proof requires final workflow_dispatch, now explicit in 030. + +No runtime code changed. Documentation source/ownership inspection and git diff --check are the wp0 evidence. Runtime verification remains wp2. diff --git a/devlog/_fin/260907_axis1_bugfixes/012_roadmap_lock.md b/devlog/_fin/260907_axis1_bugfixes/012_roadmap_lock.md new file mode 100644 index 0000000000..cf2bf0afce --- /dev/null +++ b/devlog/_fin/260907_axis1_bugfixes/012_roadmap_lock.md @@ -0,0 +1,5 @@ +# Roadmap lock + +The second independent audit returned VERDICT: PASS with no remaining blockers. The three accepted slices are ready for scoped implementation. Original quota author: Éverton Toffanetto (everton-dgn), commit identity from 4f3779c04753 and 3ef0ade296c3. Issue reporters: garysassano (10464497) and Hu9956 (282876394). Reporter acknowledgement is separate from code authorship. + +Preserve raw unequal version diagnostics. Detailed recovery outcomes must travel in the shared flight, not caller-local closures. Quota observations use immutable dispatch identity. Final verification is hosted workflow_dispatch for full Windows coverage; local suites remain prohibited. diff --git a/devlog/_fin/260907_axis1_bugfixes/020_bounded_fixes.md b/devlog/_fin/260907_axis1_bugfixes/020_bounded_fixes.md new file mode 100644 index 0000000000..836f743a73 --- /dev/null +++ b/devlog/_fin/260907_axis1_bugfixes/020_bounded_fixes.md @@ -0,0 +1,20 @@ +# wp1: implement bounded bug fixes + +## Quota +Carry only the source PR diff onto current dev, with original-author trailer. Header utilization fraction -> percentage; reset epoch -> timestamp. Creation: parser; serialization: account quota cache; deserialization: existing hydration; consumers: account ranking/health and management reading. Account-bound writer generation is captured with serving credentials, including retry/sidecar/continuation rebinds. Header observations merge model-specific windows and cannot indefinitely postpone probes. Existing 429 eligibility and retry count stay unchanged. Explicit reset evidence must not be truncated by an invented six-hour policy; any unresolved policy piece is deferred. +Scenarios: 200 and 429 on main/sidecar/continuation attribute only the serving account; generation invalidation discards writes; partial/malformed headers preserve known fields; no prior probe means model-window probe is still due; weekly rejected reset outlasts five-hour reset; absent evidence retains existing fallback. Verify with focused tests included in final hosted CI. + +## Version guidance +Compare CLI and running proxy using existing semantic-version utilities if present. CLI newer points to service restart; proxy newer points to upgrading/PATH resolution of CLI; equal/unknown retain suppression; incomparable differing builds use neutral wording. status and doctor share advice. Preserve whether requests are allowed and do not perform repair. Test both directions, prereleases, placeholders, malformed versions and consumer projection. + +## Recovery reasons +Keep existing public wrapper returning boolean and typed detailed result. Classify actual upstream HTTP refusal, transport error, timeout/caller cancellation, response-body/decode failures with a bounded vocabulary. Creation: request/collector; propagation: detailed recovery result; consumers: existing response reason projection/tests/docs. No raw upstream body/errors/tokens/ciphertext in output. Strict admission, one attempt, same credential and unchanged request mutation guarantees. Exercise each failure branch, cancellation races, malformed terminal output and successful recovery in final hosted CI. + +Main owns src/server/responses/core.ts and layout metadata. Source/security review must check public boundaries and negative cases, not only implementation-mirroring tests. Source-only C evidence does not claim runtime correctness; wp2 is mandatory. + +## Source-map clarification from independent #3464 research +Use src/lib/strict-semver.ts unchanged. Raw unequal versions remain skewed; equal precedence with different build metadata and invalid/whitespace/v-prefixed values get neutral wording, not normalization or a guessed direction. Placeholder suppression is unchanged. src/cli/doctor.ts must not call suppressed placeholders a confirmed match. Focused files: tests/cli/cli-version-skew.test.ts, tests/cli/cli-status-json.test.ts, tests/codex-integration/doctor.test.ts. Documentation: reference/cli/lifecycle.md and directly affected Korean/Russian pages. Existing launcher landed via #3616 (4e2246c32); no service runtime changes. + +## Audit refinements +Quota: observe physical responses at the existing oauthDispatch boundary before any main/continuation replacement or return. Use immutable request binding to pair response with selected account; skip when final authorization headers do not prove that bearer or credentialGeneration has changed. An active-account switch alone does not invalidate another account's in-flight observation. Native Claude passthrough and single-account expansion remain outside #3809 carry. Preserve Retry-After precedence; only reject nonfinite/unrepresentable deadlines rather than invent an anomaly ceiling. Header-only rows are probe-due; hydrated Anthropic observations must be probe-due unless probe time is proven. Failed probes settle with the most recent committed observation for all joiners. +Recovery: worker owns agent-task-recovery-cache.ts and bounded-body.ts narrow decode discriminator alongside focused tests. Shared flight carries typed outcome, cache retains only success plaintext, cancelled waiters remain local. Recognized caller cancellation precedes owned timeout, which precedes decode/transport classification. Fatal UTF-8 discriminator must identify actual decoder exceptions without reclassifying fetch/body-reader TypeErrors. Rejected-response cancellation is nonblocking best effort. Keep current public wrappers and combo error projection. Update documented reason lists in structure/04_transports-and-sidecars.md and docs-site/reference/architecture.md. diff --git a/devlog/_fin/260907_axis1_bugfixes/021_source_review.md b/devlog/_fin/260907_axis1_bugfixes/021_source_review.md new file mode 100644 index 0000000000..516a760813 --- /dev/null +++ b/devlog/_fin/260907_axis1_bugfixes/021_source_review.md @@ -0,0 +1,7 @@ +# wp1 source review + +Three bounded patches implemented with regression coverage. Hooke independently passed the physical-response quota observer wiring; Tesla independently passed quota/recovery security and source review with zero blockers. Version comparator and status/doctor projections inspected by main. All source workers report no local suite/typecheck/build execution. + +Quota source: #3809, Éverton Toffanetto; Co-authored-by included in f215f79b4. Version report: garysassano; Reported-by included in f91e3953a. Recovery report: Hu9956; Reported-by included in recovery commit. + +Source-only checks: git diff --check and documentation fence/whitespace inspection. These do not prove runtime correctness. wp2 final cumulative hosted CI is still mandatory. Final CI dispatch includes Windows because ordinary PR workflow omits it. No release/deploy workflow will be dispatched. diff --git a/devlog/_fin/260907_axis1_bugfixes/030_delivery.md b/devlog/_fin/260907_axis1_bugfixes/030_delivery.md new file mode 100644 index 0000000000..be851f530d --- /dev/null +++ b/devlog/_fin/260907_axis1_bugfixes/030_delivery.md @@ -0,0 +1,7 @@ +# wp2: hosted proof and manual-stack landing + +Publish task-owned branches with --no-verify. Standard PR template, source links, truthful skipped-local/lower-CI disclosure and contributor trailers. Lower layers use [skip ci], final cumulative head runs existing Cross-platform CI; never modify shared workflow filters or fabricate checks. On final failure inspect failing jobs, fix owned defects, and only then use lower CI to localize ambiguity. Leave unrelated/unresolvable slices unmerged with evidence. + +Before admin merge: source/security review findings resolved, final CI SHA/run pinned, current PR head and manual membership inspected. Record owner-authorized admin review/lower-CI exception. Merge bottom-up with original commits preserved; do not delete parent branches while children depend on them. Retarget child to dev after parent landing. Reconcile concurrent dev before claiming final integrated proof. Verify every merge SHA is ancestor of refreshed origin/dev. Close #3809 only after its accepted replacement scope lands; keep #3661 open for multipart/retry and #3464 open if broader original acceptance remains unresolved. No release/deploy. + +Final full platform evidence uses workflow_dispatch ci.yml on the final cumulative branch, because ordinary PR CI excludes the Windows runtime job. Cancel only duplicate task-owned PR CI runs; skipped/cancelled runs are not passing evidence. diff --git a/devlog/_fin/260907_axis1_bugfixes/031_delivery_record.md b/devlog/_fin/260907_axis1_bugfixes/031_delivery_record.md new file mode 100644 index 0000000000..439c395f8b --- /dev/null +++ b/devlog/_fin/260907_axis1_bugfixes/031_delivery_record.md @@ -0,0 +1,53 @@ +# Axis 1 delivery record + +Terminal outcome: DONE for the authorized bounded bug/diagnostic scope, with the explicitly listed broader work deferred. Completed 2026-09-07. + +## Delivered + +- #3825 carries #3809 with serving-credential quota attribution, upstream deadline handling, probe-clock preservation and known-reset expiration. Invalid reset metadata does not erase otherwise valid usage; no new unknown-window TTL or synthetic zero was introduced. +- #3826 corrects CLI-versus-proxy version guidance in both directions and prevents false doctor match claims. +- #3827 exposes bounded recovery refusal/timeout/transport/invalid-output reasons through shared flights while preserving admission, success-only caching and caller-local cancellation. +- #3842 is supporting validation work: exact private BigInt file identities preserve existing Aside profile boundaries, including high-ID distinction and directory replacement detection. Public IO/serialization and link refusals remain unchanged. + +## Landing proof + +All four ordinary PRs were merged bottom-up with owner-authorized admin authority. No native stack was registered. Children were retargeted to dev before their parent branches could be automatically deleted. + +| PR | Reviewed layer head | Merge commit | +| --- | --- | --- | +| [#3825](https://github.com/lidge-jun/opencodex/pull/3825) | `d3c70f9d8c8cc6fced7a93577b93e8b141473ea3` | `85fbdb59621046da3db1839a5cce4c7260f99385` | +| [#3826](https://github.com/lidge-jun/opencodex/pull/3826) | `872f0e5aa714f6a2e757510195d1c038ac70e26d` | `860baaf9032fa7ea3030c78ab555608e3325a338` | +| [#3827](https://github.com/lidge-jun/opencodex/pull/3827) | `2e8ef03428f8e619dc92b250fbbc5d5dd7ad53cb` | `5a97db9b20f03a65e714ddc88d2523bea9aeacae` | +| [#3842](https://github.com/lidge-jun/opencodex/pull/3842) | `b29bbb440aaf70b283445a9c37e194a4a4e6859a` | `5fdf9bbdd9ff7657f0b6d7101697317d708af0e7` | + +The runtime integration commit is `5fdf9bbdd9ff7657f0b6d7101697317d708af0e7`. Its full tree `90a75118402d2f310393bef9ac3e4668cfcbdcfa` exactly matches the final combined validation candidate `9470fdb1bc9a02715a3760c36301d3d030a4e4fa`. A fresh fetch and ancestor check confirmed every merge on dev. The candidate included dev `bf85e675484a2391b94b2135bbebe739813a9621` plus all four layers. + +## Verification + +- [Cross-platform CI 34074350604](https://github.com/lidge-jun/opencodex/actions/runs/34074350604): all 26 jobs succeeded at the combined candidate, including Linux, macOS, Windows, Docker smoke, typecheck, privacy, build and operational checks. +- [Service lifecycle 34074351720](https://github.com/lidge-jun/opencodex/actions/runs/34074351720): Linux, macOS and Windows succeeded at the same candidate. +- Independent Astra high source/security audits covered the scoped implementations, merge interactions and exact-identity support. +- All current review threads on the four delivered PRs were resolved after runtime evidence was available. +- No local application test suite or local typecheck ran. Pushes used --no-verify; per-layer CI was deferred by explicit owner instruction. Cancelled and skipped checks were never represented as passing tests. +- Privacy scanning passed. Documentation static build produced 425 pages in 8.23 seconds at 2522264d5; its documentation subtree remained unchanged by the supporting identity fix. Dependencies were installed from the frozen lockfile with install scripts disabled. The build changed no tracked files. +- The assigned pre-existing working-tree changes were preserved; delivery used an isolated worktree. + +## Corrections and remaining limits + +Initial verification exposed incomplete test homes/default configuration and old calendar reset dates in current-measurement fixtures. Those fixtures were corrected without removing behavioral assertions. Known-expiry tests use explicit simulated time. Later review added expired-window handling, field normalization and a global test network guard. + +Imported axis-five closeout contact addresses blocked privacy scanning. [#3836](https://github.com/lidge-jun/opencodex/pull/3836) removed the addresses while retaining author names and all commit attribution; no scanner rule or allowlist was weakened. + +Earlier Windows Aside incidents reported an apparent shared catalog target. Their actual file IDs were not captured. The independently demonstrable Number-precision defect was corrected by #3842, and semantic/native regressions plus the previously failing route case passed in final CI. This does not retroactively prove every earlier incident's raw IDs or cause. + +An earlier Windows outbound-proxy test timed out at its existing 15-second bound. Its scoped test/transport files were unchanged and the stalled phase was not measured. No timeout increase or unrelated proxy repair was made; later passing execution is not a claim that the timing root cause was fixed. + +## Attribution and issue disposition + +Éverton Toffanetto's Co-authored-by trailer is retained in reachable commit `f215f79b4562735029ad5672a68bc6104e534b98`. The issue reporters garysassano and Hu9956 are acknowledged in the corresponding diagnostic commits. Merge commits preserve those commits and trailers. + +The original #3809 was confirmed closed with a landed-via-#3825 marker at final recheck. The initial carry source was 4a1012359; the original author subsequently updated the source PR, so this record does not claim a verbatim merge of its later head. + +#3464 remains open for its broader automatic-repair/request-policy requests. #3661 remains open for multipart reconstruction and recovery retry policy. Those choices were outside this delivery. No release, deployment, new account-selection strategy or authentication-default change was performed. + +The preceding numbered documents are historical plans and audits; their original _plan paths refer to the planning stage. diff --git a/devlog/_fin/260907_axis3_protocol/000_plan.md b/devlog/_fin/260907_axis3_protocol/000_plan.md new file mode 100644 index 0000000000..d0511f46ec --- /dev/null +++ b/devlog/_fin/260907_axis3_protocol/000_plan.md @@ -0,0 +1,17 @@ +# Axis 3 protocol fidelity roadmap + +Mode: satisfy-spec HOTL, requested by the maintainer on 2026-09-07. Deliver source-grounded dispositions for #3815, #3816, #3807, #3719 and land accepted fixes with original authors credited in commits. No local suites or typecheck; verification is remote exact final-head CI, with lower-layer CI only on final failure. Ordinary manual PR chain only; admin merge authorized. No explicit token or wall-time limit was requested; agents use bounded tasks and waits. Do not invoke private provider accounts or spend inference credits. Tools: local Git/files, GitHub gh, Astra high leaf agents. Writes confined to task worktrees and this axis's GitHub branches/PRs. Preserve unrelated dirty work. + +Scope: ordered Claude thinking/redacted/tool-result envelope fidelity; Grok strict-client control frame projection; valid task-seed diagnosis. Exclude new auth/routing/default policies, fabricated provider signatures or tool pairing IDs (new Responses reasoning item IDs are permitted transport identities), cache savings claims, unrelated axes, deployment/release. Unknown field/runtime reports receive explicit deferred dispositions per user direction. + +Work phases: wp0 roadmap audit and lock; wp1 prepare two independently reviewable source layers and any justified contract regressions, then remote final combined verification; wp2 publish/merge ordinary PRs bottom-up and record final ancestry/dispositions. The two source fixes are independent; the manual chain is the user's requested integration/CI grouping, not a runtime dependency. + +Success: roadmap verified, accepted changes reviewed and remotely validated, commits credit SB Yoon (yansigit) and Yumi for #3815 and Danh Thanh (dt418) for #3816, landed SHA proven ancestor of refreshed dev; uncertain #3807/#3719 runtime or cache claims remain open. Stop only after accepted delivery and explicit dispositions. Escalate only an unavoidable owner-policy choice; defer that portion and continue the rest. + +Acceptance: (1) thinking then text/tool then result retains order and genuine signatures; opaque blocks remain bounded and malformed/nested signatures fail closed. (2) Grok user agent receives ordinary Responses data without codex.rate_limits/codex.response.metadata, while proxy inspection and normal clients retain metadata. (3) valid external task seeds preserve text/order; absent metadata invalid tool outputs still reject. (4) no credential, admission, cache-retention default, provider/routing policy mutation. (5) final CI must really run relevant tests/typecheck, not skip/cancel or fabricate success. No local suite was run. Final failure permits lower-layer CI for localization; unrelated failures may defer delivery, never count as success. + +Sources: PRs https://github.com/lidge-jun/opencodex/pull/3815 and /pull/3816; issues /issues/3807 and /issues/3719. Current dev 137d6a727. Evidence snapshots under .tmp/axis3. Public notes contain no unreleased vulnerability detail; any new security investigation stays in scratch. + +## Terminal outcome + +Runtime scope delivered in3830–3832 with the evidence and explicit diagnostic remainders in021_delivery_record.md. Documentation-only completion retains the late source-author rows and archives this unit. Initial planning statements are historical; the delivery record is the outcome authority. diff --git a/devlog/_fin/260907_axis3_protocol/001_roadmap_lock.md b/devlog/_fin/260907_axis3_protocol/001_roadmap_lock.md new file mode 100644 index 0000000000..115f8c3dfa --- /dev/null +++ b/devlog/_fin/260907_axis3_protocol/001_roadmap_lock.md @@ -0,0 +1,3 @@ +# Roadmap lock + +Independent Astra high reviewer Pauli passed the amended wp0 roadmap. Transport reasoning IDs are permitted; fabricated tool pairing IDs remain prohibited. Claude fallback retention must be bounded or removed and checked remotely. Grok parser must follow SSE last-field/reset semantics. No runtime was changed in wp0. Next: wp1 carries source layers, adds justified regression coverage and verifies the final combined head remotely. diff --git a/devlog/_fin/260907_axis3_protocol/010_prepare_and_verify.md b/devlog/_fin/260907_axis3_protocol/010_prepare_and_verify.md new file mode 100644 index 0000000000..c278f094bf --- /dev/null +++ b/devlog/_fin/260907_axis3_protocol/010_prepare_and_verify.md @@ -0,0 +1,42 @@ +# Prepare and verify combined protocol candidate + +Reverify base/source heads before build. Carry exact source deltas from the scratch diff snapshots, fold independently confirmed review fixes only. Each commit contains verified contributor trailers. Do not include upstream planning notes or unrelated changes. + +Layer 1 MODIFY: +scripts/test-layout/layout.json +src/claude/inbound.ts +src/claude/outbound.ts +src/responses/reasoning-envelope.ts +tests/claude-integration/claude-code-thought-signature-scope.test.ts +tests/claude-integration/claude-inbound.test.ts +tests/claude-integration/claude-outbound.test.ts +tests/claude-integration/claude-source-envelope.test.ts +tests/fixtures/test-layout-expected.json +tests/responses/reasoning-envelope.test.ts + +Preserve genuine signatures; encode bounded unsigned/redacted fallback; keep structured tool results. Layer 2 NEW src/server/grok-responses-control-frame.ts and MODIFY: +src/server/grok-responses-control-frame.ts +src/server/responses/core.ts +tests/responses/responses-snapshot-repair-server.test.ts + +Separate strict-client filtering from internal inspection. On a Grok metadata frame, forward no incompatible client frame; on ordinary delta, preserve unchanged; ordinary clients remain unchanged. No shared account/routing changes. + +Potential follow-up tests belong only in existing responses/Claude test files after diagnosis, with independent expected values. If no valid unhandled #3807 input is established, leave production guards unchanged. #3719 cache-hit and true Anthropic signed replay cannot be certified by codec fixtures. + +SoT: update docs-site/src/content/docs/guides/claude-code.md and existing translated counterparts only if #3815 makes their drop-policy statements stale. Read docs-site/AGENTS.md first. No global retention change. + +Verification: user prohibits local suites/typecheck (NOT RUN). Inspect source and diff-check locally. Push task branches with --no-verify. Dispatch existing Cross-platform CI workflow on final combined head, lane all. Confirm workflow head SHA, jobs, conclusion, test/typecheck execution from logs. Final CI failure permits lower-layer CI. Keep workflow/protection configuration unchanged; suppress only task-owned redundant automatic runs when needed for requested top-first scheduling, reporting cancelled runs honestly. No real accounts are used. + +## Audit amendments + +New rs_ reasoning IDs are normal transport identity, not fabricated tool call pairing. Do not synthesize tool-call IDs to bypass #3807 validation. + +Before acceptance, remove unbounded thinkingBuf retention introduced by #3815 or charge it to the existing TranslatorBudget retained bytes with normal fail-closed overflow. Use the established budget and error event; no silent truncation or new policy default. Cover multi-part text exactness, empty continuity fallback, and overflow with a small injected existing budget in remote regression tests. Decoder/consumer traces must prove any compact continuity marker still replays the original summary. + +#3816 must use SSE last-event-field-wins semantics, including colonless/empty resets and removal of only one optional leading space. Test event-only, data-only, repeated event fields in both orders, and preservation of ordinary completion data. Keep downstream Grok WebSocket support deferred because the existing surface marker is absent there; do not claim this HTTP/SSE patch solves it. + +## WP1 source refresh and scoped hardening + +Previous D: roadmap locked; execute reviewed source preparation. PR #3815 advanced to 76e07d181c48dca8c80167878381e1edb5642395 during investigation, including budget fixes and translated guide changes; carry fresh source, not old snapshots. Add a third dependent hardening layer only for source-proven preservation faults. MODIFY src/responses/parser.ts: retain recognized redacted-only and empty signed envelopes even when text is empty, preserving real boundary grouping. MODIFY src/bridge.ts: preserve signed block boundaries and redacted block positions identically in streaming/buffered output; signature fragments must be assembled at owning adapter boundary. MODIFY src/claude/outbound.ts only for exact block order/text restoration where current contract permits; do not invent a new signed continuity carrier or change hide-thinking policy. If hidden signed replay needs a new policy/carrier, explicitly defer that part rather than widening scope. Existing budget/guard contracts remain. + +Tests: existing tests/responses/anthropic-thinking-signature.test.ts or matching current domain file and Claude envelope tests get exact block-array roundtrip oracles; no fixture claims a live genuine signature. tests/responses/responses-compaction-routing.test.ts gets an established-history complete send_message_to_thread envelope across normal response, stored-ID continuation, v2 compaction_trigger and v1 compact endpoint, preserving real pairing and task content. If current fixture support makes a case impractical, record exact gap; no runtime seed repair. diff --git a/devlog/_fin/260907_axis3_protocol/011_candidate.md b/devlog/_fin/260907_axis3_protocol/011_candidate.md new file mode 100644 index 0000000000..7edc9aa1ce --- /dev/null +++ b/devlog/_fin/260907_axis3_protocol/011_candidate.md @@ -0,0 +1,9 @@ +# Combined candidate + +Source baseline: dev 137d6a727. Foundation carries #3815 through 76e07d181 with SB Yoon/Yumi commit trailers. Grok carries #3816 d5e0a9a2 and corrects SSE event overwrite/reset semantics, with Danh Thanh trailers. Added established-history external-task HTTP/continuation/compact fixtures without changing the missing-ID guard. Replay hardening preserves signed/opaque-only inputs and block ordering; signature updates replace previous values according to the SDK accumulator contract, and block closure waits for the next semantic event. + +Independent source reviews: Pauli scoped foundation PASS (18/18 files); Faraday Grok/seed PASS. Final Claude combined source audit and remote CI pending. Local suites/typecheck/build not run under user instruction. No live accounts invoked. + +Deferred: #3807 lacks raw failing current-version input; #3719 still needs live intended-Anthropic acceptance and controlled cache comparisons. Locally hidden text through Claude and legacy combined-envelope streaming order recovery are not claimed supported. Existing compatibility enforcement, hidden presentation, credential/admission and retention policies remain. + +Ordinary PR chain is an integration grouping requested by owner, with final combined CI first. Lower-layer runs only if it fails. Admin merge is authorized after accepted evidence. No GitHub native stack or fabricated check status. diff --git a/devlog/_fin/260907_axis3_protocol/020_delivery.md b/devlog/_fin/260907_axis3_protocol/020_delivery.md new file mode 100644 index 0000000000..714a9c0b8e --- /dev/null +++ b/devlog/_fin/260907_axis3_protocol/020_delivery.md @@ -0,0 +1,15 @@ +# Publish and deliver verified manual chain + +Prerequisite: wp1 accepted-source review and successful final-head remote validation, or source-grounded defer outcome. Publish ordinary PRs targeting dev then the parent branch, using every repository template section. Bodies name source PRs, own layer-only diff, exact final combined CI evidence and explicit lower-layer CI deferral per owner instruction. Do not attest local CI. Preserve original contributor trailers in commits; admin merge with merge commits preserves their identity. + +Read live native-stack membership and head/base identity before merge. Never register a native stack. Parent merges to dev first; retain its branch, retarget child to dev, verify current head and ancestry. If integration tree changes materially, refresh final combined CI before landing. Use --admin and --match-head-commit exact guard. Do not merge into the parent branch by mistake. Refresh origin/dev and prove each merge SHA ancestor. Close superseded source PRs only after equivalent fix is actually landed, with credit and replacement link. Keep #3807 and #3719 open if real reproduction/cache acceptance remains unmet. No release or deployment. + +Record final PR URLs, source-to-delivery mapping, commit authors/trailers, CI run and exact SHA, review verdicts, remaining limitations and preserved dirty-work evidence. No fabricated status checks. Completion: every candidate has an honest disposition, accepted work is landed, unresolved diagnostics explicitly deferred under user direction. + +## Delivery revalidation + +Previous D: all 24 real GitHub runtime producer jobs succeeded at final9b5b670db; same-head remote Bun1.4 full suite20897pass18skip0fail, focused405pass, docs build pass. Aggregate ci is still queued; do not claim the workflow complete or manufacture a status. Its only operation is combining those passed producer results. Maintainer explicitly authorized admin merge, and live dev rules expose no required_status_checks rule. Delivery may use the actual completed producer evidence with aggregation status explicitly disclosed; never waive an unrun or failed runtime producer. + +Carry late source docs #3815 through221353662: eight outbound redacted-reasoning table rows in the same eight locales. Prepared docs-only68d90aa37 has runtime/test trees identical to9b and remote docs build passed. After three runtime PRs land bottom-up, bring this docs-only tail and a final delivery record into a fourth ordinary PR. MOVE the completed owning unit from devlog/_plan/260907_axis3_protocol to devlog/_fin/260907_axis3_protocol and NEW021_delivery.md with actual merge/CI/source-credit evidence and deferred issues. No new runtime tests: exact code-tree equality plus docs build/hygiene are the applicable checks. + +Refresh dev and membership before each guarded admin merge; compare merged runtime tree with tested9b. Any unrelated concurrent dev change requires integration review and appropriate renewed evidence. Original #3815 and #3816 close only after their full carried changes (including docs tail) are landed. #3807 and #3719 remain open for the already recorded limits. diff --git a/devlog/_fin/260907_axis3_protocol/021_delivery_record.md b/devlog/_fin/260907_axis3_protocol/021_delivery_record.md new file mode 100644 index 0000000000..e27fd8b41b --- /dev/null +++ b/devlog/_fin/260907_axis3_protocol/021_delivery_record.md @@ -0,0 +1,31 @@ +# Axis 3 delivery record + +## Delivered runtime + +Ordinary PR chain, merged bottom-up with explicit owner admin authorization: + +| PR | Scope | Merge commit | +| --- | --- | --- | +| [3830](https://github.com/lidge-jun/opencodex/pull/3830) | Claude envelope foundation from #3815 | 2269e076d4222ada6ea3694fb8eed04f91a201d2 | +| [3831](https://github.com/lidge-jun/opencodex/pull/3831) | Grok strict-client projection from #3816 and SSE field correction | 07f8d70a75f088b19f4c9dd849e34034a88ab5f3 | +| [3832](https://github.com/lidge-jun/opencodex/pull/3832) | Replay boundaries, terminal overflow, established-history fixtures | 4349cf3cefdb5ed04575f49023ae34ffe6462e1c | + +Original contributors are retained in commits: SB Yoon and Yumi for #3815, Danh Thanh for #3816. Merge commits preserve the carried commits. The documentation-only tail of #3815 through221353662 is carried with both original contributor trailers in68d90aa37. + +## Verification + +- [Final candidate CI](https://github.com/lidge-jun/opencodex/actions/runs/34065721438) completed SUCCESS: all25 jobs at9b5b670db3e24ae5522c5d61e74c071c71257a26, including Linux, macOS shards/control and all six Windows shards. +- Same-head remote Linux Bun1.4.0 full suite:20897pass18skip0fail with `bun run test -- --parallel=1`; typecheck, privacy scan and documentation build passed. Focused protocol coverage:405pass1skip0fail. +- While CI ran, dev advanced to b65b9d8f2 with BigModel/Raycast changes. Conflict-free integration cc6afe2c97fb423363e99682b906bcb529478688 passed remote typecheck and633tests1skip0fail across15 relevant files, including shared passthrough/registry/layout guards. +- Actual runtime landing tree at4349cf3ce equals the integration tree ccaf0a0383cb3e8808e24576271c861625b506fb exactly. This is integration proof, not a claim that the earlier full CI ran on4349cf3ce. +- Independent Astra high source/security/integration reviews passed. The terminal-closure overflow finding was fixed before acceptance. New-test oracle mistakes found remotely were corrected without weakening exact assistant-array or pairing assertions. +- The earlier parallel remote run had21 catalog timeouts; isolated and final sequential runs passed, and final hosted CI passed. No separate root-cause fix is claimed. +- No local test suite or typecheck ran. All pushes used `--no-verify`. Native stacks and fabricated check statuses were not used. Automatic lower/intermediate CI was deferred or cancelled under the owner's combined-first direction. + +## Explicit remainders + +#3807 remains open: the demonstrated complete external-task envelope is already supported, and current-version raw reporter reproduction is unavailable. New ordinary, stored-ID continuation, v2-trigger and v1-compact fixtures preserve established history without relaxing missing-call-ID validation. + +#3719 remains open: live intended-Anthropic acceptance and controlled cache measurements are unverified. Locally hidden text through the Claude boundary and legacy combined-envelope streaming ordering remain outside the preservation claim. Existing compatibility enforcement, hidden display, authentication, routing and cache-retention defaults remain intact. + +The supplied dirty worktree and existing remote main checkout were preserved; execution used separate task worktrees. No release, deployment or account configuration change was made. diff --git a/devlog/_fin/260907_axis5_display_cli/000_plan.md b/devlog/_fin/260907_axis5_display_cli/000_plan.md new file mode 100644 index 0000000000..eb6ed46d27 --- /dev/null +++ b/devlog/_fin/260907_axis5_display_cli/000_plan.md @@ -0,0 +1,37 @@ +# Axis 5: display names and provider automation + +Date: 2026-09-07. Class C3, scoped satisfy-spec HOTL loop requested by owner. +Goal: deliver feasible unique changes from #3627, #2716, #3780 on dev with original author trailers. +Scope: display-only catalog metadata, discovered-model editor, optional JSONL CLI output, regression coverage and their docs. No auth/default/routing changes, native stacks, releases, or edits to existing dirty work. +Resources: existing repository/GitHub credentials and Astra high leaf agents; no user-set time/token cap. Isolated checkout /tmp/ocx-axis5-01a078d6. Owner authorizes no-verify push and admin merge. All local suites are prohibited; typecheck/build/test evidence will come from final combined GitHub CI. No invented lower-layer CI successes. +Terminal: merged, proven already delivered, or evidence-backed deferred when infeasible; finish after verifying all dispositions. New product decisions are isolated and deferred rather than guessed. +Records: this unit, .tmp/axis5-evidence, and session-bound .codexclaw goalplan. + +## Roadmap + +WP0: documentation-only source-delta and delivery plan, independent plan audit and document validation. +WP1: implement three scoped source carries with individual credited commits, publish ordinary manual PR chain, audit final tree, validate final combined head, merge verified layers bottom-up, and record dev ancestry. +The three layers are a user-requested review/integration sequence, not a claimed runtime dependency: native catalog -> JSONL CLI -> discovered editor. Source PR branches are never rewritten. +Read 010_delivery.md for diff-level scope and activation scenarios. + +## Sources + +- https://github.com/lidge-jun/opencodex/pull/3627 +- https://github.com/lidge-jun/opencodex/pull/2716 +- https://github.com/lidge-jun/opencodex/pull/3780 +- Base dev: 137d6a7270e7ecfb1c791993800a17c0e30022d9 +- Existing API display-name contract from #3212 is already on dev; only missing UI is carried. + +## CI and merge + +.github/workflows/ci.yml has pull_request triggers on all bases and workflow_dispatch lane=all for complete coverage. Pushes to feature branches do not independently trigger it. Defer/cancel only this task's lower-layer expensive runs as authorized, recording cancellation as cancellation. Dispatch all on final head; only if final CI fails use lower-layer runs to isolate. Do not edit shared workflow policy or fabricate check statuses. +Use merge commits and retain parent branches so commit identity and author trailers survive bottom-up merges. Retarget a child only after its parent lands. If dev moves concurrently, integrate the new dev into the top and refresh exact combined CI before shipping the resulting changed tree. +Review-ready requirements remain visible; local suite prohibition is explicitly documented instead of ticking a false local attestation. Admin waiver applies to the requested merge, not to truthful evidence. + +CI scope refinement: the discovered editor is the final layer so the final commit and PR diff include gui/**, activating GUI lint/build/artifact jobs. ci.yml gates always run GUI tests; docs deployment is NOT dispatched because it publishes. Public docs receive static source consistency inspection here, with docs build explicitly unverified unless an existing build-only remote path is available. + +CI scheduling refinement: lower-layer head commits may use GitHub documented [skip ci] to avoid push/pull_request suite launches; this yields missing/pending evidence, NOT green. Final head has no skip marker and receives lane=all workflow_dispatch. Source: https://docs.github.com/en/actions/how-tos/manage-workflow-runs/skip-workflow-runs (opened 2026-09-07). Admin merge records this explicit owner-requested lower-layer waiver. Do not propagate skip markers into integration merge messages. + +## Terminal status + +DONE: all three feature layers landed; see 020_delivery.md for exact commits, verification boundaries and deferred Mac test-runner investigation. diff --git a/devlog/_fin/260907_axis5_display_cli/001_roadmap_audit.md b/devlog/_fin/260907_axis5_display_cli/001_roadmap_audit.md new file mode 100644 index 0000000000..2e4b740b4d --- /dev/null +++ b/devlog/_fin/260907_axis5_display_cli/001_roadmap_audit.md @@ -0,0 +1,11 @@ +# Roadmap audit closure + +WP0 documentation implementation, 2026-09-07. +Independent Astra high reviewers: Carver (#3627), Godel (#2716), Anscombe (#3780 and integrated roadmap). + +The integrated verdict was GO-WITH-FIXES (four blockers). The plan now distinguishes lower-layer waived CI from final combined passing evidence; removes the unreachable empty-provider CLI acceptance; requires confirmed-persistence reconciliation after GUI refresh failure; and requires timeout reachability analysis against the installed bounded-fetch wrapper before adding any timeout logic. + +Source heads: native f699ec7f998d56bf205db96762b821cd8c228a35; editor 93ed44053b68a9707f8271981d5f7e4bc25e9b70; JSONL 9b873e6f7519a022dd4658db4d1cb92689bb4663. +The physical manual chain is native -> JSONL -> GUI, enabling final GUI CI jobs. It is owner-requested integration ordering, not a claimed runtime dependency. +Native external-name preservation is qualified by existing pinned Astra normalization; existing policy remains intact. +No product tests, typecheck or build ran. WP0 checks only roadmap structure, source paths, explicit acceptance and credit records. Product verification remains WP1 remote CI. diff --git a/devlog/_fin/260907_axis5_display_cli/010_delivery.md b/devlog/_fin/260907_axis5_display_cli/010_delivery.md new file mode 100644 index 0000000000..b9cc7e2c4d --- /dev/null +++ b/devlog/_fin/260907_axis5_display_cli/010_delivery.md @@ -0,0 +1,37 @@ +# WP1: reconcile, deliver, verify and merge axis 5 + +Depends on WP0 roadmap audit. Source baseline dev 137d6a727. Previous D must confirm roadmap-only completion before production patches. + +## Layer 1 — #3627 native display names + +MODIFY src/codex/catalog/sync.ts: introduce reversible native label overlay at observed-state merge, restore original label before metadata normalization, strip marker from template clones, apply configured label to supported bare native rows only. MODIFY src/codex/convergence.ts: supply the same modelDisplayNames map as retained sync. MODIFY tests/codex-integration/codex-catalog.test.ts and provider configuration docs (English, Japanese, Korean, Simplified Chinese). +Field chain: existing providers.openai.modelDisplayNames config -> both merge call sites -> nativeDisplayNames argument -> display_name plus catalog-only opencodex_native_display_name {slug,original,applied} -> JSON catalog serialization -> restoration before next normalization. Clone consumers must remove overlay markers; source inputs remain immutable. +Activation: configured label replaces native name; removing/blanking restores owned original; external Sol rename is preserved; Astra remains subject to existing pinned-metadata normalization and docs/tests state that exception; newer native metadata upgrades after reset; repeated serialized cycles stable; account-qualified/combo/pro/custom rows unchanged. Exact model IDs and capabilities unchanged. +Credit: Co-authored-by: Éverton Toffanetto . + +## Layer 2 — #2716 discovered name editor + +NEW gui/src/components/ModelDisplayNameDialog.tsx and gui/tests/models-display-name-editor.test.tsx from source PR after current API contract comparison. MODIFY gui/src/pages/Models.tsx, models-shared.ts, gui/src/styles.css, all nine locale modules, English provider configuration docs. +Field chain: existing /api/models displayNameOverride/displayNameSource -> ModelRow optional fields -> Name action/dialog -> existing display-name save/reset endpoint -> persisted provider modelDisplayNames -> reload /api/models. No new persisted field or endpoint is needed. +Activation: save/reset/unchanged cancel; blank/too long/slash/control input; one submit under double click; save failure retains dialog; reload failure remains recoverable; focus returns after close; original selector always visible and alias action remains separate. +Credit: Co-authored-by: Zig Zag . +Browser smoke: render real isolated app, open Name dialog and observe screenshot; use mocked management responses or isolated disposable home, never mutate personal config. GUI tests/build/i18n/lint and docs build are remote CI obligations; not run locally. + +## Layer 3 — #3780 provider JSONL + +MODIFY src/cli/provider.ts and src/cli/capabilities.ts to accept --jsonl, emit existing configured-array objects one per line, reject combined --json/--jsonl before reading config. MODIFY tests/cli/cli-provider.test.ts, public CLI docs and skills/ocx/references/01_management_surface.md, 02_json_shapes.md, 03_recipes.md. Regenerate or reconcile derived surface with generator source; no unrelated output. +Field chain: argv -> consumeFlag -> output choice; no config serialization changes. JSONL entries use exactly existing JSON configured fields; no credentials added. The real config loader seeds providers; a zero-provider CLI scenario is not a reachable acceptance claim. Preserve existing loader behavior. Extend source tests to compare every emitted object with --json.configured for multiple registry/custom providers, ensure empty stdout on both conflicting flag orders, and verify escaping. Update all seven translated CLI provider tables and describe consumer-side line processing without claiming producer streaming. +Activation: multiple providers including custom names -> one parseable record each; default human and --json unchanged; both flags rejected; unknown args still rejected; conflicting flags -> empty stdout before config loading. +Credit: Co-authored-by: 투린 . + +## Verification and disposition + +Static git diff --check and independent source audits throughout. Existing focused test paths are reviewed for target coverage, but ALL LOCAL SUITES NOT RUN by owner instruction. Final ci.yml workflow_dispatch lane=all on published final SHA supplies typecheck, full tests and platform results; inspect actual job conclusions and head SHA. Add missing coverage within source scope if audit identifies a contract gap. Inspect GUI workflow coverage and obtain remote GUI/build evidence if not present in final dispatch. +Source-of-truth: provider configuration and CLI docs above; update structure/03_catalog-and-subagents.md only for native overlay contract. No new enforcement layer; tests/CI are evidence, admin bypass is owner-authorized and recorded. +Before merging: fresh heads and native membership, independent review dispositions, final CI proof, original author trailers, screenshot for GUI PR. If infeasible, record concrete cause and leave only that layer unmerged. After each merge: verify mergeCommit SHA and inclusion on fetched dev. Close superseded original PR only once its delivery is on dev and preserve attribution. + +Audit amendment: native label restoration preserves an external edit only subject to existing metadata normalization, notably pinned Astra replacement. Do not change native normalization policy. Add the Astra external-edit regression and qualify the promise consistently in all four affected docs. The native feature must preserve metadata including capabilities; English/Japanese wording is explicit. Final physical branch order is native -> JSONL -> GUI to activate final GUI gates; numeric sections above identify features, not alternate dependency claims. + +GUI audit amendment: confirmed persisted save/reset must reconcile editor snapshot and draft even when reload fails. A saved:true error is distinct from an unpersisted error. Stalled requests must not lock every dialog exit indefinitely: use existing UI request cancellation/deadline conventions, and represent uncertain write outcome without claiming rollback. Add focused source tests for first-save/reset plus reload failure, saved:true errors, duplicate protection and stalled cancellation. + +Plan audit synthesis (Astra high Anscombe): GO-WITH-FIXES, four blockers folded. (1) Lower layer CI is explicitly waived/deferred, never labeled passing; fresh head/base checks plus resulting tree equivalence tie admin merges to final combined evidence. (2) Removed unreachable empty-provider CLI scenario; loader behavior preserved. (3) Confirmed-persistence vs refresh state and tests required. (4) First rederive stalled-request reachability through installed global createBoundedFetch; reuse existing bound if it already applies, add no duplicate budget. Any remaining timeout scenario must be production-reachable. diff --git a/devlog/_fin/260907_axis5_display_cli/020_delivery.md b/devlog/_fin/260907_axis5_display_cli/020_delivery.md new file mode 100644 index 0000000000..7a2b76d0f8 --- /dev/null +++ b/devlog/_fin/260907_axis5_display_cli/020_delivery.md @@ -0,0 +1,42 @@ +# Axis five delivery record + +Outcome: DONE on 2026-09-07. The three feature layers landed in dev through owner-authorized admin integration. Original contribution credit is present in both carried commits and merge commits. + +| Source | Delivery | Merge commit | +| --- | --- | --- | +| #3627 native OpenAI display names | #3820 | 1e16fe4c077ecf353d79c46873d8039d9176704d | +| #3780 provider list JSONL | #3821 | be24986e5ff8474ca6699895855f0ad9352e9d86 | +| #2716 discovered-model name editor | #3824 | 44c69fdd619b272066113388edd80f6c59b0682a | + +The source pull requests were closed after landing. The late #3627 head 81f150e4 added metadata wording already covered by the delivery; its runtime files were checked byte-for-byte against dev before closure. + +## Delivered behavior + +Native labels are reversible overlays on supported bare native rows. IDs, capabilities and routing remain intact; restoring a label still respects existing pinned Astra normalization. Both retained synchronization and convergence pass the same configuration map. + +JSONL emits one configured-provider object per line using the existing JSON fields. Both conflicting flag orders fail without stdout. Multi-provider parity and escaping are covered, and all translated CLI tables and generated capability documentation were updated. + +The editor preserves exact selectors, validates labels, supports reset, and recovers confirmed saves separately from failed refreshes and unknown transport outcomes. Stalled operations use the existing bounded-fetch mechanism. Draft reconciliation preserves the mounted dialog and focus behavior. Desktop/mobile Korean rendering and save/reset/validation/focus were driven against the compiled CI artifact with disposable fixtures. + +## Verification boundaries + +- Feature head f51ec2421c49df0fd4eac8a9a56a6283b426387d: [Cross-platform CI attempt 2](https://github.com/lidge-jun/opencodex/actions/runs/34068041704/attempts/2), 25 successful jobs. Dashboard tests: 1,737 passed, zero failed. Typecheck, lint, scans and build passed. +- Late platform base changes had zero overlap with the 39-file feature delta and passed [their 26-job CI](https://github.com/lidge-jun/opencodex/actions/runs/34068218011). Independent compatibility review checked the decompression diagnostics and container lifecycle interaction. +- Prospective merge tree 85c9b25818a93859a6d6fc824e2ed0678da46c8f passed 370 focused tests on isolated Linux with project Bun 1.4.0: 344 catalog/CLI tests and 26 editor tests, zero failures. The transmitted source archive SHA-256 was ae191e1f0a809e75c9c198bc92233964880541f6747e4603a47b2c180f773d49. +- The actual final runtime merge 44c69fdd619b272066113388edd80f6c59b0682a has exactly that tested tree. This is focused merged-tree evidence plus full feature-head CI, not a claim of full CI on the final merge commit. +- No local test suite, typecheck or build ran. Pushes used --no-verify. Lower-layer CI was deferred until a final-head failure, and no cancelled or missing check was presented as passing. +- Public documentation was source-reviewed. This axis did not run a documentation build. + +## Diagnostic disposition + +One Mac shard reached its 20-minute limit after an unchanged history-lock test. The full Mac control had two Cursor decoded-frame-silence assertion failures; the separately annotated server-auth stream reset was intentional and its test passed. Only the unsuccessful Mac jobs were replayed, with unchanged source and limits, and they passed. The [baseline control comparison](https://github.com/lidge-jun/opencodex/actions/runs/34069848260) also passed. These observations do not establish the stall or timing root cause. No threshold increase, assertion suppression, or unrelated harness fix was included; deeper investigation remains deferred. + +## Attribution + +- Éverton Toffanetto +- 투린 +- Zig Zag + +Original author identities remain in the landed commits; this note lists names without contact addresses. + +The preceding numbered files are the historical roadmap and audits; their original _plan locations refer to the planning phase before this closeout. diff --git a/devlog/_plan/260904_raycast_integration/000_plan.md b/devlog/_plan/260904_raycast_integration/000_plan.md new file mode 100644 index 0000000000..c98701a2cd --- /dev/null +++ b/devlog/_plan/260904_raycast_integration/000_plan.md @@ -0,0 +1,121 @@ +# Raycast Custom Providers integration — plan + +Raycast (Pro-only) reads `~/.config/raycast/ai/providers.yaml` and watches it, so a +file-toggle client is the right shape. Spec: https://manual.raycast.com/ai/custom-providers. + +Decisions taken with the maintainer: + +1. Install signal is `~/.config/raycast/ai` (the directory Raycast creates on + "Reveal Providers Config"), not `Raycast.app`. +2. A non-Pro plan is a warning in status/GUI, never a refusal. +3. Every exported model declares `tools: supported: true` (same stance as Hermes: + every routed model is tool-capable). +4. Array ownership goes into the shared merge/classifier layer as a path-segment + selector rather than a Raycast-only patcher. `structure/09_client-integrations.md` + forbids a special case that lives only in the writer or only in status; a + selector segment that `readPath`/`setPath`/`deletePath` all understand is the + one way both keep agreeing. + +## Raycast file shape + +```yaml +providers: + - id: opencodex # <- our one owned sequence item + name: OpenCodex + base_url: http://127.0.0.1:10100/v1 + models: + - id: anthropic/claude-opus-5 + name: Claude Opus 5 + context: 200000 + abilities: + temperature: { supported: true } + vision: { supported: true } + system_message: { supported: true } + tools: { supported: true } + reasoning_effort: { supported: false } +``` + +No `api_keys`: loopback is unauthenticated and the file has no env interpolation, +so the client is `loopbackOnly: true`. + +## Pro signal (macOS) + +`defaults read com.raycast.macos.v1 subscriptions_active` → `1` / `0`. Read via +`Bun.spawnSync`, not by parsing the binary plist (cfprefsd caches). Windows: `unknown`. + +## Work packages (disjoint files, run in parallel) + +| WP | Files | +|---|---| +| 1 merge selector | `src/integrations/merge.ts`, `src/integrations/state.ts`, `tests/integrations-merge.test.ts` | +| 2 client | `src/clients/config-export.ts`, `src/integrations/registry.ts`, `src/cli/registry.ts`, `src/cli/help.ts`, `tests/raycast-client.test.ts`, list-assertion tests | +| 3 sync fan-out | `src/integrations/owned-refresh.ts`, `src/cli/dispatch.ts`, `src/server/management/config-routes.ts`, `src/cli/index.ts`, `tests/sync-client-integrations.test.ts` | +| 4 detect + API + GUI | `src/integrations/raycast-detect.ts`, `src/server/management/integration-routes.ts`, `src/cli/integrations.ts`, `gui/**`, i18n | +| 5 docs | `docs-site/**` | + +### WP1 — `[field=value]` path segment + +```ts +// merge.ts +const ARRAY_SELECTOR = /^\[([A-Za-z_][A-Za-z0-9_]*)=([^\]]+)\]$/u; +export type PathSegment = { kind: "key"; key: string } | { kind: "select"; field: string; value: string }; +export function parseSegment(raw: string): PathSegment; +export class AmbiguousSelectorError extends Error {} +``` + +- `setPath`: a `select` segment addresses the element of an array whose + `item[field] === value`. Missing parent → `[]` is created (recorded by + `createdContainerPaths`). Match found → replace in place; none → push; ≥2 → + throw `AmbiguousSelectorError` (writer maps it to `unsafe` alongside + `UnserializableValueError`). +- `deletePath`: splice the match; an emptied array we created is pruned by the + existing `createdContainers` walk. +- `state.ts readPath`: `select` → `Array.prototype.find`. Because the classifier + and the writer share this one function, status and mutation cannot disagree. +- `blockedContainerPath`: a non-array, non-undefined value where a `select` + segment expects an array is blocked (`providers: {}` written by the user). +- `createdContainerPaths`: unchanged join rule; a `select` segment is never a + container prefix on its own. +- A key-only path is byte-for-byte the old behaviour; the twelve existing clients + do not change. + +### WP2 — client registration + +`config-export.ts`: `"raycast"` in `ExportClientId`; `raycastAiDir(env, home)` = +`join(home, ".config", "raycast", "ai")` (Raycast ignores XDG; same path on Windows); +`raycastConfigPath` = `…/providers.yaml`; types `RaycastAbility`, +`RaycastModelEntry`, `RaycastProviderEntry`, `RaycastGeneratedConfig`; +`buildRaycastClientConfig(ctx)` over `normalizeExportModels(ctx.models)` with +`exportModelLabel(model)` as `name`, `contextWindow` → `context`, abilities: +`temperature: !(reasoningEfforts?.length)`, `vision: inputModalities?.includes("image") ?? false`, +`system_message: true`, `tools: true`, `reasoning_effort: (reasoningEfforts?.length ?? 0) > 0`. +`buildRaycastContribution` = `singleFragment("raycast", ["providers", "[id=opencodex]"], providers[0])`. +`summarizeRaycast` finds the `opencodex` item. `EXPORT_CLIENTS.raycast`: +`filename: "raycast-providers.yaml"`, `format: "yaml"`, `apiKeyEnv: ""`, `loopbackOnly: true`. + +`registry.ts`: `configPath: raycastConfigPath`, `detectDir: raycastAiDir`, no +`sourcePreservingYaml` (that patcher handles block-map leaves only), no `writerLock`. + +### WP3 — sync fan-out + +Raycast joins the shared `refreshOwnedCatalogIntegrations` coordinator. Model +selection changes use its default `["pi", "aside", "raycast"]` set; +`POST /api/sync` uses `["mcode", "pi", "aside", "raycast"]`; direct CLI sync +updates `["mcode", "pi", "raycast"]` locally and keeps Aside behind its +server-owned multi-profile route. Startup and ensure refresh the owned Raycast +catalog after the Codex catalog publishes, using the live port. + +### WP4 — detection, API, GUI + +`raycast-detect.ts` mirrors `cursor-detect.ts` (injectable deps, read-only): +`RaycastPlan = "pro" | "free" | "unknown"`, `detectRaycast(deps)` → +`{ appPath, aiDirPresent, plan }`. `GET /api/client-integrations/raycast` +adds `raycast: { plan, appPath, aiDirPresent }` to the envelope (only for this +client). `ocx integration client status --client raycast` prints `plan`. GUI: +every surface in `devlog/_fin/260831_aside_client_and_integrations_ux/002_registration_checklist.md` +plus one `RaycastPlanNotice` shown when `plan !== "pro"` or `!aiDirPresent`. + +### WP5 — docs + +`guides/integrations.md` row + paragraph (Pro, reveal-first), `reference/cli/agents.md`, +translated locales, `bun run build` in `docs-site`. diff --git a/devlog/_plan/260907_platform_validation/000_plan.md b/devlog/_plan/260907_platform_validation/000_plan.md new file mode 100644 index 0000000000..d1b3cb632f --- /dev/null +++ b/devlog/_plan/260907_platform_validation/000_plan.md @@ -0,0 +1,31 @@ +# Platform verification follow-up + +Baseline: dev `137d6a7270e7ecfb1c791993800a17c0e30022d9` (2026-09-07). + +## Objective and authority + +Satisfy the existing platform contracts for #3383, #3449, #3522 and #3573. The owner requested ordinary manual PRs, top-of-stack CI first, lower-layer CI only to diagnose a failed final run, no local test suites, push with --no-verify, admin merge after verification, and original contributor credit in commit trailers. No native GitHub stack registration. No publish, release, global settings changes, admission-limit increases, ACL relaxation, or speculative recovery policy. + +The initial assigned checkout contains unrelated dirty work and is preserved. Work lives in an isolated worktree. No SessionStart FSM binding is available in the supplied context; this record documents the work without claiming automatic loop continuation is armed. + +## Evidence and scope + +Dockerfile, compose.yaml, docker/bootstrap-token.ts and the source-build guide already exist. Cross-platform CI has no real image build/start/recreate check. #3522 requires same-process Windows recovery evidence; #3573 requires actual rejected compact-byte evidence. Existing diagnostics must be checked before adding anything. PR #3383 is a mixed historical source: only Windows temp/teardown residuals are in scope, not picker controls. + +Original Docker contributor: Buseong Kim , verified from original #3421 commit metadata. Carry this identity in commit trailers. + +## Dependency map + +1. `010_oauth_teardown.md`: drain the asynchronous ACL fixture before deletion. +2. `020_container_smoke.md`: executable isolated container acceptance probe. +3. `030_container_ci.md`: CI consumes that probe and gates its result. +4. `035_body_diagnostics.md`: distinguish declared size, observed lower bound, and decoded size without changing admission. +5. `040_residual_evidence.md`: settle the Windows/spill/compact residuals; implement only a proven narrow gap through a plan amendment, otherwise preserve open status. + +The manual review chain contains the independent OAuth fixture carry, bounded body diagnostics, the container probe, then its dependent CI integration. Independent code is prepared in disjoint files; the top CI validates their combined tree. Existing workflow triggers remain honest: final branch workflow_dispatch supplies the complete integration result; lower PR runs are not represented as passed if skipped/cancelled. Every implemented layer is reviewed, and final head is pinned before CI. After successful final CI, merge bottom-up using merge commits so reviewed commit ancestry survives. Revalidate the resulting integration and distinguish unrelated concurrent dev changes. + +## Verification and completion + +Local suites and typecheck are NOT RUN by owner instruction. Syntax and read-only diff checks are allowed. The real verifier is GitHub Cross-platform CI on the final branch, including the new Docker job. A failed final run is diagnosed on the smallest affected scope; do not repeatedly run passing gates. Independent Astra high review covers functionality and workflow/security boundaries. Security working notes remain in scratch, not this public unit. + +Completion means verified deliverable PRs merged with commit attribution, plus explicit no-op/blocked disposition for unavailable field evidence. It does not mean every original issue is fixed. New product/security policy choices remain outside scope. Evidence and final outcome are appended to this unit; workflow run URLs and SHAs are preserved. diff --git a/devlog/_plan/260907_platform_validation/001_plan_audit.md b/devlog/_plan/260907_platform_validation/001_plan_audit.md new file mode 100644 index 0000000000..96ac86c266 --- /dev/null +++ b/devlog/_plan/260907_platform_validation/001_plan_audit.md @@ -0,0 +1,5 @@ +# Plan audit disposition + +Independent Astra high reviewer: NEAR-PASS. OAuth teardown and bounded body diagnostics passed within scope. Three Docker/CI conditions were incorporated before implementation: explicit final lane=all executed-job inventory; isolated project/image/port and bounded cleanup; concrete readiness/admission/catalog/persistence checks before and after actual replacement. + +Main judgment: pass with those amendments. Scope remains unchanged: existing Docker contract verification, test-fixture teardown, bounded diagnostics. Live spill recovery and exact historical compact-body proof remain deferred. No local suites or typecheck were run. diff --git a/devlog/_plan/260907_platform_validation/010_oauth_teardown.md b/devlog/_plan/260907_platform_validation/010_oauth_teardown.md new file mode 100644 index 0000000000..d4ee405020 --- /dev/null +++ b/devlog/_plan/260907_platform_validation/010_oauth_teardown.md @@ -0,0 +1,14 @@ +# OAuth fixture teardown carry + +Original source: #3383 commit 51726d2c7c58146defdd6088aefa2b95a1e58553. +Original contributor: x3M3x (Git commit metadata). + +## Concrete delta + +MODIFY `tests/oauth/oauth-store-multi.test.ts` only: import flushConfigDirHardeningForTests and the async ICACLS test runner; stub synchronous and asynchronous runners consistently in setup. Change teardown to await the tracked hardening work before resetting runners/caches, restoring OPENCODEX_HOME, or removing the fixture. Preserve removeTreeWithRetry and all production semantics. Add a deterministic held-async-runner regression against the actual cleanup routine if the existing fixture seams allow it without a new production test API. + +Production path proof: store reads call hardenConfigDir; config/paths tracks asynchronous directory hardening; resetHardenedStateForTests clears caches but does not drain those jobs. Deletion retries alone do not ensure ordering. The prior carry #3258 only replaced the removal function. + +## Acceptance + +No real asynchronous ICACLS escapes the fixture runner. Cleanup waits while a controlled ACL flight is unresolved and only deletes/restores environment after completion. The same OAuth test file passes in final Linux/macOS/Windows CI. Local tests/typecheck are NOT RUN by owner instruction. No numeric-open-flags change is included without current Bun reproduction. No new API/auth policy, credentials, or production runtime change. diff --git a/devlog/_plan/260907_platform_validation/020_container_smoke.md b/devlog/_plan/260907_platform_validation/020_container_smoke.md new file mode 100644 index 0000000000..17d7139d35 --- /dev/null +++ b/devlog/_plan/260907_platform_validation/020_container_smoke.md @@ -0,0 +1,25 @@ +# Container smoke executable + +## File delta + +NEW `scripts/ci/docker-smoke.ts`: bounded Bun-native TypeScript probe for the existing source-build Compose contract. Reuse the canonical compatibility generator and docker/bootstrap-token.ts; do not add an alternative token writer or deployment configuration. The probe creates a unique temporary Compose project and image, builds the actual Dockerfile, bootstraps a freshly generated throwaway token through stdin, starts the hub, verifies health and data-plane admission, recreates the container on the same named volumes, and verifies persistent state again. Cleanup is limited to the unique test project and its generated artifacts. Never use an operator project, host home, provider credentials, global docker prune, or real upstream inference. + +MODIFY owning documentation only as needed to explain the CI acceptance scope and its limits; no claim of upstream-provider validation. + +## Acceptance + +- Real image builds from the checkout with a generated compatibility manifest. +- Read-only/non-root Compose service becomes healthy; requests without a token are refused. +- A synthetic catalog in the separate Codex volume is served with the throwaway token, proving admission and persistence without provider access. +- /readyz succeeds separately from liveness, token reinitialization fails without replacement, and effective container restrictions are verified. +- Token/config/catalog persist across an actual container replacement (different container id, same volumes). +- Failures and cleanup are bounded; token/body contents never appear in logs. +- Existing Docker settings and defaults remain unchanged. + +Run only in final remote CI. Locally perform source/static inspection, not the smoke or a test suite. Read the current lifecycle/API contracts before implementing assertions. + +## Audit amendments + +Use explicit unique project on every Compose command, unique image tag via a temporary override, controlled Compose environment, and loopback ephemeral host port. Preserve pre-existing generated files; cleanup must fail the probe if it cannot remove its own project resources. Bound every child, output capture and cleanup; terminate/reap timed-out children. Never print raw runtime logs or complete inspect output. + +Before/after replacement: require readyz 200 with status ready; authenticated catalog 200 with exact synthetic fixture; missing/wrong token 401 for catalog, Responses and compact. Second bootstrap must fail and preserve the original token while rejecting the proposed replacement. Verify different container IDs, identical named-volume identities and persistent config/catalog evidence without reseeding; check effective non-root UID and read-only root. diff --git a/devlog/_plan/260907_platform_validation/025_container_lifecycle_mode.md b/devlog/_plan/260907_platform_validation/025_container_lifecycle_mode.md new file mode 100644 index 0000000000..c86f4fc765 --- /dev/null +++ b/devlog/_plan/260907_platform_validation/025_container_lifecycle_mode.md @@ -0,0 +1,10 @@ +# Container lifecycle mode + +Amendment after real Docker recreation verification. Docker supervises the foreground hub and must retain persisted routed state across replacement. + +MODIFY Dockerfile runtime ENV: set existing OCX_SERVICE=1, with no service manager installation or privilege change. Preserve image digest, foreground CMD, listener authentication, separate writable homes and read-only root. +MODIFY scripts/ci/docker-smoke.ts: assert the actual container process receives service lifecycle mode. Retain the routed synthetic slug and exact token/catalog/config hashes across graceful recreation. +MODIFY tests/service/container-bootstrap.test.ts: include the runtime ENV declaration in the existing packaging contract. +MODIFY docs-site/src/content/docs/guides/remote-hub.md: document service-mode foreground lifecycle, Compose restart/recreation, and the limit on other dashboard restart paths. + +Independent Astra high lifecycle/security review accepted the bounded packaging change. Actual remote CLI comparison confirmed preservation with service mode. Final image CI must prove the same real container lifecycle; no local tests or Docker execution. This does not change shared CLI cleanup, restart policy, or authentication code. diff --git a/devlog/_plan/260907_platform_validation/030_container_ci.md b/devlog/_plan/260907_platform_validation/030_container_ci.md new file mode 100644 index 0000000000..28f3e08fc9 --- /dev/null +++ b/devlog/_plan/260907_platform_validation/030_container_ci.md @@ -0,0 +1,21 @@ +# Container CI integration + +Depends on the committed probe from phase 1. + +## File delta + +MODIFY `.github/workflows/ci.yml`: include Dockerfile, compose.yaml, .dockerignore and docker/** in relevant scope detection; add an ubuntu-latest Docker smoke job using the existing pinned checkout and setup-project-bun action; invoke the script after installing required project dependencies if the generator needs them. Preserve read-only workflow permissions and persist-credentials false. Add the job to aggregate ci needs so failures cannot silently pass. No registry publishing, credentials, native stack integration or changes to existing suite retry/concurrency policy. + +MODIFY `tests/ci-workflows/ci-workflows.test.ts`: extend the existing source-oracle checks for scope paths, direct aggregate dependency, pinned actions, and actual probe invocation. Keep existing domain/layout registration unchanged by using the owning test file. + +MODIFY `docs-site/src/content/docs/guides/remote-hub.md`: describe image lifecycle validation and separate readiness/provider-auth limitations. + +## Acceptance and verifier + +Final-branch Cross-platform CI workflow_dispatch must run the smoke and the existing platform gates. The Docker job's failures must reach ci. Local suite/typecheck NOT RUN per owner. Independent review checks full workflow event, permission, input, credential, and cleanup boundaries before publishing. Existing source-oracle tests execute remotely in CI. + +Publish branches with --no-verify; do not claim lower-layer CI if only the final tree was tested. Final failure permits narrower runs. User authorized admin merge of verified layers; original author names/emails come from source commit metadata and are included as Co-authored-by trailers. + +## Final execution inventory + +Dispatch existing Cross-platform CI with lane=all on the immutable final head. Record each expected job and actual conclusion: Docker, four Linux shards, storage-policy, api-usage, gates, two macOS shards, macos-control, six Windows shards, keyring jobs, any selected npm packaging jobs, and ci. Aggregate green alone does not prove Windows or Docker ran. Explain legitimate scope skips instead of counting them as tests. diff --git a/devlog/_plan/260907_platform_validation/035_body_diagnostics.md b/devlog/_plan/260907_platform_validation/035_body_diagnostics.md new file mode 100644 index 0000000000..5165526583 --- /dev/null +++ b/devlog/_plan/260907_platform_validation/035_body_diagnostics.md @@ -0,0 +1,17 @@ +# Bounded inbound-body diagnostic semantics + +Issue #3573 requests usable size evidence. The existing error stores a byte value but returns only the admission limit; the byte value currently mixes declared length, observed wire bytes, an artificial limit+1 lower bound, and exact decoded length. + +## File delta + +MODIFY `src/server/request-decompress.ts`: extend DecompressedBodyTooLargeError with a closed measurement category and retained limit, preserving existing constructor call compatibility. Annotate existing throw sites: declared_wire, observed_wire_lower_bound, decoded_exact, decoded_lower_bound. Append a bounded numeric/category suffix to the current message so existing core.ts error mapping carries it. No request body, path, headers, item counts, further inflate/read, admission-limit changes, or new retry semantics. + +MODIFY `tests/usage/request-decompress.test.ts`: extend small-cap fixtures to verify identity/gzip/zstd/deflate and declared/fragmented input semantics. In particular, limit+1 remains a lower bound, never exact size. Verify HTTP 413 and existing error code/type through existing handler mapping. Preserve stream cancellation. + +MODIFY `docs-site/src/content/docs/reference/proxy-formats.md`: explain wire declared length vs measured/lower-bound diagnostics, separately from compact-response limits. State that Bun listener rejection may happen before application diagnostics and that this does not measure the exact historical compact payload. + +## Acceptance + +Unchanged 256 MiB listener/decoder limit and rejection classification. No context-window wording that causes errors.ts to reclassify the failure. Message remains bounded, only fixed categories and finite numeric values. Negative tests run in final remote CI; no local test/typecheck. Keep #3573 open pending exact real compact evidence. + +This is a new diagnostic refinement of an issue, not a carry of a new contributor PR. Credit reporter @nowhere1975 in commit prose without inventing name/email. Any borrowed existing PR patches must additionally retain their actual git author trailers. diff --git a/devlog/_plan/260907_platform_validation/040_residual_evidence.md b/devlog/_plan/260907_platform_validation/040_residual_evidence.md new file mode 100644 index 0000000000..f5466a4d38 --- /dev/null +++ b/devlog/_plan/260907_platform_validation/040_residual_evidence.md @@ -0,0 +1,15 @@ +# Windows and request diagnostic residuals + +## Read-only targets + +- #3383: inspect current PR and merged descendants for Windows temp creation and OAuth teardown. Confirm current source behavior and test coverage before proposing a residual patch. No picker UI changes. +- #3522: inspect response spill telemetry and fresh-versus-memoized timeout handling. The acceptance is recovery within the same affected Windows process; generic synthetic success does not prove the reported process recovered. +- #3573: inspect decompression rejection diagnostics and exact latest issue measurements. Serialized journal size and normal requests after raising a cap do not prove the rejected compact payload size or compact success. + +## Conditional delta + +No production edit is pre-approved by this document without a source-grounded residual. If the existing code covers the measurement, record the missing field evidence and leave the issue open. If a specific content-free diagnostic is missing, amend with exact files, field flow and negative assertions before implementation. Never change admission caps, parse a rejected body to count items, relax ACLs, clear memo state, or choose a new recovery/retry policy. + +## Completion + +Record source/commit evidence, original contributor attribution where code is carried, and a separate status per candidate: already implemented, proven patch delivered, or blocked on field evidence. Do not close an original feature PR or issue merely because one residual probe passes. diff --git a/docs-site/public/pr-screenshots/raycast-integration.png b/docs-site/public/pr-screenshots/raycast-integration.png new file mode 100644 index 0000000000..e17261c158 Binary files /dev/null and b/docs-site/public/pr-screenshots/raycast-integration.png differ diff --git a/docs-site/src/content/docs/fr/guides/claude-code.md b/docs-site/src/content/docs/fr/guides/claude-code.md index 5c13e041b6..2ae3940254 100644 --- a/docs-site/src/content/docs/fr/guides/claude-code.md +++ b/docs-site/src/content/docs/fr/guides/claude-code.md @@ -500,12 +500,14 @@ Le proxy traduit chaque requête Anthropic Messages API au format Codex Response | Texte assistant | `output_text` | | Assistant `tool_use` | `function_call` (`input` → JSON-stringifié `arguments`) | | Utilisateur `tool_result` | `function_call_output` (`is_error` → préfixe `[tool error]`) | -| Relecture de `thinking` / `redacted_thinking` | Ignorée | +| Relecture de `thinking` / `redacted_thinking` | Éléments `reasoning` avec enveloppes `ocxr1` bornées pour les signatures et les contenus masqués | | Outils fonctionnels | `{type: "function"}` (`web_search*` → `{type: "web_search"}`) | | `tool_choice` | `auto`→`auto`, `none`→`none`, `any`→`required`, fonction nommée→`{type:"function",name}`, hébergée WebSearch/web_search→`{type:"web_search"}` | | `max_tokens` | `max_output_tokens` | | `stop_sequences` | `stop` | +Sur l’adaptateur Anthropic prévu, les blocs signés non masqués (y compris thinking vide) et les blocs redacted opaques sont préservés. `hideThinkingSummary` reste inchangé : le texte signé masqué localement n’est pas exposé aux clients Claude ; sa relecture sans perte via cette frontière reste non établie. Les anciennes enveloppes combinées ne permettent pas de rétablir l’ordre après émission du texte en streaming. `claudeCode.compatibility: "enforce"` refuse toujours la relecture thinking. Cela ne prouve ni l’acceptation réelle par Anthropic ni une amélioration du cache ; [#3719](https://github.com/lidge-jun/opencodex/issues/3719) reste ouvert. + **Cas d'erreur (400) :** JSON mal formé ; `model` absent ou vide ; `messages` absent ou vide ; rôle non pris en charge ; `tool_result` sans `tool_use_id` ; `tool_use` sans identifiant ni nom ; `tool_choice` nommé sans nom. @@ -516,7 +518,8 @@ Le proxy traduit chaque requête Anthropic Messages API au format Codex Response | `response.created` | `message_start` + `ping` | | Battement de coeur | `ping` | | Deltas de texte | `content_block_start` → `content_block_delta` (texte) → `content_block_stop` | -| Résumé ou texte de raisonnement | Bloc `thinking` avec signature synthétique | +| Résumé ou texte de raisonnement | Bloc `thinking` avec la signature relue, ou une enveloppe de secours `ocxr1` bornée | +| Raisonnement expurgé | Blocs `redacted_thinking` relus depuis l'enveloppe de raisonnement | | Trames d'appel de fonction | Bloc `tool_use` avec `input_json_delta` | | Événement terminal | `message_delta` → `message_stop` | | EOF avant la borne | style 502 `api_error` | diff --git a/docs-site/src/content/docs/fr/guides/integrations.md b/docs-site/src/content/docs/fr/guides/integrations.md index c65531a4d3..c718801ddc 100644 --- a/docs-site/src/content/docs/fr/guides/integrations.md +++ b/docs-site/src/content/docs/fr/guides/integrations.md @@ -1,10 +1,10 @@ --- title: Intégrations -description: Connectez opencodex à OpenCode, Pi, OMP, Hermes, OpenClaw, Kimi Code, Gajae Code, DeepSeek Harness et MiniMax Code depuis le tableau de bord — un commutateur par client, avec une sauvegarde avant chaque écriture. +description: Connectez opencodex à OpenCode, Pi, OMP, Hermes, OpenClaw, Kimi Code, Gajae Code, DeepSeek Harness, MiniMax Code, ZCode, Prime Agent, Aside et Raycast depuis le tableau de bord — un commutateur par client, avec une sauvegarde avant chaque écriture. --- L'onglet **Intégrations** écrit le bloc fournisseur d'opencodex dans le fichier de configuration du client, -puis peut le retirer. Neuf clients fonctionnent ainsi, chacun avec son propre commutateur : +puis peut le retirer. Treize clients fonctionnent ainsi, chacun avec son propre commutateur : | Client | Fichier de configuration | Format | Prise d'effet de la modification | Identifiant | |---|---|---|---|---| @@ -17,6 +17,10 @@ puis peut le retirer. Neuf clients fonctionnent ainsi, chacun avec son propre co | Gajae Code | `~/.gjc/agent/models.yml` | YAML | dans les nouvelles sessions ou à l'ouverture de `/model` |`OPENCODEX_GAJAE_API_KEY` | | DeepSeek Harness (DSH) | `$DSH_HOME/settings.yaml` (`~/.dsh/settings.yaml` par défaut) | YAML | rechargement à chaud | jeton porteur fictif et non secret pour le bouclage | | MiniMax Code | `~/.minimax/config.yaml` | YAML | dans les nouvelles sessions ou après l’ouverture du sélecteur de modèles | valeur fictive de bouclage | +| Prime Agent | `~/.prime/agent/models.json` | JSON | dans les nouvelles sessions | valeur fictive de bouclage | +| ZCode | `~/.zcode/v2/config.json` | JSON | au redémarrage | valeur fictive de bouclage | +| Aside | `~/.aside/u//models.json` | JSON | après avoir quitté complètement puis rouvert Aside | valeur fictive de bouclage | +| Raycast | `~/.config/raycast/ai/providers.yaml` | YAML | immédiatement à l'enregistrement — Raycast surveille le fichier | aucun — bouclage uniquement | La prise en charge gérée de DSH exige au minimum **DSH 0.1.0-rc.6**. OpenCodex ne possède que le fragment `llm-pi-ai.providers.opencodex` : **Appliquer** et **Actualiser** remplacent ce fragment, **Désactiver** ne @@ -33,6 +37,37 @@ L’actualisation de l’intégration met également à jour les fenêtres de co d’effort de raisonnement faisant autorité ; les capacités inconnues sont omises et l’effort courant, qui appartient à la session MCode, est préservé. +Raycast a deux prérequis. Les fournisseurs personnalisés (Custom Providers) sont une fonctionnalité +**Raycast Pro** : avec un forfait gratuit, le fichier est tout de même écrit, mais +`ocx integration client status --client raycast` et la page Intégrations signalent un avertissement, +car Raycast ne le lira pas. Et Raycast ne crée son dossier `ai` que lorsque vous ouvrez une fois +Raycast → Settings → AI → **Reveal Providers Config** ; opencodex utilise ce dossier comme signal +d'installation et indique que le client n'est pas installé tant qu'il n'existe pas. Raycast lit +`~/.config/raycast/ai/providers.yaml` aussi bien sur macOS que sur Windows et n'honore pas +`XDG_CONFIG_HOME` ; ce chemin ne peut donc pas être déplacé. + +Le bloc géré est un seul élément, `id: opencodex`, dans la séquence `providers` du fichier : +`name: OpenCodex`, `base_url: http://:/v1`, et chaque modèle routé avec ses `abilities` — +`tools` et `system_message` sont définis à `true` par convention d’export, `vision` suit les modalités d'entrée du +catalogue, `reasoning_effort` est défini lorsque le modèle dispose d'une échelle d'effort, et +`temperature` est désactivé pour les modèles de raisonnement. Les autres fournisseurs du fichier sont +préservés, et la désactivation ne retire que l'élément OpenCodex. Raycast prend en compte la +modification dès l'enregistrement du fichier, sans redémarrage ; les modèles apparaissent dans le +sélecteur de modèles de Raycast regroupés sous **OpenCodex**. Raycast accepte le champ facultatif +`api_keys`, mais OpenCodex l’omet volontairement et refuse les cibles hors bouclage ou exigeant +authentification : cette intégration ne fournit pas l’en-tête d’admission requis par OpenCodex. +Le signal Pro issu d’une préférence privée macOS est indicatif ; Windows ne la lit jamais et +renvoie un état inconnu. Il ne bloque pas l’écriture. Les métadonnées exportées ne prouvent pas +la prise en charge des outils pour chaque modèle. Les valeurs des autres fournisseurs sont +préservées, sans garantie pour les commentaires ou la mise en forme YAML. Le format est documenté sur +[manual.raycast.com/ai/custom-providers](https://manual.raycast.com/ai/custom-providers). + +Les exports Raycast en CLI et les téléchargements utilisent la destination et la politique +d’admission du serveur actif, y compris son listener de bouclage sans authentification. +`ocx ensure` ne réactualise pas Raycast depuis sa copie de configuration enregistrée, qui peut +différer du serveur actif. Le démarrage du serveur et la synchronisation explicite restent disponibles. + + Les chemins respectent les variables de remplacement propres à chaque client, lorsqu'elles existent. Pour OMP, la présence de `OMP_PROFILE` l'emporte sur `PI_PROFILE`, même si sa valeur est explicitement vide. Un profil nommé emploie `PI_CONFIG_DIR` comme nom de répertoire relatif au dossier personnel de l'utilisateur @@ -93,7 +128,7 @@ niveaux. Dans ces cas, le commutateur est verrouillé afin que rien ne soit modi **OMP** n'est pas affecté non plus par les modifications voisines, mais pour une autre raison : son outil d'écriture ne modifie, octet par octet, que sa propre plage `providers.opencodex` ; le reste du fichier n'est jamais réécrit. Pour les autres formats susceptibles de contenir des commentaires (Hermes, OpenClaw, -Kimi Code, Gajae Code et MiniMax Code — documents YAML, JSON5 et TOML réécrits en entier), ou lorsque les propres entrées +Kimi Code, Gajae Code, MiniMax Code, ZCode, Prime Agent, Aside et Raycast — documents YAML, JSON5 et TOML réécrits en entier), ou lorsque les propres entrées d'opencodex ont été modifiées, le commutateur se verrouille et la désactivation est refusée plutôt que de deviner quelles modifications vous appartiennent. @@ -169,9 +204,11 @@ ocx integration client enable --client mcode ocx mcode ``` -Une fois l’intégration connectée, `ocx sync` actualise également le bloc MCode géré avec les fenêtres de -contexte et les niveaux d’effort de raisonnement actuels. Les blocs absents, modifiés par un tiers, non sûrs -ou jamais gérés restent intacts ; réactivez explicitement l’intégration lorsque vous souhaitez la reconnecter. +Une fois l’intégration connectée, `ocx sync` et `POST /api/sync` actualisent les catalogues MCode, +Pi, Aside et Raycast gérés. Le démarrage du proxy actualise aussi le catalogue Raycast géré. +Les changements de visibilité, de fournisseur ou de préréglage actualisent Pi, Aside et Raycast. +Les blocs absents, modifiés par un tiers, non sûrs ou supprimés manuellement restent intacts ; +réactivez explicitement l’intégration lorsque vous souhaitez la reconnecter. Le CLI distinct de la plateforme MiniMax (`mmx`) n’est pas une intégration à commutateur de fichier. Ses commandes textuelles utilisent le point de terminaison compatible avec Anthropic de MiniMax ; OpenCodex diff --git a/docs-site/src/content/docs/fr/guides/providers.md b/docs-site/src/content/docs/fr/guides/providers.md index 988ca03cf7..89b3a7c626 100644 --- a/docs-site/src/content/docs/fr/guides/providers.md +++ b/docs-site/src/content/docs/fr/guides/providers.md @@ -312,6 +312,7 @@ promotionnels de Cline ne sont accessibles que dans l'IDE ou la CLI Cline, pas p | NVIDIA NIM | `https://integrate.api.nvidia.com/v1` | | Z.AI (GLM Coding) | `https://api.z.ai/api/coding/paas/v4` | | Zhipu AI (BigModel) | `https://open.bigmodel.cn/api/paas/v4` | +| [BigModel Coding Plan — Responses (liste statique)](/guides/providers/#bigmodel-coding-plan-over-responses) | `https://open.bigmodel.cn/api/v1` | | Qwen Cloud | Forfait à jetons (par défaut) : `https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1` · Facturation à l'usage : `https://dashscope.aliyuncs.com/compatible-mode/v1` · ou personnalisé | | Tencent Cloud Coding Plan | `https://api.lkeap.cloud.tencent.com/coding/v3` | | SiliconFlow | `https://api.siliconflow.cn/v1` | @@ -495,7 +496,7 @@ une barre trompeuse. > programmation interactifs. L'automatisation générale par API, les services applicatifs personnalisés et les > traitements par lots non interactifs sont interdits et peuvent entraîner la suspension de la clé du forfait. -> **Deux routes GLM :** `zai` correspond à l'abonnement international Z.AI Coding Plan ; `zhipu-bigmodel` +> **Facturation GLM :** `zai` correspond à l'abonnement international Z.AI Coding Plan ; `zhipu-bigmodel` > correspond au point de terminaison national BigModel de Zhipu, facturé à l'usage. Les hôtes, les clés et la > facturation diffèrent : une clé émise pour l'un ne permet pas de s'authentifier auprès de l'autre. diff --git a/docs-site/src/content/docs/fr/reference/cli/agents.md b/docs-site/src/content/docs/fr/reference/cli/agents.md index e1501048c6..749119f70a 100644 --- a/docs-site/src/content/docs/fr/reference/cli/agents.md +++ b/docs-site/src/content/docs/fr/reference/cli/agents.md @@ -164,7 +164,7 @@ Gérez et appliquez la clôture du modèle Grok Build. ## Exportation de la configuration client -### `ocx export --client ` +### `ocx export --client ` Imprimez une configuration client connectée au proxy en cours d'exécution. La commande sérialise le bloc fournisseur `opencodex` — URL de base, liste de modèles et référence d’identifiant du client @@ -175,7 +175,7 @@ les modèles Codex peuvent actuellement voir. | Option | Actions | | --- | --- | -| `--client ` | Requis. Sélectionne le dialecte de configuration client. | +| `--client ` | Requis. Sélectionne le dialecte de configuration client. | | `--json` | Imprimez le document généré en tant que JSON sur la sortie standard pour les scripts. Il s'agit de JSON même lorsque le format natif du client sélectionné est YAML, TOML ou JSON5. | | `--out ` | Écrivez le format de configuration natif du client dans ``. Refuse de remplacer un fichier existant. | | `--force` | Autoriser `--out` à remplacer un fichier existant. | @@ -205,6 +205,17 @@ propres valeurs par défaut à ces lignes. | `mcode` | `~/.minimax/config.yaml` (`MINIMAX_DATA_DIR`, puis l'ancien `MAVIS_DATA_DIR`, l'emportent une fois définis ; une valeur relative est refusée) | `mcode-config.yaml` | aucun — espace réservé de bouclage | | `zcode` | `~/.zcode/v2/config.json` (`ZCODE_DATA_DIR` l'emporte une fois défini ; une valeur relative est refusée) | `config.json` | aucun — espace réservé de bouclage | | `prime` | `~/.prime/agent/models.json` (`PRIME_AGENT_CODING_AGENT_DIR` l'emporte une fois défini ; une valeur relative est refusée) | `prime-models.json` | aucun — espace réservé de bouclage | +| `raycast` | `~/.config/raycast/ai/providers.yaml`, sur macOS comme sur Windows (Raycast n'honore pas `XDG_CONFIG_HOME`) | `raycast-providers.yaml` | aucun — bouclage uniquement, aucune entrée `api_keys` n'est écrite | + +L'exportation Raycast est un document `providers.yaml` autonome contenant un seul élément `id: opencodex` +dans la séquence `providers` : `name: OpenCodex`, l'URL de base `/v1` du proxy et chaque modèle routé avec +ses `abilities` (`tools` et `system_message` toujours pris en charge, `vision` d'après les modalités d'entrée +du catalogue, `reasoning_effort` lorsque le modèle dispose d'une échelle d'effort, `temperature` désactivé +pour les modèles de raisonnement). Les fournisseurs personnalisés sont une fonctionnalité Raycast Pro, et +Raycast surveille le fichier : une modification enregistrée prend effet sans redémarrage. Le format est +documenté sur [manual.raycast.com/ai/custom-providers](https://manual.raycast.com/ai/custom-providers). +Aucune entrée `api_keys` n'est écrite ; cette exportation est donc limitée au bouclage et une liaison hors +bouclage est refusée. L'exportation DSH gérée nécessite DSH 0.1.0-rc.6 ou plus récent et ne possède que `llm-pi-ai.providers.opencodex`. DSH recharge à chaud ce fournisseur ; le modèle par défaut de l'utilisateur et diff --git a/docs-site/src/content/docs/fr/reference/cli/providers-accounts.md b/docs-site/src/content/docs/fr/reference/cli/providers-accounts.md index 284c8c20c3..ac4e42bbc2 100644 --- a/docs-site/src/content/docs/fr/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/fr/reference/cli/providers-accounts.md @@ -14,7 +14,7 @@ Gestion des fournisseurs non interactive. Les entrées de registre sont classée | Sous-commande | Drapeaux pris en charge | Actions | | --- | --- | --- | -| `list` | `--json` | Répertoriez les fournisseurs configurés et les entrées de registre restantes. | +| `list` | `--json`, `--jsonl` | Répertoriez les fournisseurs configurés et les entrées de registre restantes. `--jsonl` émet un objet JSON par fournisseur configuré et par ligne. | | `add ` | `--adapter `, `--base-url `, `--api-key `, `--default-model `, `--set-default`, `--force`, `--json`, `--sync` | Ajoutez un fournisseur registry/custom. `--force` écrase ; `--sync` actualise un proxy en cours d'exécution en mode sortie humaine. | | `edit ` | indicateurs de champ du fournisseur, `--headers `, `--json` | Modifiez les champs de fournisseur en direct validés sans remplacer les pools de clés. `--headers` fusionne les en-têtes de requête personnalisés ; passez `{}` ou `-` pour les effacer. | | `test ` | `--json` | Sondez le véritable point de terminaison du modèle en amont. | @@ -28,6 +28,7 @@ Gestion des fournisseurs non interactive. Les entrées de registre sont classée ```bash ocx provider list --json +ocx provider list --jsonl ocx provider test ark ocx provider add anthropic --api-key sk-ant-... --set-default --sync ocx provider add local-dev --adapter openai-chat --base-url http://localhost:11434/v1 @@ -36,6 +37,8 @@ ocx models --provider anthropic --json ocx models live --provider ark --json ``` +`--jsonl` écrit uniquement les fournisseurs configurés, un objet JSON par ligne. Chaque objet contient les mêmes champs qu’un élément du tableau `configured` de `--json`, sans le résumé `registryCount`. Les scripts peuvent traiter les objets ligne par ligne. `--json` et `--jsonl` ne peuvent pas être combinés. + :::caution[Les en-têtes personnalisés ne sont pas un canal d'identification] `--headers` est destiné aux métadonnées de requête non secrètes : conseils de routage, locataire ou sélecteurs de projets, identifiants de traçage. Ce n'est **pas** un endroit pour mettre l'authentification diff --git a/docs-site/src/content/docs/guides/claude-code.md b/docs-site/src/content/docs/guides/claude-code.md index 5ed946c72a..0b1c0e9db4 100644 --- a/docs-site/src/content/docs/guides/claude-code.md +++ b/docs-site/src/content/docs/guides/claude-code.md @@ -27,9 +27,18 @@ rotation does not protect against provider enforcement. Operational contract when enabled: -- Upstream **429** cools that account using `Retry-After` when present (else a default backoff), - clears its affinities, and may rotate to another eligible account within the same request - (bounded). +- Upstream **429** cools that account, clears its affinities, and may rotate to another eligible + account within the same request (bounded). The cooldown uses a usable `Retry-After` when present, + otherwise the latest valid reset time among windows Anthropic marks `rejected`, including + weekly windows. Valid upstream deadlines are not shortened to a fixed cooldown ceiling. + A refusal with no usable deadline falls back to a 60-second default backoff. +- Responses report the serving account's 5-hour and weekly utilization, and whichever of those + two the response carries is recorded for that account — each window independently, and a + refusal counts as well as a success. Usage-aware selection works from ordinary traffic, + without waiting for a dashboard poll. Headers preserve model-specific quota windows and do + not postpone usage probes or clear a failed usage probe's unavailable status. Measurements + whose known reset time has passed are discarded as unknown, including retained model-specific + windows. Values without a known reset are preserved; missing data is never reported as zero usage. - Affinity is **process-local** (lost on proxy restart). - **401/403** credential failures quarantine the account (`needsReauth`) so it is excluded from selection until re-authenticated. @@ -513,12 +522,14 @@ The proxy translates every Anthropic Messages API request into the Codex Respons | Assistant text | `output_text` | | Assistant `tool_use` | `function_call` (`input` → JSON-stringified `arguments`) | | User `tool_result` | `function_call_output` (`is_error` → `[tool error]` prefix) | -| `thinking` / `redacted_thinking` replay | Dropped | +| `thinking` / `redacted_thinking` replay | `reasoning` items with bounded `ocxr1` envelopes for signatures and redacted payloads | | Function tools | `{type: "function"}` (`web_search*` → `{type: "web_search"}`) | | `tool_choice` | `auto`→`auto`, `none`→`none`, `any`→`required`, named function→`{type:"function",name}`, hosted WebSearch/web_search→`{type:"web_search"}` | | `max_tokens` | `max_output_tokens` | | `stop_sequences` | `stop` | +Replay preserves non-hidden signed blocks (including empty thinking) and opaque redacted blocks on the intended Anthropic adapter. `hideThinkingSummary` remains unchanged: locally hidden signed text is not exposed to Claude clients, and lossless replay through that hidden Claude boundary is not established. Older combined reasoning envelopes cannot recover original block order once streaming text has been emitted. `claudeCode.compatibility: "enforce"` still rejects thinking replay. This does not establish live Anthropic acceptance or cache-hit improvements; [#3719](https://github.com/lidge-jun/opencodex/issues/3719) remains open. + **Error cases (400):** malformed JSON; missing/empty `model`; missing/empty `messages`; unsupported role; `tool_result` without `tool_use_id`; `tool_use` without id/name; named `tool_choice` without name. @@ -530,7 +541,8 @@ name. | `response.created` | `message_start` + `ping` | | Heartbeat | `ping` | | Text deltas | `content_block_start` → `content_block_delta` (text) → `content_block_stop` | -| Reasoning summary/text | `thinking` block with synthetic signature | +| Reasoning summary/text | `thinking` block with the replayed signature, or a bounded `ocxr1` fallback envelope | +| Redacted reasoning | `redacted_thinking` blocks replayed from the reasoning envelope | | Function-call frames | `tool_use` block with `input_json_delta` | | Terminal event | `message_delta` → `message_stop` | | EOF before terminal | 502-style `api_error` | diff --git a/docs-site/src/content/docs/guides/integrations.md b/docs-site/src/content/docs/guides/integrations.md index 0c95908206..ea3c93f2dd 100644 --- a/docs-site/src/content/docs/guides/integrations.md +++ b/docs-site/src/content/docs/guides/integrations.md @@ -1,10 +1,10 @@ --- title: Integrations -description: Connect opencodex to OpenCode, Pi, OMP, Hermes, OpenClaw, Kimi Code, Gajae Code, DeepSeek Harness, MiniMax Code, ZCode, Prime Agent and Aside from the dashboard — one switch per client, with a backup taken before every write. +description: Connect opencodex to OpenCode, Pi, OMP, Hermes, OpenClaw, Kimi Code, Gajae Code, DeepSeek Harness, MiniMax Code, ZCode, Prime Agent, Aside and Raycast from the dashboard — one switch per client, with a backup taken before every write. --- The **Integrations** tab writes opencodex's provider block into a client's own config -file, and removes it again. Twelve clients work this way, each with a switch: +file, and removes it again. Thirteen clients work this way, each with a switch: | Client | Config file | Format | When the change takes effect | Credential | |---|---|---|---|---| @@ -20,6 +20,7 @@ file, and removes it again. Twelve clients work this way, each with a switch: | Prime Agent | `~/.prime/agent/models.json` | JSON | new sessions | loopback placeholder | | ZCode | `~/.zcode/v2/config.json` | JSON | on restart | loopback placeholder | | Aside | `~/.aside/u//models.json` | JSON | after fully quitting and reopening Aside | loopback placeholder | +| Raycast | `~/.config/raycast/ai/providers.yaml` | YAML | immediately on save — Raycast watches the file | none — loopback only | Generated catalogs include only enabled models from each provider selection. This applies to both downloads and managed integrations, including Pi and Aside. The management model list still shows @@ -61,6 +62,42 @@ One caveat specific to Aside: the running app rewrites `models.json` itself, so fully quit and reopen Aside after applying, the same way Claude Desktop needs a restart. Aside's block is loopback-only and never carries a real credential. +Raycast has two prerequisites. Custom Providers is a **Raycast Pro** feature: on a +free plan the file is still written, but `ocx integration client status --client +raycast` and the Integrations page report a warning, because Raycast will not +read it. And Raycast only creates its `ai` folder when you open Raycast → +Settings → AI → **Reveal Providers Config** once; opencodex uses that folder as +the install signal and reports the client as not installed until then. Raycast +reads `~/.config/raycast/ai/providers.yaml` on macOS and Windows alike and does +not honor `XDG_CONFIG_HOME`, so that path is not relocatable. + +The managed block is one element, `id: opencodex`, in the file's `providers` +sequence: `name: OpenCodex`, `base_url: http://:/v1`, and every +routed model with its `abilities` — the exporter sets `tools` and `system_message` to +`true` as a client-export convention, `vision` follows the catalog's input modalities, `reasoning_effort` +is set when the model has an effort ladder, and `temperature` is turned off for +reasoning models. Other providers in the file are preserved, and disable removes +only the OpenCodex element. Raycast picks up the change as soon as the file is +saved, no restart needed; the models appear in Raycast's model picker grouped +under **OpenCodex**. Raycast supports optional `api_keys`, but OpenCodex intentionally +omits them and refuses non-loopback or admission-authenticated targets; this integration +cannot supply OpenCodex's required admission header. + +The macOS private preference is only an advisory Pro hint; Windows never reads it and +reports the plan as unknown. Plan detection does not authorize or block a write. +The export metadata has no authoritative tool-support flag, so `tools: true` does not +prove every routed model supports tools. Vision and effort flags follow catalog metadata; +turning temperature off for an effort ladder is conservative export behavior. +Provider values are preserved; YAML formatting and comments are not guaranteed to survive. +The format is documented at +[manual.raycast.com/ai/custom-providers](https://manual.raycast.com/ai/custom-providers). + +Raycast CLI exports and dashboard downloads use the running server's destination and +admission policy, including a configured unauthenticated loopback listener. `ocx ensure` +does not refresh Raycast from its saved configuration snapshot: that can differ from the +running server. Server startup and explicit sync remain the catalog refresh paths. + + Cursor has a tab but is not one of these switches. Regular Cursor calls custom endpoints from its own backend, so a loopback proxy is unreachable without a public tunnel, and Cursor's separate Private Inference build is configured inside Cursor. The **Cursor** tab is read-only: @@ -130,7 +167,7 @@ than 1000 levels — which locks the switch instead, so nothing is silently chan **OMP** is unaffected by sibling edits too, for a different reason: its writer patches only its own `providers.opencodex` range byte-wise, so the rest of the file is never rewritten. For the remaining formats that can carry comments -(Hermes, OpenClaw, Kimi Code, Gajae Code, MiniMax Code — YAML, JSON5 and TOML +(Hermes, OpenClaw, Kimi Code, Gajae Code, MiniMax Code, Raycast — YAML, JSON5 and TOML written as whole documents), or whenever our own entries were edited, the switch locks and disable refuses rather than guessing which edits were yours. @@ -216,10 +253,12 @@ ocx integration client enable --client mcode ocx mcode ``` -Once connected, `ocx sync` refreshes owned MCode, Pi, and Aside catalogs with the current -model selection, context windows, and reasoning-effort ladders. Changes to model visibility, -provider selection, or presets also refresh connected Pi and Aside catalogs. Foreign-edited -or unsafe blocks stay untouched, as do previously owned blocks you removed manually. +Once connected, `ocx sync` and `POST /api/sync` refresh owned MCode, Pi, Aside, and +Raycast catalogs with the current model selection, context windows, and reasoning-effort +ladders. Proxy startup refreshes an owned Raycast catalog. Changes to model visibility, +provider selection, or presets also refresh connected Pi, Aside, and Raycast catalogs. +Missing, foreign-edited, or unsafe blocks stay untouched, as do previously owned blocks +you removed manually. An enabled Aside profile is an exception to the usual owned-only refresh: if its account directory exists and it has never had an owned block, sync may create its first block when that slot is empty. A prior Aside connection enables this behavior for all registered diff --git a/docs-site/src/content/docs/guides/providers.md b/docs-site/src/content/docs/guides/providers.md index 05f586a816..5e46979816 100644 --- a/docs-site/src/content/docs/guides/providers.md +++ b/docs-site/src/content/docs/guides/providers.md @@ -367,6 +367,7 @@ free-experimentation model. | NVIDIA NIM | `https://integrate.api.nvidia.com/v1` | | Z.AI (GLM Coding) | `https://api.z.ai/api/coding/paas/v4` | | Zhipu AI (BigModel) | `https://open.bigmodel.cn/api/paas/v4` | +| BigModel Coding Plan (Responses, static roster) | `https://open.bigmodel.cn/api/v1` | | Qwen Cloud | Token plan (default): `https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1` · Pay as you go: `https://dashscope.aliyuncs.com/compatible-mode/v1` · or Custom | | Tencent Cloud Coding Plan | `https://api.lkeap.cloud.tencent.com/coding/v3` | | SiliconFlow | `https://api.siliconflow.cn/v1` | @@ -582,10 +583,44 @@ negative, or internally inconsistent billing totals produce no report rather tha > interactive coding tools only. General API automation, custom application backends, and > non-interactive batch use are prohibited and may cause the plan key to be suspended. -> **Two GLM routes:** `zai` is the Z.AI international coding-plan subscription; `zhipu-bigmodel` +> **GLM billing routes:** `zai` is the Z.AI international coding-plan subscription; `zhipu-bigmodel` > is Zhipu's domestic BigModel pay-as-you-go endpoint. Different hosts, different keys, different > billing — a key issued for one will not authenticate against the other. +### BigModel Coding Plan over Responses + +Select **Zhipu AI — BigModel Coding Plan (Responses)** (`zhipu-bigmodel-responses`) +for the `openai-responses` endpoint `https://open.bigmodel.cn/api/v1`. This is separate +from `zhipu-bigmodel-coding`, which uses Chat Completions at `/api/coding/paas/v4`. + +The preset uses a **static roster** (`liveModels: false`) taken from the +[official BigModel Codex example](https://docs.bigmodel.cn/cn/coding-plan/tool/codex.md): + +| Model | Context tokens | Upstream selectable effort | Default effort | Reasoning summaries | +| --- | ---: | --- | --- | --- | +| `glm-5.3` | 1,048,576 | `low`, `high`, `max` | `max` | Supported | +| `glm-5-turbo` | 204,800 | None (empty list) | `max` | Supported | + +Both entries declare upstream text-only input. The Codex catalog advertises text and +image because opencodex's existing vision sidecar can describe images for text-only +models. Image handling requires an available, enabled vision sidecar; this does not +declare native BigModel image support. + +The default model is `glm-5.3`; Responses reasoning content is preserved on replay. +The existing Codex export adds its compatibility +`ultra` tier to GLM-5.3 and omits Turbo's default-effort field because Turbo has no +selectable ladder; the provider metadata still records `max` for both models. +For Turbo, outgoing Responses requests omit `reasoning.effort`, including a caller's +`max` or `ultra`, while preserving requested reasoning summaries. This leaves effort +selection to the upstream default; opencodex does not inject a selectable or wire `max`. + +The example's `models.json` is a local catalog file, not a documented HTTP model-list +response. This preset does not perform live model discovery. `glm-5.3-flash` is not +seeded here because its exact Responses metadata is not verified. An existing custom +provider with the same name keeps its configured destination and metadata. +CLI key login also skips the undocumented `/models` probe and reports validation as +unknown; successful key authentication is established by a subsequent inference request. + ### Multiple API keys Key-based providers can also keep multiple keys. Adding a key through the Providers page stores it diff --git a/docs-site/src/content/docs/guides/remote-hub.md b/docs-site/src/content/docs/guides/remote-hub.md index 2334303be7..6a2b2a33bd 100644 --- a/docs-site/src/content/docs/guides/remote-hub.md +++ b/docs-site/src/content/docs/guides/remote-hub.md @@ -167,7 +167,11 @@ opencodex does not publish an official container image. The repository does main [`compose.yaml`](https://github.com/lidge-jun/opencodex/blob/main/compose.yaml), and a narrow `.dockerignore`. The build pins the multi-platform Bun 1.4.0 image index by digest, runs the proxy as the non-root `bun` user, keeps the root filesystem read-only, drops Linux capabilities, and publishes -only the data listener on the host's `127.0.0.1:10100` by default. +only the data listener on the host's `127.0.0.1:10100` by default. The foreground process uses +`OCX_SERVICE=1`, so stopping or recreating the container preserves routed Codex state instead +of restoring a native desktop configuration. Docker supplies supervision; no OS service manager +is installed in the image. Use Compose to restart/recreate the container; this does not extend +support to every dashboard restart path. The image seeds a first-run `hub` configuration that binds the container listener to `0.0.0.0`. Before the first normal start, stream a freshly generated data-plane token into the bootstrap helper. @@ -287,6 +291,12 @@ unreadable, a non-loopback hub must not be accepted as ready. Never treat livene `docker compose down --volumes` as destructive: it deletes configuration, OAuth credentials, usage history, the data-plane token, and persisted Codex state together. +Cross-platform CI builds the source image and checks startup, data-plane token admission, and +container recreation using an isolated Compose project with throwaway credentials. It verifies that +both named volumes and a synthetic catalog survive replacement. This check does not validate a +real provider account, OAuth callback, custom mount migration, or every CPU architecture; perform +the authenticated routed-response check above for your deployment. + ## Rollback Inspect existing Serve mappings before changing them. `tailscale serve reset` removes every mapping diff --git a/docs-site/src/content/docs/ja/guides/claude-code.md b/docs-site/src/content/docs/ja/guides/claude-code.md index 8c9f433956..384c3f50df 100644 --- a/docs-site/src/content/docs/ja/guides/claude-code.md +++ b/docs-site/src/content/docs/ja/guides/claude-code.md @@ -368,12 +368,14 @@ Claude Code の `/effort` 設定はアダプターでも維持されます。 | Assistant テキスト | `output_text` | | Assistant `tool_use` | `function_call`(`input` → JSON 文字列に変換した `arguments`) | | ユーザー `tool_result` | `function_call_output`(`is_error` → `[tool error]` 接頭辞) | -| `thinking` / `redacted_thinking` 再生 | 破棄 | +| `thinking` / `redacted_thinking` 再生 | シグネチャと秘匿ペイロードを境界付き `ocxr1` エンベロープに保持した `reasoning` 項目 | | Function ツール | `{type: "function"}`(`web_search*` → `{type: "web_search"}`) | | `tool_choice` | `auto`→`auto`、`none`→`none`、`any`→`required`、名前指定関数→`{type:"function",name}`、ホスト型 WebSearch/web_search→`{type:"web_search"}` | | `max_tokens` | `max_output_tokens` | | `stop_sequences` | `stop` | +意図した Anthropic アダプターでは、非表示でない署名付きブロック(空の thinking を含む)と不透明な redacted ブロックを保持します。`hideThinkingSummary` は変更しません。ローカルで隠した署名付きテキストは Claude クライアントに公開せず、この非表示境界での無損失再生は未確認です。旧形式の結合エンベロープは、テキスト送信後に元のブロック順を復元できません。`claudeCode.compatibility: "enforce"` は引き続き thinking 再生を拒否します。実際の Anthropic 受理やキャッシュ改善の証明ではなく、[#3719](https://github.com/lidge-jun/opencodex/issues/3719) は未解決です。 + **エラー条件(400):** 不正な JSON、欠落または空の `model`、欠落または空の `messages`、未サポートの role、`tool_use_id` のない `tool_result`、id/name のない `tool_use`、name のない名前指定 `tool_choice` です。 @@ -384,7 +386,8 @@ role、`tool_use_id` のない `tool_result`、id/name のない `tool_use`、na | `response.created` | `message_start` + `ping` | | Heartbeat | `ping` | | テキスト delta | `content_block_start` → `content_block_delta`(text) → `content_block_stop` | -| 推論要約/テキスト | 合成シグネチャ付きの `thinking` ブロック | +| 推論要約/テキスト | 再生されたシグネチャ、または境界付き `ocxr1` フォールバックを持つ `thinking` ブロック | +| 秘匿化された推論 | 推論エンベロープから再生される `redacted_thinking` ブロック | | Function-call フレーム | `input_json_delta` を持つ `tool_use` ブロック | | 終了イベント | `message_delta` → `message_stop` | | 終了前に EOF | 502 形式 `api_error` | diff --git a/docs-site/src/content/docs/ja/guides/providers.md b/docs-site/src/content/docs/ja/guides/providers.md index 33be9fc694..ae692e1e2c 100644 --- a/docs-site/src/content/docs/ja/guides/providers.md +++ b/docs-site/src/content/docs/ja/guides/providers.md @@ -216,6 +216,7 @@ Cline IDE/CLI のみで API からは使えません。`minimax/minimax-m2.5` | NVIDIA NIM | `https://integrate.api.nvidia.com/v1` | | Z.AI (GLM Coding) | `https://api.z.ai/api/coding/paas/v4` | | Zhipu AI (BigModel) | `https://open.bigmodel.cn/api/paas/v4` | +| [BigModel Coding Plan — Responses (静的モデル一覧)](/guides/providers/#bigmodel-coding-plan-over-responses) | `https://open.bigmodel.cn/api/v1` | | Qwen Cloud | トークンプラン(デフォルト): `https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1` · 従量課金: `https://dashscope.aliyuncs.com/compatible-mode/v1` · またはカスタム | | Tencent Cloud Coding Plan | `https://api.lkeap.cloud.tencent.com/coding/v3` | | SiliconFlow | `https://api.siliconflow.cn/v1` | @@ -338,7 +339,7 @@ model ごとに capability が異なるため、provider 全体の parallel tool > コーディングツール専用としています。一般的な API 自動化、カスタムアプリのバックエンド、 > 非対話型バッチ利用は禁止されており、プランキーが停止される場合があります。 -> **GLM の経路は 2 つあります:** `zai` は Z.AI の国際コーディングプラン契約、`zhipu-bigmodel` +> **GLM の課金経路:** `zai` は Z.AI の国際コーディングプラン契約、`zhipu-bigmodel` > は Zhipu の中国国内向け BigModel 従量課金エンドポイントです。ホストもキーも課金も別で、 > 一方で発行したキーはもう一方では認証されません。 diff --git a/docs-site/src/content/docs/ja/reference/cli/agents.md b/docs-site/src/content/docs/ja/reference/cli/agents.md index cd1b4fa30f..a223362a56 100644 --- a/docs-site/src/content/docs/ja/reference/cli/agents.md +++ b/docs-site/src/content/docs/ja/reference/cli/agents.md @@ -125,7 +125,7 @@ Grok Build モデル フェンスを管理および適用します。 ## クライアント設定のエクスポート -### `ocx export --client ` +### `ocx export --client ` 実行中のプロキシに接続するクライアント設定を出力します。このコマンドは、ベース URL、モデル一覧、およびクライアントに応じた認証情報参照または `opencodex-loopback` プレースホルダーを含む `opencodex` プロバイダーブロックを、選択したクライアントのネイティブ形式でシリアル化します。 @@ -133,7 +133,7 @@ Grok Build モデル フェンスを管理および適用します。 |旗 |アクション | | --- | --- | -| `--client ` |必須。クライアントの設定形式を選択します。 | +| `--client ` |必須。クライアントの設定形式を選択します。 | | `--json` |構成 JSON のみを標準出力に出力するため、リダイレクトはバイト正確な出力をキャプチャします。 `--out` 書き込みメモを含むすべての診断は stderr に送られます。 | | `--out ` |設定を `` に書き込みます。既存のファイルの置き換えを拒否します。 | | `--force` | `--out` が既存のファイルを置き換えることを許可します。 | @@ -160,6 +160,9 @@ ocx export --client opencode --out ~/opencodex-opencode.json | `mcode` | `~/.minimax/config.yaml` (`MINIMAX_DATA_DIR`、次に旧 `MAVIS_DATA_DIR` が設定時に優先。相対値は拒否されます) | `mcode-config.yaml` | なし — loopback placeholder | | `zcode` | `~/.zcode/v2/config.json` (`ZCODE_DATA_DIR` が設定時に優先。相対値は拒否されます) | `config.json` | なし — loopback placeholder | | `prime` | `~/.prime/agent/models.json` (`PRIME_AGENT_CODING_AGENT_DIR` が設定時に優先。相対値は拒否されます) | `prime-models.json` | なし — loopback placeholder | +| `raycast` | `~/.config/raycast/ai/providers.yaml` (macOS と Windows で同じ。Raycast は `XDG_CONFIG_HOME` を尊重しません) | `raycast-providers.yaml` | なし — loopback のみ。`api_keys` エントリは書き込まれません | + +Raycast のエクスポートは、`providers` シーケンスに `id: opencodex` 要素を 1 つだけ持つ独立した `providers.yaml` 文書です。内容は `name: OpenCodex`、プロキシの `/v1` ベース URL、および `abilities` 付きのルーティング済み全モデルです (`tools` と `system_message` は常にサポート、`vision` はカタログの入力モダリティから、`reasoning_effort` はモデルに effort ラダーがある場合、`temperature` は推論モデルではオフ)。Custom Providers は Raycast Pro の機能で、Raycast はこのファイルを監視しているため、保存した変更は再起動なしで反映されます。形式は [manual.raycast.com/ai/custom-providers](https://manual.raycast.com/ai/custom-providers) に記載されています。`api_keys` エントリは書き込まれないため、このエクスポートは loopback 専用で、loopback 以外のバインドは拒否されます。 opencode は `{env:OPENCODEX_OPENCODE_API_KEY}` を補間します。opencodex が生成する Pi のエクスポートには環境変数が不要で、リテラルのプレースホルダー `opencodex-loopback` が入ります。この値は必須です。Pi はモデル リストを構築する際に `apiKey` を解決し、既存の設定に未設定の環境変数参照がある場合はプロバイダー全体を隠すためです。ループバックでは、生成されたプレースホルダーをプロキシが検査することはありません。 diff --git a/docs-site/src/content/docs/ja/reference/cli/providers-accounts.md b/docs-site/src/content/docs/ja/reference/cli/providers-accounts.md index d20483a8a2..594d1fc30e 100644 --- a/docs-site/src/content/docs/ja/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/ja/reference/cli/providers-accounts.md @@ -13,7 +13,7 @@ description: プロバイダー構成、資格情報、クォータ、および |サブコマンド |サポートされているフラグ |アクション | | --- | --- | --- | -| `list` | `--json` |構成されたプロバイダーと残りのレジストリ エントリを一覧表示します。 | +| `list` | `--json`, `--jsonl` |構成されたプロバイダーと残りのレジストリ エントリを一覧表示します。 `--jsonl` は設定済みプロバイダーごとに1行の JSON オブジェクトを出力します。 | | `add ` | `--adapter `、`--base-url `、`--api-key `、`--default-model `、`--set-default`、`--force`、`--json`、`--sync` |レジストリ/カスタムプロバイダーを追加します。 `--force` は上書きします。 `--sync` は、実行中のプロキシを人間出力モードで更新します。 | | `edit ` |プロバイダーフィールドフラグ、`--headers `、`--json` |キー プールを置き換えずに、検証済みのライブ プロバイダー フィールドを編集します。`--headers` はカスタム要求ヘッダーをマージします。`{}` または `-` を渡すとクリアします。 | | `test ` | `--json` |実際の上流モデルのエンドポイントを調査します。 | @@ -27,6 +27,7 @@ description: プロバイダー構成、資格情報、クォータ、および ```bash ocx provider list --json +ocx provider list --jsonl ocx provider test ark ocx provider add anthropic --api-key sk-ant-... --set-default --sync ocx provider add local-dev --adapter openai-chat --base-url http://localhost:11434/v1 @@ -35,6 +36,8 @@ ocx models --provider anthropic --json ocx models live --provider ark --json ``` +`--jsonl` は設定済みプロバイダーのみを、1行につき1つの JSON オブジェクトとして出力します。各オブジェクトのフィールドは `--json` の `configured` 配列の要素と同じで、`registryCount` の集計は含みません。スクリプトは各行のオブジェクトを順に処理できます。`--json` と `--jsonl` は同時に指定できません。 + :::caution[カスタムヘッダーは認証情報の経路ではありません] `--headers` は秘密ではないリクエストメタデータ用です — ルーティングヒント、テナントや プロジェクトのセレクター、トレース ID など。認証情報を入れる場所ではなく、バリデーターは diff --git a/docs-site/src/content/docs/ja/reference/configuration/providers.md b/docs-site/src/content/docs/ja/reference/configuration/providers.md index d4bfc49a6f..ddbb22d666 100644 --- a/docs-site/src/content/docs/ja/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ja/reference/configuration/providers.md @@ -370,6 +370,14 @@ Vercel AI Gateway は、1 つのモデルを複数の基盤となる推論プロ 表示名には `modelDisplayNames` を使用します。優先順位は、運用者が設定した `modelDisplayNames`、プロバイダーカタログのメタデータ、通常の `provider/model` 表示の順です。キーはこのプロバイダー内の正確なネイティブモデル ID です。例えば `xai/grok-4.6` のキーは `grok-4.6` です。ラベルは表示専用で、正確なルーティング ID や上流モデル ID を変更しません。`config.json` の既存プロバイダー設定にこのフィールドだけを追加し、他のすべてのフィールドを残してください。`PUT /api/providers/:provider/model-display-names` に `{ "modelId": "grok-4.6", "displayName": "Grok 4.6" }` を送ると保存され、`displayName: null` を送るとその名前だけがリセットされます。 +ローカル Codex カタログでサポートされるプレフィックスなしのネイティブ GPT 行にも、 +`providers.openai.modelDisplayNames` で正確な表示名を指定できます。例えば `"gpt-6-astra": "GPT 6 Astra"` です。 +起動時の同期とローカルカタログの収束処理は、どちらもこれらの名前を再適用します。名前の設定を削除すると、行の現在の表示名が +適用済みの上書きとまだ一致する場合にのみ、元のネイティブ名が復元されます。外部で変更された表示名にも既存のネイティブメタデータ正規化が適用されます。 +例えば Astra (`gpt-6-astra`) では、固定されたネイティブ名と異なる名前は引き続きその固定名に置き換えられます。 +表示名の上書きによってモデル ID、メタデータ(機能を含む)、順序、ルーティングされたコンボのエイリアス、アカウント修飾付きの行は変更されません。 +このローカルカタログの上書きは、HTTP のモデル一覧や仮想 `*-pro` 行の表示名には適用されません。 + プレビュー GPT-5.6 フォールバック エントリは同じメカニズムを使用します。 OpenAI API キー プリセットは、ベース ID と Pro ID にコンテキスト `922000` と最大入力 `922000` をシードします。 OpenRouter は、コンテキスト `922000` を持つ `openai/gpt-5.6-sol`、`openai/gpt-5.6-terra`、および `openai/gpt-5.6-luna` をシードします。プール/ダイレクトは `922000` をアドバタイズします。同期されたカタログは、`xhigh` を区別しつつ、`max` をアドバタイズします。 ```json diff --git a/docs-site/src/content/docs/ko/guides/claude-code.md b/docs-site/src/content/docs/ko/guides/claude-code.md index 1368cf5698..676800d1e6 100644 --- a/docs-site/src/content/docs/ko/guides/claude-code.md +++ b/docs-site/src/content/docs/ko/guides/claude-code.md @@ -406,12 +406,14 @@ Claude Code의 `/effort` 설정은 어댑터에서도 유지돼요. | Assistant 텍스트 | `output_text` | | Assistant `tool_use` | `function_call`(`input` → JSON 문자열로 변환한 `arguments`) | | 사용자 `tool_result` | `function_call_output`(`is_error` → `[tool error]` 접두사) | -| `thinking` / `redacted_thinking` 재생 | 버려요 | +| `thinking` / `redacted_thinking` 재생 | 서명과 비공개 페이로드를 제한된 `ocxr1` 봉투에 담은 `reasoning` 항목 | | Function 도구 | `{type: "function"}`(`web_search*` → `{type: "web_search"}`) | | `tool_choice` | `auto`→`auto`, `none`→`none`, `any`→`required`, 이름 지정 함수→`{type:"function",name}`, 호스팅 WebSearch/web_search→`{type:"web_search"}` | | `max_tokens` | `max_output_tokens` | | `stop_sequences` | `stop` | +의도한 Anthropic 어댑터에서는 숨기지 않은 서명 블록(빈 thinking 포함)과 불투명 redacted 블록을 보존해요. `hideThinkingSummary` 정책은 유지돼요. 로컬에서 숨긴 서명 텍스트를 Claude 클라이언트에 노출하지 않으며, 이 숨김 경계를 통한 무손실 재생은 아직 보장하지 않아요. 이전 결합 봉투는 스트리밍 텍스트가 이미 전송됐다면 원래 블록 순서를 복원할 수 없어요. `claudeCode.compatibility: "enforce"`는 여전히 thinking 재생을 거절해요. 실제 Anthropic 수락이나 캐시 적중 개선을 증명한 것은 아니며 [#3719](https://github.com/lidge-jun/opencodex/issues/3719)는 열어 둬요. + **오류 조건(400):** 잘못된 JSON, 누락되거나 빈 `model`, 누락되거나 빈 `messages`, 지원하지 않는 role, `tool_use_id` 없는 `tool_result`, id/name 없는 `tool_use`, name 없는 이름 지정 `tool_choice`예요. @@ -422,7 +424,8 @@ role, `tool_use_id` 없는 `tool_result`, id/name 없는 `tool_use`, name 없는 | `response.created` | `message_start` + `ping` | | Heartbeat | `ping` | | 텍스트 delta | `content_block_start` → `content_block_delta`(text) → `content_block_stop` | -| 추론 요약/텍스트 | 합성 signature가 있는 `thinking` 블록 | +| 추론 요약/텍스트 | 재생된 서명 또는 제한된 `ocxr1` 폴백이 있는 `thinking` 블록 | +| 비공개 추론 | 추론 봉투에서 재생되는 `redacted_thinking` 블록 | | Function-call 프레임 | `input_json_delta`가 있는 `tool_use` 블록 | | 종료 이벤트 | `message_delta` → `message_stop` | | 종료 전에 EOF | 502 형식 `api_error` | diff --git a/docs-site/src/content/docs/ko/guides/providers.md b/docs-site/src/content/docs/ko/guides/providers.md index 7781cc4f52..c49ede4ec6 100644 --- a/docs-site/src/content/docs/ko/guides/providers.md +++ b/docs-site/src/content/docs/ko/guides/providers.md @@ -216,6 +216,7 @@ Cline IDE/CLI에서만 제공되며 API로는 사용할 수 없습니다. `minim | NVIDIA NIM | `https://integrate.api.nvidia.com/v1` | | Z.AI (GLM Coding) | `https://api.z.ai/api/coding/paas/v4` | | Zhipu AI (BigModel) | `https://open.bigmodel.cn/api/paas/v4` | +| [BigModel Coding Plan — Responses (정적 모델 목록)](/guides/providers/#bigmodel-coding-plan-over-responses) | `https://open.bigmodel.cn/api/v1` | | Qwen Cloud | Token plan(기본): `https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1` · 종량제: `https://dashscope.aliyuncs.com/compatible-mode/v1` · 또는 사용자 지정 | | Tencent Cloud Coding Plan | `https://api.lkeap.cloud.tencent.com/coding/v3` | | SiliconFlow | `https://api.siliconflow.cn/v1` | @@ -328,7 +329,7 @@ provider 전체 parallel tool call이나 OpenAI `reasoning_effort`를 광고하 > 안내합니다. 일반 API 자동화, 사용자 애플리케이션 백엔드 및 비대화형 일괄 호출은 금지되며 > 플랜 키가 정지될 수 있습니다. -> **GLM 경로는 두 개입니다:** `zai`는 Z.AI 국제 코딩 플랜 구독이고, `zhipu-bigmodel`은 +> **GLM 과금 경로:** `zai`는 Z.AI 국제 코딩 플랜 구독이고, `zhipu-bigmodel`은 > Zhipu의 중국 내수 BigModel 종량제 엔드포인트입니다. 호스트도 키도 과금도 다르며, 한쪽에서 > 발급한 키는 다른 쪽에서 인증되지 않습니다. diff --git a/docs-site/src/content/docs/ko/reference/cli/agents.md b/docs-site/src/content/docs/ko/reference/cli/agents.md index a229551a83..3624a2a803 100644 --- a/docs-site/src/content/docs/ko/reference/cli/agents.md +++ b/docs-site/src/content/docs/ko/reference/cli/agents.md @@ -131,7 +131,7 @@ Grok Build model fence를 관리하고 적용합니다. ## 클라이언트 설정 내보내기 -### `ocx export --client ` +### `ocx export --client ` 실행 중인 프록시에 연결할 client config를 출력합니다. 이 명령은 base URL, model list, 그리고 client에 따라 credential reference 또는 `opencodex-loopback` placeholder를 포함한 `opencodex` provider block을 선택한 client의 네이티브 형식으로 직렬화합니다. @@ -139,7 +139,7 @@ Grok Build model fence를 관리하고 적용합니다. | 플래그 | 동작 | | --- | --- | -| `--client ` | 필수입니다. 클라이언트 설정 형식을 선택합니다. | +| `--client ` | 필수입니다. 클라이언트 설정 형식을 선택합니다. | | `--json` | config JSON만 stdout에 출력하므로, redirect가 byte-exact 출력을 캡처합니다. `--out` write note를 포함한 모든 진단 메시지는 stderr로 갑니다. | | `--out ` | config를 ``에 씁니다. 기존 파일이 있으면 덮어쓰지 않습니다. | | `--force` | `--out`이 기존 파일을 덮어쓰도록 허용합니다. | @@ -166,6 +166,9 @@ ocx export --client opencode --out ~/opencodex-opencode.json | `mcode` | `~/.minimax/config.yaml` (`MINIMAX_DATA_DIR`, 그다음 레거시 `MAVIS_DATA_DIR`가 설정되면 우선. 상대 경로는 거부됩니다) | `mcode-config.yaml` | 없음 — loopback placeholder | | `zcode` | `~/.zcode/v2/config.json` (`ZCODE_DATA_DIR`가 설정되면 우선. 상대 경로는 거부됩니다) | `config.json` | 없음 — loopback placeholder | | `prime` | `~/.prime/agent/models.json` (`PRIME_AGENT_CODING_AGENT_DIR`가 설정되면 우선. 상대 경로는 거부됩니다) | `prime-models.json` | 없음 — loopback placeholder | +| `raycast` | `~/.config/raycast/ai/providers.yaml` (macOS와 Windows 모두 동일. Raycast는 `XDG_CONFIG_HOME`을 따르지 않습니다) | `raycast-providers.yaml` | 없음 — loopback 전용. `api_keys` 항목은 쓰지 않습니다 | + +Raycast 내보내기는 `providers` 시퀀스에 `id: opencodex` 요소 하나만 담은 독립 `providers.yaml` 문서입니다. 내용은 `name: OpenCodex`, proxy의 `/v1` base URL, 그리고 `abilities`가 붙은 라우팅된 모든 모델입니다(`tools`와 `system_message`는 항상 지원, `vision`은 카탈로그의 입력 모달리티를 따름, `reasoning_effort`는 모델에 effort 사다리가 있을 때, `temperature`는 추론 모델에서 꺼짐). Custom Providers는 Raycast Pro 기능이며, Raycast가 이 파일을 감시하므로 저장한 변경은 재시작 없이 적용됩니다. 형식은 [manual.raycast.com/ai/custom-providers](https://manual.raycast.com/ai/custom-providers)에 문서화되어 있습니다. `api_keys` 항목은 쓰지 않으므로 이 내보내기는 loopback 전용이며, loopback이 아닌 bind는 거부됩니다. opencode는 `{env:OPENCODEX_OPENCODE_API_KEY}`를 보간합니다. opencodex가 생성한 Pi 블록에는 환경 변수가 필요 없으며, 리터럴 placeholder인 `opencodex-loopback`이 들어갑니다. 이 값은 필수입니다. Pi는 모델 목록을 만들 때 `apiKey`를 해석하고, 기존 config에 설정되지 않은 env 참조가 있으면 provider 전체를 숨기기 때문입니다. 루프백에서 proxy는 생성된 placeholder를 검사하지 않습니다. diff --git a/docs-site/src/content/docs/ko/reference/cli/lifecycle.md b/docs-site/src/content/docs/ko/reference/cli/lifecycle.md index 4847614674..068807025b 100644 --- a/docs-site/src/content/docs/ko/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ko/reference/cli/lifecycle.md @@ -82,6 +82,19 @@ dedicated-provider history도 포함됩니다. 상태를 백업하고 이 전체 ### `ocx status [--json]` +status와 `ocx doctor`는 현재 CLI와 실행 중인 프록시의 버전을 비교합니다. CLI가 더 새로우면 +원하는 최신 설치로 프록시를 재시작하십시오. 백그라운드 서비스라면 `ocx service repair`를 +실행합니다(`ocx service restart`는 별칭). 프록시가 더 새로우면 CLI를 업그레이드하거나 +`PATH`가 원하는 설치를 가리키도록 수정하십시오. 이 진단은 서비스를 복구하거나 요청 허용 +여부를 바꾸지 않습니다. + +버전 문자열이 같거나 어느 쪽이 `unknown` / `0.0.0`이면 경고하지 않으며, 프록시 버전이 없어도 +경고하지 않습니다. doctor는 placeholder를 버전 일치로 확정하지 않습니다. 엄격한 SemVer로 +해석할 수 없는 서로 다른 문자열이나 build metadata만 다른 버전은 어느 쪽이 오래됐다고 +단정하지 않는 중립 경고를 표시합니다. 공백을 제거하거나 앞의 `v`를 정규화하지 않습니다. +JSON의 `versionSkew`에도 같은 안내가 들어가며 필드는 `cliVersion`, `proxyVersion`, `skewed`, +`warning` 그대로입니다. + 읽기 전용 진단 요약을 출력합니다. 프록시 PID, `/healthz` 도달 가능 여부, 대시보드 URL, 설정 경로, 기본 공급자, Codex 자동 시작 설정, 서비스 상태, shim 상태, 그리고 마스킹된 실제로 적용되는 Codex 홈이 포함됩니다. 명시적이고 높은 신뢰도의 Windows Orca 런타임 홈 시그니처만 diff --git a/docs-site/src/content/docs/ko/reference/cli/providers-accounts.md b/docs-site/src/content/docs/ko/reference/cli/providers-accounts.md index 250b3d7b1b..ed3c6a565d 100644 --- a/docs-site/src/content/docs/ko/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/ko/reference/cli/providers-accounts.md @@ -13,7 +13,7 @@ description: 제공자 설정, 자격 증명, 할당량, 모델 카탈로그 명 | 하위 명령 | 지원 플래그 | 동작 | | --- | --- | --- | -| `list` | `--json` | 설정된 제공자와 남아 있는 레지스트리 항목을 나열합니다. | +| `list` | `--json`, `--jsonl` | 설정된 제공자와 남아 있는 레지스트리 항목을 나열합니다. `--jsonl`은 설정된 제공자마다 JSON 객체를 한 줄씩 출력합니다. | | `add ` | `--adapter `, `--base-url `, `--api-key `, `--default-model `, `--set-default`, `--force`, `--json`, `--sync` | 레지스트리/사용자 지정 제공자를 추가합니다. `--force`는 덮어쓰고, `--sync`는 사람이 읽는 출력 모드에서 실행 중인 프록시를 새로 고칩니다. | | `edit ` | 제공자 필드 플래그, `--headers `, `--json` | 키 풀을 바꾸지 않고 검증된 실시간 제공자 필드를 수정합니다. `--headers`는 사용자 지정 요청 헤더를 병합하며, `{}` 또는 `-`로 지울 수 있습니다. | | `test ` | `--json` | 실제 상위 모델 엔드포인트를 확인합니다. | @@ -27,6 +27,7 @@ description: 제공자 설정, 자격 증명, 할당량, 모델 카탈로그 명 ```bash ocx provider list --json +ocx provider list --jsonl ocx provider test ark ocx provider add anthropic --api-key sk-ant-... --set-default --sync ocx provider add local-dev --adapter openai-chat --base-url http://localhost:11434/v1 @@ -35,6 +36,8 @@ ocx models --provider anthropic --json ocx models live --provider ark --json ``` +`--jsonl`은 설정된 제공자만 JSON 객체 하나당 한 줄로 출력합니다. 각 객체의 필드는 `--json`의 `configured` 배열 항목과 같으며, `registryCount` 요약은 포함하지 않습니다. 스크립트에서 각 줄의 객체를 순서대로 처리할 수 있습니다. `--json`과 `--jsonl`은 함께 사용할 수 없습니다. + :::caution[커스텀 헤더는 자격증명 통로가 아닙니다] `--headers`는 비밀이 아닌 요청 메타데이터용입니다 — 라우팅 힌트, 테넌트나 프로젝트 선택자, 추적 id 같은 것들이요. 인증 정보를 넣는 자리가 아니고, 검증기는 표준 자격증명 diff --git a/docs-site/src/content/docs/ko/reference/configuration/providers.md b/docs-site/src/content/docs/ko/reference/configuration/providers.md index c9c4de5ede..160d313be3 100644 --- a/docs-site/src/content/docs/ko/reference/configuration/providers.md +++ b/docs-site/src/content/docs/ko/reference/configuration/providers.md @@ -377,6 +377,14 @@ Vercel AI Gateway는 하나의 모델을 여러 기반 추론 공급자에 걸 표시 이름은 `modelDisplayNames`로 설정합니다. 우선순위는 운영자가 설정한 `modelDisplayNames`, 공급자 카탈로그 메타데이터, 일반 `provider/model` 표시 순서입니다. 키는 이 공급자 안의 정확한 네이티브 모델 id입니다. 예를 들어 `xai/grok-4.6`의 키는 `grok-4.6`입니다. 이름은 표시 전용이며 정확한 라우팅 id나 업스트림 모델 id를 바꾸지 않습니다. `config.json`의 기존 공급자 설정에 이 필드만 추가하고 다른 모든 필드는 유지하세요. `PUT /api/providers/:provider/model-display-names`에 `{ "modelId": "grok-4.6", "displayName": "Grok 4.6" }`를 보내 저장하고, `displayName: null`을 보내 해당 이름만 초기화합니다. +로컬 Codex 카탈로그에서 지원되는 접두사 없는 네이티브 GPT 항목에도 +`providers.openai.modelDisplayNames`로 정확한 표시 이름을 지정할 수 있습니다. 예를 들어 `"gpt-6-astra": "GPT 6 Astra"`를 사용합니다. +시작 시 동기화와 로컬 카탈로그 수렴은 모두 이 이름을 다시 적용합니다. 이름 설정을 삭제하면 항목의 현재 표시 이름이 +적용된 재정의와 여전히 일치할 때만 원래 네이티브 이름을 복원합니다. 외부에서 변경된 표시 이름도 기존 네이티브 메타데이터 정규화 규칙을 따릅니다. +예를 들어 Astra (`gpt-6-astra`)는 고정된 네이티브 이름과 다른 이름을 여전히 그 고정 이름으로 교체합니다. +표시 이름 재정의는 모델 ID, 기능을 포함한 메타데이터, 정렬 순서, 라우팅된 콤보 별칭 및 계정 선택자가 붙은 항목을 바꾸지 않습니다. +이 로컬 카탈로그 재정의는 HTTP 모델 목록이나 가상 `*-pro` 항목의 이름을 바꾸지 않습니다. + 프리뷰 GPT-5.6 폴백 항목도 같은 메커니즘을 사용합니다. OpenAI API 키 프리셋은 base와 Pro id에 컨텍스트 `922000`, 최대 입력 `922000`을 채웁니다. OpenRouter는 `openai/gpt-5.6-sol`, `openai/gpt-5.6-terra`, `openai/gpt-5.6-luna`에 컨텍스트 `922000`을 채웁니다. Pool/Direct는 `922000`을 노출하고, 동기화된 카탈로그는 `xhigh`를 구분한 채 `max`를 노출합니다. ```json diff --git a/docs-site/src/content/docs/reference/architecture.md b/docs-site/src/content/docs/reference/architecture.md index 8e1e361a81..e0fbc8bcba 100644 --- a/docs-site/src/content/docs/reference/architecture.md +++ b/docs-site/src/content/docs/reference/architecture.md @@ -233,7 +233,17 @@ response is not cacheable. Post-commit and 5xx errors keep the no-resend path. When encrypted agent-task recovery refuses a routed task, its existing 400 error can include a bounded `recovery_reason`: `unsupported_envelope`, -`admission_denied`, `recovery_unavailable`, `caller_cancelled`, or `input_changed`. -The field is omitted when no classified recovery result exists. +`admission_denied`, `recovery_unavailable`, `caller_cancelled`, `input_changed`, +`recovery_http_rejected`, `recovery_timeout`, `recovery_aborted`, +`recovery_transport_error`, or `recovery_invalid_output`. +HTTP rejection requires an observed non-success response. Invalid output includes +invalid UTF-8, oversized bodies, malformed or incomplete recovery streams, and +invalid or conflicting assignments. A caller's cancellation takes precedence over +an owned deadline, which takes precedence over decode/transport failures. +`recovery_aborted` describes a shared recovery cancelled independently of that caller. +Shared-flight waiters receive the same underlying failure unless individually cancelled; +only successful plaintext is cached. Diagnostics contain no upstream error or payload text. +The field is omitted when no classified recovery result exists, and existing combo +branches that return the original target failure keep that response. `recovery_unavailable` includes cache/singleflight capacity and does not prove an upstream request was attempted. No retry or broader envelope acceptance is enabled. diff --git a/docs-site/src/content/docs/reference/cli/agents.md b/docs-site/src/content/docs/reference/cli/agents.md index e6470eae0e..300bb7d5e2 100644 --- a/docs-site/src/content/docs/reference/cli/agents.md +++ b/docs-site/src/content/docs/reference/cli/agents.md @@ -207,7 +207,7 @@ Manage and apply the Grok Build model fence. ## Client config export -### `ocx export --client ` +### `ocx export --client ` Print a client config wired to the running proxy. The command serializes the `opencodex` provider block — base URL, model list, and the client's credential @@ -218,7 +218,7 @@ models Codex can currently see. | Flag | Action | | --- | --- | -| `--client ` | Required. Selects the client config dialect. | +| `--client ` | Required. Selects the client config dialect. | | `--json` | Print the generated document as JSON on stdout for scripts. This is JSON even when the selected client's native format is YAML, TOML, or JSON5. | | `--out ` | Write the client's native config format to ``. Refuses to replace an existing file. | | `--force` | Allow `--out` to replace an existing file. | @@ -248,6 +248,7 @@ client applies its own defaults for those). | `zcode` | `~/.zcode/v2/config.json` (`ZCODE_DATA_DIR` wins when set; a relative value is refused) | `config.json` | none — loopback placeholder | | `prime` | `~/.prime/agent/models.json` (`PRIME_AGENT_CODING_AGENT_DIR` wins when set; a relative value is refused) | `prime-models.json` | none — loopback placeholder | | `aside` | `~/.aside/u//models.json` for the account Aside's own `accounts.json` names as current; an unreadable manifest is refused rather than defaulting to an account | `aside-models.json` | none — loopback placeholder | +| `raycast` | `~/.config/raycast/ai/providers.yaml` on macOS and Windows alike (Raycast does not honor `XDG_CONFIG_HOME`) | `raycast-providers.yaml` | none — loopback only, no `api_keys` entry is written | The managed DSH export requires DSH 0.1.0-rc.6 or newer and owns only `llm-pi-ai.providers.opencodex`. DSH hot reloads that provider; the user's default model and @@ -260,6 +261,15 @@ hide the whole provider when an existing config contains an unset env reference. checks the generated placeholder on loopback. OMP supports provider-level headers, but this initial integration deliberately remains loopback-only; remote `x-opencodex-api-key` wiring is deferred. +The Raycast export is a standalone `providers.yaml` document with one `id: opencodex` element +in the `providers` sequence: `name: OpenCodex`, the proxy's `/v1` base URL, and every routed model +with its `abilities` (`tools` and `system_message` always supported, `vision` from the catalog's +input modalities, `reasoning_effort` when the model has an effort ladder, `temperature` off for +reasoning models). Custom Providers is a Raycast Pro feature, and Raycast watches the file, so a +saved change takes effect without a restart. The format is documented at +[manual.raycast.com/ai/custom-providers](https://manual.raycast.com/ai/custom-providers). No +`api_keys` entry is written, so this export is loopback-only and a non-loopback bind is refused. + The MCode, ZCode and Prime exports are loopback-only for the same reason and likewise carry the `opencodex-loopback` placeholder rather than a real credential. Prime Agent reads the same `models.json` contract Pi does, so the two exports produce the same document; only the destination diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index e75a2b6241..0dda487b3a 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -88,6 +88,19 @@ are left in place. ### `ocx status [--json]` +Status and `ocx doctor` compare this CLI's version with the running proxy. If the CLI is newer, +restart the proxy using the intended current installation; for a background service, run +`ocx service repair` (`ocx service restart` is an alias). If the proxy is newer, upgrade the CLI +or resolve `PATH` to the intended installation. These diagnostics do not repair the service or +change whether requests are allowed. + +Identical version strings and the `unknown` / `0.0.0` placeholders suppress the warning, as does +an absent proxy version. Doctor does not report placeholders as a confirmed match. Different +strings still produce a neutral warning when they cannot be strictly parsed as SemVer or differ +only in build metadata; neither side is called older. Versions are not trimmed and a leading `v` +is not normalized. JSON exposes the same advice in `versionSkew`, whose fields remain +`cliVersion`, `proxyVersion`, `skewed`, and `warning`. + Print a read-only diagnostic summary: proxy PID, `/healthz` reachability, dashboard URL, config path, default provider, Codex autostart setting, service state, shim state, and the redacted effective Codex home. Only the explicit, high-confidence Windows Orca runtime-home signature adds an actionable App-home @@ -261,9 +274,10 @@ bundled Bun paths are deliberately rediscovered after upgrades instead of being Definitions installed before this change still carry the old versioned paths and cannot migrate themselves — once the old executable is deleted, no opencodex code runs to fix it. Run `ocx service repair` once after upgrading; after that, each service start follows the launcher. -An already-running proxy is not replaced by an external upgrade: restart the service (or run -`ocx service repair`) so the new build serves, and treat a CLI/proxy version mismatch warning as -exactly that signal. +An already-running proxy is not replaced by an external upgrade: when the installed CLI is newer +than the running proxy, restart the service (or run `ocx service repair`) so the new build serves. +If the proxy is newer instead, check the CLI installation and `PATH` as described under +[`ocx status`](#ocx-status---json). | Subcommand | Action | | --- | --- | diff --git a/docs-site/src/content/docs/reference/cli/providers-accounts.md b/docs-site/src/content/docs/reference/cli/providers-accounts.md index b31c0f3159..3d602799bb 100644 --- a/docs-site/src/content/docs/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/reference/cli/providers-accounts.md @@ -14,7 +14,7 @@ both `--adapter` and `--base-url`. | Subcommand | Supported flags | Action | | --- | --- | --- | -| `list` | `--json` | List configured providers and the remaining registry entries. | +| `list` | `--json`, `--jsonl` | List configured providers and the remaining registry entries; `--jsonl` emits one configured provider object per line. | | `add ` | `--adapter `, `--base-url `, `--api-key `, `--default-model `, `--set-default`, `--force`, `--json`, `--sync` | Add a registry/custom provider. `--force` overwrites; `--sync` refreshes a running proxy in human-output mode. | | `edit ` | provider field flags, `--headers `, `--json` | Edit validated live provider fields without replacing key pools. `--headers` merges custom request headers; pass `{}` or `-` to clear them. | | `test ` | `--json` | Probe the real upstream model endpoint. | @@ -29,6 +29,7 @@ both `--adapter` and `--base-url`. ```bash ocx provider list --json +ocx provider list --jsonl # one configured provider object per line ocx provider test ark ocx provider add anthropic --api-key sk-ant-... --set-default --sync ocx provider add local-dev --adapter openai-chat --base-url http://localhost:11434/v1 @@ -37,6 +38,11 @@ ocx models --provider anthropic --json ocx models live --provider ark --json ``` +`--jsonl` writes only configured providers, one JSON object per line, and omits the +`registryCount` summary from `--json`. Each object has the same fields as an item in the `configured` array. +Use it for scripts that process one configured provider object per line. +`--json` and `--jsonl` cannot be combined. + :::caution[Custom headers are not a credential channel] `--headers` is for non-secret request metadata — routing hints, tenant or project selectors, tracing ids. It is **not** a place to put authentication diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index 02d5ba4323..6aa8c78d00 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -230,6 +230,16 @@ all other provider settings. The example includes the surrounding required field } ``` +Supported bare native GPT rows in the local Codex catalog also accept exact labels in +`providers.openai.modelDisplayNames`, for example `"gpt-6-astra": "GPT 6 Astra"`. +Both startup synchronization and local catalog convergence reapply these labels. Removing a label +restores the original native name only when the row's display name still matches the applied +override. A newer external display name is preserved subject to existing native metadata normalization; +for example, Astra (`gpt-6-astra`) still replaces a non-pinned name with its pinned native name. +The label overlay leaves model IDs, metadata (including capabilities), ordering, +routed combo aliases, and account-qualified rows unchanged. This local catalog override does +not relabel the HTTP model listings or virtual `*-pro` rows. + The effective label order is operator `modelDisplayNames`, then provider catalog metadata, then the normal `provider/model` fallback. The routed selector remains `xai/grok-4.6`, while the upstream wire model remains `grok-4.6`. Labels are display only. They do not change authentication, adapter @@ -239,6 +249,20 @@ label. A management client can set or reset one label with `{ "modelId": "grok-4.6", "displayName": "Grok 4.6" }`; send `displayName: null` to reset it. Provider `PATCH` does not edit this map. Use this dedicated `PUT` endpoint to change or remove labels. +The dashboard exposes the same durable setting on **Models**. Expand the provider, find a +discovered model, and choose **Name**. The dialog keeps the exact `provider/model` selector visible +while you save a friendly label. Choose **Reset name** to return to provider metadata or the normal +selector fallback. **Name** changes presentation only; the separate alias pencil changes the +short routing alias and is not a display name editor. Native OpenAI and custom model rows keep their +existing controls. + +If the change is saved but refreshing fails, the dialog reflects the saved override and keeps +**Retry** available. Retry repeats catalog convergence when the server reported it failed, or +reloads the list when only the list request failed. Reset recovery keeps the reset operation; +it does not restore the old name. Requests have a 60-second deadline covering the write and its +follow-up list refresh. A timeout does not undo a write: use **Retry** to check the current name +before making another change. + ## Codex catalog and root `config.toml` settings These settings belong in the root of `$CODEX_HOME/config.toml`, alongside @@ -430,14 +454,31 @@ rotation may trigger provider restrictions. | `anthropicAccountPool.enabled?` | `boolean` | `false` | Enable sticky session affinity and quota-ranked new-session selection. **429 failover is not gated here**: it activates whenever two or more usable accounts are stored, exactly like every other multi-credential provider, and cannot be switched off. | | `anthropicAccountPool.autoSwitchThreshold?` | `number` | `80` | For new sessions, when the active account reaches this threshold, choose the lowest known cached usage in the configured window; the account chosen does not itself have to be at or above the threshold. `0` disables **proactive** usage-based switching only — new-session selection and routing recovery after an eligible 429 still consult `quotaWindow`. | | `anthropicAccountPool.strategy?` | `"quota" \| "round-robin" \| "fill-first"` | `"quota"` | New-session strategy; `quota` ranks accounts by the window set by `quotaWindow`, and `fill-first` evaluates its drain threshold in that same window. | -| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | The cached provider-reported utilization bar used for usage-aware account selection. `five-hour` keeps the original behavior. `weekly` scores the weekly bar and skips accounts whose 5-hour bar is exhausted while another eligible account remains, but falls back to exhausted candidates when none do. `max-utilization` scores the highest known bar, so it can use 5-hour usage before weekly usage is available; if neither is known, the account follows unknown-usage ordering. Known usage ranks before unknown usage under the opt-in `weekly` and `max-utilization` windows only; an omitted or explicit `five-hour` preserves the legacy ordering. If every eligible account is unknown, selection still returns one in eligible order. After the documented lower-5-hour tie-break, exact ties preserve eligible order. A healthy affinity-bound session is not proactively rebalanced. For new-session assignment and routing recovery after an eligible 429 replacement, `quota` ranks eligible candidates directly with this window; `fill-first` advances in stable order using this window's threshold and exhaustion rules; `round-robin` ignores it. Cooldown, failover limits, and reauthentication eligibility remain separate local state. Per-account weekly bars are only known once the dashboard Providers page has polled them. | +| `anthropicAccountPool.quotaWindow?` | `"five-hour" \| "weekly" \| "max-utilization"` | `"five-hour"` | The cached provider-reported utilization bar used for usage-aware account selection. `five-hour` keeps the original behavior. `weekly` scores the weekly bar and skips accounts whose 5-hour bar is exhausted while another eligible account remains, but falls back to exhausted candidates when none do. `max-utilization` scores the highest known bar, so it can use 5-hour usage before weekly usage is available; if neither is known, the account follows unknown-usage ordering. Known usage ranks before unknown usage under the opt-in `weekly` and `max-utilization` windows only; an omitted or explicit `five-hour` preserves the legacy ordering. If every eligible account is unknown, selection still returns one in eligible order. After the documented lower-5-hour tie-break, exact ties preserve eligible order. A healthy affinity-bound session is not proactively rebalanced. For new-session assignment and routing recovery after an eligible 429 replacement, `quota` ranks eligible candidates directly with this window; `fill-first` advances in stable order using this window's threshold and exhaustion rules; `round-robin` ignores it. Cooldown, failover limits, and reauthentication eligibility remain separate local state. Per-account weekly bars come from usage probes or observed response headers. | | `anthropicAccountPool.stickyLimit?` | `number` | `1` | Successful new-session binds retained on one round-robin selection. Range 1–100. | -When enabled, 429 records bounded cooldown from `Retry-After` or a default backoff and may rotate -within the request. Affinity is process-local and size-bounded. Credential 401/403 marks the account -as needing reauthentication. If all eligible accounts are cooling, clients receive 429 with +When enabled, 429 records a cooldown and may rotate within the request. The cooldown length comes +from a usable `Retry-After`, otherwise from the latest valid reset time among rate-limit windows +Anthropic reports as `rejected`, including weekly windows. Valid upstream deadlines are not +shortened to a fixed cooldown ceiling; non-finite or unrepresentable deadlines are ignored. +A refusal with no usable deadline falls back to a 60-second default backoff. Affinity is process-local +and size-bounded. Credential 401/403 marks the account as needing reauthentication. If all eligible accounts are cooling, clients receive 429 with `Retry-After` when known, not an authentication error. +Anthropic responses also report the serving account's 5-hour and weekly utilization, and whichever +of those two a given response carries is recorded against that account — each window independently, +on refusals as well as successes. Usage-aware selection therefore works from the accounts you +actually use, without waiting for the dashboard Providers page to poll them. These readings refresh +the existing row rather than replacing it, so the model-scoped weekly bars that only the usage +endpoint reports are preserved until their known reset time passes. Expired measurements become +unknown, including retained standard windows omitted by later headers. A reset-only header cannot +extend an older utilization measurement. Values with no known reset retain their existing behavior; +missing measurements are never replaced with zero usage. + +Header observations do not postpone usage probes or clear a failed +probe's unavailable status. After restart, cached Anthropic observations remain available while +the next quota read probes again, because the saved observations do not include the probe clock. + :::caution[Experimental] Leave this disabled unless you understand Anthropic account policy risk. Prefer manual `ocx account use anthropic ` switching when unsure. @@ -747,6 +788,12 @@ container usually has no unlocked keychain session, so requests would fail close `${ENV_VAR}` reference in the service environment there instead. Env references are left untouched by `store`. +The `zhipu-bigmodel-responses` preset seeds `glm-5.3` and `glm-5-turbo` with +`liveModels: false` for `https://open.bigmodel.cn/api/v1`. Its static roster and +per-model context, effort, and summary metadata come from the +[BigModel Responses guide](/guides/providers/#bigmodel-coding-plan-over-responses). +The official local `models.json` example does not establish a live `/models` API. + With `liveModels: false`, an empty or omitted `models` list seeds the configured `defaultModel` first, followed by `retainModels`; duplicate ids are removed while preserving first occurrence. A nonempty explicit `models` list instead seeds `models` followed by `retainModels`, without diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index 7008194e19..cb97ad7076 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -409,7 +409,30 @@ default provider is enabled and is not itself an OpenAI-family entry; account-qu such as `side/gpt-5.6-sol` still fail closed. The proxy logs one notice per provider when this fallback engages. Configurations with an enabled canonical `openai` provider are unchanged. -Native compact responses are buffered with a 32 MiB maximum, including responses whose declared +Inbound bodies on both `/v1/responses` and `/v1/responses/compact` retain the shared 256 MiB +wire/decompression admission limit. Application-level size rejection returns HTTP 413 with +`type` and `code` both `invalid_request_error`. Its message includes a bounded diagnostic suffix, +for example: + +```text +Decompressed request body exceeds 268435456 bytes [measurement=decoded_lower_bound; bytes=268435457] +``` + +| Measurement | Meaning of `bytes` | +| --- | --- | +| `declared_wire` | Numeric `Content-Length` declared by the sender; rejected before reading, not a measured decoded size | +| `observed_wire_lower_bound` | Wire bytes encountered when reading stopped; the complete body may be larger | +| `decoded_exact` | Exact size of the buffer supplied to the identity decoder or returned by a decoder | +| `decoded_lower_bound` | Admission limit plus one after inflation aborts; a lower bound, never the exact decoded size | + +The suffix contains only a fixed category and a finite numeric byte value. Rejected bodies are +not read or inflated further, parsed for item counts, or retained for diagnostics. Legacy errors +without measurement provenance retain the limit-only message. Bun's listener can reject an +oversized wire body before application diagnostics run, so not every 413 carries this suffix. +A lower-bound diagnostic cannot establish the complete compact payload size. The admission +limit and retry behavior are unchanged. + +Native compact responses are buffered with a separate 32 MiB maximum, including responses whose declared `Content-Length` already exceeds the limit. The compact-specific failures include: | Status | Type or code | Meaning | diff --git a/docs-site/src/content/docs/ru/guides/claude-code.md b/docs-site/src/content/docs/ru/guides/claude-code.md index 3f6c07a4aa..60464bfb90 100644 --- a/docs-site/src/content/docs/ru/guides/claude-code.md +++ b/docs-site/src/content/docs/ru/guides/claude-code.md @@ -393,12 +393,14 @@ Claude Code — это лишь учётные данные для доступ | Текст ассистента | `output_text` | | `tool_use` ассистента | `function_call` (`input` → `arguments` в виде JSON-строки) | | `tool_result` пользователя | `function_call_output` (`is_error` → префикс `[tool error]`) | -| Повтор `thinking` / `redacted_thinking` | Отбрасывается | +| Повтор `thinking` / `redacted_thinking` | Элементы `reasoning` с ограниченными конвертами `ocxr1` для подписей и скрытых данных | | Function-инструменты | `{type: "function"}` (`web_search*` → `{type: "web_search"}`) | | `tool_choice` | `auto`→`auto`, `none`→`none`, `any`→`required`, именованная функция→`{type:"function",name}`, размещённый WebSearch/web_search→`{type:"web_search"}` | | `max_tokens` | `max_output_tokens` | | `stop_sequences` | `stop` | +На выбранном адаптере Anthropic сохраняются нескрытые подписанные блоки (включая пустой thinking) и непрозрачные блоки redacted. Политика `hideThinkingSummary` не меняется: локально скрытый подписанный текст не раскрывается клиентам Claude, а воспроизведение без потерь через эту границу пока не подтверждено. Старые объединённые конверты не восстанавливают порядок после отправки потокового текста. `claudeCode.compatibility: "enforce"` по-прежнему отклоняет thinking replay. Приём реальным Anthropic и улучшение кеша не доказаны; [#3719](https://github.com/lidge-jun/opencodex/issues/3719) остаётся открытым. + **Случаи ошибок (400):** некорректный JSON; отсутствующий или пустой `model`; отсутствующий или пустой `messages`; неподдерживаемая роль; `tool_result` без `tool_use_id`; `tool_use` без id/name; именованный `tool_choice` без имени. @@ -410,7 +412,8 @@ id/name; именованный `tool_choice` без имени. | `response.created` | `message_start` + `ping` | | Heartbeat | `ping` | | Текстовые дельты | `content_block_start` → `content_block_delta` (text) → `content_block_stop` | -| Резюме/текст рассуждений | Блок `thinking` с синтетической подписью | +| Резюме/текст рассуждений | Блок `thinking` с повторно переданной подписью или ограниченным резервным конвертом `ocxr1` | +| Скрытое рассуждение | Блоки `redacted_thinking`, воспроизведённые из конверта рассуждений | | Кадры function-call | Блок `tool_use` с `input_json_delta` | | Завершающее событие | `message_delta` → `message_stop` | | EOF до завершающего события | `api_error` в стиле 502 | diff --git a/docs-site/src/content/docs/ru/guides/providers.md b/docs-site/src/content/docs/ru/guides/providers.md index b057cf77c6..e680f1bd91 100644 --- a/docs-site/src/content/docs/ru/guides/providers.md +++ b/docs-site/src/content/docs/ru/guides/providers.md @@ -229,6 +229,7 @@ opencodex поставляется с 79 встроенными пресетам | NVIDIA NIM | `https://integrate.api.nvidia.com/v1` | | Z.AI (GLM Coding) | `https://api.z.ai/api/coding/paas/v4` | | Zhipu AI (BigModel) | `https://open.bigmodel.cn/api/paas/v4` | +| [BigModel Coding Plan — Responses (статический список)](/guides/providers/#bigmodel-coding-plan-over-responses) | `https://open.bigmodel.cn/api/v1` | | Qwen Cloud | Token plan (по умолчанию): `https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1` · Pay as you go: `https://dashscope.aliyuncs.com/compatible-mode/v1` · или Custom | | Tencent Cloud Coding Plan | `https://api.lkeap.cloud.tencent.com/coding/v3` | | SiliconFlow | `https://api.siliconflow.cn/v1` | @@ -367,7 +368,7 @@ plan. Ключ создаётся в [дашборде Featherless](https://feat > в интерактивных инструментах программирования. Автоматизация общего API, серверы пользовательских > приложений и неинтерактивные пакетные вызовы запрещены и могут привести к блокировке ключа плана. -> **Два маршрута GLM:** `zai` — это международная подписка Z.AI на coding-план, а `zhipu-bigmodel` — +> **Тарификация GLM:** `zai` — это международная подписка Z.AI на coding-план, а `zhipu-bigmodel` — > внутренняя китайская конечная точка BigModel с оплатой по факту использования. Разные хосты, > разные ключи, разная тарификация: ключ от одного сервиса не подойдёт к другому. diff --git a/docs-site/src/content/docs/ru/reference/cli/agents.md b/docs-site/src/content/docs/ru/reference/cli/agents.md index b49162dbc6..8df8175173 100644 --- a/docs-site/src/content/docs/ru/reference/cli/agents.md +++ b/docs-site/src/content/docs/ru/reference/cli/agents.md @@ -152,7 +152,7 @@ override, но файлы на диске никогда не меняются. ## Экспорт client config -### `ocx export --client ` +### `ocx export --client ` Печатает client config, направленный на работающий прокси. Команда сериализует блок провайдера `opencodex` в нативном формате выбранного клиента: base URL, список моделей и, @@ -163,7 +163,7 @@ override, но файлы на диске никогда не меняются. | Флаг | Действие | | --- | --- | -| `--client ` | Обязателен. Выбирает формат конфигурации клиента. | +| `--client ` | Обязателен. Выбирает формат конфигурации клиента. | | `--json` | Печатать только JSON-конфиг в stdout, чтобы redirect сохранял побайтно точный вывод. Вся диагностика, включая заметку о записи через `--out`, идёт в stderr. | | `--out ` | Записать конфиг в ``. Перезаписывать существующий файл не позволит. | | `--force` | Разрешить `--out` заменить существующий файл. | @@ -193,6 +193,17 @@ ocx export --client opencode --out ~/opencodex-opencode.json | `mcode` | `~/.minimax/config.yaml` (`MINIMAX_DATA_DIR`, затем устаревшая `MAVIS_DATA_DIR`, имеют приоритет, если заданы; относительное значение отклоняется) | `mcode-config.yaml` | нет — loopback placeholder | | `zcode` | `~/.zcode/v2/config.json` (`ZCODE_DATA_DIR` имеет приоритет, если задана; относительное значение отклоняется) | `config.json` | нет — loopback placeholder | | `prime` | `~/.prime/agent/models.json` (`PRIME_AGENT_CODING_AGENT_DIR` имеет приоритет, если задана; относительное значение отклоняется) | `prime-models.json` | нет — loopback placeholder | +| `raycast` | `~/.config/raycast/ai/providers.yaml` одинаково на macOS и Windows (Raycast не учитывает `XDG_CONFIG_HOME`) | `raycast-providers.yaml` | нет — только loopback, запись `api_keys` не создаётся | + +Экспорт для Raycast — это отдельный документ `providers.yaml` с одним элементом `id: opencodex` в +последовательности `providers`: `name: OpenCodex`, базовый URL прокси с `/v1` и каждая маршрутизируемая +модель с её `abilities` (`tools` и `system_message` поддерживаются всегда, `vision` берётся из входных +модальностей каталога, `reasoning_effort` задаётся, когда у модели есть шкала усилий, `temperature` +отключена для рассуждающих моделей). Custom Providers — функция Raycast Pro, а Raycast следит за файлом, +поэтому сохранённое изменение вступает в силу без перезапуска. Формат описан на +[manual.raycast.com/ai/custom-providers](https://manual.raycast.com/ai/custom-providers). Запись +`api_keys` не создаётся, поэтому этот экспорт работает только через loopback, а привязка вне loopback +отклоняется. opencode интерполирует `{env:OPENCODEX_OPENCODE_API_KEY}`. Сгенерированный opencodex экспорт для Pi не требует переменной окружения и несёт литеральную заглушку `opencodex-loopback`. Это значение diff --git a/docs-site/src/content/docs/ru/reference/cli/lifecycle.md b/docs-site/src/content/docs/ru/reference/cli/lifecycle.md index 1ace7cc10f..7be5d5ad77 100644 --- a/docs-site/src/content/docs/ru/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ru/reference/cli/lifecycle.md @@ -89,6 +89,19 @@ ocx eject back ### `ocx status [--json]` +Status и `ocx doctor` сравнивают версии текущего CLI и работающего прокси. Если CLI новее, +перезапустите прокси из нужной актуальной установки. Для фоновой службы используйте +`ocx service repair` (`ocx service restart` — её псевдоним). Если новее прокси, обновите CLI +или исправьте `PATH`, чтобы он указывал на нужную установку. Диагностика не ремонтирует службу +и не меняет разрешение запросов. + +При одинаковых строках версий, значениях `unknown` / `0.0.0` или отсутствии версии прокси +предупреждение подавляется. Doctor не считает placeholder подтверждённым совпадением. +Разные строки, которые нельзя строго разобрать как SemVer, и версии, отличающиеся только +build metadata, вызывают нейтральное предупреждение без указания устаревшей стороны. +Пробелы не удаляются, префикс `v` не нормализуется. JSON содержит ту же рекомендацию в +`versionSkew` с прежними полями `cliVersion`, `proxyVersion`, `skewed` и `warning`. + Печатает read-only диагностическую сводку: PID прокси, достижимость `/healthz`, URL дашборда, путь к конфигу, провайдера по умолчанию, настройку автозапуска Codex, состояние службы, состояние shim'а и redacted effective Codex home. Только явная и высокоуверенная сигнатура mismatch diff --git a/docs-site/src/content/docs/ru/reference/cli/providers-accounts.md b/docs-site/src/content/docs/ru/reference/cli/providers-accounts.md index 56bde92668..4ae2bc7b5f 100644 --- a/docs-site/src/content/docs/ru/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/ru/reference/cli/providers-accounts.md @@ -15,7 +15,7 @@ pool'ами и контролируют каталог моделей, кото | Подкоманда | Поддерживаемые флаги | Действие | | --- | --- | --- | -| `list` | `--json` | Показать настроенных провайдеров и оставшиеся записи registry. | +| `list` | `--json`, `--jsonl` | Показать настроенных провайдеров и оставшиеся записи registry. `--jsonl` выводит по одному JSON-объекту настроенного провайдера на строку. | | `add ` | `--adapter `, `--base-url `, `--api-key `, `--default-model `, `--set-default`, `--force`, `--json`, `--sync` | Добавить registry/custom-провайдера. `--force` перезаписывает; `--sync` обновляет живой прокси в human-output mode. | | `edit ` | provider field flags, `--headers `, `--json` | Изменить валидированные live-поля провайдера, не заменяя key-pool'ы. `--headers` объединяет пользовательские request-header'ы; передайте `{}` или `-`, чтобы очистить их. | | `test ` | `--json` | Пробный запрос к реальному upstream model-endpoint'у. | @@ -29,6 +29,7 @@ pool'ами и контролируют каталог моделей, кото ```bash ocx provider list --json +ocx provider list --jsonl ocx provider test ark ocx provider add anthropic --api-key sk-ant-... --set-default --sync ocx provider add local-dev --adapter openai-chat --base-url http://localhost:11434/v1 @@ -37,6 +38,8 @@ ocx models --provider anthropic --json ocx models live --provider ark --json ``` +`--jsonl` выводит только настроенных провайдеров: один JSON-объект на строку. Поля каждого объекта совпадают с полями элемента массива `configured` в `--json`; сводка `registryCount` не включается. Скрипты могут обрабатывать объекты построчно. Флаги `--json` и `--jsonl` нельзя использовать вместе. + :::caution[Пользовательские заголовки — не канал для учётных данных] `--headers` предназначен для несекретных метаданных запроса — подсказок маршрутизации, селекторов тенанта или проекта, идентификаторов трассировки. Это не diff --git a/docs-site/src/content/docs/tr/guides/claude-code.md b/docs-site/src/content/docs/tr/guides/claude-code.md index 5450d6b748..4be81a4de8 100644 --- a/docs-site/src/content/docs/tr/guides/claude-code.md +++ b/docs-site/src/content/docs/tr/guides/claude-code.md @@ -582,12 +582,14 @@ dönüştürür: | Asistan metni | `output_text` | | Asistan `tool_use` | `function_call` (`input` → JSON dizgeleştirilmiş `arguments`) | | Kullanıcı `tool_result` | `function_call_output` (`is_error` → `[tool error]` öneki) | -| `thinking` / `redacted_thinking` tekrarı | Bırakılır | +| `thinking` / `redacted_thinking` tekrarı | İmzaları ve gizli yükleri sınırlı `ocxr1` zarflarında taşıyan `reasoning` öğeleri | | Fonksiyon araçları | `{type: "function"}` (`web_search*` → `{type: "web_search"}`) | | `tool_choice` | `auto`→`auto`, `none`→`none`, `any`→`required`, adlandırılmış fonksiyon→`{type:"function",name}`, barındırılan WebSearch/web_search→`{type:"web_search"}` | | `max_tokens` | `max_output_tokens` | | `stop_sequences` | `stop` | +Hedeflenen Anthropic adaptöründe gizlenmemiş imzalı bloklar (boş thinking dahil) ve opak redacted blokları korunur. `hideThinkingSummary` değişmez: yerel olarak gizlenen imzalı metin Claude istemcilerine gösterilmez; bu sınır üzerinden kayıpsız yeniden oynatma doğrulanmamıştır. Eski birleşik zarflarda metin akışla gönderildikten sonra özgün blok sırası geri getirilemez. `claudeCode.compatibility: "enforce"` thinking yeniden oynatmasını hâlâ reddeder. Bu, gerçek Anthropic kabulünü veya önbellek iyileşmesini kanıtlamaz; [#3719](https://github.com/lidge-jun/opencodex/issues/3719) açık kalır. + **Hata durumları (400):** hatalı biçimlendirilmiş JSON; eksik/boş `model`; eksik/boş `messages`; desteklenmeyen rol; `tool_use_id` içermeyen `tool_result`; kimlik/ad içermeyen `tool_use`; ad içermeyen adlandırılmış `tool_choice`. @@ -599,7 +601,8 @@ kimlik/ad içermeyen `tool_use`; ad içermeyen adlandırılmış `tool_choice`. | `response.created` | `message_start` + `ping` | | Kalp atışı (Heartbeat) | `ping` | | Metin farkları | `content_block_start` → `content_block_delta` (metin) → `content_block_stop` | -| Akıl yürütme özeti/metni | Sentetik imzalı `thinking` bloğu | +| Akıl yürütme özeti/metni | Tekrarlanan imzayı veya sınırlı bir `ocxr1` yedeğini taşıyan `thinking` bloğu | +| Gizli akıl yürütme | Akıl yürütme zarfından yeniden oynatılan `redacted_thinking` blokları | | Fonksiyon çağrısı çerçeveleri | `input_json_delta` ile `tool_use` bloğu | | Terminal olayı | `message_delta` → `message_stop` | | Terminalden önce EOF | 502 tarzı `api_error` | diff --git a/docs-site/src/content/docs/tr/guides/integrations.md b/docs-site/src/content/docs/tr/guides/integrations.md index fea4b37dd4..f068b0233f 100644 --- a/docs-site/src/content/docs/tr/guides/integrations.md +++ b/docs-site/src/content/docs/tr/guides/integrations.md @@ -1,10 +1,10 @@ --- title: Entegrasyonlar -description: Kontrol panelinden OpenCode, Pi, OMP, Hermes, OpenClaw, Kimi Code, Gajae Code, DeepSeek Harness ve MiniMax Code'u opencodex'e bağlayın — istemci başına tek bir anahtar ve her yazmadan önce alınan bir yedek. +description: Kontrol panelinden OpenCode, Pi, OMP, Hermes, OpenClaw, Kimi Code, Gajae Code, DeepSeek Harness, MiniMax Code, ZCode, Prime Agent, Aside ve Raycast'i opencodex'e bağlayın — istemci başına tek bir anahtar ve her yazmadan önce alınan bir yedek. --- **Entegrasyonlar** sekmesi, opencodex'in sağlayıcı bloğunu istemcinin kendi -yapılandırma dosyasına yazar ve tekrar kaldırır. Dokuz istemci bu şekilde +yapılandırma dosyasına yazar ve tekrar kaldırır. On üç istemci bu şekilde çalışır, her biri bir anahtarla: | İstemci | Yapılandırma dosyası | Format | Değişiklik ne zaman geçerli olur? | Kimlik bilgisi | @@ -18,6 +18,10 @@ yapılandırma dosyasına yazar ve tekrar kaldırır. Dokuz istemci bu şekilde | Gajae Code | `~/.gjc/agent/models.yml` | YAML | yeni oturumlarda veya `/model` açtığınızda | `OPENCODEX_GAJAE_API_KEY` | | DeepSeek Harness (DSH) | `$DSH_HOME/settings.yaml` (varsayılan `~/.dsh/settings.yaml`) | YAML | çalışırken yeniden yükleme | gizli olmayan geri döngü bearer yer tutucusu | | MiniMax Code | `~/.minimax/config.yaml` | YAML | yeni oturumlarda veya model seçici açıldıktan sonra | geri döngü (loopback) yer tutucusu | +| Prime Agent | `~/.prime/agent/models.json` | JSON | yeni oturumlarda | geri döngü yer tutucusu | +| ZCode | `~/.zcode/v2/config.json` | JSON | yeniden başlatmada | geri döngü yer tutucusu | +| Aside | `~/.aside/u//models.json` | JSON | Aside tamamen kapatılıp yeniden açıldıktan sonra | geri döngü yer tutucusu | +| Raycast | `~/.config/raycast/ai/providers.yaml` | YAML | kaydedildiği anda — Raycast dosyayı izler | yok — yalnızca geri döngü | Yönetilen DSH desteğinin en düşük uyumlu sürümü **DSH 0.1.0-rc.6**'dır. OpenCodex yalnızca `llm-pi-ai.providers.opencodex` bölümünü yönetir: Uygula ve Yenile bu bölümü değiştirir, Devre Dışı @@ -35,6 +39,39 @@ Entegrasyon yenilendiğinde model başına doğrulanmış bağlam pencereleri ve çabası seçenekleri de yenilenir; bilinmeyen yetenekler atlanır ve MCode oturumunun yönettiği geçerli çaba seçimi korunur. +Raycast'in iki ön koşulu vardır. Özel sağlayıcılar (Custom Providers) bir **Raycast Pro** +özelliğidir: ücretsiz planda dosya yine yazılır, ancak Raycast onu okumayacağı için +`ocx integration client status --client raycast` ve Entegrasyonlar sayfası bir uyarı +bildirir. Ayrıca Raycast `ai` klasörünü yalnızca Raycast → Settings → AI → +**Reveal Providers Config** seçeneğini bir kez açtığınızda oluşturur; opencodex bu +klasörü kurulum sinyali olarak kullanır ve klasör var olana kadar istemciyi kurulu değil +olarak bildirir. Raycast, `~/.config/raycast/ai/providers.yaml` dosyasını macOS ve +Windows'ta aynı şekilde okur ve `XDG_CONFIG_HOME` değerini dikkate almaz; bu nedenle bu +yol taşınamaz. + +Yönetilen blok, dosyanın `providers` dizisindeki tek bir öğedir: `id: opencodex`, +`name: OpenCodex`, `base_url: http://:/v1` ve `abilities` alanıyla birlikte +yönlendirilen her model — dışa aktarma kuralı olarak `tools` ve `system_message` değeri `true` olur, `vision` +kataloğun giriş modalitelerini izler, `reasoning_effort` modelin bir çaba merdiveni +varsa ayarlanır ve `temperature` akıl yürütme modelleri için kapatılır. Dosyadaki diğer +sağlayıcılar korunur ve devre dışı bırakma yalnızca OpenCodex öğesini kaldırır. Raycast +değişikliği dosya kaydedilir kaydedilmez, yeniden başlatma gerekmeden alır; modeller +Raycast'in model seçicisinde **OpenCodex** altında gruplanmış olarak görünür. Raycast şeması +isteğe bağlı `api_keys` alanını destekler; OpenCodex bu alanı bilerek yazmaz ve geri döngü +dışı veya kimlik doğrulaması gerektiren hedefleri reddeder. Bu entegrasyon OpenCodex'in +zorunlu kabul başlığını sağlayamaz. macOS'taki özel tercih yalnızca bir Pro ipucudur; +Windows bu tercihi hiç okumaz ve durumu bilinmiyor olarak bildirir. Bu bilgi yazmayı engellemez. +Dışa aktarılan meta veriler her modelin araç desteğini doğrulamaz. Diğer sağlayıcıların +değerleri korunur; YAML biçimlendirmesi ve yorumlarının korunması garanti edilmez. Format +[manual.raycast.com/ai/custom-providers](https://manual.raycast.com/ai/custom-providers) +adresinde belgelenmiştir. + +Raycast CLI dışa aktarmaları ve panel indirmeleri, yapılandırılmış kimlik doğrulamasız +geri döngü dinleyicisi dahil çalışan sunucunun adresini ve kabul politikasını kullanır. +`ocx ensure`, çalışan sunucudan farklı olabilecek kayıtlı yapılandırma kopyasıyla Raycast'i +yenilemez. Sunucu başlangıcı ve açık senkronizasyon katalog yenilemeye devam eder. + + Yollar, varsa her istemcinin kendi ortam geçersiz kılmalarını dikkate alır. OMP için `OMP_PROFILE`, açıkça boş olduğunda bile varlığıyla `PI_PROFILE`'a üstün gelir. Adlandırılmış bir profil, `PI_CONFIG_DIR`'i kullanıcının ev dizinine göre @@ -112,7 +149,7 @@ hiçbir şey sessizce değiştirilmez veya düşürülmez. **OMP** de yanındaki düzenlemelerden etkilenmez, ama başka bir nedenle: writer'ı yalnızca kendi `providers.opencodex` aralığını bayt bayt yamalar, dosyanın geri kalanı hiçbir zaman yeniden yazılmaz. Yorum taşıyabilen diğer biçimlerde (Hermes, OpenClaw, -Kimi Code, Gajae Code, MiniMax Code — bütün belge olarak yazılan YAML, JSON5 ve TOML) veya +Kimi Code, Gajae Code, MiniMax Code, Raycast — bütün belge olarak yazılan YAML, JSON5 ve TOML) veya kendi girdilerimiz düzenlenmişse, anahtar kilitlenir ve hangi düzenlemelerin size ait olduğunu tahmin etmek yerine devre dışı bırakmayı reddeder. @@ -192,10 +229,12 @@ ocx integration client enable --client mcode ocx mcode ``` -Bağlandıktan sonra `ocx sync`, yönetilen MCode bloğunu güncel bağlam pencereleri ve -akıl yürütme çabası seçenekleriyle de yeniler. Eksik, dışarıdan düzenlenmiş, güvenli -olmayan veya hiç sahiplenilmemiş bloklara dokunmaz; yeniden bağlamak istediğinizde -entegrasyonu açıkça yeniden etkinleştirin. +Bağlandıktan sonra `ocx sync` ve `POST /api/sync`, yönetilen MCode, Pi, Aside ve +Raycast kataloglarını yeniler. Proxy başlangıcı da yönetilen Raycast kataloğunu +yeniler. Model görünürlüğü, sağlayıcı veya ön ayar değişiklikleri Pi, Aside ve +Raycast kataloglarını günceller. Eksik, dışarıdan düzenlenmiş, güvenli olmayan +veya elle kaldırılmış bloklara dokunmaz; yeniden bağlamak istediğinizde +entegrasyonu açıkça etkinleştirin. Ayrı MiniMax platform CLI'si (`mmx`) bir dosya anahtarı entegrasyonu değildir. Metin komutları MiniMax'ın Anthropic uyumlu uç noktasını kullandığı için OpenCodex, diff --git a/docs-site/src/content/docs/tr/guides/providers.md b/docs-site/src/content/docs/tr/guides/providers.md index c5564e74a1..6ff4f1c038 100644 --- a/docs-site/src/content/docs/tr/guides/providers.md +++ b/docs-site/src/content/docs/tr/guides/providers.md @@ -355,6 +355,7 @@ yalnızca Cline IDE/CLI içinde mevcuttur; `minimax/minimax-m2.5` belgelenmiş A | NVIDIA NIM | `https://integrate.api.nvidia.com/v1` | | Z.AI (GLM Kodlama) | `https://api.z.ai/api/coding/paas/v4` | | Zhipu AI (BigModel) | `https://open.bigmodel.cn/api/paas/v4` | +| [BigModel Coding Plan — Responses (statik model listesi)](/guides/providers/#bigmodel-coding-plan-over-responses) | `https://open.bigmodel.cn/api/v1` | | Qwen Cloud | Token planı (varsayılan): `https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1` · Kullandıkça öde: `https://dashscope.aliyuncs.com/compatible-mode/v1` · veya Özel | | Tencent Cloud Coding Plan | `https://api.lkeap.cloud.tencent.com/coding/v3` | | SiliconFlow | `https://api.siliconflow.cn/v1` | @@ -537,7 +538,7 @@ tutarsız faturalandırma toplamları yanıltıcı bir çubuk yerine hiçbir rap > **Tencent Cloud Coding Plan kullanım kısıtlaması:** Tencent bu aboneliği yalnızca etkileşimli kodlama araçları için belgeler. Genel API otomasyonu, özel uygulama arka uçları ve etkileşimsiz toplu kullanım yasaktır ve plan anahtarının askıya alınmasına neden olabilir. -> **İki GLM rotası:** `zai`, Z.AI uluslararası kodlama planı aboneliğidir; `zhipu-bigmodel`, Zhipu'nun yerel BigModel kullandıkça öde uç noktasıdır. Farklı ana bilgisayarlar, farklı anahtarlar, farklı faturalandırma — biri için verilen bir anahtar diğerine karşı kimlik doğrulaması yapmaz. +> **GLM faturalandırma rotaları:** `zai`, Z.AI uluslararası kodlama planı aboneliğidir; `zhipu-bigmodel`, Zhipu'nun yerel BigModel kullandıkça öde uç noktasıdır. Farklı ana bilgisayarlar, farklı anahtarlar, farklı faturalandırma — biri için verilen bir anahtar diğerine karşı kimlik doğrulaması yapmaz. ### Birden fazla API anahtarı diff --git a/docs-site/src/content/docs/tr/reference/cli/agents.md b/docs-site/src/content/docs/tr/reference/cli/agents.md index a3e184661d..04e72a766c 100644 --- a/docs-site/src/content/docs/tr/reference/cli/agents.md +++ b/docs-site/src/content/docs/tr/reference/cli/agents.md @@ -191,7 +191,7 @@ Grok Build model çitini yönetin ve uygulayın. ## İstemci yapılandırma dışa aktarma -### `ocx export --client ` +### `ocx export --client ` Çalışan proxy'ye bağlı bir istemci yapılandırmasını yazdırın. Komut, `opencodex` sağlayıcı bloğunu — temel URL, model listesi ve istemcinin kimlik bilgisi @@ -203,7 +203,7 @@ yalnızca Codex'in şu anda görebildiği modelleri yayınlar. | Bayrak | Eylem | | --- | --- | -| `--client ` | Gerekli. İstemci yapılandırma lehçesini seçer. | +| `--client ` | Gerekli. İstemci yapılandırma lehçesini seçer. | | `--json` | Betikler için stdout üzerinde oluşturulan belgeyi JSON olarak yazdırın. Bu, seçilen istemcinin yerel formatı YAML, TOML veya JSON5 olsa bile JSON'dur. | | `--out ` | İstemcinin yerel yapılandırma formatını `` konumuna yazın. Mevcut bir dosyanın üzerine yazmayı reddeder. | | `--force` | `--out`'un mevcut bir dosyanın üzerine yazmasına izin verin. | @@ -233,6 +233,18 @@ için kendi varsayılanlarını uygular) gelir. | `mcode` | `~/.minimax/config.yaml` (ayarlandığında `MINIMAX_DATA_DIR`, ardından eski `MAVIS_DATA_DIR` öncelikli; göreli değer reddedilir) | `mcode-config.yaml` | yok — geri döngü yer tutucusu | | `zcode` | `~/.zcode/v2/config.json` (ayarlandığında `ZCODE_DATA_DIR` öncelikli; göreli değer reddedilir) | `config.json` | yok — geri döngü yer tutucusu | | `prime` | `~/.prime/agent/models.json` (ayarlandığında `PRIME_AGENT_CODING_AGENT_DIR` öncelikli; göreli değer reddedilir) | `prime-models.json` | yok — geri döngü yer tutucusu | +| `raycast` | `~/.config/raycast/ai/providers.yaml`, macOS ve Windows'ta aynı (Raycast `XDG_CONFIG_HOME` değerini dikkate almaz) | `raycast-providers.yaml` | yok — yalnızca geri döngü, `api_keys` girdisi yazılmaz | + +Raycast dışa aktarımı, `providers` dizisinde tek bir `id: opencodex` öğesi içeren bağımsız +bir `providers.yaml` belgesidir: `name: OpenCodex`, proxy'nin `/v1` temel URL'si ve +`abilities` alanıyla birlikte yönlendirilen her model (`tools` ve `system_message` her +zaman destekli, `vision` kataloğun giriş modalitelerinden, `reasoning_effort` modelin bir +çaba merdiveni varsa, `temperature` akıl yürütme modelleri için kapalı). Özel sağlayıcılar +bir Raycast Pro özelliğidir ve Raycast dosyayı izlediği için kaydedilen bir değişiklik +yeniden başlatma gerekmeden etkili olur. Format +[manual.raycast.com/ai/custom-providers](https://manual.raycast.com/ai/custom-providers) +adresinde belgelenmiştir. Hiçbir `api_keys` girdisi yazılmaz; bu yüzden bu dışa aktarım +yalnızca geri döngü içindir ve geri döngü dışı bir bağlama reddedilir. opencode `{env:OPENCODEX_OPENCODE_API_KEY}` değerini enterpole eder. Üretilen Pi ve OMP dışa aktarımları bir ortam değişkeni gerektirmez: her biri değişmez diff --git a/docs-site/src/content/docs/tr/reference/cli/providers-accounts.md b/docs-site/src/content/docs/tr/reference/cli/providers-accounts.md index f611d7be73..2d58adae3b 100644 --- a/docs-site/src/content/docs/tr/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/tr/reference/cli/providers-accounts.md @@ -16,7 +16,7 @@ bir ad hem `--adapter` hem de `--base-url` gerektirir. | Alt komut | Desteklenen bayraklar | Eylem | | --- | --- | --- | -| `list` | `--json` | Yapılandırılmış sağlayıcıları ve kalan kayıt defteri girdilerini listeleyin. | +| `list` | `--json`, `--jsonl` | Yapılandırılmış sağlayıcıları ve kalan kayıt defteri girdilerini listeleyin. `--jsonl`, yapılandırılmış her sağlayıcı için satır başına bir JSON nesnesi üretir. | | `add ` | `--adapter `, `--base-url `, `--api-key `, `--default-model `, `--set-default`, `--force`, `--json`, `--sync` | Bir kayıt defteri/özel sağlayıcı ekleyin. `--force` üzerine yazar; `--sync`, insan çıktısı modunda çalışan bir proxy'yi yeniler. | | `edit ` | sağlayıcı alan bayrakları, `--headers `, `--json` | Anahtar havuzlarını değiştirmeden doğrulanmış canlı sağlayıcı alanlarını düzenleyin. `--headers` özel istek başlıklarını birleştirir; temizlemek için `{}` veya `-` iletin. | | `test ` | `--json` | Gerçek yukarı akış model uç noktasını araştırın. | @@ -30,6 +30,7 @@ bir ad hem `--adapter` hem de `--base-url` gerektirir. ```bash ocx provider list --json +ocx provider list --jsonl ocx provider test ark ocx provider add anthropic --api-key sk-ant-... --set-default --sync ocx provider add local-dev --adapter openai-chat --base-url http://localhost:11434/v1 @@ -38,6 +39,8 @@ ocx models --provider anthropic --json ocx models live --provider ark --json ``` +`--jsonl` yalnızca yapılandırılmış sağlayıcıları, her satırda bir JSON nesnesi olacak şekilde yazar. Her nesne, `--json` çıktısındaki `configured` dizisinin bir öğesiyle aynı alanları içerir; `registryCount` özeti eklenmez. Betikler nesneleri satır satır işleyebilir. `--json` ve `--jsonl` birlikte kullanılamaz. + :::caution[Özel başlıklar bir kimlik bilgisi kanalı değildir] `--headers`, gizli olmayan istek meta verileri içindir — yönlendirme ipuçları, kiracı veya proje seçicileri, izleme kimlikleri. Kimlik doğrulama materyali diff --git a/docs-site/src/content/docs/zh-cn/guides/claude-code.md b/docs-site/src/content/docs/zh-cn/guides/claude-code.md index 3bbe49646b..dd8bc740b8 100644 --- a/docs-site/src/content/docs/zh-cn/guides/claude-code.md +++ b/docs-site/src/content/docs/zh-cn/guides/claude-code.md @@ -344,12 +344,14 @@ Claude Code 的 `/effort` 设置会完整保留并传递给适配器: | Assistant 文本 | `output_text` | | Assistant `tool_use` | `function_call`(`input` → JSON 字符串化的 `arguments`) | | 用户 `tool_result` | `function_call_output`(`is_error` → `[tool error]` 前缀) | -| 重放 `thinking` / `redacted_thinking` | 丢弃 | +| 重放 `thinking` / `redacted_thinking` | `reasoning` 项;签名和脱敏载荷保存在有界 `ocxr1` 信封中 | | Function 工具 | `{type: "function"}`(`web_search*` → `{type: "web_search"}`) | | `tool_choice` | `auto`→`auto`,`none`→`none`,`any`→`required`,指定函数→`{type:"function",name}`,托管 WebSearch/web_search→`{type:"web_search"}` | | `max_tokens` | `max_output_tokens` | | `stop_sequences` | `stop` | +在预期的 Anthropic 适配器上,保留未隐藏的签名块(包括空 thinking)和不透明的 redacted 块。`hideThinkingSummary` 策略不变:不会向 Claude 客户端公开本地隐藏的签名文本,尚未证明经过此隐藏边界的无损重放。旧版组合信封在流式文本发出后无法恢复原始块顺序。`claudeCode.compatibility: "enforce"` 仍拒绝 thinking 重放。这不证明真实 Anthropic 接受请求或缓存命中改善;[#3719](https://github.com/lidge-jun/opencodex/issues/3719) 仍未关闭。 + **错误情况(400):**JSON 格式错误;缺少/空的 `model`;缺少/空的 `messages`;不支持的 role;`tool_result` 缺少 `tool_use_id`;`tool_use` 缺少 id/name;指定名称的 `tool_choice` 缺少 name。 @@ -361,7 +363,8 @@ role;`tool_result` 缺少 `tool_use_id`;`tool_use` 缺少 id/name;指定 | `response.created` | `message_start` + `ping` | | 心跳 | `ping` | | 文本增量 | `content_block_start` → `content_block_delta`(文本)→ `content_block_stop` | -| 推理摘要/文本 | 带合成签名的 `thinking` 块 | +| 推理摘要/文本 | 带重放签名或有界 `ocxr1` 回退信封的 `thinking` 块 | +| 脱敏推理 | 从推理信封重放的 `redacted_thinking` 块 | | Function-call 帧 | 带 `input_json_delta` 的 `tool_use` 块 | | 终止事件 | `message_delta` → `message_stop` | | 在终止事件前 EOF | 502 风格的 `api_error` | diff --git a/docs-site/src/content/docs/zh-cn/guides/providers.md b/docs-site/src/content/docs/zh-cn/guides/providers.md index 3fb72a4e6a..b4010cdae5 100644 --- a/docs-site/src/content/docs/zh-cn/guides/providers.md +++ b/docs-site/src/content/docs/zh-cn/guides/providers.md @@ -205,6 +205,7 @@ Cline IDE/CLI 中提供,不能通过 API 使用;`minimax/minimax-m2.5` 是 | NVIDIA NIM | `https://integrate.api.nvidia.com/v1` | | Z.AI (GLM Coding) | `https://api.z.ai/api/coding/paas/v4` | | 智谱 AI (BigModel) | `https://open.bigmodel.cn/api/paas/v4` | +| [BigModel Coding Plan — Responses (静态模型列表)](/guides/providers/#bigmodel-coding-plan-over-responses) | `https://open.bigmodel.cn/api/v1` | | Qwen Cloud | Token plan(默认): `https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1` · 按量付费: `https://dashscope.aliyuncs.com/compatible-mode/v1` · 或自定义 | | 腾讯云 Coding Plan | `https://api.lkeap.cloud.tencent.com/coding/v3` | | SiliconFlow | `https://api.siliconflow.cn/v1` | @@ -316,7 +317,7 @@ Bearer key。公开模型列表只保留同时报告 `model_type: chat` 和 `cha > **腾讯云 Coding Plan 使用限制:**腾讯将此订阅限定为交互式编程工具使用。禁止通用 API > 自动化、自定义应用后端和非交互式批量调用;违规使用可能导致套餐密钥被停用。 -> **两条 GLM 线路:**`zai` 是 Z.AI 的国际 coding plan 订阅,`zhipu-bigmodel` 是智谱国内 +> **GLM 计费线路:**`zai` 是 Z.AI 的国际 coding plan 订阅,`zhipu-bigmodel` 是智谱国内 > BigModel 的按量付费端点。二者主机、密钥与计费均不同,为其中一方签发的密钥无法在另一方通过鉴权。 ### 多个 API 密钥 diff --git a/docs-site/src/content/docs/zh-cn/reference/cli/agents.md b/docs-site/src/content/docs/zh-cn/reference/cli/agents.md index 11e1c38ee1..89203420e9 100644 --- a/docs-site/src/content/docs/zh-cn/reference/cli/agents.md +++ b/docs-site/src/content/docs/zh-cn/reference/cli/agents.md @@ -132,7 +132,7 @@ ocx claude desktop import [--apply] Validate and import JSON ## Client config export -### `ocx export --client ` +### `ocx export --client ` 输出连接到正在运行代理的客户端配置。此命令会以所选客户端的原生格式序列化 `opencodex` provider 块,其中包含基础 URL、模型列表,以及该客户端适用的凭据引用或 `opencodex-loopback` 占位值。 @@ -140,7 +140,7 @@ ocx claude desktop import [--apply] Validate and import JSON | 标志 | 动作 | | --- | --- | -| `--client ` | 必需。选择客户端配置格式。 | +| `--client ` | 必需。选择客户端配置格式。 | | `--json` | 仅在 stdout 打印配置 JSON,这样重定向即可捕获字节级精确输出。包括 `--out` 写入提示在内的所有诊断信息都会输出到 stderr。 | | `--out ` | 将配置写入 ``。拒绝替换已存在的文件。 | | `--force` | 允许 `--out` 替换已存在的文件。 | @@ -167,6 +167,9 @@ ocx export --client opencode --out ~/opencodex-opencode.json | `mcode` | `~/.minimax/config.yaml` (设置后 `MINIMAX_DATA_DIR` 优先,其次是旧的 `MAVIS_DATA_DIR`;相对路径会被拒绝) | `mcode-config.yaml` | 无 — loopback placeholder | | `zcode` | `~/.zcode/v2/config.json` (设置后 `ZCODE_DATA_DIR` 优先;相对路径会被拒绝) | `config.json` | 无 — loopback placeholder | | `prime` | `~/.prime/agent/models.json` (设置后 `PRIME_AGENT_CODING_AGENT_DIR` 优先;相对路径会被拒绝) | `prime-models.json` | 无 — loopback placeholder | +| `raycast` | `~/.config/raycast/ai/providers.yaml`(macOS 与 Windows 相同;Raycast 不遵循 `XDG_CONFIG_HOME`) | `raycast-providers.yaml` | 无 — 仅限回环,不会写入 `api_keys` 条目 | + +Raycast 导出是一份独立的 `providers.yaml` 文档,在 `providers` 序列中只有一个 `id: opencodex` 元素:`name: OpenCodex`、代理的 `/v1` 基础 URL,以及每个已路由模型及其 `abilities`(`tools` 与 `system_message` 始终支持,`vision` 取自目录的输入模态,`reasoning_effort` 在模型有 effort 阶梯时设置,`temperature` 对推理模型关闭)。Custom Providers 是 Raycast Pro 功能,且 Raycast 会监视该文件,因此保存后的更改无需重启即可生效。格式见 [manual.raycast.com/ai/custom-providers](https://manual.raycast.com/ai/custom-providers)。不会写入任何 `api_keys` 条目,所以该导出仅限回环,非回环绑定会被拒绝。 opencode 会插值 `{env:OPENCODEX_OPENCODE_API_KEY}`。opencodex 生成的 Pi 导出不需要环境变量,而是携带字面占位值 `opencodex-loopback`。这个值是必需的:Pi 在构建模型列表时会解析 `apiKey`,如果已有配置包含未设置的环境变量引用,它就会隐藏整个 provider。回环上的代理从不校验生成的占位值。 diff --git a/docs-site/src/content/docs/zh-cn/reference/cli/providers-accounts.md b/docs-site/src/content/docs/zh-cn/reference/cli/providers-accounts.md index 85633f54f5..a6fe332390 100644 --- a/docs-site/src/content/docs/zh-cn/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/zh-cn/reference/cli/providers-accounts.md @@ -14,7 +14,7 @@ description: 提供方配置、凭据、配额,以及模型目录命令。 | 子命令 | 支持的标志 | 操作 | | --- | --- | --- | -| `list` | `--json` | 列出已配置的提供方以及剩余的注册表条目。 | +| `list` | `--json`, `--jsonl` | 列出已配置的提供方以及剩余的注册表条目。 `--jsonl` 为每个已配置的提供方输出一行 JSON 对象。 | | `add ` | `--adapter `, `--base-url `, `--api-key `, `--default-model `, `--set-default`, `--force`, `--json`, `--sync` | 添加一个注册表/自定义提供方。`--force` 会覆盖;`--sync` 会在有人类输出模式运行的代理上刷新配置。 | | `edit ` | 提供方字段标志,`--headers `,`--json` | 在不替换密钥池的情况下,编辑经过校验的在线提供方字段。`--headers` 会合并自定义请求头;传入 `{}` 或 `-` 可清空。 | | `test ` | `--json` | 探测真实的上游模型端点。 | @@ -28,6 +28,7 @@ description: 提供方配置、凭据、配额,以及模型目录命令。 ```bash ocx provider list --json +ocx provider list --jsonl ocx provider test ark ocx provider add anthropic --api-key sk-ant-... --set-default --sync ocx provider add local-dev --adapter openai-chat --base-url http://localhost:11434/v1 @@ -36,6 +37,8 @@ ocx models --provider anthropic --json ocx models live --provider ark --json ``` +`--jsonl` 仅输出已配置的提供方,每行一个 JSON 对象。每个对象的字段与 `--json` 输出中 `configured` 数组的元素相同,不包含 `registryCount` 汇总。脚本可以逐行处理这些对象。`--json` 与 `--jsonl` 不能同时使用。 + :::caution[自定义请求头不是凭据通道] `--headers` 用于非机密的请求元数据 —— 路由提示、租户或项目选择器、追踪 ID 等。它不是 存放认证信息的地方,校验器会拒绝标准凭据请求头名称(`Authorization`、`X-Api-Key`、 diff --git a/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md b/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md index b7339cd4c2..f121d67bc0 100644 --- a/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md +++ b/docs-site/src/content/docs/zh-cn/reference/configuration/providers.md @@ -371,6 +371,14 @@ Vercel AI Gateway 可以在多个底层推理提供者之间路由一个模型 请使用 `modelDisplayNames` 设置显示名称。优先顺序是操作者设置的 `modelDisplayNames`、提供者目录元数据,然后是普通的 `provider/model` 显示。键是此提供者内精确的原生模型 id,例如 `xai/grok-4.6` 的键是 `grok-4.6`。名称只改变显示,不会改变精确路由 id 或上游模型 id。请只把此字段加入 `config.json` 中现有的提供者设置,并保留所有其他字段。向 `PUT /api/providers/:provider/model-display-names` 发送 `{ "modelId": "grok-4.6", "displayName": "Grok 4.6" }` 可保存名称,发送 `displayName: null` 只重置该名称。 +本地 Codex 目录中受支持的不带前缀的原生 GPT 条目也可以通过 +`providers.openai.modelDisplayNames` 设置精确的显示名称, 例如 `"gpt-6-astra": "GPT 6 Astra"`。 +启动时同步和本地目录收敛都会重新应用这些名称。删除名称设置时, 只有条目的当前显示名称仍与已应用的覆盖值一致, +才会恢复原始原生名称。外部更改的显示名称仍受现有原生元数据规范化规则约束。 +例如,Astra (`gpt-6-astra`) 仍会将不同于固定原生名称的名称替换为该固定名称。 +显示名称覆盖不会改变模型 ID、元数据(包括能力)、排序、路由组合别名和带账户限定的条目。 +此本地目录覆盖不会重命名 HTTP 模型列表中的条目或虚拟 `*-pro` 条目。 + 预览版 GPT-5.6 回退条目使用相同机制。OpenAI API key 预设会为基础和 Pro id 设定 `922000` 上下文和 `922000` 最大输入;OpenRouter 会为 `openai/gpt-5.6-sol`、`openai/gpt-5.6-terra` 和 `openai/gpt-5.6-luna` 设定 `922000` 上下文。Pool/Direct 会声明 `922000`;同步后的目录会声明 `max`,同时保留 `xhigh` 的独立性。 ```json diff --git a/docs-site/src/content/docs/zh-tw/guides/claude-code.md b/docs-site/src/content/docs/zh-tw/guides/claude-code.md index ccfb3b9ddd..86a3ea0782 100644 --- a/docs-site/src/content/docs/zh-tw/guides/claude-code.md +++ b/docs-site/src/content/docs/zh-tw/guides/claude-code.md @@ -420,12 +420,14 @@ Claude Code 的 `/effort` 設定會完整保留並傳遞給適配器: | Assistant 文字 | `output_text` | | Assistant `tool_use` | `function_call`(`input` → JSON 字串化的 `arguments`) | | 使用者 `tool_result` | `function_call_output`(`is_error` → `[tool error]` 字首) | -| 重放 `thinking` / `redacted_thinking` | 丟棄 | +| 重放 `thinking` / `redacted_thinking` | `reasoning` 項目;簽名與遮蔽載荷保存在有界 `ocxr1` 信封中 | | Function 工具 | `{type: "function"}`(`web_search*` → `{type: "web_search"}`) | | `tool_choice` | `auto`→`auto`,`none`→`none`,`any`→`required`,指定名稱 function→`{type:"function",name}`,hosted WebSearch/web_search→`{type:"web_search"}` | | `max_tokens` | `max_output_tokens` | | `stop_sequences` | `stop` | +在預期的 Anthropic 適配器上,保留未隱藏的簽名區塊(包括空 thinking)和不透明的 redacted 區塊。`hideThinkingSummary` 政策不變:不會向 Claude 用戶端公開本地隱藏的簽名文字,尚未證明經過此隱藏邊界的無損重播。舊版組合信封在串流文字發出後無法恢復原始區塊順序。`claudeCode.compatibility: "enforce"` 仍拒絕 thinking 重播。這不證明真實 Anthropic 接受請求或快取命中改善;[#3719](https://github.com/lidge-jun/opencodex/issues/3719) 仍未關閉。 + **錯誤情況(400):**JSON 格式錯誤;缺少/空的 `model`;缺少/空的 `messages`;不支援的 role;`tool_result` 缺少 `tool_use_id`;`tool_use` 缺少 id/name;指定名稱的 `tool_choice` 缺少 name。 @@ -437,7 +439,8 @@ role;`tool_result` 缺少 `tool_use_id`;`tool_use` 缺少 id/name;指定 | `response.created` | `message_start` + `ping` | | 心跳 | `ping` | | 文字增量 | `content_block_start` → `content_block_delta`(文字)→ `content_block_stop` | -| 推理摘要/文字 | 帶合成簽名的 `thinking` 塊 | +| 推理摘要/文字 | 帶重播簽名或有界 `ocxr1` 備援信封的 `thinking` 塊 | +| 遮蔽推理 | 從推理信封重播的 `redacted_thinking` 塊 | | Function-call 幀 | 帶 `input_json_delta` 的 `tool_use` 塊 | | 終止事件 | `message_delta` → `message_stop` | | 在終止事件前 EOF | 502 風格的 `api_error` | diff --git a/docs-site/src/content/docs/zh-tw/guides/integrations.md b/docs-site/src/content/docs/zh-tw/guides/integrations.md index 54751d5620..46b03df9a1 100644 --- a/docs-site/src/content/docs/zh-tw/guides/integrations.md +++ b/docs-site/src/content/docs/zh-tw/guides/integrations.md @@ -1,9 +1,9 @@ --- title: 整合 -description: 從儀表板把 opencodex 連接到 OpenCode、Pi、OMP、Hermes、OpenClaw、Kimi Code、Gajae Code、DeepSeek Harness 與 MiniMax Code——每個客戶端一個開關,每次寫入前都會先備份。 +description: 從儀表板把 opencodex 連接到 OpenCode、Pi、OMP、Hermes、OpenClaw、Kimi Code、Gajae Code、DeepSeek Harness、MiniMax Code、ZCode、Prime Agent、Aside 與 Raycast——每個客戶端一個開關,每次寫入前都會先備份。 --- -**整合(Integrations)** 分頁會把 opencodex 的 provider 區塊寫入客戶端自己的設定檔,也會把它移除。共有九個客戶端以這種方式運作,每個都有一個開關: +**整合(Integrations)** 分頁會把 opencodex 的 provider 區塊寫入客戶端自己的設定檔,也會把它移除。共有十三個客戶端以這種方式運作,每個都有一個開關: | 客戶端 | 設定檔 | 格式 | 變更生效時機 | 憑證 | |---|---|---|---|---| @@ -16,6 +16,10 @@ description: 從儀表板把 opencodex 連接到 OpenCode、Pi、OMP、Hermes、 | Gajae Code | `~/.gjc/agent/models.yml` | YAML | 新 sessions,或當你開啟 `/model` 時 | `OPENCODEX_GAJAE_API_KEY` | | DeepSeek Harness (DSH) | `$DSH_HOME/settings.yaml`(預設 `~/.dsh/settings.yaml`) | YAML | 熱重載 | 非秘密的 loopback bearer 佔位符 | | MiniMax Code | `~/.minimax/config.yaml` | YAML | 新 sessions,或開啟模型選擇器後 | loopback 佔位符 | +| Prime Agent | `~/.prime/agent/models.json` | JSON | 新 sessions | loopback 佔位符 | +| ZCode | `~/.zcode/v2/config.json` | JSON | 重新啟動時 | loopback 佔位符 | +| Aside | `~/.aside/u//models.json` | JSON | 完全結束並重新開啟 Aside 後 | loopback 佔位符 | +| Raycast | `~/.config/raycast/ai/providers.yaml` | YAML | 儲存後立即生效——Raycast 會監看該檔案 | 無——僅限 loopback | 受管理 DSH 支援的相容性下限是 **DSH 0.1.0-rc.6**。OpenCodex 只擁有 `llm-pi-ai.providers.opencodex`:Apply 與 Refresh 會取代該片段,Disable 只移除該片段, @@ -30,6 +34,30 @@ MiniMax Code 依序遵循 `MINIMAX_DATA_DIR`、`MAVIS_DATA_DIR`,最後才回 逐模型 context window 與 reasoning-effort 選項;未知能力會省略,而 MCode session 目前選取的 effort 不會被覆寫。 +Raycast 有兩個前提。Custom Providers 是 **Raycast Pro** 功能:免費方案下檔案仍會被寫入,但 +`ocx integration client status --client raycast` 與整合頁面會回報警告,因為 Raycast 不會讀取它。 +另外,Raycast 只有在你開啟一次 Raycast → Settings → AI → **Reveal Providers Config** 後才會建立 +`ai` 資料夾;opencodex 以該資料夾作為安裝訊號,在它存在之前都會回報客戶端尚未安裝。Raycast 在 +macOS 與 Windows 上同樣讀取 `~/.config/raycast/ai/providers.yaml`,且不遵循 `XDG_CONFIG_HOME`, +所以該路徑無法搬移。 + +受管理區塊是檔案 `providers` 序列中的單一元素 `id: opencodex`:`name: OpenCodex`、 +`base_url: http://:/v1`,以及每個路由模型及其 `abilities`——`tools` 與 +`system_message` 依匯出慣例設為 `true`,`vision` 依目錄的輸入模態而定,`reasoning_effort` 在模型有 effort +階梯時設定,`temperature` 對推理模型關閉。檔案中的其他 provider 會被保留,停用只移除 OpenCodex +元素。檔案一儲存 Raycast 就會套用變更,不需重新啟動;模型會在 Raycast 的模型選擇器中歸在 +**OpenCodex** 群組下。Raycast 支援選填的 `api_keys`,但 OpenCodex 刻意省略該欄位,並拒絕 +非 loopback 或需要准入驗證的目標,因為此整合無法提供 OpenCodex 要求的准入標頭。 +macOS 私有偏好設定僅提供 Pro 狀態提示;Windows 完全不讀取該設定,狀態會是未知。 +此提示不會阻擋寫入。匯出中繼資料並未證實每個模型的工具能力。其他 provider 的值會保留, +但不保證 YAML 格式與註解不變。格式說明見 +[manual.raycast.com/ai/custom-providers](https://manual.raycast.com/ai/custom-providers)。 + +Raycast CLI 匯出與儀表板下載會使用執行中伺服器的目標位址和准入規則,包含已設定的 +無驗證 loopback listener。`ocx ensure` 不會以可能與執行中伺服器不同的已儲存設定快照 +重新整理 Raycast;伺服器啟動與明確執行的同步仍會更新目錄。 + + 路徑遵循客戶端自己的環境覆寫(environment override)。對 OMP 而言,`OMP_PROFILE` 以存在與否優先於 `PI_PROFILE`,即使明確為空也一樣。具名 profile 會把 `PI_CONFIG_DIR` 當作相對於使用者家目錄的目錄名稱,並忽略 `PI_CODING_AGENT_DIR`;沒有具名 profile 時,`PI_CODING_AGENT_DIR` 勝出。OMP 支援 provider 層級的 headers,但這個最初的整合刻意只支援 loopback;遠端 `x-opencodex-api-key` 的連線設定被延後。搬移過的 `HERMES_HOME`、`KIMI_CODE_HOME` 與 `XDG_CONFIG_HOME` 路徑同樣會被遵循,而非猜測。表格列出每個客戶端的預設值。 對原生 OpenAI 模型,產生的 OMP 區塊會選用其模型層級的 Responses API,保留圖片輸入與 reasoning-effort 控制。路由模型則維持 provider 的 Chat Completions 方言,讓它們既有的 adapters 保持相容。 @@ -52,7 +80,7 @@ opencodex 從自己的環境讀取這些變數。如果你的 gateway 以 profil - **Restore this point…** 會出現在較舊的操作上,或當檔案在那次操作之後有變更時。跨過這樣的變更做回復會再詢問一次,才覆蓋你的較新編輯——並且也會備份它們,所以那次的回復本身也可以復原。 - 每個客戶端保留十份備份。超過之後,最舊的快照檔案會被移除,其歷史列顯示為 **Backup expired**。 -停用只移除 opencodex 記錄為自己寫入的條目。如果你的檔案在我們寫入之後有變更,後續行為取決於我們自己的條目是否完好,以及檔案的格式。對於嚴格 JSON 設定檔(OpenCode、Pi),在我們的區塊**旁邊**進行的編輯——例如新增 MCP 伺服器或你自己的 provider——會顯示為**需要更新**:重新整理會在保留你的條目的前提下合併寫入,但格式可能會被正規化。例外情況是 JSON 無法精確重寫的內容——例如 `1e999` 這類非有限數字、重寫會被四捨五入的數字(極大的整數,或小到會塌縮成零的數字)、`-0`、同一個物件裡重複出現的鍵,或巢狀層數超過 1000 層——此時開關會鎖定,確保沒有任何值被悄悄改動或刪除。**OMP** 同樣不受旁邊編輯影響,但原因不同:它的 writer 只逐位元組修補自己的 `providers.opencodex` 範圍,檔案其餘部分從不會被重寫。至於其餘可以包含註解的格式(Hermes、OpenClaw、Kimi Code、Gajae Code、MiniMax Code——以整份文件寫出的 YAML、JSON5 與 TOML),或當我們自己的條目被編輯過時,開關會鎖定,停用會拒絕執行,而不是猜測哪些編輯是你的。 +停用只移除 opencodex 記錄為自己寫入的條目。如果你的檔案在我們寫入之後有變更,後續行為取決於我們自己的條目是否完好,以及檔案的格式。對於嚴格 JSON 設定檔(OpenCode、Pi),在我們的區塊**旁邊**進行的編輯——例如新增 MCP 伺服器或你自己的 provider——會顯示為**需要更新**:重新整理會在保留你的條目的前提下合併寫入,但格式可能會被正規化。例外情況是 JSON 無法精確重寫的內容——例如 `1e999` 這類非有限數字、重寫會被四捨五入的數字(極大的整數,或小到會塌縮成零的數字)、`-0`、同一個物件裡重複出現的鍵,或巢狀層數超過 1000 層——此時開關會鎖定,確保沒有任何值被悄悄改動或刪除。**OMP** 同樣不受旁邊編輯影響,但原因不同:它的 writer 只逐位元組修補自己的 `providers.opencodex` 範圍,檔案其餘部分從不會被重寫。至於其餘可以包含註解的格式(Hermes、OpenClaw、Kimi Code、Gajae Code、MiniMax Code、Raycast——以整份文件寫出的 YAML、JSON5 與 TOML),或當我們自己的條目被編輯過時,開關會鎖定,停用會拒絕執行,而不是猜測哪些編輯是你的。 ## 誠實的預期 @@ -98,9 +126,11 @@ ocx integration client enable --client mcode ocx mcode ``` -完成一次連接後,`ocx sync` 也會以目前的 context window 與 reasoning-effort 階梯更新 -OpenCodex 已擁有的 MCode 區塊。若區塊已刪除、遭外部修改、不安全或從未由 OpenCodex -建立,sync 會保持原檔不動;只有在你確定要重新連接時才再次執行 enable。 +完成一次連接後,`ocx sync` 與 `POST /api/sync` 會更新 OpenCodex 已擁有的 +MCode、Pi、Aside 與 Raycast 目錄。proxy 啟動也會更新已擁有的 Raycast 目錄。 +模型可見性、provider 或 preset 變更會更新 Pi、Aside 與 Raycast。若區塊已刪除、 +遭外部修改、不安全或由你手動移除,sync 會保持原檔不動;只有在你確定要重新 +連接時才再次執行 enable。 另一個 MiniMax 平台 CLI(`mmx`)不是檔案開關整合。其文字命令使用 MiniMax 的 Anthropic 相容端點,因此 OpenCodex 提供憑證隔離、僅限 loopback 的 launcher: diff --git a/docs-site/src/content/docs/zh-tw/guides/providers.md b/docs-site/src/content/docs/zh-tw/guides/providers.md index 96cf91ccfb..d26d093b7e 100644 --- a/docs-site/src/content/docs/zh-tw/guides/providers.md +++ b/docs-site/src/content/docs/zh-tw/guides/providers.md @@ -273,6 +273,7 @@ IDE/CLI,不透過 API;`minimax/minimax-m2.5` 是文件列出的 API 免費 | NVIDIA NIM | `https://integrate.api.nvidia.com/v1` | | Z.AI (GLM Coding) | `https://api.z.ai/api/coding/paas/v4` | | Zhipu AI (BigModel) | `https://open.bigmodel.cn/api/paas/v4` | +| [BigModel Coding Plan — Responses (靜態模型清單)](/guides/providers/#bigmodel-coding-plan-over-responses) | `https://open.bigmodel.cn/api/v1` | | Qwen Cloud | Token plan(預設):`https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1` · pay as you go:`https://dashscope.aliyuncs.com/compatible-mode/v1` · 或 Custom | | Tencent Cloud Coding Plan | `https://api.lkeap.cloud.tencent.com/coding/v3` | | SiliconFlow | `https://api.siliconflow.cn/v1` | @@ -418,7 +419,7 @@ quota probe 只會把 active key 傳送到 canonical A6API host,並拒絕 redi > **Tencent Cloud Coding Plan 使用限制:** Tencent 文件將此訂閱限定為互動式 coding tool。一般 API > automation、自訂 application backend 與非互動 batch 使用都被禁止,並可能造成 plan key 被停用。 -> **兩條 GLM 路徑:** `zai` 是 Z.AI 國際 Coding Plan 訂閱;`zhipu-bigmodel` 是智譜國內 BigModel +> **GLM 計費路徑:** `zai` 是 Z.AI 國際 Coding Plan 訂閱;`zhipu-bigmodel` 是智譜國內 BigModel > pay-as-you-go endpoint。兩者 host、key 與 billing 都不同;其中一邊發出的 key 無法在另一邊通過認證。 ### 多個 API 金鑰 diff --git a/docs-site/src/content/docs/zh-tw/reference/cli/agents.md b/docs-site/src/content/docs/zh-tw/reference/cli/agents.md index 497d2e4252..d04c099ebf 100644 --- a/docs-site/src/content/docs/zh-tw/reference/cli/agents.md +++ b/docs-site/src/content/docs/zh-tw/reference/cli/agents.md @@ -130,7 +130,7 @@ ocx claude desktop import [--apply] 驗證並匯入 JSON ## 客戶端設定匯出 -### `ocx export --client ` +### `ocx export --client ` 印出連接到執行中代理的客戶端設定。此指令會用所選客戶端的原生格式,序列化含有 base URL、模型清單,以及適用的環境變數參考或 loopback 佔位符的 `opencodex` provider 區塊。 @@ -138,7 +138,7 @@ ocx claude desktop import [--apply] 驗證並匯入 JSON | 旗標 | 動作 | | --- | --- | -| `--client ` | 必填。選擇客戶端設定格式。 | +| `--client ` | 必填。選擇客戶端設定格式。 | | `--json` | 僅在 stdout 印出設定 JSON,使重導向能擷取逐位元組輸出。所有診斷訊息(含 `--out` 寫入提示)皆送至 stderr。 | | `--out ` | 將設定寫入 ``。拒絕覆寫既有檔案。 | | `--force` | 允許 `--out` 覆寫既有檔案。 | @@ -165,6 +165,9 @@ ocx export --client opencode --out ~/opencodex-opencode.json | `mcode` | `~/.minimax/config.yaml` (設定後 `MINIMAX_DATA_DIR` 優先,其次為舊的 `MAVIS_DATA_DIR`;相對路徑會被拒絕) | `mcode-config.yaml` | 無——loopback 佔位符 | | `zcode` | `~/.zcode/v2/config.json` (設定後 `ZCODE_DATA_DIR` 優先;相對路徑會被拒絕) | `config.json` | 無——loopback 佔位符 | | `prime` | `~/.prime/agent/models.json` (設定後 `PRIME_AGENT_CODING_AGENT_DIR` 優先;相對路徑會被拒絕) | `prime-models.json` | 無——loopback 佔位符 | +| `raycast` | `~/.config/raycast/ai/providers.yaml`(macOS 與 Windows 相同;Raycast 不遵循 `XDG_CONFIG_HOME`) | `raycast-providers.yaml` | 無——僅限 loopback,不會寫入 `api_keys` 項目 | + +Raycast 匯出是一份獨立的 `providers.yaml` 文件,在 `providers` 序列中只有一個 `id: opencodex` 元素:`name: OpenCodex`、proxy 的 `/v1` base URL,以及每個路由模型及其 `abilities`(`tools` 與 `system_message` 一律支援,`vision` 依目錄的輸入模態而定,`reasoning_effort` 在模型有 effort 階梯時設定,`temperature` 對推理模型關閉)。Custom Providers 是 Raycast Pro 功能,且 Raycast 會監看該檔案,因此儲存後的變更不需重新啟動即可生效。格式說明見 [manual.raycast.com/ai/custom-providers](https://manual.raycast.com/ai/custom-providers)。不會寫入任何 `api_keys` 項目,所以此匯出僅限 loopback,非 loopback 的 bind 會被拒絕。 opencode 會插值 `{env:OPENCODEX_OPENCODE_API_KEY}`。Pi 與 OMP 的匯出不需要環境變數, 而是帶有字面值 `opencodex-loopback`。DSH 匯出需要 DSH 0.1.0-rc.6 或更新版本,且只擁有 diff --git a/docs-site/src/content/docs/zh-tw/reference/cli/providers-accounts.md b/docs-site/src/content/docs/zh-tw/reference/cli/providers-accounts.md index c50a6d54ae..fbf1ff186c 100644 --- a/docs-site/src/content/docs/zh-tw/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/zh-tw/reference/cli/providers-accounts.md @@ -13,7 +13,7 @@ description: 供應商設定、憑證、配額與模型目錄指令。 | 子指令 | 支援的旗標 | 動作 | | --- | --- | --- | -| `list` | `--json` | 列出已設定的供應商與剩餘的 registry 項目。 | +| `list` | `--json`, `--jsonl` | 列出已設定的供應商與剩餘的 registry 項目。 `--jsonl` 為每個已設定的供應商輸出一行 JSON 物件。 | | `add ` | `--adapter `, `--base-url `, `--api-key `, `--default-model `, `--set-default`, `--force`, `--json`, `--sync` | 新增 registry/自訂供應商。`--force` 覆寫;`--sync` 在人類輸出模式下重新整理執行中的代理。 | | `edit ` | 供應商欄位旗標, `--json` | 編輯已驗證的即時供應商欄位而不替換金鑰池。 | | `test ` | `--json` | 探測真實上游模型端點。 | @@ -27,6 +27,7 @@ description: 供應商設定、憑證、配額與模型目錄指令。 ```bash ocx provider list --json +ocx provider list --jsonl ocx provider test ark ocx provider add anthropic --api-key sk-ant-... --set-default --sync ocx provider add local-dev --adapter openai-chat --base-url http://localhost:11434/v1 @@ -35,6 +36,8 @@ ocx models --provider anthropic --json ocx models live --provider ark --json ``` +`--jsonl` 僅輸出已設定的供應商,每行一個 JSON 物件。每個物件的欄位與 `--json` 輸出中 `configured` 陣列的元素相同,不包含 `registryCount` 摘要。指令碼可以逐行處理這些物件。`--json` 與 `--jsonl` 不能同時使用。 + ## 認證 ### `ocx login ` diff --git a/gui/public/provider-icons/README.md b/gui/public/provider-icons/README.md index 1fc7c57857..f5e64b568b 100644 --- a/gui/public/provider-icons/README.md +++ b/gui/public/provider-icons/README.md @@ -47,6 +47,16 @@ Export-client marks (used by the API tab's connect rows, not the provider list): on the web (`aside.com/favicon.svg` is a 404), so the shipping application is the first-party source. +- `raycast.svg` — fetched 2026-09-04 from + `https://fz1sd71lwhbqy6sh.public.blob.vercel-storage.com/press/images/logo/raycast-logo-dark.svg`, + the "Logo (dark)" download Raycast's own press kit (`raycast.com/press`) links. + `raycast.com/favicon.svg` and the other conventional paths are 404s, so the + press kit is the first-party source. Path data and the `#FF6363` fill are + verbatim; the fixed `width`/`height` are dropped in favour of the `viewBox`, + and the `` wrapper — a full-frame white `` the export tool left + behind — is removed because the path never leaves the frame and the rect + would read as a second ink to the mark tooling here. + - `minimax.svg` — fetched 2026-08-31 from `https://raw.githubusercontent.com/MiniMax-AI/MiniMax-01/main/figures/minimax.svg`, MiniMax's own symbol as committed in their own model repository. The API-docs @@ -135,6 +145,9 @@ Decisions that are not obvious from looking at the file: - `aside.svg` **is masked.** It already paints with `currentColor`, so it would follow the theme either way; masking keeps it consistent with the other silhouettes rather than depending on inherited color. +- `raycast.svg` **is not masked.** One ink, but that ink is #FF6363 — Raycast + red, the same case as `openai.svg` and `deepseek-harness.svg`. Legible on both + surfaces as an image. Both directions are enforced in `gui/tests/integration-marks.test.ts`, including a luminance check that fails any single-ink near-neutral mark left as an image. That diff --git a/gui/public/provider-icons/raycast.svg b/gui/public/provider-icons/raycast.svg new file mode 100644 index 0000000000..b6a40c7ba2 --- /dev/null +++ b/gui/public/provider-icons/raycast.svg @@ -0,0 +1,3 @@ + + + diff --git a/gui/src/app-routing.ts b/gui/src/app-routing.ts index bab41b1eee..c5971ffb6b 100644 --- a/gui/src/app-routing.ts +++ b/gui/src/app-routing.ts @@ -100,6 +100,7 @@ export const INTEGRATION_TAB_HASHES = [ "integrations/zcode", "integrations/prime", "integrations/aside", + "integrations/raycast", ] as const; export function hashBelongsToPage(rawHash: string, page: Page): boolean { diff --git a/gui/src/components/ModelDisplayNameDialog.tsx b/gui/src/components/ModelDisplayNameDialog.tsx new file mode 100644 index 0000000000..2a57ff8279 --- /dev/null +++ b/gui/src/components/ModelDisplayNameDialog.tsx @@ -0,0 +1,175 @@ +import { useEffect, useId, useRef, useState } from "react"; +import { useT, type TKey } from "../i18n/shared"; +import { + modelDisplayNameValidationKey, + type ModelRow, +} from "../pages/models-shared"; + +interface ModelDisplayNameDialogProps { + model: ModelRow; + saving: boolean; + requestError: string | null; + currentNamePending?: boolean; + onRetry?: () => void; + onEdit?: () => void; + onSave: (displayName: string) => void; + onReset: () => void; + onClose: () => void; +} + +const SOURCE_LABEL_KEYS: Record, TKey> = { + operator: "models.displayNameSourceOperator", + provider: "models.displayNameSourceProvider", + fallback: "models.displayNameSourceFallback", +}; + +export default function ModelDisplayNameDialog({ + model, + saving, + requestError, + currentNamePending = false, + onRetry, + onEdit, + onSave, + onReset, + onClose, +}: ModelDisplayNameDialogProps) { + const t = useT(); + const dialogRef = useRef(null); + const inputRef = useRef(null); + const wasSavingRef = useRef(saving); + const titleId = useId(); + const helpId = useId(); + const errorId = useId(); + const [draftSnapshot, setDraftSnapshot] = useState(model); + const [draft, setDraft] = useState(model.displayNameOverride ?? ""); + const [validationKey, setValidationKey] = useState(null); + + useEffect(() => { + const dialog = dialogRef.current; + if (dialog && !dialog.open) dialog.showModal(); + inputRef.current?.focus(); + return () => { if (dialog?.open) dialog.close(); }; + }, []); + + useEffect(() => { + const saveFailed = wasSavingRef.current && !saving && Boolean(requestError); + wasSavingRef.current = saving; + if (saveFailed) inputRef.current?.focus(); + }, [requestError, saving]); + + // Parent replaces this snapshot only after a confirmed mutation, not typing or polling. + // Adjust before committing children, preserving the mounted dialog and its focus refs. + if (draftSnapshot !== model) { + setDraftSnapshot(model); + setDraft(model.displayNameOverride ?? ""); + setValidationKey(null); + } + + const validationError = validationKey ? t(validationKey) : null; + const visibleError = validationError ?? requestError; + const sourceKey = model.displayNameSource + ? SOURCE_LABEL_KEYS[model.displayNameSource] + : "models.displayNameSourceFallback"; + + const requestClose = () => { + if (!saving) onClose(); + }; + + return ( + { + event.preventDefault(); + requestClose(); + }} + > + + + +
+ {t("models.displayNameModelId")} + {model.namespaced} +
+ +
+ {t("models.displayNameCurrent")} + {currentNamePending ? t("models.displayNameCurrentUnavailable") : model.displayName ?? model.namespaced} + {!currentNamePending && {t(sourceKey)}} +
+ + + { + onEdit?.(); + setDraft(event.target.value); + setValidationKey(null); + }} + /> +

+ {t("models.displayNameHelp", { model: model.namespaced })} +

+ {visibleError && ( + + )} + +
+ + + +
+ +
+ ); +} diff --git a/gui/src/components/apikeys-workspace/client-config-clients.ts b/gui/src/components/apikeys-workspace/client-config-clients.ts index c7c42d3e56..afd4484551 100644 --- a/gui/src/components/apikeys-workspace/client-config-clients.ts +++ b/gui/src/components/apikeys-workspace/client-config-clients.ts @@ -8,7 +8,7 @@ * with EXPORT_CLIENT_IDS by hand; adding a client server-side renders no row * until this tuple changes. */ -export const CLIENTS = ["opencode", "pi", "omp", "hermes", "openclaw", "kimi", "gajae", "dsh", "mcode", "zcode", "prime", "aside"] as const; +export const CLIENTS = ["opencode", "pi", "omp", "hermes", "openclaw", "kimi", "gajae", "dsh", "mcode", "zcode", "prime", "aside", "raycast"] as const; export type ExportClientId = (typeof CLIENTS)[number]; export const CLIENT_LABEL_KEYS = { @@ -24,6 +24,7 @@ export const CLIENT_LABEL_KEYS = { zcode: "api.clientConfig.clientZcode", prime: "api.clientConfig.clientPrime", aside: "api.clientConfig.clientAside", + raycast: "api.clientConfig.clientRaycast", } as const; /** @@ -70,6 +71,8 @@ export const CLIENT_MARKS: Partial> = { zcode: "/provider-icons/zcode.svg", prime: "/provider-icons/prime-agent.svg", aside: "/provider-icons/aside.svg", + // Raycast red (#FF6363) is the brand, so like `dsh` it stays an image. + raycast: "/provider-icons/raycast.svg", }; /** diff --git a/gui/src/components/integration-marks.ts b/gui/src/components/integration-marks.ts index e8786224ec..eca38510bd 100644 --- a/gui/src/components/integration-marks.ts +++ b/gui/src/components/integration-marks.ts @@ -57,6 +57,7 @@ export const INTEGRATION_MARKS: Record = { zcode: CLIENT_MARKS.zcode ?? null, prime: CLIENT_MARKS.prime ?? null, aside: CLIENT_MARKS.aside ?? null, + raycast: CLIENT_MARKS.raycast ?? null, }; /** diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 9086c9bf42..5faab4b356 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -1093,6 +1093,7 @@ export const de: Record = { "integrations.tab.zcode": "ZCode", "integrations.tab.prime": "Prime Agent", "integrations.tab.aside": "Aside", + "integrations.tab.raycast": "Raycast", "integrations.aside.profilesTitle": "Aside-Profile", "integrations.aside.profilesHint": "Wähle, welche Profile die ausgewählten Modelle erhalten. Das aktive Aside-Profil bleibt unverändert.", "integrations.aside.all": "Alle Profile synchronisieren", @@ -1252,6 +1253,10 @@ export const de: Record = { "integrations.semantics.zcode": "Verwaltet nur provider.opencodex in ~/.zcode/v2/config.json. Z.ai-Anmeldung und andere Provider bleiben unverändert. ZCode nach Änderungen neu starten.", "integrations.semantics.prime": "Verwaltet nur providers.opencodex in der models.json von Prime Agent — ~/.prime/agent, sofern PRIME_AGENT_CODING_AGENT_DIR sie nicht umleitet. Andere Provider und Modell-Overrides bleiben unverändert. Gilt für neue Sitzungen.", "integrations.semantics.aside": "Verwaltet nur providers.opencodex in der ~/.aside/u//models.json dieses Profils. Andere Provider bleiben unverändert. Beende Aside nach dem Anwenden vollständig und öffne es erneut.", + "integrations.semantics.raycast": "Fügt einen OpenCodex-Provider-Eintrag in die providers.yaml von Raycast ein, damit jedes geroutete Modell in der Modellauswahl von Raycast AI erscheint. Raycast Pro erforderlich.", + "integrations.raycast.proRequired": "Custom Providers ist eine Funktion von Raycast Pro. Die Datei wird geschrieben, aber Raycast ignoriert sie, bis ein Pro-Abonnement aktiv ist.", + "integrations.raycast.planUnknown": "Es konnte nicht festgestellt werden, ob Raycast Pro aktiv ist; Custom Providers erfordert Raycast Pro.", + "integrations.raycast.revealConfig": "Öffnen Sie Raycast → Einstellungen → AI und klicken Sie einmal auf „Reveal Providers Config“, damit der Providers-Ordner existiert.", "codexAuth.mainAccount": "Hauptkonto", "codexAuth.logLabel": "Log-Kennung", "codexAuth.codexApp": "Codex App", @@ -1580,6 +1585,7 @@ export const de: Record = { "api.clientConfig.clientZcode": "ZCode", "api.clientConfig.clientPrime": "Prime Agent", "api.clientConfig.clientAside": "Aside", + "api.clientConfig.clientRaycast": "Raycast", "api.clientConfig.copy": "Konfiguration kopieren", "api.clientConfig.download": "Herunterladen", "api.clientConfig.loading": "Client-Konfiguration wird erstellt…", @@ -2548,4 +2554,27 @@ export const de: Record = { "integrations.cursor.colReasoning": "Reasoning-Aufwand", "integrations.cursor.colContext": "Kontext", "integrations.cursor.guide": "Anleitung zu Cursor Private Inference öffnen", + "models.displayNameSavedRefreshFailed": "Die Änderung wurde gespeichert, aber die Modellliste konnte nicht aktualisiert werden. Versuchen Sie es erneut.", + "models.displayNameOutcomeUnknown": "Die Anfrage wurde nicht abgeschlossen. Die Änderung wurde möglicherweise gespeichert. Prüfen Sie den aktuellen Namen durch erneutes Versuchen, bevor Sie ihn weiter ändern.", + "models.displayNameCurrentUnavailable": "Aktueller Name erst nach Aktualisierung verfügbar", + "models.displayNameReloaded": "Modellliste aktualisiert", + "models.displayNameAction": "Name", + "models.displayNameActionLabel": "Anzeigenamen für {model} bearbeiten", + "models.displayNameTitle": "Anzeigename", + "models.displayNameModelId": "Modell-ID", + "models.displayNameCurrent": "Aktueller Name", + "models.displayNameSourceOperator": "Ihr Name", + "models.displayNameSourceProvider": "Anbietername", + "models.displayNameSourceFallback": "Modell-ID als Ersatz", + "models.displayNameField": "Anzeigename", + "models.displayNamePlaceholder": "z. B. Grok 4.6", + "models.displayNameHelp": "Ändert nur die Anzeige. Das Routing bleibt {model}.", + "models.displayNameReset": "Name zurücksetzen", + "models.displayNameSaved": "Anzeigename gespeichert", + "models.displayNameResetDone": "Anzeigename zurückgesetzt", + "models.displayNameSaveFailed": "Anzeigename konnte nicht gespeichert werden", + "models.displayNameRequired": "Geben Sie einen Anzeigenamen ein oder verwenden Sie Name zurücksetzen.", + "models.displayNameTooLong": "Der Anzeigename darf höchstens 128 Zeichen lang sein.", + "models.displayNameNoSlash": "Der Anzeigename darf kein / enthalten.", + "models.displayNameNoControl": "Der Anzeigename darf keine Steuerzeichen enthalten.", }; diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index 0d2f1d05d4..c71208942f 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -1600,6 +1600,7 @@ export const en = { "integrations.tab.zcode": "ZCode", "integrations.tab.prime": "Prime Agent", "integrations.tab.aside": "Aside", + "integrations.tab.raycast": "Raycast", "integrations.aside.profilesTitle": "Aside profiles", "integrations.aside.profilesHint": "Choose which profiles receive the selected models. Aside’s active profile stays unchanged.", "integrations.aside.all": "Sync all profiles", @@ -1799,6 +1800,10 @@ export const en = { "integrations.semantics.zcode": "Manages only provider.opencodex in ~/.zcode/v2/config.json. Your Z.ai login and other providers stay unchanged. Restart ZCode after changes.", "integrations.semantics.prime": "Manages only providers.opencodex in Prime Agent's models.json — ~/.prime/agent unless PRIME_AGENT_CODING_AGENT_DIR redirects it. Your other providers and model overrides stay unchanged. Applies to new sessions.", "integrations.semantics.aside": "Manages only providers.opencodex in this profile’s ~/.aside/u//models.json. Your other providers stay unchanged. Fully quit and reopen Aside after applying.", + "integrations.semantics.raycast": "Adds an OpenCodex provider entry to Raycast's providers.yaml so every routed model appears in the Raycast AI model picker. Raycast Pro required.", + "integrations.raycast.proRequired": "Custom Providers is a Raycast Pro feature. The file will be written, but Raycast ignores it until a Pro subscription is active.", + "integrations.raycast.planUnknown": "Could not determine whether Raycast Pro is active; Custom Providers requires Raycast Pro.", + "integrations.raycast.revealConfig": "Open Raycast → Settings → AI and click Reveal Providers Config once so the providers folder exists.", "codexAuth.mainAccount": "Main Account", "codexAuth.logLabel": "Log label", "codexAuth.codexApp": "Codex App", @@ -2138,6 +2143,7 @@ export const en = { "api.clientConfig.clientZcode": "ZCode", "api.clientConfig.clientPrime": "Prime Agent", "api.clientConfig.clientAside": "Aside", + "api.clientConfig.clientRaycast": "Raycast", "api.clientConfig.copy": "Copy config", "api.clientConfig.download": "Download", "api.clientConfig.loading": "Building client config…", @@ -2582,6 +2588,29 @@ export const en = { "usage.scope.machine": "This machine", "usage.scope.hub": "Hub-wide", "usage.hubOffline": "Hub usage is unavailable. Local usage was not substituted.", + "models.displayNameSavedRefreshFailed": "The change was saved, but the model list could not be refreshed. Retry to refresh it.", + "models.displayNameOutcomeUnknown": "The request did not finish. The change may have been saved. Retry to check the current name before making another change.", + "models.displayNameCurrentUnavailable": "Current name unavailable until refresh", + "models.displayNameReloaded": "Model list refreshed", + "models.displayNameAction": "Name", + "models.displayNameActionLabel": "Edit friendly name for {model}", + "models.displayNameTitle": "Friendly name", + "models.displayNameModelId": "Model ID", + "models.displayNameCurrent": "Current name", + "models.displayNameSourceOperator": "Your name", + "models.displayNameSourceProvider": "Provider name", + "models.displayNameSourceFallback": "Model ID fallback", + "models.displayNameField": "Friendly name", + "models.displayNamePlaceholder": "e.g. Grok 4.6", + "models.displayNameHelp": "Changes presentation only. Routing remains {model}.", + "models.displayNameReset": "Reset name", + "models.displayNameSaved": "Display name saved", + "models.displayNameResetDone": "Display name reset", + "models.displayNameSaveFailed": "Failed to save display name", + "models.displayNameRequired": "Enter a friendly name, or use Reset name.", + "models.displayNameTooLong": "Friendly name must be 128 characters or fewer.", + "models.displayNameNoSlash": "Friendly name cannot contain /.", + "models.displayNameNoControl": "Friendly name cannot contain control characters.", } as const; export type TKey = keyof typeof en; diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index b6eb03f0b0..e1b3519ef1 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -1572,6 +1572,7 @@ export const fr: Record = { "integrations.tab.zcode": "ZCode", "integrations.tab.prime": "Prime Agent", "integrations.tab.aside": "Aside", + "integrations.tab.raycast": "Raycast", "integrations.aside.profilesTitle": "Profils Aside", "integrations.aside.profilesHint": "Choisissez les profils qui recevront les modèles sélectionnés. Le profil actif dans Aside reste inchangé.", "integrations.aside.all": "Synchroniser tous les profils", @@ -1731,6 +1732,10 @@ export const fr: Record = { "integrations.semantics.zcode": "Gère uniquement provider.opencodex dans ~/.zcode/v2/config.json. Votre connexion Z.ai et les autres fournisseurs restent inchangés. Redémarrez ZCode après toute modification.", "integrations.semantics.prime": "Gère uniquement providers.opencodex dans le models.json de Prime Agent — ~/.prime/agent, sauf si PRIME_AGENT_CODING_AGENT_DIR le redirige. Vos autres fournisseurs et surcharges de modèles restent inchangés. S'applique aux nouvelles sessions.", "integrations.semantics.aside": "Gère uniquement providers.opencodex dans le fichier ~/.aside/u//models.json de ce profil. Vos autres fournisseurs restent inchangés. Quittez complètement Aside et relancez-le après application.", + "integrations.semantics.raycast": "Ajoute une entrée de fournisseur OpenCodex dans le providers.yaml de Raycast afin que chaque modèle routé apparaisse dans le sélecteur de modèles de Raycast AI. Raycast Pro requis.", + "integrations.raycast.proRequired": "Custom Providers est une fonctionnalité Raycast Pro. Le fichier sera écrit, mais Raycast l'ignore tant qu'un abonnement Pro n'est pas actif.", + "integrations.raycast.planUnknown": "Impossible de déterminer si Raycast Pro est actif ; Custom Providers nécessite Raycast Pro.", + "integrations.raycast.revealConfig": "Ouvrez Raycast → Réglages → AI et cliquez une fois sur « Reveal Providers Config » pour que le dossier des fournisseurs existe.", "codexAuth.mainAccount": "Compte principal", "codexAuth.logLabel": "Libellé du journal", "codexAuth.codexApp": "Application Codex", @@ -2057,6 +2062,7 @@ export const fr: Record = { "api.clientConfig.clientZcode": "ZCode", "api.clientConfig.clientPrime": "Prime Agent", "api.clientConfig.clientAside": "Aside", + "api.clientConfig.clientRaycast": "Raycast", "api.clientConfig.copy": "Copier la configuration", "api.clientConfig.download": "Télécharger", "api.clientConfig.loading": "Génération de la configuration du client…", @@ -2535,4 +2541,27 @@ export const fr: Record = { "integrations.cursor.colReasoning": "Raisonnement", "integrations.cursor.colContext": "Contexte", "integrations.cursor.guide": "Ouvrir le guide de Cursor Private Inference", + "models.displayNameSavedRefreshFailed": "La modification a été enregistrée, mais la liste des modèles n’a pas pu être actualisée. Réessayez.", + "models.displayNameOutcomeUnknown": "La requête n’a pas abouti. La modification a peut-être été enregistrée. Réessayez pour vérifier le nom actuel avant toute autre modification.", + "models.displayNameCurrentUnavailable": "Nom actuel indisponible avant actualisation", + "models.displayNameReloaded": "Liste des modèles actualisée", + "models.displayNameAction": "Nom", + "models.displayNameActionLabel": "Modifier le nom d’affichage de {model}", + "models.displayNameTitle": "Nom d’affichage", + "models.displayNameModelId": "ID du modèle", + "models.displayNameCurrent": "Nom actuel", + "models.displayNameSourceOperator": "Votre nom d’affichage", + "models.displayNameSourceProvider": "Nom du fournisseur", + "models.displayNameSourceFallback": "ID du modèle par défaut", + "models.displayNameField": "Nom d’affichage", + "models.displayNamePlaceholder": "p. ex. Grok 4.6", + "models.displayNameHelp": "Modifie uniquement l’affichage. Le routage reste {model}.", + "models.displayNameReset": "Réinitialiser le nom", + "models.displayNameSaved": "Nom d’affichage enregistré", + "models.displayNameResetDone": "Nom d’affichage réinitialisé", + "models.displayNameSaveFailed": "Impossible d’enregistrer le nom d’affichage", + "models.displayNameRequired": "Saisissez un nom d’affichage ou utilisez Réinitialiser le nom.", + "models.displayNameTooLong": "Le nom d’affichage doit contenir au maximum 128 caractères.", + "models.displayNameNoSlash": "Le nom d’affichage ne peut pas contenir /.", + "models.displayNameNoControl": "Le nom d’affichage ne peut pas contenir de caractères de contrôle.", }; diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 4b16912324..cf94831583 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -1513,6 +1513,7 @@ export const ja: Record = { "integrations.tab.zcode": "ZCode", "integrations.tab.prime": "Prime Agent", "integrations.tab.aside": "Aside", + "integrations.tab.raycast": "Raycast", "integrations.aside.profilesTitle": "Asideのプロファイル", "integrations.aside.profilesHint": "選択したモデルを同期するプロファイルを選んでください。Asideで使用中のプロファイルは変わりません。", "integrations.aside.all": "すべてのプロファイルを同期", @@ -1672,6 +1673,10 @@ export const ja: Record = { "integrations.semantics.zcode": "~/.zcode/v2/config.json の provider.opencodex のみを管理します。Z.ai ログインと他のプロバイダーは変更しません。変更後は ZCode を再起動してください。", "integrations.semantics.prime": "Prime Agent の models.json 内の providers.opencodex のみを管理します。場所は ~/.prime/agent ですが、PRIME_AGENT_CODING_AGENT_DIR が設定されている場合はそちらが優先されます。他のプロバイダーとモデルオーバーライドは変更しません。新しいセッションから適用されます。", "integrations.semantics.aside": "このプロファイルの ~/.aside/u//models.json 内の providers.opencodex のみを管理します。他のプロバイダーは変更しません。適用後は Aside を完全に終了してから開き直してください。", + "integrations.semantics.raycast": "Raycast の providers.yaml に OpenCodex のプロバイダーエントリを追加し、ルーティングされたすべてのモデルを Raycast AI のモデル選択に表示します。Raycast Pro が必要です。", + "integrations.raycast.proRequired": "Custom Providers は Raycast Pro の機能です。ファイルは書き込まれますが、Pro サブスクリプションが有効になるまで Raycast はこれを無視します。", + "integrations.raycast.planUnknown": "Raycast Pro が有効かどうか確認できませんでした。Custom Providers には Raycast Pro が必要です。", + "integrations.raycast.revealConfig": "Raycast → 設定 → AI を開き、「Reveal Providers Config」を一度クリックして providers フォルダを作成してください。", "codexAuth.mainAccount": "メインアカウント", "codexAuth.logLabel": "ログラベル", "codexAuth.codexApp": "Codex App", @@ -2005,6 +2010,7 @@ export const ja: Record = { "api.clientConfig.clientZcode": "ZCode", "api.clientConfig.clientPrime": "Prime Agent", "api.clientConfig.clientAside": "Aside", + "api.clientConfig.clientRaycast": "Raycast", "api.clientConfig.copy": "設定をコピー", "api.clientConfig.download": "ダウンロード", "api.clientConfig.loading": "クライアント設定を生成中…", @@ -2569,4 +2575,27 @@ export const ja: Record = { "integrations.cursor.colReasoning": "推論", "integrations.cursor.colContext": "コンテキスト", "integrations.cursor.guide": "Cursor Private Inference のガイドを開く", + "models.displayNameSavedRefreshFailed": "変更は保存されましたが、モデル一覧を更新できませんでした。再試行してください。", + "models.displayNameOutcomeUnknown": "リクエストが完了しませんでした。変更が保存されている可能性があります。再度変更する前に再試行して現在の名前を確認してください。", + "models.displayNameCurrentUnavailable": "更新するまで現在の名前を確認できません", + "models.displayNameReloaded": "モデル一覧を更新しました", + "models.displayNameAction": "名前", + "models.displayNameActionLabel": "{model} の表示名を編集", + "models.displayNameTitle": "表示名", + "models.displayNameModelId": "モデル ID", + "models.displayNameCurrent": "現在の名前", + "models.displayNameSourceOperator": "設定した名前", + "models.displayNameSourceProvider": "プロバイダー名", + "models.displayNameSourceFallback": "モデル ID の既定値", + "models.displayNameField": "表示名", + "models.displayNamePlaceholder": "例: Grok 4.6", + "models.displayNameHelp": "表示だけを変更します。ルーティングは {model} のままです。", + "models.displayNameReset": "名前をリセット", + "models.displayNameSaved": "表示名を保存しました", + "models.displayNameResetDone": "表示名をリセットしました", + "models.displayNameSaveFailed": "表示名を保存できませんでした", + "models.displayNameRequired": "表示名を入力するか、名前をリセットしてください。", + "models.displayNameTooLong": "表示名は 128 文字以内にしてください。", + "models.displayNameNoSlash": "表示名に / は使用できません。", + "models.displayNameNoControl": "表示名に制御文字は使用できません。", }; diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index a87bf608e5..c1959482b7 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -1117,6 +1117,7 @@ export const ko: Record = { "integrations.tab.zcode": "ZCode", "integrations.tab.prime": "Prime Agent", "integrations.tab.aside": "Aside", + "integrations.tab.raycast": "Raycast", "integrations.aside.profilesTitle": "Aside 프로필", "integrations.aside.profilesHint": "선택한 모델을 동기화할 프로필을 고르세요. Aside에서 사용 중인 프로필은 바뀌지 않습니다.", "integrations.aside.all": "모든 프로필 동기화", @@ -1276,6 +1277,10 @@ export const ko: Record = { "integrations.semantics.zcode": "~/.zcode/v2/config.json의 provider.opencodex만 관리하며 Z.ai 로그인과 다른 프로바이더는 변경하지 않습니다. 변경 후 ZCode를 재시작하세요.", "integrations.semantics.prime": "Prime Agent의 models.json에서 providers.opencodex만 관리합니다. 위치는 ~/.prime/agent이며 PRIME_AGENT_CODING_AGENT_DIR가 설정되면 그쪽이 우선합니다. 다른 프로바이더와 모델 오버라이드는 변경하지 않습니다. 새 세션부터 적용됩니다.", "integrations.semantics.aside": "이 프로필의 ~/.aside/u//models.json에서 providers.opencodex만 관리합니다. 다른 프로바이더는 그대로 유지됩니다. 적용 후 Aside를 완전히 종료하고 다시 여세요.", + "integrations.semantics.raycast": "Raycast의 providers.yaml에 OpenCodex 프로바이더 항목을 추가해 라우팅된 모든 모델이 Raycast AI 모델 선택기에 표시되도록 합니다. Raycast Pro가 필요합니다.", + "integrations.raycast.proRequired": "Custom Providers는 Raycast Pro 기능입니다. 파일은 기록되지만 Pro 구독이 활성화될 때까지 Raycast는 이를 무시합니다.", + "integrations.raycast.planUnknown": "Raycast Pro 활성 여부를 확인할 수 없습니다. Custom Providers에는 Raycast Pro가 필요합니다.", + "integrations.raycast.revealConfig": "Raycast → 설정 → AI를 열고 「Reveal Providers Config」를 한 번 클릭해 providers 폴더를 만드세요.", "codexAuth.mainAccount": "메인 계정", "codexAuth.logLabel": "로그 라벨", "codexAuth.codexApp": "Codex App", @@ -1607,6 +1612,7 @@ export const ko: Record = { "api.clientConfig.clientZcode": "ZCode", "api.clientConfig.clientPrime": "Prime Agent", "api.clientConfig.clientAside": "Aside", + "api.clientConfig.clientRaycast": "Raycast", "api.clientConfig.copy": "설정 복사", "api.clientConfig.download": "다운로드", "api.clientConfig.loading": "클라이언트 설정 생성 중…", @@ -2570,4 +2576,27 @@ export const ko: Record = { "integrations.cursor.colReasoning": "추론", "integrations.cursor.colContext": "컨텍스트", "integrations.cursor.guide": "Cursor Private Inference 가이드 열기", + "models.displayNameSavedRefreshFailed": "변경 사항은 저장되었지만 모델 목록을 새로 고치지 못했습니다. 다시 시도해 주세요.", + "models.displayNameOutcomeUnknown": "요청이 완료되지 않았습니다. 변경 사항이 저장되었을 수 있습니다. 다시 변경하기 전에 재시도하여 현재 이름을 확인하세요.", + "models.displayNameCurrentUnavailable": "새로 고침 전까지 현재 이름을 확인할 수 없음", + "models.displayNameReloaded": "모델 목록을 새로 고쳤습니다", + "models.displayNameAction": "이름", + "models.displayNameActionLabel": "{model}의 표시 이름 편집", + "models.displayNameTitle": "표시 이름", + "models.displayNameModelId": "모델 ID", + "models.displayNameCurrent": "현재 이름", + "models.displayNameSourceOperator": "운영자 지정 이름", + "models.displayNameSourceProvider": "프로바이더 제공 이름", + "models.displayNameSourceFallback": "모델 ID 기본값", + "models.displayNameField": "표시 이름", + "models.displayNamePlaceholder": "예: Grok 4.6", + "models.displayNameHelp": "표시 방식만 변경합니다. 라우팅은 {model}로 유지됩니다.", + "models.displayNameReset": "이름 초기화", + "models.displayNameSaved": "표시 이름이 저장되었습니다", + "models.displayNameResetDone": "표시 이름이 초기화되었습니다", + "models.displayNameSaveFailed": "표시 이름을 저장하지 못했습니다", + "models.displayNameRequired": "표시 이름을 입력하거나 이름 초기화를 사용하세요.", + "models.displayNameTooLong": "표시 이름은 128자 이하여야 합니다.", + "models.displayNameNoSlash": "표시 이름에 /를 사용할 수 없습니다.", + "models.displayNameNoControl": "표시 이름에 제어 문자를 사용할 수 없습니다.", }; diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index 70eb364002..0109f5ebdc 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -1583,6 +1583,7 @@ export const ru: Record = { "integrations.tab.zcode": "ZCode", "integrations.tab.prime": "Prime Agent", "integrations.tab.aside": "Aside", + "integrations.tab.raycast": "Raycast", "integrations.aside.profilesTitle": "Профили Aside", "integrations.aside.profilesHint": "Выберите профили, в которые будут добавлены выбранные модели. Активный профиль Aside не изменится.", "integrations.aside.all": "Синхронизировать все профили", @@ -1742,6 +1743,10 @@ export const ru: Record = { "integrations.semantics.zcode": "Управляет только provider.opencodex в ~/.zcode/v2/config.json. Вход Z.ai и другие провайдеры не меняются. Перезапустите ZCode после изменений.", "integrations.semantics.prime": "Управляет только providers.opencodex в models.json Prime Agent — ~/.prime/agent, если PRIME_AGENT_CODING_AGENT_DIR не переопределяет путь. Другие провайдеры и переопределения моделей не меняются. Применяется к новым сессиям.", "integrations.semantics.aside": "Управляет только providers.opencodex в файле ~/.aside/u//models.json этого профиля. Другие провайдеры остаются без изменений. После применения полностью закройте и снова откройте Aside.", + "integrations.semantics.raycast": "Добавляет запись провайдера OpenCodex в providers.yaml Raycast, чтобы каждая маршрутизируемая модель появилась в выборе моделей Raycast AI. Требуется Raycast Pro.", + "integrations.raycast.proRequired": "Custom Providers — функция Raycast Pro. Файл будет записан, но Raycast игнорирует его, пока не активна подписка Pro.", + "integrations.raycast.planUnknown": "Не удалось определить, активен ли Raycast Pro; для Custom Providers требуется Raycast Pro.", + "integrations.raycast.revealConfig": "Откройте Raycast → Настройки → AI и один раз нажмите «Reveal Providers Config», чтобы папка провайдеров появилась.", "codexAuth.mainAccount": "Основной аккаунт", "codexAuth.logLabel": "Метка журнала", "codexAuth.codexApp": "Codex App", @@ -2075,6 +2080,7 @@ export const ru: Record = { "api.clientConfig.clientZcode": "ZCode", "api.clientConfig.clientPrime": "Prime Agent", "api.clientConfig.clientAside": "Aside", + "api.clientConfig.clientRaycast": "Raycast", "api.clientConfig.copy": "Копировать конфигурацию", "api.clientConfig.download": "Скачать", "api.clientConfig.loading": "Формируется конфигурация клиента…", @@ -2571,4 +2577,27 @@ export const ru: Record = { "integrations.cursor.colReasoning": "Рассуждения", "integrations.cursor.colContext": "Контекст", "integrations.cursor.guide": "Открыть руководство по Cursor Private Inference", + "models.displayNameSavedRefreshFailed": "Изменение сохранено, но список моделей не удалось обновить. Повторите попытку.", + "models.displayNameOutcomeUnknown": "Запрос не завершён. Изменение могло сохраниться. Повторите попытку, чтобы проверить текущее имя перед следующим изменением.", + "models.displayNameCurrentUnavailable": "Текущее имя недоступно до обновления", + "models.displayNameReloaded": "Список моделей обновлён", + "models.displayNameAction": "Имя", + "models.displayNameActionLabel": "Изменить понятное имя для {model}", + "models.displayNameTitle": "Понятное имя", + "models.displayNameModelId": "ID модели", + "models.displayNameCurrent": "Текущее имя", + "models.displayNameSourceOperator": "Ваше имя", + "models.displayNameSourceProvider": "Имя провайдера", + "models.displayNameSourceFallback": "ID модели по умолчанию", + "models.displayNameField": "Понятное имя", + "models.displayNamePlaceholder": "например, Grok 4.6", + "models.displayNameHelp": "Меняет только отображение. Маршрут остаётся {model}.", + "models.displayNameReset": "Сбросить имя", + "models.displayNameSaved": "Понятное имя сохранено", + "models.displayNameResetDone": "Понятное имя сброшено", + "models.displayNameSaveFailed": "Не удалось сохранить понятное имя", + "models.displayNameRequired": "Введите понятное имя или используйте Сбросить имя.", + "models.displayNameTooLong": "Понятное имя должно содержать не более 128 символов.", + "models.displayNameNoSlash": "Понятное имя не может содержать /.", + "models.displayNameNoControl": "Понятное имя не может содержать управляющие символы.", }; diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index ca233f452e..fa8b8e9c25 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -1590,6 +1590,7 @@ export const tr: Record = { "integrations.tab.zcode": "ZCode", "integrations.tab.prime": "Prime Agent", "integrations.tab.aside": "Aside", + "integrations.tab.raycast": "Raycast", "integrations.aside.profilesTitle": "Aside profilleri", "integrations.aside.profilesHint": "Seçili modellerin hangi profillere aktarılacağını seçin. Aside’ın etkin profili değişmez.", "integrations.aside.all": "Tüm profilleri eşitle", @@ -1748,6 +1749,10 @@ export const tr: Record = { "integrations.semantics.zcode": "Yalnızca ~/.zcode/v2/config.json içindeki provider.opencodex bölümünü yönetir. Z.ai oturumu ve diğer sağlayıcılar değişmez. Değişikliklerden sonra ZCode'u yeniden başlatın.", "integrations.semantics.prime": "Yalnızca Prime Agent'ın models.json dosyasındaki providers.opencodex bölümünü yönetir — PRIME_AGENT_CODING_AGENT_DIR ayarlı değilse ~/.prime/agent. Diğer sağlayıcılar ve model geçersiz kılmaları değişmez. Yeni oturumlarda geçerli olur.", "integrations.semantics.aside": "Yalnızca bu profilin ~/.aside/u//models.json dosyasındaki providers.opencodex bölümünü yönetir. Diğer sağlayıcılarınız değişmez. Uyguladıktan sonra Aside’ı tamamen kapatıp yeniden açın.", + "integrations.semantics.raycast": "Raycast'in providers.yaml dosyasına bir OpenCodex sağlayıcı girdisi ekler; böylece yönlendirilen her model Raycast AI model seçicisinde görünür. Raycast Pro gerekir.", + "integrations.raycast.proRequired": "Custom Providers bir Raycast Pro özelliğidir. Dosya yazılır, ancak bir Pro aboneliği etkin olana kadar Raycast bunu yok sayar.", + "integrations.raycast.planUnknown": "Raycast Pro’nun etkin olup olmadığı belirlenemedi; Custom Providers için Raycast Pro gerekir.", + "integrations.raycast.revealConfig": "Raycast → Ayarlar → AI bölümünü açıp sağlayıcı klasörünün oluşması için „Reveal Providers Config“ seçeneğine bir kez tıklayın.", "integrations.semantics.omp": "Kataloğu yüklemek için OMP'yi yeniden başlatın.", "codexAuth.mainAccount": "Ana Hesap", "codexAuth.logLabel": "Günlük etiketi", @@ -2082,6 +2087,7 @@ export const tr: Record = { "api.clientConfig.clientZcode": "ZCode", "api.clientConfig.clientPrime": "Prime Agent", "api.clientConfig.clientAside": "Aside", + "api.clientConfig.clientRaycast": "Raycast", "api.clientConfig.copy": "JSON Kopyala", "api.clientConfig.download": "İndir", "api.clientConfig.loading": "İstemci konfigürasyonu oluşturuluyor…", @@ -2571,4 +2577,27 @@ export const tr: Record = { "integrations.cursor.colReasoning": "Akıl yürütme", "integrations.cursor.colContext": "Bağlam", "integrations.cursor.guide": "Cursor Private Inference kılavuzunu aç", + "models.displayNameSavedRefreshFailed": "Değişiklik kaydedildi ancak model listesi yenilenemedi. Yenilemek için tekrar deneyin.", + "models.displayNameOutcomeUnknown": "İstek tamamlanmadı. Değişiklik kaydedilmiş olabilir. Başka bir değişiklik yapmadan önce geçerli adı kontrol etmek için tekrar deneyin.", + "models.displayNameCurrentUnavailable": "Geçerli ad yenilemeye kadar kullanılamıyor", + "models.displayNameReloaded": "Model listesi yenilendi", + "models.displayNameAction": "Ad", + "models.displayNameActionLabel": "{model} için görünen adı düzenle", + "models.displayNameTitle": "Görünen ad", + "models.displayNameModelId": "Model kimliği", + "models.displayNameCurrent": "Geçerli ad", + "models.displayNameSourceOperator": "Sizin adınız", + "models.displayNameSourceProvider": "Sağlayıcı adı", + "models.displayNameSourceFallback": "Model kimliği varsayılanı", + "models.displayNameField": "Görünen ad", + "models.displayNamePlaceholder": "örn. Grok 4.6", + "models.displayNameHelp": "Yalnızca görünümü değiştirir. Yönlendirme {model} olarak kalır.", + "models.displayNameReset": "Adı sıfırla", + "models.displayNameSaved": "Görünen ad kaydedildi", + "models.displayNameResetDone": "Görünen ad sıfırlandı", + "models.displayNameSaveFailed": "Görünen ad kaydedilemedi", + "models.displayNameRequired": "Bir görünen ad girin veya Adı sıfırla seçeneğini kullanın.", + "models.displayNameTooLong": "Görünen ad en fazla 128 karakter olabilir.", + "models.displayNameNoSlash": "Görünen ad / içeremez.", + "models.displayNameNoControl": "Görünen ad denetim karakterleri içeremez.", }; diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 2b7e6ac6ba..3bc246543a 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -2178,6 +2178,7 @@ export const zhTW: Record = { "integrations.tab.zcode": "ZCode", "integrations.tab.prime": "Prime Agent", "integrations.tab.aside": "Aside", + "integrations.tab.raycast": "Raycast", "integrations.aside.profilesTitle": "Aside 設定檔", "integrations.aside.profilesHint": "選擇要接收所選模型的設定檔。Aside 目前使用的設定檔不會改變。", "integrations.aside.all": "同步所有設定檔", @@ -2337,6 +2338,10 @@ export const zhTW: Record = { "integrations.semantics.zcode": "僅管理 ~/.zcode/v2/config.json 中的 provider.opencodex,不會變更 Z.ai 登入狀態或其他供應商。變更後請重新啟動 ZCode。", "integrations.semantics.prime": "僅管理 Prime Agent 的 models.json 中的 providers.opencodex;預設位於 ~/.prime/agent,若設定 PRIME_AGENT_CODING_AGENT_DIR 則以其為準。不會變更其他供應商或模型覆寫設定。對新工作階段生效。", "integrations.semantics.aside": "僅管理此設定檔的 ~/.aside/u//models.json 中的 providers.opencodex。其他供應商維持不變。套用後請完全結束並重新開啟 Aside。", + "integrations.semantics.raycast": "在 Raycast 的 providers.yaml 中新增一個 OpenCodex 供應商項目,讓所有已路由的模型出現在 Raycast AI 模型選擇器中。需要 Raycast Pro。", + "integrations.raycast.proRequired": "Custom Providers 是 Raycast Pro 功能。檔案會被寫入,但在 Pro 訂閱生效之前 Raycast 會忽略它。", + "integrations.raycast.planUnknown": "無法確認 Raycast Pro 是否已啟用;Custom Providers 需要 Raycast Pro。", + "integrations.raycast.revealConfig": "開啟 Raycast → 設定 → AI,點一次「Reveal Providers Config」,以便建立 providers 資料夾。", "codexAuth.pinned": "已固定", "codexAuth.pinnedHint": "你手動選取了此帳號,因此較高的選擇順序不會越過它。此固定會持續到該帳號用盡、你改選其他帳號,或你變更任一選擇順序為止。", "codexAuth.requestUserInput": "在 Default 模式中要求輸入", @@ -2378,6 +2383,7 @@ export const zhTW: Record = { "api.clientConfig.clientZcode": "ZCode", "api.clientConfig.clientPrime": "Prime Agent", "api.clientConfig.clientAside": "Aside", + "api.clientConfig.clientRaycast": "Raycast", "cws.tabsLabel": "Combo 詳細區段", "cws.field.nativeAlias": "原生 OpenAI 別名", "cws.field.nativeAliasHint": "讓此 combo 擁有受支援的未限定原生 OpenAI 模型 ID。帶有帳號或供應商限定的 OpenAI 路由仍保持獨立。", @@ -2533,4 +2539,27 @@ export const zhTW: Record = { "integrations.cursor.colReasoning": "推理", "integrations.cursor.colContext": "上下文", "integrations.cursor.guide": "開啟 Cursor Private Inference 指南", + "models.displayNameSavedRefreshFailed": "變更已儲存,但無法重新整理模型清單。請重試。", + "models.displayNameOutcomeUnknown": "請求未完成。變更可能已儲存。再次變更之前,請重試以檢查目前名稱。", + "models.displayNameCurrentUnavailable": "重新整理之前無法取得目前名稱", + "models.displayNameReloaded": "模型清單已重新整理", + "models.displayNameAction": "名稱", + "models.displayNameActionLabel": "編輯 {model} 的友善名稱", + "models.displayNameTitle": "友善名稱", + "models.displayNameModelId": "模型 ID", + "models.displayNameCurrent": "目前名稱", + "models.displayNameSourceOperator": "你的名稱", + "models.displayNameSourceProvider": "供應商名稱", + "models.displayNameSourceFallback": "模型 ID 預設值", + "models.displayNameField": "友善名稱", + "models.displayNamePlaceholder": "例如 Grok 4.6", + "models.displayNameHelp": "只變更顯示方式。路由仍為 {model}。", + "models.displayNameReset": "重設名稱", + "models.displayNameSaved": "友善名稱已儲存", + "models.displayNameResetDone": "友善名稱已重設", + "models.displayNameSaveFailed": "無法儲存友善名稱", + "models.displayNameRequired": "請輸入友善名稱,或使用重設名稱。", + "models.displayNameTooLong": "友善名稱不能超過 128 個字元。", + "models.displayNameNoSlash": "友善名稱不能包含 /。", + "models.displayNameNoControl": "友善名稱不能包含控制字元。", }; diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 42ac3941d4..b10c48688d 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -1110,6 +1110,7 @@ export const zh: Record = { "integrations.tab.zcode": "ZCode", "integrations.tab.prime": "Prime Agent", "integrations.tab.aside": "Aside", + "integrations.tab.raycast": "Raycast", "integrations.aside.profilesTitle": "Aside 配置文件", "integrations.aside.profilesHint": "选择要接收所选模型的配置文件。Aside 当前使用的配置文件不会改变。", "integrations.aside.all": "同步所有配置文件", @@ -1269,6 +1270,10 @@ export const zh: Record = { "integrations.semantics.zcode": "仅管理 ~/.zcode/v2/config.json 中的 provider.opencodex,不会更改 Z.ai 登录状态或其他提供商。更改后请重启 ZCode。", "integrations.semantics.prime": "仅管理 Prime Agent 的 models.json 中的 providers.opencodex;默认位于 ~/.prime/agent,若设置 PRIME_AGENT_CODING_AGENT_DIR 则以其为准。不会更改其他提供商或模型覆盖设置。对新会话生效。", "integrations.semantics.aside": "仅管理此配置文件的 ~/.aside/u//models.json 中的 providers.opencodex。其他提供商保持不变。应用后请完全退出并重新打开 Aside。", + "integrations.semantics.raycast": "在 Raycast 的 providers.yaml 中添加一个 OpenCodex 提供商条目,让所有已路由的模型出现在 Raycast AI 模型选择器中。需要 Raycast Pro。", + "integrations.raycast.proRequired": "Custom Providers 是 Raycast Pro 功能。文件会被写入,但在 Pro 订阅生效之前 Raycast 会忽略它。", + "integrations.raycast.planUnknown": "无法确定 Raycast Pro 是否已激活;Custom Providers 需要 Raycast Pro。", + "integrations.raycast.revealConfig": "打开 Raycast → 设置 → AI,点击一次“Reveal Providers Config”,以便创建 providers 文件夹。", "codexAuth.mainAccount": "主账号", "codexAuth.logLabel": "日志标签", "codexAuth.codexApp": "Codex App", @@ -1600,6 +1605,7 @@ export const zh: Record = { "api.clientConfig.clientZcode": "ZCode", "api.clientConfig.clientPrime": "Prime Agent", "api.clientConfig.clientAside": "Aside", + "api.clientConfig.clientRaycast": "Raycast", "api.clientConfig.copy": "复制配置", "api.clientConfig.download": "下载", "api.clientConfig.loading": "正在生成客户端配置…", @@ -2569,4 +2575,27 @@ export const zh: Record = { "integrations.cursor.colReasoning": "推理", "integrations.cursor.colContext": "上下文", "integrations.cursor.guide": "打开 Cursor Private Inference 指南", + "models.displayNameSavedRefreshFailed": "更改已保存,但无法刷新模型列表。请重试以刷新。", + "models.displayNameOutcomeUnknown": "请求未完成。更改可能已保存。再次更改之前,请重试以检查当前名称。", + "models.displayNameCurrentUnavailable": "刷新之前无法获取当前名称", + "models.displayNameReloaded": "模型列表已刷新", + "models.displayNameAction": "名称", + "models.displayNameActionLabel": "编辑 {model} 的友好名称", + "models.displayNameTitle": "友好名称", + "models.displayNameModelId": "模型 ID", + "models.displayNameCurrent": "当前名称", + "models.displayNameSourceOperator": "你的名称", + "models.displayNameSourceProvider": "提供商名称", + "models.displayNameSourceFallback": "模型 ID 默认值", + "models.displayNameField": "友好名称", + "models.displayNamePlaceholder": "例如 Grok 4.6", + "models.displayNameHelp": "仅更改显示方式。路由仍为 {model}。", + "models.displayNameReset": "重置名称", + "models.displayNameSaved": "友好名称已保存", + "models.displayNameResetDone": "友好名称已重置", + "models.displayNameSaveFailed": "无法保存友好名称", + "models.displayNameRequired": "请输入友好名称,或使用重置名称。", + "models.displayNameTooLong": "友好名称不能超过 128 个字符。", + "models.displayNameNoSlash": "友好名称不能包含 /。", + "models.displayNameNoControl": "友好名称不能包含控制字符。", }; diff --git a/gui/src/pages/Models.tsx b/gui/src/pages/Models.tsx index 22ea51bc20..c342866d7e 100644 --- a/gui/src/pages/Models.tsx +++ b/gui/src/pages/Models.tsx @@ -1,4 +1,5 @@ import { CodexStaleBanner } from "../components/codex-stale-banner"; +import ModelDisplayNameDialog from "../components/ModelDisplayNameDialog"; import { fetchCodexAppServerState } from "../codex-app-server-state"; import type { AppServerStateOutcome } from "../codex-app-server-state"; import { useCodexRestart } from "../use-codex-restart"; @@ -8,7 +9,7 @@ import { IconChevron, IconBoxes, IconInfo, IconCheck, IconAlert, IconRefresh, Ic import { useT } from "../i18n/shared"; import type { TFn, TKey } from "../i18n/shared"; import { modelLabel } from "../model-display"; -import { formatNamespacedModelId, formatProviderDisplayName, providerDisplaySlug } from "../provider-icons"; +import { formatProviderDisplayName, providerDisplaySlug } from "../provider-icons"; import { readJsonIfOk, readJsonOrThrow } from "../fetch-json"; import { describeIntegrationRefusalParts } from "./integrations/refusal-copy"; import { readSessionListCache, writeSessionListCache } from "../session-list-cache"; @@ -328,6 +329,22 @@ export default function Models({ apiBase, restartEpoch = 0 }: { apiBase: string; const [showThreadsCustom, setShowThreadsCustom] = useState(false); const [v2HelpOpen, setV2HelpOpen] = useState(false); const [customModalOpen, setCustomModalOpen] = useState(false); + const [displayNameModel, setDisplayNameModel] = useState(null); + const [displayNameSaving, setDisplayNameSaving] = useState(false); + const [displayNameRequestError, setDisplayNameRequestError] = useState(null); + const [displayNameRecovery, setDisplayNameRecovery] = useState<{ + value: string | null | undefined; + confirmed: boolean; + } | null>(null); + const [displayNameCurrentPending, setDisplayNameCurrentPending] = useState(false); + const displayNameRequestRef = useRef(null); + const displayNameSavingRef = useRef(false); + useEffect(() => () => { + displayNameRequestRef.current?.controller.abort(); + displayNameRequestRef.current?.clear(); + displayNameRequestRef.current = null; + }, []); + const displayNameTriggerRef = useRef(null); const reloadAliases = useCallback(async (signal?: AbortSignal) => { const response = await fetch(`${apiBase}/api/aliases`, { signal }); @@ -535,12 +552,12 @@ export default function Models({ apiBase, restartEpoch = 0 }: { apiBase: string; ); const catalogState = catalogResource.state; - const load = useCallback(async (force = false): Promise => { + const load = useCallback(async (force = false, signal?: AbortSignal): Promise => { if (loadPendingRef.current && !force) return false; loadPendingRef.current = true; const generation = ++loadGenerationRef.current; try { - const next = await fetchCatalog(new AbortController().signal); + const next = await fetchCatalog(signal ?? new AbortController().signal); if (!shouldApplyLoadGeneration(generation, loadGenerationRef.current)) return false; applyCatalog(next); // Follow-up mutation refreshes retain their existing awaitable contract while publishing @@ -557,6 +574,118 @@ export default function Models({ apiBase, restartEpoch = 0 }: { apiBase: string; } }, [applyCatalog, cacheKey, fetchCatalog, pickerResource.refresh]); + const finishDisplayNameEdit = useCallback(() => { + const trigger = displayNameTriggerRef.current; + setDisplayNameModel(null); + setDisplayNameRequestError(null); + setDisplayNameRecovery(null); + setDisplayNameCurrentPending(false); + window.setTimeout(() => { + if (trigger?.isConnected) trigger.focus(); + }, 0); + }, []); + + const closeDisplayNameEdit = useCallback(() => { + if (!displayNameSavingRef.current) finishDisplayNameEdit(); + }, [finishDisplayNameEdit]); + + // undefined retries only the read after a confirmed write or an unknown outcome. + const saveDisplayName = useCallback(async (displayName: string | null | undefined) => { + const model = displayNameModel; + if (!model || displayNameSavingRef.current) return; + const bounded = createBoundedFetch(60_000); + displayNameRequestRef.current = bounded; + displayNameSavingRef.current = true; + setDisplayNameSaving(true); + setDisplayNameRequestError(null); + // A failed convergence retry cannot invalidate an earlier persistence receipt + // for the same value. Editing the draft clears recovery and starts a new intent. + let confirmed = displayNameRecovery?.confirmed === true + && (displayName === undefined || displayName === displayNameRecovery.value); + let receivedReceipt = displayName === undefined; + let refreshOnly = displayName === undefined; + try { + if (displayName !== undefined) { + const response = await fetch( + `${apiBase}/api/providers/${encodeURIComponent(model.provider)}/model-display-names`, + { + method: "PUT", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ modelId: model.id, displayName }), + signal: bounded.signal, + }, + ); + // The route can persist the value and return 503 when catalog convergence fails. + // Keep that receipt instead of throwing away saved:true with the error body. + type DisplayNameReceipt = { + saved?: boolean; + error?: string; + displayName?: string; + displayNameOverride?: string | null; + displayNameSource?: ModelRow["displayNameSource"]; + }; + const result: DisplayNameReceipt | undefined = response.ok + ? await readJsonOrThrow(response, t("models.displayNameSaveFailed")) + : await response.json(); + bounded.signal.throwIfAborted(); + if (!result || typeof result !== "object" || Array.isArray(result) + || (!response.ok && result.saved !== true && typeof result.error !== "string")) { + throw new Error(t("models.displayNameSaveFailed")); + } + receivedReceipt = true; + const receiptConfirmed = response.ok || result.saved === true; + confirmed = confirmed || receiptConfirmed; + if (receiptConfirmed) { + const override = result.displayNameOverride === null ? undefined + : result.displayNameOverride ?? displayName ?? undefined; + const fields: Pick = { + displayName: result.displayName ?? override, + displayNameOverride: override, + displayNameSource: result.displayNameSource ?? (override ? "operator" : undefined), + }; + setModels(current => current.map(row => row.namespaced === model.namespaced ? { ...row, ...fields } : row)); + setDisplayNameModel({ ...model, ...fields }); + // A saved:true reset receipt omits the provider's effective fallback label. + setDisplayNameCurrentPending(fields.displayName === undefined); + } + if (!response.ok) { + throw new Error(result.error || t("models.displayNameSaveFailed")); + } + refreshOnly = true; + } + if (!await load(true, bounded.signal)) throw new Error(t("models.loadFail")); + bounded.signal.throwIfAborted(); + publishFeedback(true, confirmed + ? t(displayName === null || (displayName === undefined && displayNameRecovery?.value === null) + ? "models.displayNameResetDone" : "models.displayNameSaved") + : t("models.displayNameReloaded")); + finishDisplayNameEdit(); + } catch (error) { + if (displayNameRequestRef.current !== bounded) return; + // A dropped connection or unreadable body can hide a committed write just + // like a timeout. Reconcile by reading; never replay an unchanged old draft. + const unknownOutcome = !receivedReceipt || bounded.signal.aborted; + if (unknownOutcome && !confirmed) setDisplayNameCurrentPending(true); + setDisplayNameRecovery(confirmed || unknownOutcome || refreshOnly + ? { value: refreshOnly || unknownOutcome ? undefined : displayName, confirmed } + : null); + setDisplayNameRequestError(confirmed + ? t("models.displayNameSavedRefreshFailed") + : unknownOutcome || refreshOnly + ? t("models.displayNameOutcomeUnknown") + : error instanceof Error && error.message + ? error.message + : t("models.displayNameSaveFailed")); + } finally { + bounded.clear(); + if (displayNameRequestRef.current === bounded) { + displayNameRequestRef.current = null; + displayNameSavingRef.current = false; + setDisplayNameSaving(false); + } + } + }, [apiBase, displayNameModel, displayNameRecovery, finishDisplayNameEdit, load, t]); + // Shadow/v2 controls must not wait on the models catalog (live discovery can be slow). useEffect(() => { // Both belong to the catalog tab; a hidden panel polling /api/v2 every ten seconds @@ -1537,9 +1666,31 @@ export default function Models({ apiBase, restartEpoch = 0 }: { apiBase: string; void applyVisibility("models", provider, [{ id: m.id, native: m.native === true }], off)} disabled={busy || m.initialSelectionPending} label={m.native ? m.id : m.namespaced} /> {m.initialSelectionPending && {t("models.initialSelectionPending")}} {aliases.models[provider]?.[m.id] && {aliases.models[provider][m.id].alias}} - {m.native ? modelLabel(m.id) : formatNamespacedModelId(m.namespaced, t)} + + {m.native ? modelLabel(m.id) : m.namespaced} + {!m.native && m.displayName?.trim() && m.displayName.trim() !== m.namespaced && ( + {m.displayName.trim()} + )} + {aliases.models[provider]?.[m.id]?.source === "builtin" && {t("models.aliasAuto")}} + {!m.native && !m.custom && ( + + )} {m.custom && ( {t("models.customBadge")} @@ -2485,6 +2636,20 @@ export default function Models({ apiBase, restartEpoch = 0 }: { apiBase: string; )} + + {displayNameModel && ( + void saveDisplayName(displayNameRecovery.value) : undefined} + onEdit={() => setDisplayNameRecovery(null)} + onSave={value => void saveDisplayName(value)} + onReset={() => void saveDisplayName(null)} + onClose={closeDisplayNameEdit} + /> + )} ); diff --git a/gui/src/pages/integrations/FileIntegrationPage.tsx b/gui/src/pages/integrations/FileIntegrationPage.tsx index 51db75bd9f..2eef2c5cf0 100644 --- a/gui/src/pages/integrations/FileIntegrationPage.tsx +++ b/gui/src/pages/integrations/FileIntegrationPage.tsx @@ -8,6 +8,7 @@ import { markFor } from "../../components/integration-marks"; import IntegrationStateBadge from "./IntegrationStateBadge"; import ConsequenceDialog, { type ConsequenceCopy } from "./ConsequenceDialog"; import RestoreDialog from "./RestoreDialog"; +import RaycastPlanNotice from "./RaycastPlanNotice"; import { RollbackHistory } from "./RollbackHistory"; import { describeRefusal } from "./refusal-copy"; import { @@ -57,6 +58,7 @@ const SEMANTICS_KEY: Record = { zcode: "integrations.semantics.zcode", prime: "integrations.semantics.prime", aside: "integrations.semantics.aside", + raycast: "integrations.semantics.raycast", }; const TAB_LABEL_KEY: Record = { @@ -72,6 +74,7 @@ const TAB_LABEL_KEY: Record = { zcode: "integrations.tab.zcode", prime: "integrations.tab.prime", aside: "integrations.tab.aside", + raycast: "integrations.tab.raycast", }; export default function FileIntegrationPage({ @@ -261,6 +264,8 @@ export default function FileIntegrationPage({

{t(SEMANTICS_KEY[client])}

{status.configPath}

+ {/* Only the raycast envelope carries this; the guard is the field, not the id. */} + {status.raycast && } {status.appliedAt && (

diff --git a/gui/src/pages/integrations/RaycastPlanNotice.tsx b/gui/src/pages/integrations/RaycastPlanNotice.tsx new file mode 100644 index 0000000000..9f08446751 --- /dev/null +++ b/gui/src/pages/integrations/RaycastPlanNotice.tsx @@ -0,0 +1,32 @@ +import { useT } from "../../i18n/shared"; +import { Notice } from "../../ui"; +import type { RaycastInstall } from "./integration-api"; + +/* + * Raycast is the one file client whose `current` state can still mean + * "ignored": Custom Providers is a Pro feature, and the file is read from a + * folder Raycast only creates after a click in its own settings. Neither fact + * is a reason to refuse the write -- the user may be about to subscribe, or + * has already clicked and the folder is seconds old -- so the page writes and + * says so here instead of showing a green badge that overstates the result. + * + * `free` is a warning because it is a known blocker; `unknown` stays muted + * because on Linux and Windows there is no subscription signal to read, and a + * Pro user there must not be told they are not one. + */ +export default function RaycastPlanNotice({ install }: { install: RaycastInstall }) { + const t = useT(); + return ( + <> + {install.plan === "free" && ( + {t("integrations.raycast.proRequired")} + )} + {install.plan === "unknown" && ( +

{t("integrations.raycast.planUnknown")}

+ )} + {!install.aiDirPresent && ( +

{t("integrations.raycast.revealConfig")}

+ )} + + ); +} diff --git a/gui/src/pages/integrations/integration-api.ts b/gui/src/pages/integrations/integration-api.ts index 7a9139f436..85ffdc7be4 100644 --- a/gui/src/pages/integrations/integration-api.ts +++ b/gui/src/pages/integrations/integration-api.ts @@ -14,6 +14,7 @@ export const FILE_INTEGRATION_CLIENTS = [ "zcode", "prime", "aside", + "raycast", ] as const; export type FileIntegrationClientId = (typeof FILE_INTEGRATION_CLIENTS)[number]; @@ -25,6 +26,7 @@ export type IntegrationReason = | "foreign-edit" | "unowned-key" | "blocked-container" + | "ambiguous-selector" | "unresolvable-path"; export type IntegrationRefusalReason = @@ -36,6 +38,19 @@ export type IntegrationRefusalReason = | "snapshot_expired" | "write_failed"; +export type RaycastPlan = "pro" | "free" | "unknown"; + +/** + * Raycast's app-side facts, sent only on `/api/client-integrations/raycast`. + * Custom Providers is a Pro feature, so a `current` file can still be one + * Raycast ignores — this is what lets the page say so instead of showing green. + */ +export interface RaycastInstall { + plan: RaycastPlan; + appPath: string | null; + aiDirPresent: boolean; +} + export interface IntegrationStatus { clientId: FileIntegrationClientId; state: IntegrationState; @@ -49,6 +64,7 @@ export interface IntegrationStatus { /** Aside's explicit account-backed profile scope and desired sync state. */ profileId?: number; enabled?: boolean; + raycast?: RaycastInstall; } export interface IntegrationStateListEnvelope { diff --git a/gui/src/pages/integrations/integration-tabs.ts b/gui/src/pages/integrations/integration-tabs.ts index 33c4f04358..99502bde87 100644 --- a/gui/src/pages/integrations/integration-tabs.ts +++ b/gui/src/pages/integrations/integration-tabs.ts @@ -46,6 +46,7 @@ export const TABS: readonly TabDefinition[] = [ { id: "zcode", hash: "integrations/zcode", labelKey: "integrations.tab.zcode" }, { id: "prime", hash: "integrations/prime", labelKey: "integrations.tab.prime" }, { id: "aside", hash: "integrations/aside", labelKey: "integrations.tab.aside" }, + { id: "raycast", hash: "integrations/raycast", labelKey: "integrations.tab.raycast" }, ] as const; export const FILE_CLIENTS = new Set([ @@ -61,4 +62,5 @@ export const FILE_CLIENTS = new Set([ "zcode", "prime", "aside", + "raycast", ]); diff --git a/gui/src/pages/integrations/overview-clients.ts b/gui/src/pages/integrations/overview-clients.ts index 4dd347b90c..7932cf5648 100644 --- a/gui/src/pages/integrations/overview-clients.ts +++ b/gui/src/pages/integrations/overview-clients.ts @@ -152,6 +152,7 @@ const FILE_LABEL_KEY: Record = { zcode: "integrations.tab.zcode", prime: "integrations.tab.prime", aside: "integrations.tab.aside", + raycast: "integrations.tab.raycast", }; /** A file client's block is in the file for both `current` and `stale`. */ diff --git a/gui/src/pages/models-shared.ts b/gui/src/pages/models-shared.ts index fdc487301c..1f5ef7786b 100644 --- a/gui/src/pages/models-shared.ts +++ b/gui/src/pages/models-shared.ts @@ -1,4 +1,4 @@ -import type { TFn } from "../i18n/shared"; +import type { TFn, TKey } from "../i18n/shared"; import type { ProviderDiscoverySummary } from "../models-groups"; import { modelVisible, type ProviderModelMap } from "../model-visibility"; import { formatNamespacedModelId } from "../provider-icons"; @@ -35,6 +35,8 @@ export interface ModelRow { custom?: boolean; customId?: string; displayName?: string; + displayNameOverride?: string; + displayNameSource?: "operator" | "provider" | "fallback"; inputModalities?: string[]; contextWindow?: number; contextCap?: number; @@ -43,6 +45,26 @@ export interface ModelRow { reasoningEfforts?: string[]; } +function containsDisplayNameControlCharacter(value: string): boolean { + return [...value].some(character => { + const codePoint = character.codePointAt(0)!; + return codePoint <= 0x1f + || (codePoint >= 0x7f && codePoint <= 0x9f) + || codePoint === 0x2028 + || codePoint === 0x2029; + }); +} + +/** Mirror the server display-name contract for immediate form feedback. */ +export function modelDisplayNameValidationKey(value: string): TKey | null { + const trimmed = value.trim(); + if (!trimmed) return "models.displayNameRequired"; + if (trimmed.length > 128) return "models.displayNameTooLong"; + if (trimmed.includes("/")) return "models.displayNameNoSlash"; + if (containsDisplayNameControlCharacter(trimmed)) return "models.displayNameNoControl"; + return null; +} + /** * Reasoning-effort labels offered in the custom-model dialog. The full set of real * `reasoning_effort` values (none, minimal, low, medium, high, xhigh, max). Deliberately diff --git a/gui/src/styles.css b/gui/src/styles.css index b0bbc0a6ff..a5838be7e4 100644 --- a/gui/src/styles.css +++ b/gui/src/styles.css @@ -2639,6 +2639,53 @@ button.prov-account-row.active { cursor: default; } /* ---- model row hover tooltip ---- */ .model-row-wrap { position: relative; } +.models-model-identity { + display: inline-flex; + min-width: 0; + flex-direction: column; + align-items: flex-start; + gap: 1px; +} +.models-model-friendly { + max-width: min(42vw, 420px); + overflow: hidden; + color: var(--muted); + text-overflow: ellipsis; + white-space: nowrap; +} +.models-display-name-trigger { flex-shrink: 0; } +.model-display-name-dialog { max-width: 460px; } +.model-display-name-identity, +.model-display-name-current { + display: grid; + gap: 5px; + margin-bottom: 16px; +} +.model-display-name-identity code { + overflow-wrap: anywhere; + color: var(--text); +} +.model-display-name-current { + grid-template-columns: 1fr auto; + align-items: center; +} +.model-display-name-current > .text-label { grid-column: 1 / -1; } +.model-display-name-current strong { min-width: 0; overflow-wrap: anywhere; } +.model-display-name-dialog > .input { margin-bottom: 6px; } +.model-display-name-dialog > .small { text-wrap: balance; } +.model-display-name-error { + margin-top: 8px; + color: var(--red); + font-size: var(--text-label); + line-height: var(--leading-body); +} +@media (max-width: 560px) { + .models-model-friendly { max-width: 58vw; } + .model-display-name-current { grid-template-columns: 1fr; } + .model-display-name-current > .text-label { grid-column: auto; } + .model-display-name-dialog .modal-actions { align-items: stretch; flex-direction: column; } + .model-display-name-dialog .modal-actions .btn { width: 100%; } +} .model-tip { z-index: 10; background: var(--surface); diff --git a/gui/tests/client-config-panel.test.tsx b/gui/tests/client-config-panel.test.tsx index 8acc44e9ee..ea8210e7e4 100644 --- a/gui/tests/client-config-panel.test.tsx +++ b/gui/tests/client-config-panel.test.tsx @@ -170,8 +170,8 @@ function rowButton(container: HTMLElement, name: string, label: string): HTMLBut .find(el => el.textContent?.trim() === label)!; } -test("the API download surface includes DSH, MiniMax Code and Aside as clients", () => { - expect(CLIENTS).toEqual(["opencode", "pi", "omp", "hermes", "openclaw", "kimi", "gajae", "dsh", "mcode", "zcode", "prime", "aside"]); +test("the API download surface includes DSH, MiniMax Code, Aside and Raycast as clients", () => { + expect(CLIENTS).toEqual(["opencode", "pi", "omp", "hermes", "openclaw", "kimi", "gajae", "dsh", "mcode", "zcode", "prime", "aside", "raycast"]); expect(CLIENT_LABEL_KEYS.dsh).toBe("api.clientConfig.clientDsh"); expect(CLIENT_LABEL_KEYS.mcode).toBe("api.clientConfig.clientMcode"); expect(CLIENT_LABEL_KEYS.zcode).toBe("api.clientConfig.clientZcode"); diff --git a/gui/tests/fr-localization.test.ts b/gui/tests/fr-localization.test.ts index 221de55d00..8c1ca29ada 100644 --- a/gui/tests/fr-localization.test.ts +++ b/gui/tests/fr-localization.test.ts @@ -118,6 +118,8 @@ const INTENTIONAL_ENGLISH = new Set([ "api.clientConfig.clientPrime", "integrations.tab.aside", "api.clientConfig.clientAside", + "integrations.tab.raycast", + "api.clientConfig.clientRaycast", "models.reasoningEffort.minimal", "models.reasoningEffort.max", "pws.pacingRpmUnit", diff --git a/gui/tests/integration-marks.test.ts b/gui/tests/integration-marks.test.ts index b964bc4ce1..b13387d1b6 100644 --- a/gui/tests/integration-marks.test.ts +++ b/gui/tests/integration-marks.test.ts @@ -61,15 +61,16 @@ test("no multi-color asset is masked", () => { /* * The inverse rule, and the one that cannot be derived from the file: a mark may * be a single ink and still not be a masking candidate, because that ink is the - * brand. openai.svg is #10A37F and deepseek-harness.svg is #4d6bfe; masking - * either repaints a trademark in the theme's text color. Pinned with their inks - * so a vendor changing its asset shows up here rather than silently satisfying - * the assertion. + * brand. openai.svg is #10A37F, deepseek-harness.svg is #4d6bfe and raycast.svg + * is #FF6363; masking any of them repaints a trademark in the theme's text + * color. Pinned with their inks so a vendor changing its asset shows up here + * rather than silently satisfying the assertion. */ test("a single-ink asset whose ink is a brand color is not masked", () => { for (const [src, ink] of [ ["/provider-icons/openai.svg", "#10a37f"], ["/provider-icons/deepseek-harness.svg", "#4d6bfe"], + ["/provider-icons/raycast.svg", "#ff6363"], ] as const) { expect(MASKED_MARKS.has(src), `${src} must not be masked`).toBe(false); expect([...inksOf(bodyOf(src))], `${src} ink changed upstream`).toEqual([ink]); diff --git a/gui/tests/integrations-api.test.ts b/gui/tests/integrations-api.test.ts index 4338d9ead8..eea7dcfa0c 100644 --- a/gui/tests/integrations-api.test.ts +++ b/gui/tests/integrations-api.test.ts @@ -16,9 +16,9 @@ import { const originalFetch = globalThis.fetch; -test("DSH and Aside are file integration clients", () => { +test("DSH, Aside and Raycast are file integration clients", () => { expect(FILE_INTEGRATION_CLIENTS).toEqual([ - "opencode", "pi", "omp", "hermes", "openclaw", "kimi", "gajae", "dsh", "mcode", "zcode", "prime", "aside", + "opencode", "pi", "omp", "hermes", "openclaw", "kimi", "gajae", "dsh", "mcode", "zcode", "prime", "aside", "raycast", ]); }); diff --git a/gui/tests/integrations-overview-rows.test.ts b/gui/tests/integrations-overview-rows.test.ts index 5bd673f849..54809a4422 100644 --- a/gui/tests/integrations-overview-rows.test.ts +++ b/gui/tests/integrations-overview-rows.test.ts @@ -290,12 +290,17 @@ test("every client counts toward the summary, not just the file clients", () => test("an unsettled file list renders unknown rows instead of dropping them", () => { const built = buildOverviewRows(sources({ clients: [], clientsSettled: false })); - expect(built.rows).toHaveLength(17); + expect(built.rows).toHaveLength(18); expect(rowById(built, "omp").state).toBe("unknown"); expect(rowById(built, "mcode").state).toBe("unknown"); expect(rowById(built, "zcode").state).toBe("unknown"); expect(rowById(built, "prime").state).toBe("unknown"); expect(rowById(built, "aside").state).toBe("unknown"); + expect(rowById(built, "raycast")).toMatchObject({ + hash: "integrations/raycast", + labelKey: "integrations.tab.raycast", + state: "unknown", + }); expect(rowById(built, "kimi").state).toBe("unknown"); expect(rowById(built, "dsh")).toMatchObject({ hash: "integrations/dsh", diff --git a/gui/tests/locale-parity.test.ts b/gui/tests/locale-parity.test.ts index 11976154c9..5ea6785493 100644 --- a/gui/tests/locale-parity.test.ts +++ b/gui/tests/locale-parity.test.ts @@ -130,6 +130,8 @@ const ZH_TW_KEEP_ENGLISH: ReadonlySet = new Set([ "api.clientConfig.clientPrime", "integrations.tab.aside", "api.clientConfig.clientAside", + "integrations.tab.raycast", + "api.clientConfig.clientRaycast", "integrations.codex.title", // Provider proper nouns kept in English "provider.name.commandCodeAuth", diff --git a/gui/tests/models-display-name-editor.test.tsx b/gui/tests/models-display-name-editor.test.tsx new file mode 100644 index 0000000000..b0656391ed --- /dev/null +++ b/gui/tests/models-display-name-editor.test.tsx @@ -0,0 +1,729 @@ +import { afterEach, beforeEach, describe, expect, jest, test } from "bun:test"; +import { Window } from "happy-dom"; +import { act } from "react"; +import type { Root } from "react-dom/client"; +import ModelDisplayNameDialog from "../src/components/ModelDisplayNameDialog"; +import { clearClientResourceStoresForTests } from "../src/client-resource"; +import { LanguageProvider } from "../src/i18n/provider"; +import { installApiAuthFetch, resetApiAuthFetchForTests } from "../src/api"; +import Models from "../src/pages/Models"; +import type { ModelRow } from "../src/pages/models-shared"; +import { modelDisplayNameValidationKey } from "../src/pages/models-shared"; + +describe("discovered model display name validation", () => { + test("accepts a safe label at both ordinary and maximum length", () => { + expect(modelDisplayNameValidationKey("Grok 4.6")).toBeNull(); + expect(modelDisplayNameValidationKey("A".repeat(128))).toBeNull(); + expect(modelDisplayNameValidationKey("모델 이름")).toBeNull(); + expect(modelDisplayNameValidationKey("🚀".repeat(64))).toBeNull(); + expect(modelDisplayNameValidationKey("🚀".repeat(65))).toBe("models.displayNameTooLong"); + }); + + test("rejects values that the management API cannot persist", () => { + expect(modelDisplayNameValidationKey(" ")).toBe("models.displayNameRequired"); + expect(modelDisplayNameValidationKey("Grok/4.6")).toBe("models.displayNameNoSlash"); + for (const control of ["\n", "\u0000", "\u007f", "\u0085", "\u2028", "\u2029"]) { + expect(modelDisplayNameValidationKey(`Grok${control}4.6`)).toBe("models.displayNameNoControl"); + } + expect(modelDisplayNameValidationKey("A".repeat(129))).toBe("models.displayNameTooLong"); + }); +}); + +describe("discovered model display name responsive styles", () => { + test("keeps the narrow action order aligned with keyboard navigation", async () => { + const styles = await Bun.file(new URL("../src/styles.css", import.meta.url)).text(); + + expect(styles).toContain( + ".model-display-name-dialog .modal-actions { align-items: stretch; flex-direction: column; }", + ); + expect(styles).not.toContain( + ".model-display-name-dialog .modal-actions { align-items: stretch; flex-direction: column-reverse; }", + ); + }); +}); + +describe("Models dashboard discovered display name integration", () => { + const globals = [ + "document", "window", "navigator", "localStorage", "sessionStorage", + "IS_REACT_ACT_ENVIRONMENT", "fetch", "setInterval", "clearInterval", + ] as const; + let previousGlobals: Record<(typeof globals)[number], PropertyDescriptor | undefined>; + let testWindow: Window; + let container: HTMLElement; + let root: Root | null; + let mutationBodies: Array<{ modelId: string; displayName: string | null }>; + let mutationFailure: string | null; + let savedFailure: boolean; + let mutationGate: Promise | null; + let modelFetches: number; + let modelFetchFailure: string | null; + let currentModels: ModelRow[]; + + const routedModel = (): ModelRow => ({ + provider: "xai-demo", + id: "grok-4.6", + namespaced: "xai-demo/grok-4.6", + disabled: false, + displayName: "Grok 4.6", + displayNameOverride: "Grok 4.6", + displayNameSource: "operator", + }); + + beforeEach(() => { + clearClientResourceStoresForTests(); + previousGlobals = Object.fromEntries( + globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]), + ) as typeof previousGlobals; + testWindow = new Window({ url: "http://localhost/#models" }); + Object.defineProperties(globalThis, { + document: { configurable: true, value: testWindow.document }, + window: { configurable: true, value: testWindow }, + navigator: { configurable: true, value: testWindow.navigator }, + localStorage: { configurable: true, value: testWindow.localStorage }, + sessionStorage: { configurable: true, value: testWindow.sessionStorage }, + IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true }, + setInterval: { configurable: true, value: () => 1 }, + clearInterval: { configurable: true, value: () => {} }, + }); + currentModels = [ + routedModel(), + { + provider: "command-code", + id: "deepseek-deepseek-v4-flash", + namespaced: "command-code/deepseek-deepseek-v4-flash", + disabled: false, + displayName: "DeepSeek V4 Flash", + displayNameSource: "provider", + }, + { provider: "openai", id: "gpt-5.5", namespaced: "openai/gpt-5.5", disabled: false, native: true }, + { + provider: "xai-demo", id: "custom-one", namespaced: "xai-demo/custom-one", + disabled: false, custom: true, customId: "custom-1", displayName: "Custom One", + }, + ]; + mutationBodies = []; + mutationFailure = null; + savedFailure = false; + resetApiAuthFetchForTests(); + mutationGate = null; + modelFetches = 0; + modelFetchFailure = null; + testWindow.localStorage.setItem("ocx-models-collapsed:v2", JSON.stringify([])); + testWindow.sessionStorage.setItem("ocx.models.catalog.v1:http://localhost", JSON.stringify({ + models: currentModels, + providers: [ + { name: "xai-demo", liveModels: false, models: ["grok-4.6", "custom-one"] }, + { name: "command-code", liveModels: false, models: ["deepseek-deepseek-v4-flash"] }, + { name: "openai", liveModels: false, models: ["gpt-5.5"] }, + ], + selectedModels: {}, + disabled: [], + contextCaps: {}, + contextCapValue: 350_000, + })); + + globalThis.fetch = (async (input, init) => { + const url = String(input); + if (url.endsWith("/api/models")) { + modelFetches += 1; + if (modelFetchFailure) { + return Response.json({ error: modelFetchFailure }, { status: 500 }); + } + return Response.json(currentModels); + } + if (url.endsWith("/api/providers")) return Response.json([ + { name: "xai-demo", liveModels: false, models: ["grok-4.6", "custom-one"] }, + { name: "command-code", liveModels: false, models: ["deepseek-deepseek-v4-flash"] }, + { name: "openai", liveModels: false, models: ["gpt-5.5"] }, + ]); + if (url.endsWith("/api/selected-models")) return Response.json({ selected: {} }); + if (url.endsWith("/api/provider-context-caps")) return Response.json({ caps: {} }); + if (url.endsWith("/api/aliases")) return Response.json({ providers: {}, models: {}, defaults: { global: false, providers: {} } }); + if (url.endsWith("/api/combos")) return Response.json({ combos: [] }); + if (url.endsWith("/api/shadow-call-settings")) return Response.json({ enabled: false, model: "" }); + if (url.endsWith("/api/v2")) return Response.json({ enabled: false, agentsMaxThreadsConflict: false, multiAgentMode: "default" }); + if (url.includes("/api/providers/xai-demo/model-display-names") && init?.method === "PUT") { + const body = JSON.parse(String(init.body)) as { modelId: string; displayName: string | null }; + mutationBodies.push(body); + if (mutationGate) await mutationGate; + if (mutationFailure && !savedFailure) return Response.json({ error: mutationFailure }, { status: 500 }); + currentModels = currentModels.map(row => row.namespaced !== "xai-demo/grok-4.6" ? row : { + ...row, + displayName: body.displayName ?? "xai-demo/grok-4.6", + displayNameOverride: body.displayName ?? undefined, + displayNameSource: body.displayName ? "operator" : "fallback", + }); + if (savedFailure) return Response.json({ + error: "model display name saved but catalog refresh failed", + saved: true, + displayNameOverride: body.displayName, + }, { status: 503 }); + const row = currentModels.find(model => model.namespaced === "xai-demo/grok-4.6")!; + return Response.json({ + ok: true, + displayName: row.displayName, + displayNameOverride: row.displayNameOverride ?? null, + displayNameSource: row.displayNameSource, + }); + } + return new Response(null, { status: 404 }); + }) as typeof fetch; + + container = testWindow.document.createElement("div"); + testWindow.document.body.appendChild(container as never); + root = null; + }); + + afterEach(async () => { + resetApiAuthFetchForTests(); + clearClientResourceStoresForTests(); + if (root) { + const mounted = root; + await act(async () => mounted.unmount()); + } + testWindow.close(); + for (const key of globals) { + const descriptor = previousGlobals[key]; + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } + }); + + async function flush() { + await act(async () => { + await new Promise(resolve => testWindow.setTimeout(resolve, 0)); + await Promise.resolve(); + }); + } + + async function mountModels() { + const { createRoot } = await import("react-dom/client"); + await act(async () => { + root = createRoot(container); + root.render(); + }); + await flush(); + } + + function nameTrigger(): HTMLButtonElement { + return container.querySelector( + '[aria-label="Edit friendly name for xai-demo/grok-4.6"]', + )!; + } + + function dialogInput(): HTMLInputElement { + return container.querySelector("dialog")! + .querySelector("input")!; + } + + function setInputValue(input: HTMLInputElement, value: string) { + Object.getOwnPropertyDescriptor(testWindow.HTMLInputElement.prototype, "value")! + .set!.call(input, value); + input.dispatchEvent(new testWindow.Event("input", { bubbles: true })); + } + + function dialogButton(label: string): HTMLButtonElement { + return [...container.querySelectorAll("dialog button")] + .find(button => button.textContent === label)!; + } + + test("only discovered rows expose Name while showing friendly and exact identities", async () => { + await mountModels(); + + expect(nameTrigger()).not.toBeNull(); + expect(container.querySelectorAll('[aria-label^="Edit friendly name for "]')).toHaveLength(2); + expect(container.querySelector('[aria-label="Edit friendly name for openai/gpt-5.5"]')).toBeNull(); + expect(container.querySelector('[aria-label="Edit friendly name for xai-demo/custom-one"]')).toBeNull(); + expect(container.textContent).toContain("Grok 4.6"); + expect(container.textContent).toContain("xai-demo/grok-4.6"); + expect([...container.querySelectorAll("code")].some(code => + code.textContent === "command-code/deepseek-deepseek-v4-flash" + )).toBe(true); + expect(container.textContent).toContain("Custom One"); + }); + + test("save and reset send exact payloads, reload the catalog, and restore trigger focus", async () => { + await mountModels(); + const trigger = nameTrigger(); + const fetchesBeforeSave = modelFetches; + + await act(async () => trigger.click()); + await act(async () => { + setInputValue(dialogInput(), " Grok Fast "); + dialogButton("Save").click(); + }); + await flush(); + + expect(mutationBodies).toEqual([{ modelId: "grok-4.6", displayName: "Grok Fast" }]); + expect(modelFetches).toBeGreaterThan(fetchesBeforeSave); + expect(container.querySelector("dialog")).toBeNull(); + expect(container.textContent).toContain("Grok Fast"); + expect(testWindow.document.activeElement).toBe(trigger); + + await act(async () => nameTrigger().click()); + await act(async () => dialogButton("Reset name").click()); + await flush(); + + expect(mutationBodies[1]).toEqual({ modelId: "grok-4.6", displayName: null }); + expect(container.querySelector("dialog")).toBeNull(); + expect(container.textContent).toContain("xai-demo/grok-4.6"); + }); + + test("a server failure keeps the dialog and edited draft available for retry", async () => { + mutationFailure = "Catalog refresh failed"; + await mountModels(); + await act(async () => nameTrigger().click()); + await act(async () => { + setInputValue(dialogInput(), "Retry Name"); + dialogButton("Save").click(); + }); + await flush(); + + expect(mutationBodies).toEqual([{ modelId: "grok-4.6", displayName: "Retry Name" }]); + expect(container.querySelector("dialog")).not.toBeNull(); + expect(dialogInput().value).toBe("Retry Name"); + expect(container.textContent).toContain("Catalog refresh failed"); + expect(testWindow.document.activeElement).toBe(dialogInput()); + mutationFailure = null; + await act(async () => dialogButton("Save").click()); + await flush(); + expect(mutationBodies).toHaveLength(2); + expect(currentModels[0]!.displayNameOverride).toBe("Retry Name"); + expect(container.querySelector("dialog")).toBeNull(); + }); + + test("a failed catalog reload after save keeps the dialog available for retry", async () => { + await mountModels(); + modelFetchFailure = "Catalog reload failed"; + await act(async () => nameTrigger().click()); + await act(async () => { + setInputValue(dialogInput(), "Retry Reload"); + dialogButton("Save").click(); + }); + await flush(); + + expect(mutationBodies).toEqual([{ modelId: "grok-4.6", displayName: "Retry Reload" }]); + expect(container.querySelector("dialog")).not.toBeNull(); + expect(dialogInput().value).toBe("Retry Reload"); + expect(container.textContent).toContain("The change was saved, but the model list could not be refreshed."); + expect(testWindow.document.activeElement).toBe(dialogInput()); + }); + + function currentNameText(): string { + return container.querySelector(".model-display-name-current")!.textContent ?? ""; + } + + test("first save followed by failed reload updates the snapshot and enables Reset", async () => { + await mountModels(); + await act(async () => nameTrigger().click()); + await act(async () => dialogButton("Reset name").click()); + await flush(); + mutationBodies = []; + await act(async () => nameTrigger().click()); + expect(dialogButton("Reset name").disabled).toBe(true); + modelFetchFailure = "reload failed"; + await act(async () => { + setInputValue(dialogInput(), " First Name "); + dialogButton("Save").click(); + }); + await flush(); + expect(dialogInput().value).toBe("First Name"); + expect(currentNameText()).toContain("First Name"); + expect(currentNameText()).toContain("Your name"); + expect(dialogButton("Reset name").disabled).toBe(false); + + modelFetchFailure = null; + await act(async () => dialogButton("Retry").click()); + await flush(); + expect(mutationBodies).toEqual([{ modelId: "grok-4.6", displayName: "First Name" }]); + expect(container.querySelector("dialog")).toBeNull(); + }); + + test("reset followed by failed reload clears the draft and Enter retries only the read", async () => { + await mountModels(); + await act(async () => nameTrigger().click()); + modelFetchFailure = "reload failed"; + await act(async () => dialogButton("Reset name").click()); + await flush(); + expect(dialogInput().value).toBe(""); + expect(currentNameText()).toContain("xai-demo/grok-4.6"); + expect(currentNameText()).not.toContain("Your name"); + expect(dialogButton("Reset name").disabled).toBe(true); + + modelFetchFailure = null; + await act(async () => container.querySelector("dialog form")!.dispatchEvent( + new testWindow.Event("submit", { bubbles: true, cancelable: true }), + )); + await flush(); + expect(mutationBodies).toEqual([{ modelId: "grok-4.6", displayName: null }]); + expect(container.querySelector("dialog")).toBeNull(); + expect(currentModels[0]!.displayNameOverride).toBeUndefined(); + }); + + for (const value of ["Saved Name", null]) { + test(`saved:true failure reconciles ${value === null ? "reset" : "save"} and retries the same operation`, async () => { + await mountModels(); + await act(async () => nameTrigger().click()); + savedFailure = true; + await act(async () => { + if (value === null) dialogButton("Reset name").click(); + else { + setInputValue(dialogInput(), value); + dialogButton("Save").click(); + } + }); + await flush(); + expect(dialogInput().value).toBe(value ?? ""); + expect(dialogButton("Reset name").disabled).toBe(value === null); + expect(currentNameText()).toContain(value ?? "Current name unavailable until refresh"); + expect(currentNameText()).not.toContain(value === null ? "Your name" : "Model ID fallback"); + expect(container.textContent).toContain("The change was saved"); + savedFailure = false; + await act(async () => dialogButton("Retry").click()); + await flush(); + expect(mutationBodies).toEqual([ + { modelId: "grok-4.6", displayName: value }, + { modelId: "grok-4.6", displayName: value }, + ]); + expect(container.querySelector("dialog")).toBeNull(); + }); + } + + test("confirmed reset survives an ordinary convergence retry error before success", async () => { + await mountModels(); + await act(async () => nameTrigger().click()); + savedFailure = true; + await act(async () => dialogButton("Reset name").click()); + await flush(); + savedFailure = false; + mutationFailure = "Temporary server failure"; + await act(async () => dialogButton("Retry").click()); + await flush(); + expect(dialogInput().value).toBe(""); + expect(dialogButton("Reset name").disabled).toBe(true); + expect(dialogButton("Retry").disabled).toBe(false); + expect(container.textContent).toContain("The change was saved"); + expect(currentNameText()).not.toContain("Your name"); + expect(currentModels[0]!.displayNameOverride).toBeUndefined(); + + mutationFailure = null; + await act(async () => container.querySelector("dialog form")!.dispatchEvent( + new testWindow.Event("submit", { bubbles: true, cancelable: true }), + )); + await flush(); + expect(mutationBodies.map(body => body.displayName)).toEqual([null, null, null]); + expect(container.querySelector("dialog")).toBeNull(); + expect(currentModels[0]!.displayNameOverride).toBeUndefined(); + }); + + for (const failure of ["transport", "body"] as const) { + for (const value of ["Saved despite disconnect", null]) { + test(`persisted ${value === null ? "reset" : "save"} with ${failure} failure retries only a read`, async () => { + await mountModels(); + const transport = globalThis.fetch; + let failedSignal: AbortSignal | null | undefined; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const response = await transport(input, init); + if (init?.method === "PUT" && String(input).includes("model-display-names")) { + failedSignal = init.signal; + if (failure === "transport") throw new TypeError("Connection closed"); + Object.defineProperty(response, "text", { + value: async () => { throw new TypeError("Response body interrupted"); }, + }); + } + return response; + }) as typeof fetch; + await act(async () => nameTrigger().click()); + await act(async () => { + if (value === null) dialogButton("Reset name").click(); + else { + setInputValue(dialogInput(), value); + dialogButton("Save").click(); + } + }); + await flush(); + expect(failedSignal?.aborted).toBe(false); + expect(currentModels[0]!.displayNameOverride).toBe(value ?? undefined); + expect(dialogInput().value).toBe(value ?? "Grok 4.6"); + expect(currentNameText()).toContain("Current name unavailable until refresh"); + expect(currentNameText()).not.toContain("Your name"); + expect(container.textContent).toContain("The change may have been saved"); + expect(dialogButton("Retry").disabled).toBe(false); + expect(dialogButton("Cancel").disabled).toBe(false); + await act(async () => container.querySelector("dialog form")!.dispatchEvent( + new testWindow.Event("submit", { bubbles: true, cancelable: true }), + )); + await flush(); + expect(mutationBodies).toEqual([{ modelId: "grok-4.6", displayName: value }]); + expect(currentModels[0]!.displayNameOverride).toBe(value ?? undefined); + expect(container.querySelector("dialog")).toBeNull(); + }); + } + } + + test("editing after a saved receipt explicitly starts a new save", async () => { + await mountModels(); + await act(async () => nameTrigger().click()); + savedFailure = true; + await act(async () => dialogButton("Reset name").click()); + await flush(); + savedFailure = false; + await act(async () => setInputValue(dialogInput(), "New intention")); + await act(async () => dialogButton("Save").click()); + await flush(); + expect(mutationBodies.map(body => body.displayName)).toEqual([null, "New intention"]); + }); + + // Exercise the real global auth wrapper over an abort-aware transport. Only + // the deadline clock is controlled; the operation must supply its own signal. + for (const stage of ["mutation", "reload"] as const) { + test(`stalled ${stage} through installed API fetch releases the editor and retries a read`, async () => { + await mountModels(); + const descriptor = Object.getOwnPropertyDescriptor(AbortSignal, "timeout"); + const deadline = new AbortController(); + const budgets: number[] = []; + const seenSignals: Array = []; + let stall = true; + const transport = globalThis.fetch; + Object.defineProperty(AbortSignal, "timeout", { + configurable: true, + value: (ms: number) => { budgets.push(ms); return deadline.signal; }, + }); + const boundedTransport = (async (input: RequestInfo | URL, init?: RequestInit) => { + if (String(input).includes("model-display-names") || String(input).endsWith("/api/models")) { + seenSignals.push(init?.signal); + } + if (stall && (stage === "mutation" + ? init?.method === "PUT" && String(input).includes("model-display-names") + : String(input).endsWith("/api/models"))) { + // Persist the write before losing its response: abort is not rollback. + if (stage === "mutation") await transport(input, init); + return new Promise((_resolve, reject) => { + const signal = init?.signal; + if (signal?.aborted) reject(signal.reason); + else signal?.addEventListener("abort", () => reject(signal.reason), { once: true }); + }); + } + return transport(input, init); + }) as typeof fetch; + Object.defineProperty(window, "fetch", { configurable: true, value: boundedTransport }); + installApiAuthFetch(); + globalThis.fetch = window.fetch; + try { + const trigger = nameTrigger(); + await act(async () => trigger.click()); + await act(async () => { + setInputValue(dialogInput(), "Possibly saved"); + dialogButton("Save").click(); + }); + await flush(); + expect(budgets).toEqual([60_000]); + expect(seenSignals.every(signal => signal != null)).toBe(true); + if (stage === "reload") expect(seenSignals[1]).toBe(seenSignals[0]); + await act(async () => deadline.abort(new DOMException("Timed out", "TimeoutError"))); + await flush(); + expect(dialogInput().disabled).toBe(false); + expect(dialogButton("Cancel").disabled).toBe(false); + expect(dialogInput().value).toBe("Possibly saved"); + expect(container.textContent).toContain(stage === "mutation" + ? "The change may have been saved" : "The change was saved"); + expect(testWindow.document.activeElement).toBe(dialogInput()); + stall = false; + if (descriptor) Object.defineProperty(AbortSignal, "timeout", descriptor); + await act(async () => dialogButton("Retry").click()); + await flush(); + expect(mutationBodies).toHaveLength(1); + expect(currentModels[0]!.displayNameOverride).toBe("Possibly saved"); + expect(container.querySelector("dialog")).toBeNull(); + expect(testWindow.document.activeElement).toBe(trigger); + } finally { + if (descriptor) Object.defineProperty(AbortSignal, "timeout", descriptor); + else Reflect.deleteProperty(AbortSignal, "timeout"); + } + }); + } + + test("a pending save blocks duplicate mutations", async () => { + let releaseMutation!: () => void; + mutationGate = new Promise(resolve => { releaseMutation = resolve; }); + await mountModels(); + await act(async () => nameTrigger().click()); + const save = dialogButton("Save"); + + await act(async () => { + setInputValue(dialogInput(), "Grok Once"); + save.click(); + save.click(); + await Promise.resolve(); + }); + expect(mutationBodies).toEqual([{ modelId: "grok-4.6", displayName: "Grok Once" }]); + expect(save.disabled).toBe(true); + + releaseMutation(); + await flush(); + expect(container.querySelector("dialog")).toBeNull(); + }); + + test("Cancel closes without mutation and restores focus to Name", async () => { + await mountModels(); + const trigger = nameTrigger(); + await act(async () => trigger.click()); + await act(async () => dialogButton("Cancel").click()); + await flush(); + + expect(mutationBodies).toHaveLength(0); + expect(container.querySelector("dialog")).toBeNull(); + expect(testWindow.document.activeElement).toBe(trigger); + }); +}); + +describe("discovered model display name dialog", () => { + const globals = ["document", "window", "navigator", "localStorage", "IS_REACT_ACT_ENVIRONMENT"] as const; + let previousGlobals: Record<(typeof globals)[number], PropertyDescriptor | undefined>; + let testWindow: Window; + let container: HTMLElement; + let root: Root | null; + + const model: ModelRow = { + provider: "xai-demo", + id: "grok-4.6", + namespaced: "xai-demo/grok-4.6", + disabled: false, + displayName: "Grok 4.6", + displayNameOverride: "Grok 4.6", + displayNameSource: "operator", + }; + + beforeEach(() => { + previousGlobals = Object.fromEntries( + globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]), + ) as typeof previousGlobals; + testWindow = new Window({ url: "http://localhost/" }); + Object.defineProperties(globalThis, { + document: { configurable: true, value: testWindow.document }, + window: { configurable: true, value: testWindow }, + navigator: { configurable: true, value: testWindow.navigator }, + localStorage: { configurable: true, value: testWindow.localStorage }, + IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true }, + }); + container = testWindow.document.createElement("div"); + testWindow.document.body.appendChild(container as never); + root = null; + }); + + afterEach(async () => { + if (root) { + const mounted = root; + await act(async () => mounted.unmount()); + } + testWindow.close(); + for (const key of globals) { + const descriptor = previousGlobals[key]; + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } + }); + + async function renderDialog(options: { + saving?: boolean; + requestError?: string | null; + onSave?: (value: string) => void; + onReset?: () => void; + onClose?: () => void; + } = {}) { + const { createRoot } = await import("react-dom/client"); + await act(async () => { + root ??= createRoot(container); + root.render( + + {})} + onReset={options.onReset ?? (() => {})} + onClose={options.onClose ?? (() => {})} + /> + , + ); + }); + } + + function setInputValue(input: HTMLInputElement, value: string) { + Object.getOwnPropertyDescriptor(testWindow.HTMLInputElement.prototype, "value")! + .set!.call(input, value); + input.dispatchEvent(new testWindow.Event("input", { bubbles: true })); + } + + test("opens with immutable identity and only the operator override in the input", async () => { + await renderDialog(); + + const dialog = container.querySelector("dialog")!; + const input = container.querySelector("input")!; + expect(dialog.open).toBe(true); + expect(dialog.textContent).toContain("xai-demo/grok-4.6"); + expect(dialog.textContent).toContain("Grok 4.6"); + expect(dialog.textContent).toContain("Your name"); + expect(input.value).toBe("Grok 4.6"); + expect(testWindow.document.activeElement).toBe(input); + }); + + test("validates before save and sends the trimmed safe draft", async () => { + const onSave = jest.fn(); + await renderDialog({ onSave }); + const input = container.querySelector("input")!; + const save = [...container.querySelectorAll("button")] + .find(button => button.textContent === "Save")!; + + await act(async () => { + setInputValue(input, "Bad/Name"); + save.click(); + }); + expect(container.textContent).toContain("Friendly name cannot contain /."); + expect(onSave).not.toHaveBeenCalled(); + + await act(async () => { + setInputValue(input, " Grok Fast "); + save.click(); + }); + expect(onSave).toHaveBeenCalledTimes(1); + expect(onSave).toHaveBeenCalledWith("Grok Fast"); + }); + + test("keeps request errors visible and locks every closing action while saving", async () => { + const onClose = jest.fn(); + const onReset = jest.fn(); + await renderDialog({ saving: true, requestError: "Catalog refresh failed", onClose, onReset }); + + expect(container.textContent).toContain("Catalog refresh failed"); + const actionButtons = [...container.querySelectorAll("button")]; + expect(actionButtons.filter(button => button.tabIndex !== -1).every(button => button.disabled)).toBe(true); + + const dialog = container.querySelector("dialog")!; + await act(async () => { + dialog.dispatchEvent(new testWindow.Event("cancel", { bubbles: false, cancelable: true })); + container.querySelector(".modal-backdrop-dismiss")!.click(); + }); + expect(onClose).not.toHaveBeenCalled(); + expect(onReset).not.toHaveBeenCalled(); + }); + + test("a request failure does not mark a valid display name as invalid", async () => { + await renderDialog({ requestError: "Catalog refresh failed" }); + + const input = container.querySelector("input")!; + expect(input.getAttribute("aria-invalid")).toBeNull(); + expect(testWindow.document.activeElement).toBe(input); + }); + + test("focus returns to the editable name after a pending save fails", async () => { + await renderDialog({ saving: true }); + testWindow.document.body.tabIndex = -1; + testWindow.document.body.focus(); + expect(testWindow.document.activeElement).toBe(testWindow.document.body); + + await renderDialog({ requestError: "Catalog refresh failed" }); + + expect(testWindow.document.activeElement).toBe(container.querySelector("input")); + }); +}); diff --git a/gui/tests/raycast-plan-notice.test.tsx b/gui/tests/raycast-plan-notice.test.tsx new file mode 100644 index 0000000000..7f08550317 --- /dev/null +++ b/gui/tests/raycast-plan-notice.test.tsx @@ -0,0 +1,61 @@ +import { expect, test } from "bun:test"; +import { createElement } from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { DICTS, I18nContext, type TFn } from "../src/i18n/shared"; +import RaycastPlanNotice from "../src/pages/integrations/RaycastPlanNotice"; +import type { RaycastInstall } from "../src/pages/integrations/integration-api"; + +/* + * Raycast reads providers.yaml only on a Pro plan and only from a folder it + * creates itself, so a `current` badge can be a lie. The notice is the one place + * that lie is corrected, and each of its three lines answers a different + * question; a regression that drops one leaves the page green and silent. + */ + +const echoT: TFn = key => key; + +function render(install: RaycastInstall, t: TFn = echoT): string { + return renderToStaticMarkup( + createElement( + I18nContext.Provider, + { value: { locale: "en", setLocale: () => {}, t } }, + createElement(RaycastPlanNotice, { install }), + ), + ); +} + +test("a Pro install with the ai folder renders nothing", () => { + expect(render({ plan: "pro", appPath: "/Applications/Raycast.app", aiDirPresent: true })).toBe(""); +}); + +test("a free plan is a warning notice, never a refusal", () => { + const markup = render({ plan: "free", appPath: "/Applications/Raycast.app", aiDirPresent: true }); + expect(markup).toContain("notice-warn"); + expect(markup).toContain("integrations.raycast.proRequired"); + expect(markup).not.toContain("notice-err"); + expect(markup).not.toContain("integrations.raycast.planUnknown"); +}); + +test("an unknown plan stays muted, because non-macOS hosts have no signal", () => { + const markup = render({ plan: "unknown", appPath: null, aiDirPresent: true }); + expect(markup).toContain('data-raycast-plan="unknown"'); + expect(markup).toContain("integrations.raycast.planUnknown"); + expect(markup).not.toContain("notice-warn"); +}); + +test("a missing ai folder adds the reveal hint independently of the plan", () => { + const markup = render({ plan: "free", appPath: "/Applications/Raycast.app", aiDirPresent: false }); + expect(markup).toContain("integrations.raycast.proRequired"); + expect(markup).toContain('data-raycast-ai-dir="absent"'); + expect(markup).toContain("integrations.raycast.revealConfig"); +}); + +test("a Windows install reports unknown Pro activity without claiming a preference read failed", () => { + const markup = render({ + plan: "unknown", appPath: "C:\\Users\\u\\AppData\\Local\\Programs\\Raycast", aiDirPresent: true, + }, key => DICTS.en[key]); + expect(markup).toContain("Could not determine whether Raycast Pro is active"); + expect(markup).not.toContain("Could not read"); + expect(markup).not.toContain("notice-warn"); + expect(markup).not.toContain(" = {}; + +class SmokeFailure extends Error {} + +function check(ok: unknown, message: string): asserts ok { + if (!ok) throw new SmokeFailure(message); +} + +// Do not include arguments, child output, HTTP bodies, or arbitrary error messages in diagnostics. +function progress(name: string): void { + stage = name; + console.log(`docker-smoke: ${name}`); +} + +async function run(args: string[], input?: string, timeout = 30_000, cleanup = false) { + if (!cleanup) cancelled.signal.throwIfAborted(); + return await new Promise<{ code: number | null; out: string }>((accept, reject) => { + const child = spawn(args[0]!, args.slice(1), { + cwd: root, env, detached: true, stdio: ["pipe", "pipe", "pipe"], + }); + const chunks: Buffer[] = []; + let bytes = 0; + let failed = false; + let killTimer: ReturnType | undefined; + let reapTimer: ReturnType | undefined; + const killGroup = (signal: NodeJS.Signals) => { + if (child.pid) { + try { process.kill(-child.pid, signal); } catch { /* already exited */ } + } + }; + const stop = () => { + if (failed) return; + failed = true; + killGroup("SIGTERM"); + killTimer = setTimeout(() => killGroup("SIGKILL"), 1_000); + // A daemon/plugin retaining a pipe must not keep the harness alive indefinitely. + reapTimer = setTimeout(() => { + child.stdout.destroy(); child.stderr.destroy(); child.stdin.destroy(); + finish(); + child.unref(); + reject(new SmokeFailure("child did not close within the termination deadline")); + }, 4_000); + }; + const timer = setTimeout(stop, timeout); + const finish = () => { + clearTimeout(timer); clearTimeout(killTimer); clearTimeout(reapTimer); + cancelled.signal.removeEventListener("abort", stop); + }; + if (!cleanup) cancelled.signal.addEventListener("abort", stop, { once: true }); + const collect = (data: Buffer, stdout: boolean) => { + bytes += data.length; + if (bytes > outputLimit) stop(); + else if (stdout) chunks.push(data); + }; + child.stdout.on("data", (data: Buffer) => collect(data, true)); + child.stderr.on("data", (data: Buffer) => collect(data, false)); + child.stdin.on("error", () => { /* EPIPE is possible on the refused bootstrap. */ }); + child.on("error", () => { finish(); reject(new SmokeFailure("child could not start")); }); + child.on("close", code => { + // A terminated CLI can close its pipes before its plugin exits. + if (failed) killGroup("SIGKILL"); + finish(); + if (failed) reject(new SmokeFailure("child exceeded time/output limit or was cancelled")); + else accept({ code, out: Buffer.concat(chunks).toString("utf8") }); + }); + child.stdin.end(input); + }); +} + +async function command(args: string[], input?: string, timeout?: number, cleanup = false) { + const result = await run(args, input, timeout, cleanup); + check(result.code === 0, `command exited ${result.code ?? "by signal"}`); + return result.out.trim(); +} + +function compose(args: string[], input?: string, timeout?: number, cleanup = false) { + return command(["docker", ...composeArgs, ...args], input, timeout, cleanup); +} + +async function build() { + const directory = join(root, "src/generated"); + const manifest = join(directory, "compatibility-version.json"); + const directoryStat = lstatSync(directory, { throwIfNoEntry: false }); + const hadDirectory = directoryStat !== undefined; + check(!directoryStat || directoryStat.isDirectory(), "unsafe generated directory"); + const originalStat = lstatSync(manifest, { throwIfNoEntry: false }); + check(!originalStat || originalStat.isFile(), "unsafe existing manifest"); + check(!originalStat || originalStat.size <= 8 * 1024 * 1024, "existing manifest exceeds limit"); + const original = originalStat ? readFileSync(manifest) : undefined; + try { + progress("generate compatibility manifest"); + await command([process.execPath, "scripts/generate-compatibility-version.ts"]); + progress("build Docker image"); + await compose(["build", "hub"], undefined, 600_000); + } finally { + if (original && originalStat) { + writeFileSync(manifest, original); + chmodSync(manifest, originalStat.mode & 0o777); + utimesSync(manifest, originalStat.atime, originalStat.mtime); + } else { + rmSync(manifest, { force: true }); + } + if (!hadDirectory && existsSync(directory)) rmdirSync(directory); + } +} + +const fixture = JSON.stringify({ models: [{ + slug: "smoke/synthetic", display_name: "Smoke fixture", description: "Synthetic catalog only", + priority: 1, visibility: "list", base_instructions: "Synthetic", input_modalities: ["text"], +}] }); +const token = randomBytes(32).toString("hex"); +const replacement = randomBytes(32).toString("hex"); +const sha256 = (value: string) => createHash("sha256").update(value).digest("hex"); +let seededConfigHash = ""; +let readyConfigHash = ""; + +// Check the loader, including its schema-repair/default-provider fallback, before server startup +// and again in each running container. This isolates synthetic inference, not all process egress. +const fixtureConfigCheck = ` + const { loadConfig } = await import('./src/config.ts'); + const effective = loadConfig(); + const provider = effective.providers.smoke; + if (Object.keys(effective.providers).join(',') !== 'smoke' || effective.defaultProvider !== 'smoke' + || provider?.adapter !== 'openai-responses' || provider?.authMode !== 'local' + || provider?.allowPrivateNetwork !== true + || provider?.baseUrl !== 'http://127.0.0.1:9/v1' || provider?.codexAccountMode !== undefined || provider?.apiKey + || effective.runtimeRole !== 'hub' || effective.hostname !== '0.0.0.0' || effective.port !== 10100 + || effective.codexAutoStart !== false || effective.codexShimAutoRestore !== false) throw new Error('unsafe effective fixture config'); +`; + +interface Container { + Id: string; + State: { Running: boolean; Health?: { Status: string } }; + HostConfig: { ReadonlyRootfs: boolean; CapDrop: string[]; SecurityOpt: string[]; Privileged: boolean }; + Config: { Image: string; Labels: Record }; + NetworkSettings: { Ports: Record | null> }; + Mounts: Array<{ Type: string; Name?: string; Destination: string; RW: boolean }>; +} + +async function inspect() { + const id = await compose(["ps", "-q", "hub"]); + check(/^[a-f0-9]{64}$/.test(id), "expected exactly one container"); + const rows = JSON.parse(await command(["docker", "inspect", id])) as Container[]; + check(rows.length === 1, "unexpected inspect result"); + const container = rows[0]!; + check(container.Id === id && container.Config.Image === image + && container.Config.Labels["com.docker.compose.project"] === project, "container identity mismatch"); + check(container.State.Running && container.State.Health?.Status === "healthy", "container not healthy"); + check(container.HostConfig.ReadonlyRootfs && !container.HostConfig.Privileged + && container.HostConfig.CapDrop.includes("ALL") + && container.HostConfig.SecurityOpt.some(value => /^no-new-privileges(?::true)?$/.test(value)), "restrictions missing"); + const ports = Object.entries(container.NetworkSettings.Ports).filter(([, entries]) => entries?.length); + check(ports.length === 1 && ports[0]![0] === "10100/tcp", "unexpected published port"); + const bindings = ports[0]![1]!; + check(bindings.length === 1 && bindings[0]!.HostIp === "127.0.0.1", "non-loopback publication"); + const port = Number(bindings[0]!.HostPort); + check(Number.isInteger(port) && port > 0 && port <= 65535, "invalid host port"); + const volumes = [".opencodex", ".codex"].map(home => { + const mounts = container.Mounts.filter(mount => mount.Destination === `/home/bun/${home}`); + check(mounts.length === 1, "missing home mount"); + const mount = mounts[0]!; + check(mount.Type === "volume" && mount.RW && mount.Name?.startsWith(`${project}_`), "unexpected home volume"); + return mount.Name; + }); + check(volumes[0] !== volumes[1], "homes share a volume"); + return { id, volumes, url: `http://127.0.0.1:${port}` }; +} + +// This runs as the image's user. Only hashes/metadata leave the container, never file bytes. +const stateProbe = ` + import { readFileSync, statSync, writeFileSync } from 'node:fs'; + import { createHash } from 'node:crypto'; + import { isDeepStrictEqual } from 'node:util'; + const phase = await Bun.stdin.text(); + if (!['seed', 'first-ready', 'steady'].includes(phase)) throw new Error('invalid state phase'); + ${fixtureConfigCheck} + const homes = ['/home/bun/.opencodex', '/home/bun/.codex']; + if (process.env.OCX_SERVICE !== '1') throw new Error('image service lifecycle mode missing'); + const uid = process.getuid(); + if (uid === 0) throw new Error('root user'); + const status = readFileSync('/proc/self/status', 'utf8'); + if (!/^CapEff:\\s+0+$/m.test(status) || !/^NoNewPrivs:\\s+1$/m.test(status)) throw new Error('effective restrictions'); + for (const home of homes) { + const s = statSync(home); + if (s.uid !== uid || (s.mode & 0o777) !== 0o700) throw new Error('home permissions'); + } + try { writeFileSync('/home/bun/app/.smoke-root-write', 'x'); throw new Error('writable root'); } + catch (e) { if (e.code !== 'EROFS') throw e; } + const paths = [homes[0] + '/config.json', homes[0] + '/service-api-token', homes[1] + '/opencodex-catalog.json']; + const hashes = paths.map(path => { + const s = statSync(path); + if (s.uid !== uid || (s.mode & 0o777) !== 0o600 || s.size > 65536) throw new Error('file permissions/size'); + return createHash('sha256').update(readFileSync(path)).digest('hex'); + }); + // The immutable shipped config was byte-verified before fixture creation. Reconstruct only + // the deliberate fixture route edits, then compare every original key on disk (not loader defaults). + const seed = JSON.parse(readFileSync('docker/config.json', 'utf8')); + seed.providers = { smoke: { adapter: 'openai-responses', baseUrl: 'http://127.0.0.1:9/v1', authMode: 'local', allowPrivateNetwork: true } }; + seed.defaultProvider = 'smoke'; + const persisted = JSON.parse(readFileSync(paths[0], 'utf8')); + const loaded = JSON.parse(JSON.stringify(effective)); + for (const key of Object.keys(seed)) { + for (const config of [persisted, loaded]) { + if (!Object.hasOwn(config, key) || !isDeepStrictEqual(config[key], seed[key])) throw new Error('seed semantics changed'); + } + } + // Independent oracle measured by isolated startup; update only for an intentional contract change. + // Do not derive expected values from runtime migration/default helpers. + const additions = { + appOwnedMemoryBudgetMb: 256, fastRows: true, managementUsageMaxReadBytes: 67108864, + openaiProviderTierVersion: 2, + subagentModels: ['gpt-6-astra', 'gpt-5.6-sol', 'gpt-5.6-terra', 'gpt-5.6-luna', 'gpt-5.5'], + subagentModelsVersion: 1, + }; + for (const config of [persisted, loaded]) { + if (Object.keys(config).some(key => !Object.hasOwn(seed, key) && !Object.hasOwn(additions, key))) throw new Error('unexpected startup config addition'); + for (const [key, expected] of Object.entries(additions)) { + if (phase !== 'seed' || Object.hasOwn(config, key)) { + if (!Object.hasOwn(config, key) || !isDeepStrictEqual(config[key], expected)) throw new Error('startup oracle mismatch'); + } + } + } + if (phase === 'seed' && Object.keys(persisted).some(key => !Object.hasOwn(seed, key))) throw new Error('premature seed addition'); + console.log(JSON.stringify(hashes)); +`; + +async function state(phase: "seed" | "first-ready" | "steady" = "steady") { + const invocation = phase === "seed" ? ["run", "--rm", "-T", "--no-deps"] : ["exec", "-T"]; + const hashes = JSON.parse(await compose([...invocation, "hub", "bun", "-e", stateProbe], phase)) as string[]; + check(hashes.length === 3 && hashes.every(hash => /^[a-f0-9]{64}$/.test(hash)), "invalid state evidence"); + check(hashes[1] === sha256(`${token}\n`) && hashes[2] === sha256(fixture), "token/catalog changed"); + if (phase === "first-ready") { + check(!readyConfigHash, "post-start config baseline already established"); + // stateProbe has checked persisted/effective semantics and the independent startup oracle. + readyConfigHash = hashes[0]!; + } else { + check(hashes[0] === (phase === "seed" ? seededConfigHash : readyConfigHash), + phase === "seed" ? "seeded config changed before startup" : "post-start config changed"); + } + return JSON.stringify(hashes); +} + +async function request(url: string, path: string, secret?: string) { + const controller = new AbortController(); + const abort = () => controller.abort(); + cancelled.signal.throwIfAborted(); + cancelled.signal.addEventListener("abort", abort, { once: true }); + const timer = setTimeout(abort, 5_000); + try { + const post = path !== "/healthz" && path !== "/readyz" && path !== "/v1/catalog"; + const response = await fetch(`${url}${path}`, { + method: post ? "POST" : "GET", redirect: "error", signal: controller.signal, + headers: { ...(secret ? { "x-opencodex-api-key": secret } : {}), ...(post ? { "content-type": "application/json" } : {}) }, + // Never send an authorized inference request, even with synthetic input. + body: post ? '{"model":"smoke/synthetic","input":[]}' : undefined, + }); + const reader = response.body?.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + try { + while (reader) { + const next = await reader.read(); + if (next.done) break; + size += next.value.length; + check(size <= 64 * 1024, "HTTP body exceeds limit"); + chunks.push(next.value); + } + } finally { controller.abort(); reader?.releaseLock(); } + return { status: response.status, body: Buffer.concat(chunks).toString("utf8") }; + } finally { + clearTimeout(timer); + cancelled.signal.removeEventListener("abort", abort); + } +} + +async function acceptance(url: string) { + check((await request(url, "/healthz")).status === 200, "liveness failed"); + const deadline = Date.now() + 60_000; + while (true) { + const ready = await request(url, "/readyz"); + const body = JSON.parse(ready.body) as { status?: string }; + if (ready.status === 200 && body.status === "ready") break; + check(ready.status === 503 && body.status === "pending" && Date.now() < deadline, "readiness failed"); + await Bun.sleep(500); + } + for (const path of ["/v1/catalog", "/v1/responses", "/v1/responses/compact"]) { + for (const secret of [undefined, replacement]) { + const result = await request(url, path, secret); + check(result.status === 401, `${path} ${secret ? "wrong" : "missing"} token returned ${result.status}, expected 401`); + } + } + const catalog = await request(url, "/v1/catalog", token); + check(catalog.status === 200 && catalog.body === fixture, "catalog not served exactly"); +} + +async function cleanup() { + let failed = false; + const attempt = async (action: () => Promise) => { + try { await action(); } catch { failed = true; } + }; + if (composeArgs.length) { + await attempt(() => compose(["down", "--volumes", "--remove-orphans", "--timeout", "10"], undefined, 45_000, true)); + for (const kind of ["container", "volume", "network"]) { + await attempt(async () => { + const remaining = await command(["docker", kind, "ls", "-q", ...(kind === "container" ? ["-a"] : []), + "--filter", `label=com.docker.compose.project=${project}`], undefined, 15_000, true); + check(!remaining, "project resources remain"); + }); + } + await attempt(async () => { + const ids = await command(["docker", "image", "ls", "-q", "--filter", `reference=${image}`], undefined, 15_000, true); + if (ids) await command(["docker", "image", "rm", image], undefined, 30_000, true); + check(!await command(["docker", "image", "ls", "-q", "--filter", `reference=${image}`], undefined, 15_000, true), "image remains"); + }); + } + try { if (scratch) rmSync(scratch, { recursive: true, force: true, maxRetries: 0 }); } catch { failed = true; } + check(!failed, "cleanup incomplete"); +} + +async function main() { + check(process.platform === "linux", "requires a disposable Linux Docker runner"); + scratch = mkdtempSync(join(tmpdir(), `${project}-`)); + mkdirSync(join(scratch, "docker"), { mode: 0o700 }); + writeFileSync(join(scratch, "empty.env"), "", { mode: 0o600 }); + writeFileSync(join(scratch, "override.json"), JSON.stringify({ + services: { hub: { image, restart: "no" } }, + }), { mode: 0o600 }); + env = { + PATH: process.env.PATH ?? "/usr/local/bin:/usr/bin:/bin", TMPDIR: scratch, + DOCKER_CONFIG: join(scratch, "docker"), DOCKER_HOST: "unix:///var/run/docker.sock", + COMPOSE_DISABLE_ENV_FILE: "1", OPENCODEX_BIND_ADDRESS: "127.0.0.1", OPENCODEX_PORT: "0", + }; + composeArgs = ["compose", "--project-name", project, "--project-directory", root, + "--env-file", join(scratch, "empty.env"), "-f", join(root, "compose.yaml"), "-f", join(scratch, "override.json")]; + progress("validate and build"); + await compose(["config", "--quiet"]); + await build(); + progress("verify shipped config and seed loopback-only fixture"); + const seeded = await run(["docker", ...composeArgs, "run", "--rm", "-T", "--no-deps", "hub", "bun", "-e", + ` + import { readFileSync, writeFileSync } from 'node:fs'; + import { createHash } from 'node:crypto'; + // Exit codes are fixed diagnostic markers; never serialize the caught exception. + let seedStage = 70; + try { + const { atomicWriteFile } = await import('./src/config/atomic-write.ts'); + seedStage = 71; + const { shipped, catalog } = JSON.parse(await Bun.stdin.text()); + const path = '/home/bun/.opencodex/config.json'; + seedStage = 72; + if (readFileSync(path, 'utf8') !== shipped || readFileSync('docker/config.json', 'utf8') !== shipped) { + throw new Error('shipped config mismatch'); + } + const config = JSON.parse(shipped); + if (config.runtimeRole !== 'hub' || config.hostname !== '0.0.0.0' || config.port !== 10100 + || config.codexAutoStart !== false || config.codexShimAutoRestore !== false) throw new Error('shipped runtime contract'); + // Port 9 has no listener in this image. Replace all provider routes before any server starts; + // even an admission regression cannot send these synthetic requests to a real provider. + config.providers = { smoke: { adapter: 'openai-responses', baseUrl: 'http://127.0.0.1:9/v1', authMode: 'local', allowPrivateNetwork: true } }; + config.defaultProvider = 'smoke'; + seedStage = 73; + const { validateConfigCandidate } = await import('./src/config.ts'); + if (!validateConfigCandidate(config).ok) throw new Error('invalid fixture'); + seedStage = 74; + atomicWriteFile(path, JSON.stringify(config) + '\\n'); + seedStage = 75; + ${fixtureConfigCheck} + seedStage = 76; + writeFileSync('/home/bun/.codex/opencodex-catalog.json', catalog, { mode: 0o600, flag: 'wx' }); + seedStage = 77; + console.log(createHash('sha256').update(readFileSync(path)).digest('hex')); + } catch { process.exitCode = seedStage; } + `], JSON.stringify({ shipped: readFileSync(join(root, "docker/config.json"), "utf8"), catalog: fixture })); + const seedFailures: Record = { + 70: "imports", 71: "input", 72: "shipped config contract", 73: "fixture validation", + 74: "atomic config write", 75: "effective config", 76: "catalog write", 77: "config hash", + }; + check(seeded.code === 0, `seed failed: ${seedFailures[seeded.code ?? -1] ?? "unclassified child failure"} (exit ${seeded.code ?? "signal"})`); + seededConfigHash = seeded.out.trim(); + check(/^[a-f0-9]{64}$/.test(seededConfigHash), "invalid seeded config evidence"); + progress("bootstrap throwaway token"); + await compose(["run", "--rm", "-T", "--no-deps", "hub", "bun", "run", "docker/bootstrap-token.ts"], `${token}\n`); + progress("verify exact seed state before startup"); + await state("seed"); + progress("start and check admission"); + await compose(["up", "--no-build", "--wait", "--wait-timeout", "120", "hub"], undefined, 150_000); + const first = await inspect(); + await acceptance(first.url); + const before = await state("first-ready"); + progress("refuse token replacement"); + const refused = await run(["docker", ...composeArgs, "run", "--rm", "-T", "--no-deps", "hub", + "bun", "run", "docker/bootstrap-token.ts"], `${replacement}\n`); + check(refused.code === 1, "bootstrap did not refuse replacement"); + check(await state() === before, "state changed after refused bootstrap"); + await acceptance(first.url); + progress("replace container and verify persistence"); + await compose(["up", "--no-build", "--force-recreate", "--wait", "--wait-timeout", "120", "hub"], undefined, 150_000); + const second = await inspect(); + check(second.id !== first.id && JSON.stringify(second.volumes) === JSON.stringify(first.volumes), "replacement/volume identity failed"); + check(await state() === before, "persistent state changed"); + await acceptance(second.url); +} + +const abort = () => cancelled.abort(); +process.once("SIGINT", abort); +process.once("SIGTERM", abort); +const deadline = setTimeout(abort, 16 * 60_000); +try { + await main(); +} catch (error) { + const reason = error instanceof SmokeFailure ? error.message : "unexpected failure; details suppressed"; + console.error(`docker-smoke: failed at ${stage}: ${reason}`); + process.exitCode = 1; +} finally { + clearTimeout(deadline); + try { await cleanup(); } catch { + console.error("docker-smoke: cleanup incomplete"); + process.exitCode = 1; + } + process.removeListener("SIGINT", abort); + process.removeListener("SIGTERM", abort); +} +if (!process.exitCode) console.log("docker-smoke: build/start/recreate acceptance passed; cleanup complete"); diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index d309073a3f..65ba23d900 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -204,6 +204,8 @@ "anthropic-image-retry.test.ts": "adapters/anthropic", "anthropic-pool-toggle-copy.test.ts": "adapters/anthropic", "anthropic-quorum-cache.test.ts": "routing", + "anthropic-quota-dispatch.test.ts": "adapters/anthropic", + "anthropic-ratelimit-headers.test.ts": "adapters/anthropic", "anthropic-reasoning.test.ts": "adapters/anthropic", "anthropic-sidecar-account-failover.test.ts": "adapters/anthropic", "anthropic-stream-hardening.test.ts": "adapters/anthropic", @@ -237,6 +239,7 @@ "aside-profiles-routes.test.ts": "server", "aside-profiles.test.ts": "clients", "aside-profile-paths.test.ts": "clients", + "aside-profile-identity.test.ts": "clients", "aside-profile-sync-owner.test.ts": "clients", "assert-mergeable-review.test.ts": "ci-workflows", "auto-compact-budget.test.ts": "providers", @@ -312,6 +315,7 @@ "claude-outbound.test.ts": "claude-integration", "claude-shell-hook.test.ts": "claude-integration", "claude-sidecar-override.test.ts": "claude-integration", + "claude-source-envelope.test.ts": "claude-integration", "claude-system-env-auto.test.ts": "claude-integration", "cleanup-orphaned-workflows.test.ts": "ci-workflows", "clearable-deadline.test.ts": "lib", @@ -690,6 +694,7 @@ "install-scripts.test.ts": "ci-workflows", "integrations-invariants.test.ts": "gui", "integrations-journal.test.ts": "clients", + "integrations-merge.test.ts": "clients", "integrations-serialize.test.ts": "clients", "integrations-state.test.ts": "clients", "integrations-writer.test.ts": "clients", @@ -998,7 +1003,10 @@ "reserve-quota-scope.test.ts": "codex-integration", "rate-limit-reset-credits.test.ts": "gui", "rate-limit-retry.test.ts": "providers", + "raycast-client.test.ts": "clients", + "raycast-detect.test.ts": "clients", "reasoning-effort.test.ts": "codex-integration", + "reasoning-envelope.test.ts": "responses", "reasoning-replay-identity.test.ts": "adapters", "reasoning-replay-robustness.test.ts": "adapters", "reasoning-replay-scope-source.test.ts": "lib", diff --git a/skills/ocx/references/01_management_surface.md b/skills/ocx/references/01_management_surface.md index d5711f3cac..10b0cd9e89 100644 --- a/skills/ocx/references/01_management_surface.md +++ b/skills/ocx/references/01_management_surface.md @@ -67,6 +67,7 @@ Drives no management route. | Flag | Value | Meaning | |---|---|---| | `--json` | boolean | Emit the provider list as JSON. | +| `--jsonl` | boolean | Emit one configured provider per JSON line. | JSON mode: `envelope`. diff --git a/skills/ocx/references/02_json_shapes.md b/skills/ocx/references/02_json_shapes.md index a91e35a2e1..261c8be5a2 100644 --- a/skills/ocx/references/02_json_shapes.md +++ b/skills/ocx/references/02_json_shapes.md @@ -52,6 +52,11 @@ to `requestedModel` is how you get a wrong answer about which provider served it `displayMetrics.cost.estimate.estimateReasons` lists why — for example `usage_estimated`, `cache_detail_missing`, `expected_price_overlay`. +## `ocx provider list --jsonl` + +One configured provider per line. Each object has the same fields as an item in the +`configured` array from `ocx provider list --json`; the `registryCount` summary is omitted. + ## `ocx logs explain ` ```json diff --git a/skills/ocx/references/03_recipes.md b/skills/ocx/references/03_recipes.md index 424ad34a53..9159751424 100644 --- a/skills/ocx/references/03_recipes.md +++ b/skills/ocx/references/03_recipes.md @@ -157,6 +157,7 @@ exist for them — do not attribute usage to either. ```bash ocx provider list --json +ocx provider list --jsonl # one configured provider per line ocx provider add --json # registry providers auto-configure by name ocx provider test --json ocx provider set-default --json diff --git a/src/adapters/anthropic.ts b/src/adapters/anthropic.ts index 6eea4764a1..a9a8279198 100644 --- a/src/adapters/anthropic.ts +++ b/src/adapters/anthropic.ts @@ -1118,9 +1118,14 @@ export function createAnthropicAdapter(provider: OcxProviderConfig, cacheRetenti break; } case "content_block_start": { - const block = data.content_block as { type: string; id?: string; name?: string; data?: string } | undefined; + const block = data.content_block as { type: string; id?: string; name?: string; data?: string; thinking?: string } | undefined; if (!block) break; currentBlockType = block.type; + if (block.type === "thinking") { + // Preserve even a display:omitted block boundary. The bridge can then + // distinguish consecutive empty signed blocks from signature updates. + yield { type: "thinking_delta", thinking: typeof block.thinking === "string" ? block.thinking : "" }; + } if (block.type === "tool_use") { currentToolCallId = usableToolUseId(block.id); currentToolCallName = toolNames.fromWire(block.name ?? ""); @@ -1151,8 +1156,8 @@ export function createAnthropicAdapter(provider: OcxProviderConfig, cacheRetenti // later text blocks independent. yield { type: "thinking_delta", thinking: delta.reasoning }; } else if (delta.type === "signature_delta" && typeof delta.signature === "string" && (currentBlockType === "thinking" || currentBlockType === "reasoning")) { - // Arrives once, just before the thinking block's content_block_stop; block-scoped - // so a stray signature on a non-thinking block can never be captured. + // Anthropic SDKs replace the signature with this value. Forward updates + // within the block; the bridge closes on the next semantic boundary. yield { type: "thinking_signature", signature: delta.signature }; } else if (delta.type === "input_json_delta" && typeof delta.partial_json === "string" && currentBlockType === "tool_use") { // Forwarded immediately: the bridge maps each delta to a client-visible diff --git a/src/adapters/openai-responses.ts b/src/adapters/openai-responses.ts index 07c0556d5e..1b8c1b076e 100644 --- a/src/adapters/openai-responses.ts +++ b/src/adapters/openai-responses.ts @@ -630,6 +630,13 @@ function mapRoutedResponsesReasoningEffort( if (provider.authMode === "forward") return body; if (configuredReasoningEfforts(provider, modelId) === undefined) return body; if (!isPlainObject(body) || !isPlainObject(body.reasoning)) return body; + const declaredEfforts = modelRecordValue(provider.modelReasoningEfforts, modelId) ?? provider.reasoningEfforts; + // An explicitly empty ladder means no effort control, not no reasoning output. + // Omit only effort so the upstream default applies; unknown/non-rankable ladders stay untouched. + if (declaredEfforts?.length === 0 && Object.hasOwn(body.reasoning, "effort")) { + const { effort: _effort, ...reasoning } = body.reasoning; + return { ...body, reasoning: Object.keys(reasoning).length > 0 ? reasoning : undefined }; + } const requested = body.reasoning.effort; if (typeof requested !== "string") return body; diff --git a/src/bridge.ts b/src/bridge.ts index 645dfff8e7..ff044a5e52 100644 --- a/src/bridge.ts +++ b/src/bridge.ts @@ -945,6 +945,13 @@ export function bridgeToResponsesSSE( } if (event.type !== "done" && event.type !== "incomplete" && event.type !== "error") continue; } + // Anthropic signature_delta supplies the latest signature, not an append-only + // fragment (anthropic-sdk-typescript MessageStream). Keep consecutive updates + // together; the next semantic event belongs to the following block. + if (pendingSignature !== undefined && event.type !== "thinking_signature" && event.type !== "heartbeat") { + if (currentReasoning) closeCurrentReasoning(); + else flushHiddenReasoningEnvelope(); + } switch (event.type) { case "assistant_boundary": { // A guarded continuation starts a fresh assistant output item while keeping the @@ -1054,15 +1061,21 @@ export function bridgeToResponsesSSE( case "thinking_signature": { pendingSignatureBytes = replaceRetainedString(pendingSignatureBytes, event.signature, "reasoning"); pendingSignature = event.signature; - // Signature arrives at the end of the thinking block. With a visible reasoning item - // open, closeCurrentReasoning attaches the envelope; hidden/suppressed blocks flush - // an envelope-only reasoning item now. - if (!currentReasoning) flushHiddenReasoningEnvelope(); + // Delay closing until the next semantic event so a signature update cannot + // create another block or become attached to the following thinking text. break; } case "redacted_thinking": { + if (currentMsg) closeCurrentMessage("commentary"); + if (currentReasoning) closeCurrentReasoning(); + if (currentRawReasoning) closeCurrentRawReasoning(); + flushHiddenRawReasoning(); + if (currentToolCall) closeCurrentToolCall(); budget?.chargeRetained(bytesOf(event.data), { kind: "reasoning" }); pendingRedacted.push(event.data); + // A redacted block is complete at content_block_start. Emit it here, + // not with a later thinking block or after a tool call at turn end. + flushHiddenReasoningEnvelope(); break; } case "kiro_redacted_reasoning": { @@ -1816,6 +1829,9 @@ function buildResponseJSONWithBudget( if (budget) releaseTranslatedEvent(e, budget); continue; } + if (batchSignature !== undefined && e.type !== "thinking_signature" && e.type !== "heartbeat") { + flushSummaryReasoning(); + } switch (e.type) { case "assistant_boundary": flushText("commentary"); @@ -1860,19 +1876,23 @@ function buildResponseJSONWithBudget( } break; case "thinking_signature": - // End of the current thinking block — flush it WITH the signature envelope so the - // block/signature pairing survives multi-block turns. + // Like streaming, retain the latest signature update until the next semantic + // event. Flushing every update would manufacture signature-only siblings. batchSignatureBytes = replaceBatchRetainedString(batchSignatureBytes, e.signature, "reasoning"); batchSignature = e.signature; - flushSummaryReasoning(); break; case "redacted_thinking": + flushText("commentary"); + flushSummaryReasoning(); + flushRawReasoning(); + flushToolCall(); { const dataBytes = bytesOf(e.data); budget?.chargeRetained(dataBytes, { kind: "reasoning" }); batchRedactedBytes += dataBytes; } batchRedacted.push(e.data); + flushSummaryReasoning(); break; case "kiro_redacted_reasoning": // Stash only — pushed after the trailing flushes. One blob per turn, so last wins. diff --git a/src/claude/inbound.ts b/src/claude/inbound.ts index 3ac4731385..5e876ca6cb 100644 --- a/src/claude/inbound.ts +++ b/src/claude/inbound.ts @@ -4,8 +4,8 @@ * Design (devlog/260711_claude_inbound/010, 003_evidence.md): * - translate-and-replay: the produced body MUST pass the real responsesRequestSchema * parse so routing/OAuth/pool/failover are inherited unchanged. - * - thinking/redacted_thinking blocks on replay are DROPPED (v1 policy) — routed - * providers carry reasoning in Responses items/ocxr1 envelopes instead. + * - thinking/redacted_thinking replay is preserved in Responses reasoning items; + * signatures and redacted payloads travel in bounded ocxr1 envelopes. * - thinking.budget_tokens is NEVER forwarded raw; it maps to an effort tier. * - top_k is accepted and silently dropped (no Responses equivalent, CCR parity). */ @@ -17,6 +17,7 @@ export { resolveInboundModel, effortForThinkingBudget, effortFromOutputConfig, e import { AnthropicRequestError, isRec, type Rec } from "./inbound-records"; import { resolveInboundModel, effortForThinkingBudget, effortFromOutputConfig, formatFromOutputConfig } from "./inbound-model-options"; import { systemToInstructions, toolsToResponses, toolChoiceToResponses } from "./inbound-content-options"; +import { decodeReasoningEnvelope, encodeReasoningEnvelope, OCX_REASONING_PREFIX } from "../responses/reasoning-envelope"; @@ -234,9 +235,26 @@ function assistantMessageToItems(content: unknown, input: Rec[]): void { input.push({ type: "function_call", call_id: raw.id, name: raw.name, arguments: JSON.stringify(raw.input ?? {}) }); break; } - case "thinking": - case "redacted_thinking": - break; // v1 policy: dropped on replay (003 evidence — safe for routed providers) + case "thinking": { + flush(); + const thinking = typeof raw.thinking === "string" ? raw.thinking : ""; + const signature = typeof raw.signature === "string" ? raw.signature : ""; + if (signature.startsWith(OCX_REASONING_PREFIX)) { + const owned = decodeReasoningEnvelope(signature); + if (!owned) throw new AnthropicRequestError("malformed ocxr1 reasoning signature"); + if (Object.hasOwn(owned, "sig")) throw new AnthropicRequestError("OpenCodex reasoning continuity cannot be replayed as an Anthropic signature"); + } + const encrypted = signature.length === 0 ? undefined : signature.startsWith(OCX_REASONING_PREFIX) ? signature : encodeReasoningEnvelope({ sig: signature }); + if (thinking.length === 0 && !encrypted) break; + input.push({ type: "reasoning", id: `rs_${crypto.randomUUID().replace(/-/g, "")}`, summary: thinking.length > 0 ? [{ type: "summary_text", text: thinking }] : [], ...(encrypted ? { encrypted_content: encrypted } : {}) }); + break; + } + case "redacted_thinking": { + flush(); + const data = typeof raw.data === "string" ? raw.data : ""; + if (data.length > 0) input.push({ type: "reasoning", id: `rs_${crypto.randomUUID().replace(/-/g, "")}`, summary: [], encrypted_content: encodeReasoningEnvelope({ red: [data] }) }); + break; + } default: break; } diff --git a/src/claude/outbound.ts b/src/claude/outbound.ts index 48bb06c15a..ac06afac2d 100644 --- a/src/claude/outbound.ts +++ b/src/claude/outbound.ts @@ -5,8 +5,8 @@ * - Transport-only `ping` events may appear at any point, including before * message_start. Semantic framing stays message_start -> * (content_block_start -> deltas -> content_block_stop)* -> message_delta -> message_stop. - * - thinking blocks get thinking_delta(s) then ONE synthetic signature_delta just - * before content_block_stop (CCR precedent: Claude Code does not verify signatures). + * - thinking blocks get thinking_delta(s), then one signature_delta containing the + * genuine replay signature or a bounded ocxr1 fallback envelope. * - message_delta.usage is cumulative; message_start embeds a full message snapshot. * - errors: {type:"error", error:{type,message}}; may arrive mid-stream after HTTP 200. */ @@ -20,6 +20,7 @@ import { type TranslatorBudget, } from "../lib/translator-budget"; import { sseFieldOffset, sseFieldValue } from "../lib/sse-decoder"; +import { decodeReasoningEnvelope, encodeReasoningEnvelope } from "../responses/reasoning-envelope"; type Rec = Record; @@ -214,6 +215,9 @@ interface OpenBlock { callId?: string; /** Last fixed-size reasoning identity (item + summary/content index) seen by this block. */ reasoningPartKey?: string; + thinkingBuf?: string; + thinkingBufBytes?: number; + reasoningSig?: string; } /** Streaming: Responses SSE bytes -> Anthropic Messages SSE bytes. */ @@ -230,6 +234,9 @@ export function responsesSseToAnthropicSse( let bufferBytes = 0; let started = false; let terminated = false; + // Starting termination can still throw while closing a block or emitting its + // terminal frame. Only a delivered terminal forbids the bounded overflow error. + let terminalDelivered = false; let cancelled = false; let blockIndex = 0; let open: OpenBlock | null = null; @@ -253,6 +260,11 @@ export function responsesSseToAnthropicSse( const bytes = queuedLiveFrameBytes.shift(); if (bytes !== undefined) translatorBudget.releaseRetained(bytes, { kind: "live_transient" }); }; + const releaseThinkingBuffer = (block: OpenBlock | null | undefined) => { + if (block?.kind !== "thinking") return; + translatorBudget.releaseRetained(block.thinkingBufBytes ?? 0, { kind: "reasoning" }); + block.thinkingBufBytes = 0; + }; return new ReadableStream({ start(controller) { @@ -296,13 +308,14 @@ export function responsesSseToAnthropicSse( open.webSearchArgsEmitted = true; } if (open.kind === "thinking") { - // Synthetic signature: Claude Code accepts it (003 E6); inbound drops replays anyway. + const signature = open.reasoningSig ?? encodeReasoningEnvelope({ txt: open.thinkingBuf ?? "" }); emit("content_block_delta", { type: "content_block_delta", index: open.index, - delta: { type: "signature_delta", signature: `ocx${Date.now()}` }, + delta: { type: "signature_delta", signature }, }); } emit("content_block_stop", { type: "content_block_stop", index: open.index }); + releaseThinkingBuffer(open); if (open.callId) translatorBudget.closeCall(open.callId); open = null; }; @@ -315,7 +328,7 @@ export function responsesSseToAnthropicSse( ? { type: "text", text: "" } : { type: "thinking", thinking: "", signature: "" }; emit("content_block_start", { type: "content_block_start", index, content_block: contentBlock }); - open = { kind, index }; + open = { kind, index, thinkingBuf: "", thinkingBufBytes: 0 }; }; const finish = (stopReason: string, usage: unknown) => { if (terminated) return; @@ -328,6 +341,7 @@ export function responsesSseToAnthropicSse( usage: anthropicUsage(usage, webSearchRequests), }); emit("message_stop", { type: "message_stop" }); + terminalDelivered = true; }; // upstreamDerived: transient upstream statuses become overloaded_error so the // Anthropic-SDK client retries with backoff; proxy-internal exceptions stay @@ -336,11 +350,15 @@ export function responsesSseToAnthropicSse( // resets reach the reader catch (no failed-tail relay) and stay api_error — // same as today, deliberate residual. const fail = (status: number, message: string, upstreamDerived = false, code?: string) => { - if (terminated) return; + // finish/fail sets terminated before closeOpenBlock. A closure-time + // allocation failure must still emit one error, without retrying closure. + if (terminated && (code !== "translation_buffer_limit" || terminalDelivered)) return; terminated = true; if (code === "translation_buffer_limit") { + releaseThinkingBuffer(open); if (open?.callId) translatorBudget.closeCall(open.callId); open = null; + terminalDelivered = true; // No normal close frames are valid after overflow. Emit exactly one bounded // typed terminal without consulting the exhausted budget. controller.enqueue(encoder.encode(sseFrame("error", anthropicErrorBody( @@ -357,10 +375,12 @@ export function responsesSseToAnthropicSse( // Do not manufacture message_start before the terminal error. Earlier transport-only // pings remain valid and do not turn the failure into a partial message. emit("error", anthropicErrorBody(status, message, type, code)); + terminalDelivered = true; return; } closeOpenBlock(); emit("error", anthropicErrorBody(status, message, type, code)); + terminalDelivered = true; }; const handleFrame = (eventName: string, data: Rec) => { @@ -374,8 +394,10 @@ export function responsesSseToAnthropicSse( case "response.output_text.delta": { if (typeof data.delta !== "string" || data.delta.length === 0) break; ensureBlock("text"); + const active = open; + if (!active || active.kind !== "text") break; emit("content_block_delta", { - type: "content_block_delta", index: open!.index, + type: "content_block_delta", index: active.index, delta: { type: "text_delta", text: data.delta }, }); break; @@ -384,6 +406,8 @@ export function responsesSseToAnthropicSse( case "response.reasoning_text.delta": { if (typeof data.delta !== "string" || data.delta.length === 0) break; ensureBlock("thinking"); + const active = open; + if (!active || active.kind !== "thinking") break; // The JSON path joins reasoning summary/content parts with "\n\n" // (responsesJsonToAnthropicMessage); mirror that at part and item boundaries // so multi-part summaries do not glue into one run-on paragraph. Frames @@ -395,15 +419,32 @@ export function responsesSseToAnthropicSse( // components while retaining item and part equality, rather than dropping item_id and // accidentally joining distinct malformed reasoning items. const partKey = `${boundedReasoningIdentity(data.item_id)}:${slot}`; - if (open!.reasoningPartKey !== undefined && open!.reasoningPartKey !== partKey) { + const needsPartSeparator = active.reasoningPartKey !== undefined + && active.reasoningPartKey !== partKey; + const appended = `${needsPartSeparator ? "\n\n" : ""}${data.delta}`; + const previous = active.thinkingBuf ?? ""; + const previousBytes = active.thinkingBufBytes ?? 0; + const nextBytes = appendedUtf8Bytes(previous, previousBytes, appended); + const scope = { kind: "reasoning" } as const; + const reservation = translatorBudget.reserveTransient(nextBytes, scope); + try { + active.thinkingBuf = previous + appended; + active.thinkingBufBytes = nextBytes; + reservation.commitRetained(); + translatorBudget.releaseRetained(previousBytes, scope); + } catch (error) { + reservation.release(); + throw error; + } + if (needsPartSeparator) { emit("content_block_delta", { - type: "content_block_delta", index: open!.index, + type: "content_block_delta", index: active.index, delta: { type: "thinking_delta", thinking: "\n\n" }, }); } - open!.reasoningPartKey = partKey; + active.reasoningPartKey = partKey; emit("content_block_delta", { - type: "content_block_delta", index: open!.index, + type: "content_block_delta", index: active.index, delta: { type: "thinking_delta", thinking: data.delta }, }); break; @@ -499,10 +540,9 @@ export function responsesSseToAnthropicSse( if (pair.completed) webSearchRequests++; break; } - if (!open) break; // Close the matching open block (message/reasoning items close implicitly on // the next block; function_call items must close here so tool input parses). - if (open.kind === "tool_use" && item.type === "function_call") { + if (open && open.kind === "tool_use" && item.type === "function_call") { if (open.bufferWebSearchArgs && !open.webSearchArgsEmitted) { const rawArgs = typeof item.arguments === "string" && item.arguments.length > 0 ? item.arguments @@ -518,8 +558,26 @@ export function responsesSseToAnthropicSse( } closeOpenBlock(); } - else if (open.kind === "text" && item.type === "message") closeOpenBlock(); - else if (open.kind === "thinking" && item.type === "reasoning") closeOpenBlock(); + else if (open && open.kind === "text" && item.type === "message") closeOpenBlock(); + else if (item.type === "reasoning") { + const encrypted = typeof item.encrypted_content === "string" ? item.encrypted_content : ""; + const env = encrypted ? decodeReasoningEnvelope(encrypted) : null; + const red = env?.red ?? []; + if (env?.sig && open?.kind !== "thinking") ensureBlock("thinking"); + if (open?.kind === "thinking") { + if (env?.sig) open.reasoningSig = env.sig; + closeOpenBlock(); + } + if (red.length > 0) { + ensureStarted(); + closeOpenBlock(); + } + for (const data of red) { + const idx = blockIndex++; + emit("content_block_start", { type: "content_block_start", index: idx, content_block: { type: "redacted_thinking", data } }); + emit("content_block_stop", { type: "content_block_stop", index: idx }); + } + } break; } case "response.completed": { @@ -704,6 +762,7 @@ export function responsesSseToAnthropicSse( fail(413, "upstream translation buffer exceeded the safe limit", false, "translation_buffer_limit"); } else fail(500, err instanceof Error ? err.message : String(err)); } finally { + releaseThinkingBuffer(open); translatorBudget.releaseRetained(bufferBytes, { kind: "live_transient" }); if (pingTimer !== undefined) clearInterval(pingTimer); reader.releaseLock(); @@ -717,6 +776,7 @@ export function responsesSseToAnthropicSse( cancel(reason) { cancelled = true; while (queuedLiveFrameBytes.length > 0) releaseDeliveredFrame(); + releaseThinkingBuffer(open); if (open?.callId) translatorBudget.closeCall(open.callId); if (pingTimer !== undefined) clearInterval(pingTimer); return reader?.cancel(reason); @@ -756,8 +816,15 @@ export function responsesJsonToAnthropicMessage(json: unknown, model: string): R if (isRec(s) && typeof s.text === "string" && s.text.length > 0) parts.push(s.text); } } - if (parts.length > 0) { - content.push({ type: "thinking", thinking: parts.join("\n\n"), signature: `ocx${Date.now()}` }); + const encrypted = typeof raw.encrypted_content === "string" ? raw.encrypted_content : ""; + const env = encrypted ? decodeReasoningEnvelope(encrypted) : null; + // Legacy combined envelopes place redacted blocks before the signed block, + // matching the Anthropic adapter. New bridge output uses separate items. + for (const data of env?.red ?? []) content.push({ type: "redacted_thinking", data }); + // env.txt may be locally hidden text. Do not expose it here or manufacture + // a new signed continuity carrier; hidden-summary replay remains limited. + if (parts.length > 0 || env?.sig) { + content.push({ type: "thinking", thinking: parts.join("\n\n"), signature: env?.sig ?? encodeReasoningEnvelope({ txt: parts.join("\n\n") }) }); } break; } @@ -923,9 +990,10 @@ export async function collectAnthropicMessage( } finally { reader.releaseLock(); } - closeBlock(); - + // Error is authoritative. In particular, do not allocate another copy of an + // unfinished thinking block after the translator reported closure overflow. if (error) return error; + closeBlock(); return { id: `msg_${uuid()}`, type: "message", diff --git a/src/cli/capabilities.ts b/src/cli/capabilities.ts index 1b5cfd6283..ff1f5fb9a2 100644 --- a/src/cli/capabilities.ts +++ b/src/cli/capabilities.ts @@ -148,7 +148,10 @@ export const CAPABILITIES: readonly Capability[] = [ summary: "Configured providers with connectivity and selected models.", // Local config + PROVIDER_REGISTRY. Does not call GET /api/providers. routes: [], - flags: [{ name: "--json", value: "boolean", summary: "Emit the provider list as JSON." }], + flags: [ + { name: "--json", value: "boolean", summary: "Emit the provider list as JSON." }, + { name: "--jsonl", value: "boolean", summary: "Emit one configured provider per JSON line." }, + ], mutates: false, json: "envelope", details: ["Reads local config; drives no management API route."], diff --git a/src/cli/config-command.ts b/src/cli/config-command.ts index cd33fefd74..f69110018b 100644 --- a/src/cli/config-command.ts +++ b/src/cli/config-command.ts @@ -38,6 +38,16 @@ function redact(value: unknown, key = ""): unknown { return value; } +function omitWebhookCredentials(value: unknown): unknown { + if (Array.isArray(value)) return value.map(omitWebhookCredentials); + if (!value || typeof value !== "object") return value; + return Object.fromEntries( + Object.entries(value as Record) + .filter(([key]) => key.toLowerCase() !== "webhookurl") + .map(([key, child]) => [key, omitWebhookCredentials(child)]), + ); +} + function pathSegments(path: string): string[] { const segments = path.split(".").map(part => part.trim()).filter(Boolean); if (segments.length === 0 || segments.some(part => BLOCKED_SEGMENTS.has(part))) throw new CliUsageError("invalid config path", USAGE); @@ -195,7 +205,7 @@ export async function handleConfigCommand(argv: string[]): Promise { const path = args.shift(); if (!path) throw new CliUsageError("export path is required", USAGE); rejectArgs(args, USAGE); - const content = `${JSON.stringify(readConfigDiagnostics().config, null, 2)}\n`; + const content = `${JSON.stringify(omitWebhookCredentials(readConfigDiagnostics().config), null, 2)}\n`; if (path === "-") process.stdout.write(content); else { writeFileSync(path, content, { encoding: "utf8", mode: 0o600 }); console.log(`Exported config to ${path}.`); } return; diff --git a/src/cli/dispatch.ts b/src/cli/dispatch.ts index 6d018536c7..c884bb2e5d 100644 --- a/src/cli/dispatch.ts +++ b/src/cli/dispatch.ts @@ -403,7 +403,7 @@ const commandRunners: Record = { }, config, port: live.port, - }, ["mcode", "pi"])); + }, ["mcode", "pi", "raycast"])); } catch (error) { console.warn(`Client integrations were not refreshed: ${error instanceof Error ? error.message : String(error)}`); } diff --git a/src/cli/doctor.ts b/src/cli/doctor.ts index 1ab4fe9f1b..d7148530a0 100644 --- a/src/cli/doctor.ts +++ b/src/cli/doctor.ts @@ -1157,11 +1157,11 @@ export async function runDoctor(args: string[] = []): Promise { // No extra probe -- findLiveProxy already carried the version back. { const { packageVersion } = await import("./help"); - const { computeVersionSkew } = await import("./version-skew"); + const { computeVersionSkew, isConfirmedVersionMatch } = await import("./version-skew"); const skew = computeVersionSkew(packageVersion(), live?.version); if (skew.skewed && skew.warning) { console.log(`!! ${skew.warning}`); - } else if (skew.proxyVersion !== null) { + } else if (isConfirmedVersionMatch(skew)) { console.log(`ok ocx ${skew.cliVersion} matches the running proxy`); } } diff --git a/src/cli/export-command.ts b/src/cli/export-command.ts index c576435432..739889a026 100644 --- a/src/cli/export-command.ts +++ b/src/cli/export-command.ts @@ -172,17 +172,29 @@ export async function handleExportCommand(argv: string[], deps: ExportCommandDep const spec = EXPORT_CLIENTS[client]; const root = await runtimeBaseUrl(deps); - const rows = await runtimeRequest("/api/models", {}, { ...deps, baseUrl: root }); - if (!Array.isArray(rows)) { - throw new RuntimeApiError("Management API returned an unexpected /api/models payload.", 502, rows); + let built: { document: unknown; text: string }; + if (client === "raycast") { + // The dial address alone cannot distinguish a wildcard authenticated bind + // from loopback. Let the live server resolve its admission/listener policy; + // saved config can differ from the process serving this request. + const exported = await runtimeRequest<{ + client: string; format: string; config: unknown; text: string; + }>("/api/client-config?client=raycast", {}, { ...deps, baseUrl: root }); + if (!exported || exported.client !== "raycast" || exported.format !== "yaml" + || typeof exported.text !== "string" || exported.config === undefined) { + throw new RuntimeApiError("Management API returned an unexpected Raycast export payload.", 502, null); + } + built = { document: exported.config, text: exported.text }; + } else { + const rows = await runtimeRequest("/api/models", {}, { ...deps, baseUrl: root }); + if (!Array.isArray(rows)) { + throw new RuntimeApiError("Management API returned an unexpected /api/models payload.", 502, rows); + } + // Discovery can persist selection; preserve the existing exporters' flow. + const config = (deps.configImpl ?? loadConfig)(); + const models = exportModelsFromProxyRows(rows, config); + built = buildClientConfigText(client, { baseUrl: proxyV1BaseUrl(root), models, config }); } - // Discovery can persist pending -> ready selection. Read from the caller's - // config source after the response, rather than filtering with a stale snapshot. - const config = (deps.configImpl ?? loadConfig)(); - const models = exportModelsFromProxyRows(rows, config); - // The text is the client's OWN format — YAML, TOML and JSON5 clients would - // otherwise receive a JSON rendering their parser reads differently. - const built = buildClientConfigText(client, { baseUrl: proxyV1BaseUrl(root), models, config }); const clientConfig = built.document; const text = built.text; diff --git a/src/cli/help.ts b/src/cli/help.ts index 0b3652ab59..0cd6bec4dc 100644 --- a/src/cli/help.ts +++ b/src/cli/help.ts @@ -77,7 +77,7 @@ Usage: ocx memory [--json] Alias of ocx observe memory ocx api-key Alias of ocx access key ocx access External API keys and endpoint information - ocx export --client Print a client config wired to the running proxy (12 clients) + ocx export --client Print a client config wired to the running proxy (13 clients) ocx integration client Enable, disable, inspect or roll back a client integration ocx grok Grok Build model selection and apply ocx system Runtime settings, startup, sync, OpenCodex updates, and Codex CLI inspection diff --git a/src/cli/index.ts b/src/cli/index.ts index 7b863630b9..663514a120 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -92,6 +92,15 @@ import { grokSyncFailureMessage, reconcileEnsureDesiredIntegrations, } from "./ensure-desired-integrations"; +import { refreshOwnedCatalogIntegrations } from "../integrations/catalog-refresh"; +import { loadExportModels } from "../server/management/model-rows"; + +import { removeOwnedConfigAfterDesktopCleanup } from "./uninstall-client-state"; +import { withProcessRuntimeProvenance } from "../lib/bun-runtime"; +import { selfLaunchArgv } from "../lib/self-launch-argv"; +import { initializeNodeLauncherContext } from "./launcher-context"; +import { createLocalAttestationSecret } from "../lib/local-management-attestation"; +import { MEMORY_DRAIN_RESTART_MS, REPLACEMENT_READY_TIMEOUT_MS } from "../lib/system-restart-contract"; /** * A failed shell-hook reconcile is not cosmetic: a stale hook keeps sourcing @@ -105,13 +114,25 @@ function reportShellHookFailure(result: { state: "installed" | "absent" | "faile console.warn(" Check ~/.zshrc for the '# opencodex claude-env hook' block."); } - -import { removeOwnedConfigAfterDesktopCleanup } from "./uninstall-client-state"; -import { withProcessRuntimeProvenance } from "../lib/bun-runtime"; -import { selfLaunchArgv } from "../lib/self-launch-argv"; -import { initializeNodeLauncherContext } from "./launcher-context"; -import { createLocalAttestationSecret } from "../lib/local-management-attestation"; -import { MEMORY_DRAIN_RESTART_MS, REPLACEMENT_READY_TIMEOUT_MS } from "../lib/system-restart-contract"; +async function refreshOwnedRaycastCatalog( + config: ReturnType, + port: number, +): Promise { + try { + const outcomes = await refreshOwnedCatalogIntegrations({ + models: () => loadExportModels(config), + config, + port, + }, ["raycast"]); + for (const outcome of outcomes) { + if (!outcome.ok) { + console.error(`⚠️ Raycast integration was not refreshed: ${outcome.reason}`); + } + } + } catch (error) { + console.error(`⚠️ Raycast integration was not refreshed: ${error instanceof Error ? error.message : String(error)}`); + } +} initializeNodeLauncherContext(); @@ -493,6 +514,7 @@ async function handleStart(options: { block?: boolean } = {}) { }, ); if (!startupSync.ran) console.log(" Codex integration OFF; startup left Codex native."); + await refreshOwnedRaycastCatalog(config, port); // #1046: one warning per startup, after BOTH writes. The server's cache // invalidation happens first and the catalog sync second, so the mtime is only // final here — and neither write site warns on its own, or a boot that hits @@ -558,6 +580,9 @@ async function handleEnsure(options: { existingIsSuccess?: boolean } = {}): Prom return null; }); if (synced?.status === "skipped") console.log(" Codex integration OFF; startup left Codex native."); + // Do not refresh Raycast from saved config here: live bind/admission and + // secondary-listener settings may differ. Explicit sync or server startup + // owns catalog refresh; ensure must not overwrite a working destination. // Ensure env file exists for already-running proxy (may have been deleted or pre-dates this feature). const systemEnv = await injectSystemEnv(live.port, config).catch(() => ({ injected: false })); reportShellHookFailure(reconcileShellHook(systemEnv.injected)); @@ -602,6 +627,8 @@ async function handleEnsure(options: { existingIsSuccess?: boolean } = {}): Prom return null; }); if (synced?.status === "skipped") console.log(" Codex integration OFF; startup left Codex native."); + // The child performs Raycast refresh with its actual startup config. The + // parent's pre-spawn snapshot is not authoritative for a client-file write. // The child opens /healthz before its best-effort roster reconcile. Await the same idempotent // operation in the parent so `ocx ensure` cannot report success while stale ocx-*.md files are // still observable. Always use the live port, including fallback-port starts. diff --git a/src/cli/integrations.ts b/src/cli/integrations.ts index bcb87d5d18..89ab3ee046 100644 --- a/src/cli/integrations.ts +++ b/src/cli/integrations.ts @@ -161,6 +161,39 @@ export async function handleGrokCommand(argv: string[], deps: RuntimeApiDeps = { }); } +/** The Raycast-only block the single-client route adds; see IntegrationStateEnvelope. */ +interface RaycastStatusBlock { + plan: string; + aiDirPresent: boolean; +} + +function raycastBlock(result: unknown): RaycastStatusBlock | null { + if (!result || typeof result !== "object") return null; + const block = (result as { raycast?: unknown }).raycast; + if (!block || typeof block !== "object") return null; + const { plan, aiDirPresent } = block as Partial; + return typeof plan === "string" && typeof aiDirPresent === "boolean" ? { plan, aiDirPresent } : null; +} + +/** + * Text view of one client's status. + * + * Raycast carries an extra block, and the generic summary would print it as + * three dotted keys. A `current` file that Raycast ignores for want of a Pro + * subscription is the one fact this view must not bury, so `plan` gets its own + * line and a missing `ai` folder gets the instruction that creates it. + */ +function singleClientStatusLines(result: unknown): string[] { + const raycast = raycastBlock(result); + if (!raycast) return summaryLines(result); + const rest = Object.fromEntries(Object.entries(result as Record).filter(([key]) => key !== "raycast")); + const lines = [...summaryLines(rest), `plan: ${raycast.plan}`]; + if (!raycast.aiDirPresent) { + lines.push('Open Raycast → Settings → AI → "Reveal Providers Config" once so the ai folder exists.'); + } + return lines; +} + /** * The headless half of the client-integration toggle. * @@ -197,7 +230,7 @@ export async function handleClientIntegrationCommand( : [String((result as { error?: string }).error ?? "No Aside profiles found.")] : rows ? rows.map(row => `${String(row.clientId)}: ${String(row.state)}${row.installed ? "" : " (not installed)"}`) - : summaryLines(result)); + : singleClientStatusLines(result)); return; } diff --git a/src/cli/provider.ts b/src/cli/provider.ts index 55c654d8d7..47f23fee62 100644 --- a/src/cli/provider.ts +++ b/src/cli/provider.ts @@ -79,26 +79,37 @@ function validateAndSave(config: ReturnType): void { function handleList(args: string[]): void { const wantsJson = consumeFlag(args, "--json"); - rejectUnknownArgs(args, "Usage: ocx provider list [--json]"); + const wantsJsonl = consumeFlag(args, "--jsonl"); + rejectUnknownArgs(args, "Usage: ocx provider list [--json|--jsonl]"); + + if (wantsJson && wantsJsonl) { + console.error("Use only one of --json or --jsonl."); + process.exit(1); + } const config = loadConfig(); const configured = Object.keys(config.providers); + const entries = configured.map(name => { + const prov = config.providers[name]; + const registryEntry = getProviderRegistryEntry(name); + return { + name, + adapter: prov.adapter, + baseUrl: prov.baseUrl, + authMode: prov.authMode ?? "key", + defaultModel: prov.defaultModel ?? null, + isDefault: name === config.defaultProvider, + source: registryEntry ? "registry" : "custom", + models: prov.models ?? [], + }; + }); + + if (wantsJsonl) { + for (const entry of entries) console.log(JSON.stringify(entry)); + return; + } if (wantsJson) { - const entries = configured.map(name => { - const prov = config.providers[name]; - const registryEntry = getProviderRegistryEntry(name); - return { - name, - adapter: prov.adapter, - baseUrl: prov.baseUrl, - authMode: prov.authMode ?? "key", - defaultModel: prov.defaultModel ?? null, - isDefault: name === config.defaultProvider, - source: registryEntry ? "registry" : "custom", - models: prov.models ?? [], - }; - }); console.log(JSON.stringify({ configured: entries, registryCount: PROVIDER_REGISTRY.length }, null, 2)); return; } @@ -444,6 +455,7 @@ Subcommands: Examples: ocx provider list + ocx provider list --jsonl ocx provider add anthropic --api-key sk-ant-... ocx provider add my-ollama --adapter openai-chat --base-url http://localhost:11434/v1 ocx provider show anthropic --json diff --git a/src/cli/registry.ts b/src/cli/registry.ts index 00ff25ed52..467a0f7971 100644 --- a/src/cli/registry.ts +++ b/src/cli/registry.ts @@ -287,8 +287,8 @@ export const CLI_COMMANDS: CliCommandEntry[] = [ { name: "api-key", usage: "ocx api-key ...", summary: "Alias of ocx access key." }, { name: "export", - usage: "ocx export --client [--json] [--out ] [--force]", - summary: "Print a client config (OpenCode, Pi, OMP, Hermes, OpenClaw, Kimi Code, Gajae Code, DeepSeek Harness, MiniMax Code, ZCode, Prime Agent, Aside) wired to the running proxy.", + usage: "ocx export --client [--json] [--out ] [--force]", + summary: "Print a client config (OpenCode, Pi, OMP, Hermes, OpenClaw, Kimi Code, Gajae Code, DeepSeek Harness, MiniMax Code, ZCode, Prime Agent, Aside, Raycast) wired to the running proxy.", details: [ "--json prints the generated document as JSON on stdout; use --out for the client's native format.", "--out writes the native config there and refuses to replace an existing file without --force.", diff --git a/src/cli/version-skew.ts b/src/cli/version-skew.ts index 588d29a307..48b71a51ee 100644 --- a/src/cli/version-skew.ts +++ b/src/cli/version-skew.ts @@ -1,5 +1,5 @@ /** - * CLI-versus-proxy version skew (#2701). + * CLI-versus-proxy version skew (#2701, #3464). * * The reported failure: `ocx` on PATH is an older install than the running proxy, so its * help describes commands the proxy does not have and its output describes a different @@ -9,6 +9,7 @@ * comparison instead of reimplementing it -- two diagnostics disagreeing about whether an * install is stale would be worse than neither reporting it. */ +import { parseStrictSemver, type StrictSemver } from "../lib/strict-semver"; /** Placeholder versions that mean "unknown", not "different". */ const PLACEHOLDERS = new Set(["unknown", "0.0.0"]); @@ -22,6 +23,30 @@ export interface VersionSkew { readonly warning: string | null; } +/** Suppressed comparisons are not confirmed matches, even when both placeholders agree. */ +export function isConfirmedVersionMatch(skew: VersionSkew): boolean { + return skew.proxyVersion === skew.cliVersion && !PLACEHOLDERS.has(skew.cliVersion); +} + +/** SemVer precedence ignores build metadata; raw equality is handled separately. */ +function compareVersions(cli: StrictSemver, proxy: StrictSemver): number { + for (let i = 0; i < cli.core.length; i++) { + if (cli.core[i]! !== proxy.core[i]!) return cli.core[i]! > proxy.core[i]! ? 1 : -1; + } + if (cli.prerelease.length === 0) return proxy.prerelease.length === 0 ? 0 : 1; + if (proxy.prerelease.length === 0) return -1; + for (let i = 0; i < Math.max(cli.prerelease.length, proxy.prerelease.length); i++) { + const left = cli.prerelease[i]; + const right = proxy.prerelease[i]; + if (left === right) continue; + if (left === undefined) return -1; + if (right === undefined) return 1; + if (typeof left !== typeof right) return typeof left === "bigint" ? -1 : 1; + return left > right ? 1 : -1; + } + return 0; +} + /** * Compare the running CLI against the live proxy. * @@ -36,11 +61,19 @@ export function computeVersionSkew(cliVersion: string, proxyVersion: string | un if (proxy === null || PLACEHOLDERS.has(proxy) || PLACEHOLDERS.has(cliVersion) || proxy === cliVersion) { return { cliVersion, proxyVersion: proxy, skewed: false, warning: null }; } + const cliSemver = parseStrictSemver(cliVersion); + const proxySemver = parseStrictSemver(proxy); + const order = cliSemver && proxySemver ? compareVersions(cliSemver, proxySemver) : 0; + const advice = order > 0 + ? "the running proxy is older than this CLI. Restart the proxy using the intended current installation. " + + "For a background service, run ocx service repair (ocx service restart is an alias)." + : order < 0 + ? "this ocx on PATH is older than the running proxy. Upgrade the CLI or resolve PATH to the intended installation." + : "the versions differ, but neither can be identified as older. Check which installations the CLI and proxy use."; return { cliVersion, proxyVersion: proxy, skewed: true, - warning: `CLI ${cliVersion} does not match the running proxy ${proxy} — this ocx on PATH is stale. ` - + "Its help and features describe a different build. Reinstall, or run the proxy's own binary.", + warning: `CLI ${cliVersion} does not match the running proxy ${proxy} — ${advice}`, }; } diff --git a/src/clients/aside-profiles.ts b/src/clients/aside-profiles.ts index 31f13d9b76..770857611a 100644 --- a/src/clients/aside-profiles.ts +++ b/src/clients/aside-profiles.ts @@ -1,4 +1,4 @@ -import { lstatSync, readFileSync, readlinkSync, realpathSync, statSync, type Stats } from "node:fs"; +import { lstatSync, readFileSync, readlinkSync, realpathSync, statSync, type BigIntStats } from "node:fs"; import { homedir } from "node:os"; import { basename, dirname, isAbsolute, join, resolve } from "node:path"; import type { IntegrationIO } from "../integrations/config-io"; @@ -14,7 +14,7 @@ export interface AsideProfile { } const MAX_PROFILES = 128; -const MAX_MANIFEST_BYTES = 4 * 1024 * 1024; +const MAX_MANIFEST_BYTES = 4n * 1024n * 1024n; const MAX_LEAF_LINKS = 40; function refuse(message: string): never { @@ -30,9 +30,10 @@ function object(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); } -function inspect(path: string, follow = false): Stats | null { +function inspect(path: string, follow = false): BigIntStats | null { try { - return follow ? statSync(path) : lstatSync(path); + // File IDs can exceed Number's exact integer range; never round identities. + return follow ? statSync(path, { bigint: true }) : lstatSync(path, { bigint: true }); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; return refuse("a filesystem boundary could not be inspected."); @@ -110,10 +111,10 @@ export function listAsideProfiles(env: NodeJS.ProcessEnv = process.env, home: st return readProfiles(root); } -type DirectoryIdentity = { path: string; dev: number; ino: number }; +type DirectoryIdentity = { path: string; dev: bigint; ino: bigint }; type Boundary = Array; -function sameIdentity(a: Pick, b: Pick): boolean { +function sameIdentity(a: Pick, b: Pick): boolean { return a.dev === b.dev && a.ino === b.ino; } @@ -162,7 +163,7 @@ function boundary(profile: AsideProfile, profiles: AsideProfile[], mutation: boo } if (absent) return identities; const leaf = inspect(profile.configPath); - if (leaf && (leaf.isSymbolicLink() || !leaf.isFile() || leaf.nlink > 1)) { + if (leaf && (leaf.isSymbolicLink() || !leaf.isFile() || leaf.nlink > 1n)) { refuse("the model catalog is a link, shared file or non-regular file."); } if (leaf && canonical(profile.configPath) !== join(parent!, "models.json")) { diff --git a/src/clients/config-export.ts b/src/clients/config-export.ts index 372abcc00e..8fb42f311d 100644 --- a/src/clients/config-export.ts +++ b/src/clients/config-export.ts @@ -37,6 +37,8 @@ export type { OmpModelEntry, OmpProviderBlock, OmpGeneratedConfig } from "./conf export type { ZcodeModelEntry, ZcodeProviderBlock, ZcodeGeneratedConfig } from "./config-export/zcode"; export type { DshReasoningEffort, DshWireReasoningEffort, DshModelEntry, DshProviderBlock, DshGeneratedConfig } from "./config-export/dsh"; export type { McodeProviderBlock, McodeModelEntry, McodeGeneratedConfig } from "./config-export/mcode"; +export type { RaycastAbility, RaycastAbilityName, RaycastModelEntry, RaycastProviderEntry, RaycastGeneratedConfig } from "./config-export/raycast"; +export { buildRaycastClientConfig, summarizeRaycast, buildRaycastContribution } from "./config-export/raycast"; import type { OpencodeLaunchEnv, OpencodeCatalogModel, ExportContext, PiModelEntry, ManagedContribution, ManagedFragment, ExportClientId, ExportClientSpec } from "./config-export/contracts"; import { OPENCODE_API_KEY_ENV_REF, OPENCODE_PROVIDER_BLOCK_DEFAULT_CONFIG, OPENCODE_CONFIG_SCHEMA, OPENCODE_PROVIDER_ID, PI_API_DIALECT, LOOPBACK_API_KEY_PLACEHOLDER, HERMES_API_KEY_ENV_REF, OPENCLAW_API_KEY_ENV_REF, GAJAE_API_KEY_ENV, OPENCODE_API_KEY_ENV, HERMES_API_KEY_ENV, OPENCLAW_API_KEY_ENV } from "./config-export/constants"; @@ -45,6 +47,7 @@ import { buildOmpClientConfig, summarizeOmp, buildOmpContribution } from "./conf import { buildDshClientConfig, summarizeDsh, buildDshContribution } from "./config-export/dsh"; import { buildMcodeClientConfig, summarizeMcode, buildMcodeContribution } from "./config-export/mcode"; import { buildZcodeClientConfig, summarizeZcode, buildZcodeContribution } from "./config-export/zcode"; +import { buildRaycastClientConfig, summarizeRaycast, buildRaycastContribution } from "./config-export/raycast"; @@ -533,6 +536,22 @@ export function asideConfigPath(env: OpencodeLaunchEnv = process.env, home: stri return join(asideAccountDir(env, home), "models.json"); } +/** + * Raycast's Custom Providers directory. Raycast hard-codes + * `~/.config/raycast/ai` on macOS AND Windows: it neither honors + * `XDG_CONFIG_HOME` nor ships a variable of its own that relocates the file, so + * unlike `opencodeGlobalConfigPath` there is no override to mirror and the env + * parameter exists only to keep the resolver signature uniform with the rest. + */ +export function raycastAiDir(_env: OpencodeLaunchEnv = process.env, home: string = homedir()): string { + return join(home, ".config", "raycast", "ai"); +} + +/** The providers file Raycast watches (manual.raycast.com/ai/custom-providers). */ +export function raycastConfigPath(env: OpencodeLaunchEnv = process.env, home: string = homedir()): string { + return join(raycastAiDir(env, home), "providers.yaml"); +} + /** Endpoint plus admission, identical for the V1 `options` and V2 `settings` field. */ function opencodeProviderConnection(baseURL: string, config: OcxConfig): OpencodeProviderConnection { const options: OpencodeProviderConnection = { baseURL }; @@ -1259,6 +1278,23 @@ export const EXPORT_CLIENTS: Record = { // bind would generate a config that 401s. loopbackOnly: true, }, + raycast: { + id: "raycast", + // Not a bare `providers.yaml`: same Downloads-folder collision argument as + // `aside-models.json`. + filename: "raycast-providers.yaml", + destination: env => raycastConfigPath(env), + apiKeyEnv: "", + exportHint: "Raycast reads providers.yaml with no api_keys entry; loopback needs no key.", + build: buildRaycastClientConfig, + format: "yaml", + summarize: summarizeRaycast, + buildContribution: buildRaycastContribution, + // Raycast's provider entry has no header field, and its `api_keys` value + // is read literally (no env interpolation), so the only way to admit a + // remote bind would be a plaintext secret on disk. Refuse instead. + loopbackOnly: true, + }, }; export const EXPORT_CLIENT_IDS: readonly ExportClientId[] = Object.keys(EXPORT_CLIENTS) as ExportClientId[]; diff --git a/src/clients/config-export/contracts.ts b/src/clients/config-export/contracts.ts index 039d7eaaf0..c888a4c257 100644 --- a/src/clients/config-export/contracts.ts +++ b/src/clients/config-export/contracts.ts @@ -93,7 +93,8 @@ export type ExportClientId = | "mcode" | "zcode" | "prime" - | "aside"; + | "aside" + | "raycast"; export interface ExportClientSpec { id: ExportClientId; diff --git a/src/clients/config-export/raycast.ts b/src/clients/config-export/raycast.ts new file mode 100644 index 0000000000..91d3e43caf --- /dev/null +++ b/src/clients/config-export/raycast.ts @@ -0,0 +1,106 @@ +import { exportPresentationLabel } from "../model-presentation"; +import { OPENCODE_PROVIDER_ID } from "./constants"; +import type { ExportContext, ManagedContribution } from "./contracts"; +import { authoritativeContextWindow, normalizeExportModels, singleFragment } from "./model-metadata"; + +export interface RaycastAbility { + supported: boolean; +} + +export type RaycastAbilityName = + | "temperature" + | "vision" + | "system_message" + | "tools" + | "reasoning_effort"; + +export interface RaycastModelEntry { + id: string; + name: string; + context?: number; + abilities: Record; +} + +export interface RaycastProviderEntry { + id: string; + name: string; + base_url: string; + models: RaycastModelEntry[]; +} + +export interface RaycastGeneratedConfig { + providers: RaycastProviderEntry[]; +} + +/** + * Raycast appends `/chat/completions` to `base_url`, so the proxy's `/v1` + * root is passed through unchanged. The format has no safe credential + * interpolation, which is why the registry exposes it only on loopback. + */ +export function buildRaycastClientConfig(ctx: ExportContext): RaycastGeneratedConfig { + const models: RaycastModelEntry[] = normalizeExportModels(ctx.models).map(model => { + const hasLadder = (model.reasoningEfforts?.length ?? 0) > 0; + const context = authoritativeContextWindow(model.contextWindow); + return { + id: model.namespaced, + name: exportPresentationLabel(model), + ...(context !== undefined ? { context } : {}), + abilities: { + temperature: { supported: !hasLadder }, + vision: { supported: model.inputModalities?.includes("image") ?? false }, + system_message: { supported: true }, + // Existing client-export convention, not a verified per-model capability: + // ExportModel has no authoritative tool-support field. + tools: { supported: true }, + reasoning_effort: { supported: hasLadder }, + }, + }; + }); + return { + providers: [ + { id: OPENCODE_PROVIDER_ID, name: "OpenCodex", base_url: ctx.baseUrl, models }, + ], + }; +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +export function summarizeRaycast( + document: unknown, +): { modelCount: number; modelsWithoutLimits: number } { + const empty = { modelCount: 0, modelsWithoutLimits: 0 }; + if (!isRecord(document) || !Array.isArray(document.providers)) return empty; + const providers = document.providers.filter( + provider => isRecord(provider) && provider.id === OPENCODE_PROVIDER_ID, + ); + // An ambiguous managed provider has no meaningful summary either. + if (providers.length !== 1) return empty; + const provider: unknown = providers[0]; + if (!isRecord(provider) || !Array.isArray(provider.models)) return empty; + const models = provider.models.filter((model): model is Record => ( + isRecord(model) + && typeof model.id === "string" && model.id.trim().length > 0 + && typeof model.name === "string" && model.name.trim().length > 0 + )); + return { + modelCount: models.length, + modelsWithoutLimits: models.filter(model => ( + typeof model.context !== "number" || authoritativeContextWindow(model.context) === undefined + )).length, + }; +} + +/** + * Raycast stores providers in a sequence. The stable id selector owns only + * OpenCodex's element, preserving user-defined providers around it. + */ +export function buildRaycastContribution(ctx: ExportContext): ManagedContribution { + const doc = buildRaycastClientConfig(ctx); + return singleFragment( + "raycast", + ["providers", `[id=${OPENCODE_PROVIDER_ID}]`], + doc.providers[0]!, + ); +} diff --git a/src/clients/model-presentation.ts b/src/clients/model-presentation.ts new file mode 100644 index 0000000000..9a5f9ae3c3 --- /dev/null +++ b/src/clients/model-presentation.ts @@ -0,0 +1,61 @@ +import { CURSOR_CAPABILITIES } from "../adapters/cursor/catalog"; +import { nativeOpenAiCapabilityDisplayName } from "../codex/catalog/metadata"; +import type { ExportModel } from "./config-export/contracts"; + +const KNOWN_ACRONYMS = new Set(["gpt", "glm", "grok"]); + +function titleWord(word: string): string { + const lower = word.toLowerCase(); + if (KNOWN_ACRONYMS.has(lower)) return lower.toUpperCase(); + if (/^\d+\.\d+$/.test(word)) return word; + return lower.charAt(0).toUpperCase() + lower.slice(1); +} + +/** + * Last-resort label when no catalog or operator name exists. Joins dotted version + * tails (`5-1` → `5.1`, `2-5` → `2.5`) so Raycast reads like a product name + * instead of a slug. + */ +function humanizeModelSlug(modelId: string): string { + const parts = modelId.split("-"); + const words: string[] = []; + for (let index = 0; index < parts.length; index += 1) { + const part = parts[index]!; + const next = parts[index + 1]; + if (/^\d+$/.test(part) && next !== undefined && /^\d+$/.test(next)) { + words.push(`${part}.${next}`); + index += 1; + continue; + } + words.push(part); + } + return words.map(titleWord).join(" "); +} + +function wireModelId(model: ExportModel): string { + if (model.id?.trim()) return model.id.trim(); + const slash = model.namespaced.lastIndexOf("/"); + return slash >= 0 ? model.namespaced.slice(slash + 1) : model.namespaced; +} + +/** + * Human-facing model label for clients whose picker shows `name` verbatim. + * + * Raycast has no second column for provider, so the shared `exportModelLabel` + * suffix `(anthropic)` would be noise — and its fallback is the raw wire id + * because management slugs are deliberately withheld from ExportModel. Resolve + * operator labels first, then the canonical capability tables, then a slug + * humanizer. + */ +export function exportPresentationLabel(model: ExportModel): string { + const configured = model.displayName?.trim(); + if (configured) return configured; + const wireId = wireModelId(model); + const fromCursor = CURSOR_CAPABILITIES[wireId]?.displayName; + if (fromCursor) return fromCursor; + if (model.native) { + const native = nativeOpenAiCapabilityDisplayName(wireId); + if (native) return native; + } + return humanizeModelSlug(wireId); +} diff --git a/src/codex/catalog/sync.ts b/src/codex/catalog/sync.ts index 22d235dbcc..972b6d74c6 100644 --- a/src/codex/catalog/sync.ts +++ b/src/codex/catalog/sync.ts @@ -307,6 +307,11 @@ function routedDisplayName(slug: string, model?: CatalogModel, config?: Pick; + if (recoverableNativeSlug(entry) === label.slug + && typeof label.original === "string" && entry.display_name === label.applied) { + entry.display_name = label.original; + } + } + return entry; +} + /** Append missing supported native rows from trusted catalog sources only. */ export function mergeCatalogModelsWithNativeRecovery( primaryCatalogModels: readonly RawEntry[], @@ -862,6 +882,8 @@ export interface ObservedCatalogMergeInput { readonly suppressedBareNativeSlugs?: ReadonlySet; readonly policy: ObservedCatalogMergePolicy; readonly openaiContextCap?: NativeContextLimitsInput; + /** Exact display-only labels for bare native OpenAI models. */ + readonly nativeDisplayNames?: Readonly>; } /** @@ -896,12 +918,14 @@ export function mergeCatalogEntriesFromObservedState({ suppressedBareNativeSlugs = new Set(), policy, openaiContextCap, + nativeDisplayNames, }: ObservedCatalogMergeInput): RawEntry[] { // Raw catalog rows contain nested arrays/objects that normalization mutates. Detach every row at // the observed-core boundary so callers can safely retain evidence objects or repeat the merge. - const detachedCatalogModels = catalogModels.map(entry => structuredClone(entry) as RawEntry); + const detachedCatalogModels = catalogModels + .map(entry => restoreNativeDisplayName(structuredClone(entry) as RawEntry)); const detachedBaselineCatalogModels = baselineCatalogModels - .map(entry => structuredClone(entry) as RawEntry); + .map(entry => restoreNativeDisplayName(structuredClone(entry) as RawEntry)); const detachedRoutedEntries = routedEntries.map(entry => structuredClone(entry) as RawEntry); // Track this invocation's generated custom rows, not ownership markers read from disk. // Their builder already finalized exact native ladders and ordinary routed mock tiers. @@ -1256,6 +1280,17 @@ export function mergeCatalogEntriesFromObservedState({ ); applyFullModelPickerOrder(versionedEntries, modelPickerOrder); for (const entry of versionedEntries) { + // Templates and account clones must not inherit the native row's overlay marker. + delete entry.opencodex_native_display_name; + const slug = recoverableNativeSlug(entry); + if (slug !== null) { + const label = nativeDisplayNames && Object.hasOwn(nativeDisplayNames, slug) + ? nativeDisplayNames[slug]?.trim() : undefined; + if (label && label !== entry.display_name) { + entry.opencodex_native_display_name = { slug, original: entry.display_name, applied: label }; + entry.display_name = label; + } + } const kind = entry.opencodex_catalog_kind; if (trustedAccountBoundNativeCatalogSlug(entry) === undefined && kind !== CODEX_CUSTOM_MODEL_CATALOG_KIND @@ -1659,6 +1694,12 @@ export function finalizeAutoReviewModelOverride( return applyAutoReviewModelOverride(models, readConfiguredAutoReviewModel(), sourceModels); } +/** + * Mescla o catálogo retido com os modelos visíveis e as configurações atuais, + * incluindo os nomes nativos. Tenta preservar o backup original e usa a permissão + * de escrita para publicar o resultado apenas se os bytes mudarem, retornando + * a contagem de entradas roteadas e por conta, o caminho e o estado da gravação. + */ function writeRetainedCatalogSync({ config, goModels, @@ -1880,6 +1921,7 @@ function writeRetainedCatalogSync({ accountBoundEntries, suppressedBareNativeSlugs, openaiContextCap, + nativeDisplayNames: config.providers[OPENAI_CODEX_PROVIDER_ID]?.modelDisplayNames, policy: { ...CANONICAL_NATIVE_CATALOG_CONTENT_POLICY, nativeBackfillSlugs: [...availableBareNativeSlugs, ...observedNativeSlugs], diff --git a/src/codex/convergence.ts b/src/codex/convergence.ts index 8b30bb9eb2..2b8a8512c6 100644 --- a/src/codex/convergence.ts +++ b/src/codex/convergence.ts @@ -226,6 +226,12 @@ function bindGatherPaths( }; } +/** + * Prepara um candidato de catálogo para convergência sem gravá-lo em disco. + * Clona a fonte e mescla as observações nativas, os modelos roteados e por conta, + * aplicando a configuração, inclusive nomes nativos, e os limites de raciocínio + * observados no runtime antes de retornar o catálogo resultante. + */ function prepareCatalog( config: Readonly, source: Extract, @@ -366,6 +372,7 @@ function prepareCatalog( accountBoundEntries, suppressedBareNativeSlugs, openaiContextCap, + nativeDisplayNames: config.providers[OPENAI_CODEX_PROVIDER_ID]?.modelDisplayNames, policy: { ...CANONICAL_NATIVE_CATALOG_CONTENT_POLICY, nativeBackfillSlugs: [...availableBareNativeSlugs, ...observedNativeSlugs], diff --git a/src/generated/model-metadata.ts b/src/generated/model-metadata.ts index 662cf6f1a7..7220aa7509 100644 --- a/src/generated/model-metadata.ts +++ b/src/generated/model-metadata.ts @@ -31,6 +31,7 @@ const PROVIDER_ALIASES: Record = { "moonshot": "moonshot", "zhipu-bigmodel": "zai", "zhipu-bigmodel-coding": "zai", + "zhipu-bigmodel-responses": "zai", "minimax": "minimax", "minimax-cn": "minimax" } as const; diff --git a/src/images/loop.ts b/src/images/loop.ts index e3a7f8252f..7d4855f91b 100644 --- a/src/images/loop.ts +++ b/src/images/loop.ts @@ -263,8 +263,16 @@ export interface ImageBridgeDeps { * Optional 429 failover for the routed (non-xAI) model. Return a rebuilt adapter for the * rotated credential, or null when the pool is exhausted. Async hooks support OAuth refresh; * existing synchronous key-pool hooks remain valid. + * + * `responseHeaders` carries the whole refusal, not just Retry-After, because an Anthropic + * 429 states the window's reset epoch even when it omits Retry-After -- and a rotation that + * cannot see it cools the drained account for the short default instead of until the window + * actually reopens. Optional so existing callers keep compiling. */ - on429?: (retryAfterHeader: string | null) => ProviderAdapter | null | Promise; + on429?: ( + retryAfterHeader: string | null, + responseHeaders?: Headers, + ) => ProviderAdapter | null | Promise; /** Opt-in same-target 429 policy (key-auth providers). When present, 429 replays on the SAME key before on429 rotation. */ retryOn429Policy?: Required | null; /** Called when the bridged Responses stream completes (parity with runTurn / routed paths). */ @@ -579,7 +587,7 @@ export async function runWithImageBridge(deps: ImageBridgeDeps): Promise {}); } catch { /* already closed */ } adapter = rotated; diff --git a/src/integrations/catalog-refresh.ts b/src/integrations/catalog-refresh.ts index 8efb990002..8b89762f30 100644 --- a/src/integrations/catalog-refresh.ts +++ b/src/integrations/catalog-refresh.ts @@ -10,7 +10,7 @@ import { /** Refresh only previously connected clients; a refused file never blocks its peers. */ export async function refreshOwnedCatalogIntegrations( input: Omit, - clientIds: readonly IntegrationClientId[] = ["pi", "aside"], + clientIds: readonly IntegrationClientId[] = ["pi", "aside", "raycast"], ): Promise { let models: Promise | undefined; const loadModels = () => models ??= Promise.resolve().then(() => diff --git a/src/integrations/merge.ts b/src/integrations/merge.ts index 4dccd48e50..ab2099b424 100644 --- a/src/integrations/merge.ts +++ b/src/integrations/merge.ts @@ -20,18 +20,103 @@ function clone(value: T): T { return value === undefined ? value : (JSON.parse(JSON.stringify(value)) as T); } -/** Write `value` at `path`, creating intermediate objects. Returns a new document. */ +/** + * `[field=value]` addresses the ONE element of a sequence whose `field` equals + * `value`. Raycast keeps its providers as a YAML list, so the element is the + * smallest thing we can own there; an index would move under us the moment + * the user reordered their own entries. Any other segment is a plain key. + */ +const ARRAY_SELECTOR = /^\[([A-Za-z_][A-Za-z0-9_]*)=([^\]]+)\]$/u; + +export type PathSegment = + | { kind: "key"; key: string } + | { kind: "select"; field: string; value: string }; + +export function parseSegment(raw: string): PathSegment { + const match = ARRAY_SELECTOR.exec(raw); + if (!match) return { kind: "key", key: raw }; + return { kind: "select", field: match[1]!, value: match[2]! }; +} + +/** + * Thrown when a selector matches more than one element. Picking either one + * would silently rewrite an entry the user may have written; the writer maps + * this to an `unsafe` refusal instead. + */ +export class AmbiguousSelectorError extends Error { + constructor(field: string, value: string) { + super(`more than one entry has ${field}=${value}`); + this.name = "AmbiguousSelectorError"; + } +} + +/** The index of the element a selector names, -1 when none matches. */ +export function selectIndex(items: readonly unknown[], field: string, value: string): number { + const matches: number[] = []; + items.forEach((item, index) => { + if (isPlainRecord(item) && item[field] === value) matches.push(index); + }); + if (matches.length > 1) throw new AmbiguousSelectorError(field, value); + return matches[0] ?? -1; +} + +function assertNever(segment: never): never { + throw new Error(`unknown path segment ${JSON.stringify(segment)}`); +} + +/** + * Write `value` at `path`, creating intermediate containers. Returns a new document. + * + * A `key` segment descends through a record, creating `{}` where the slot is + * absent or holds something else. A `select` segment descends through an + * array the same way, creating `[]`; a missing element is pushed, a matching + * one is replaced in place so the user's ordering survives. + */ export function setPath(doc: unknown, path: readonly string[], value: unknown): unknown { if (path.length === 0) throw new Error("setPath needs a non-empty path"); - const root: Record = isPlainRecord(doc) ? clone(doc) : {}; - let cursor = root; - for (const key of path.slice(0, -1)) { - const next = cursor[key]; - if (!isPlainRecord(next)) cursor[key] = {}; - cursor = cursor[key] as Record; + /* + * `parent[slot]` is the position the segment just consumed addresses. The + * root sits in a one-key holder so the first segment needs no special case: + * a non-record document is replaced by `{}` exactly as before. + */ + const holder: Record = { root: isPlainRecord(doc) ? clone(doc) : {} }; + let parent: Record | unknown[] = holder; + let slot: string | number = "root"; + const read = (): unknown => (Array.isArray(parent) ? parent[slot as number] : parent[slot as string]); + const write = (next: unknown): void => { + if (Array.isArray(parent)) parent[slot as number] = next; + else parent[slot as string] = next; + }; + for (const raw of path) { + const segment = parseSegment(raw); + switch (segment.kind) { + case "key": { + if (!isPlainRecord(read())) write({}); + parent = read() as Record; + slot = segment.key; + break; + } + case "select": { + if (!Array.isArray(read())) write([]); + const items = read() as unknown[]; + const found = selectIndex(items, segment.field, segment.value); + parent = items; + if (found >= 0) { + slot = found; + } else { + // Seed the element so the selector stays true for whatever a deeper + // segment writes into it; a last-position select replaces it whole. + slot = items.length; + items.push({ [segment.field]: segment.value }); + } + break; + } + default: + return assertNever(segment); + } } - cursor[path[path.length - 1]!] = clone(value); - return root; + write(clone(value)); + return holder.root; } /** @@ -54,27 +139,53 @@ export function deletePath( ): { doc: unknown; removed: boolean } { if (!isPlainRecord(doc) || path.length === 0) return { doc, removed: false }; const root = clone(doc) as Record; - const chain: Record[] = [root]; - let cursor: Record = root; - for (const key of path.slice(0, -1)) { - const next = cursor[key]; - if (!isPlainRecord(next)) return { doc: root, removed: false }; - cursor = next; - chain.push(cursor); + // `chain[i]` is the container segment `i` is resolved against; `slots[i]` is + // the key or index it resolved to, so the prune walk can delete by position. + const chain: (Record | unknown[])[] = [root]; + const slots: (string | number)[] = []; + for (let depth = 0; depth < path.length; depth += 1) { + const container = chain[depth]!; + const segment = parseSegment(path[depth]!); + switch (segment.kind) { + case "key": { + if (Array.isArray(container) || !(segment.key in container)) return { doc: root, removed: false }; + slots.push(segment.key); + chain.push(container[segment.key] as Record | unknown[]); + break; + } + case "select": { + if (!Array.isArray(container)) return { doc: root, removed: false }; + const found = selectIndex(container, segment.field, segment.value); + if (found < 0) return { doc: root, removed: false }; + slots.push(found); + chain.push(container[found] as Record | unknown[]); + break; + } + default: + return assertNever(segment); + } + // Only the leaf may be a scalar; walking into one means the path is absent. + if (depth < path.length - 1) { + const next = chain[depth + 1]; + if (!isPlainRecord(next) && !Array.isArray(next)) return { doc: root, removed: false }; + } } - const leaf = path[path.length - 1]!; - if (!(leaf in cursor)) return { doc: root, removed: false }; - delete cursor[leaf]; + const remove = (container: Record | unknown[], slot: string | number): void => { + if (Array.isArray(container)) container.splice(slot as number, 1); + else delete container[slot as string]; + }; + remove(chain[path.length - 1]!, slots[path.length - 1]!); /* * Walk back up, pruning only containers this deletion emptied AND that we * created. The root is never pruned. */ - for (let index = chain.length - 1; index >= 1; index -= 1) { + for (let index = path.length - 1; index >= 1; index -= 1) { const container = chain[index]!; - if (Object.keys(container).length > 0) break; + const empty = Array.isArray(container) ? container.length === 0 : Object.keys(container).length === 0; + if (!empty) break; const containerPath = path.slice(0, index).join("\u0000"); if (!createdContainers.has(containerPath)) break; - delete chain[index - 1]![path[index - 1]!]; + remove(chain[index - 1]!, slots[index - 1]!); } return { doc: root, removed: true }; } @@ -121,9 +232,31 @@ export function createdContainerPaths( for (const fragment of contribution.fragments) { let cursor: unknown = doc; for (let depth = 0; depth < fragment.path.length - 1; depth += 1) { - const key = fragment.path[depth]!; - const next = isPlainRecord(cursor) ? cursor[key] : undefined; - if (!isPlainRecord(next)) { + const segment = parseSegment(fragment.path[depth]!); + let next: unknown; + switch (segment.kind) { + case "key": { + /* + * The container this key must hold is whatever the NEXT segment + * descends into: an array when that is a selector, a record + * otherwise. Either one is ours to create when absent. + */ + const nextSegment = parseSegment(fragment.path[depth + 1]!); + next = isPlainRecord(cursor) ? cursor[segment.key] : undefined; + if (nextSegment.kind === "select" ? !Array.isArray(next) : !isPlainRecord(next)) next = undefined; + break; + } + case "select": { + // A selector that matches nothing means setPath will push the element. + next = Array.isArray(cursor) + ? cursor[selectIndex(cursor, segment.field, segment.value)] + : undefined; + break; + } + default: + return assertNever(segment); + } + if (next === undefined) { created.add(fragment.path.slice(0, depth + 1).join("\u0000")); cursor = undefined; continue; diff --git a/src/integrations/raycast-detect.ts b/src/integrations/raycast-detect.ts new file mode 100644 index 0000000000..7ae70edf46 --- /dev/null +++ b/src/integrations/raycast-detect.ts @@ -0,0 +1,111 @@ +/** + * Detect a Raycast install and whether Custom Providers can take effect. + * + * Custom Providers is a Raycast Pro feature: Raycast reads + * `~/.config/raycast/ai/providers.yaml` only while a subscription is active, and + * the `ai` directory itself only exists once the user has clicked "Reveal + * Providers Config" in Settings > AI. Neither fact stops the writer — the plan + * (devlog/_plan/260904_raycast_integration/000_plan.md) makes a free plan a + * WARNING, never a refusal — so this module only answers what status and the + * GUI need to explain a file that is written but ignored. + * + * Detection is read-only and injectable, like cursor-detect.ts: nothing here + * writes to the Raycast install or its preferences, and the tests run against + * stubbed deps rather than the machine they execute on. + */ +import { existsSync } from "node:fs"; +import { homedir } from "node:os"; +import { posix, win32 } from "node:path"; + +export type RaycastPlan = "pro" | "free" | "unknown"; + +export interface RaycastInstall { + /** The app bundle or install directory, or null when none of the well-known locations exist. */ + appPath: string | null; + /** `~/.config/raycast/ai` exists — the install signal the registry uses. */ + aiDirPresent: boolean; + plan: RaycastPlan; +} + +export interface RaycastDetectDeps { + platform: string; + homedir: string; + env: Record; + exists(path: string): boolean; + /** stdout of `defaults read ` trimmed, or null when the command fails / is unavailable. */ + readDefault(domain: string, key: string): string | null; +} + +/** + * A private preference used only as an advisory subscription hint, not an + * entitlement API or a condition for writes. Read through + * `defaults` rather than by parsing the plist: cfprefsd caches writes, so the + * file on disk can lag what the running app believes. + */ +const RAYCAST_DEFAULTS_DOMAIN = "com.raycast.macos.v1"; +const RAYCAST_SUBSCRIPTION_KEY = "subscriptions_active"; + +export function realRaycastDetectDeps(): RaycastDetectDeps { + return { + platform: process.platform, + homedir: homedir(), + env: process.env, + exists: path => { + try { + return existsSync(path); + } catch { + return false; + } + }, + readDefault: (domain, key) => { + // `defaults` is macOS-only; elsewhere the plan is simply unknown. + if (process.platform !== "darwin") return null; + try { + const result = Bun.spawnSync(["defaults", "read", domain, key], { stdout: "pipe", stderr: "pipe" }); + if (result.exitCode !== 0) return null; + return result.stdout.toString().trim(); + } catch { + return null; + } + }, + }; +} + +function appPathFor(deps: RaycastDetectDeps): string | null { + // Join with the target platform's separator so a test describing another OS + // gets that OS's paths, not the host's. + const { join } = deps.platform === "win32" ? win32 : posix; + if (deps.platform === "darwin") { + for (const candidate of ["/Applications/Raycast.app", join(deps.homedir, "Applications", "Raycast.app")]) { + if (deps.exists(candidate)) return candidate; + } + return null; + } + if (deps.platform === "win32") { + const local = deps.env.LOCALAPPDATA; + if (!local) return null; + const candidate = join(local, "Programs", "Raycast"); + return deps.exists(candidate) ? candidate : null; + } + return null; +} + +function planFor(deps: RaycastDetectDeps): RaycastPlan { + if (deps.platform !== "darwin") return "unknown"; + // Read once: `defaults` spawns a process, and the answer cannot change + // between two reads inside one detection. + const value = deps.readDefault(RAYCAST_DEFAULTS_DOMAIN, RAYCAST_SUBSCRIPTION_KEY); + if (value === "1") return "pro"; + if (value === "0") return "free"; + return "unknown"; +} + +export function detectRaycast(deps: RaycastDetectDeps = realRaycastDetectDeps()): RaycastInstall { + const { join } = deps.platform === "win32" ? win32 : posix; + return { + appPath: appPathFor(deps), + // Raycast ignores XDG and uses this path on every platform it ships on. + aiDirPresent: deps.exists(join(deps.homedir, ".config", "raycast", "ai")), + plan: planFor(deps), + }; +} diff --git a/src/integrations/registry.ts b/src/integrations/registry.ts index 13662d52d5..f5780f4f98 100644 --- a/src/integrations/registry.ts +++ b/src/integrations/registry.ts @@ -35,6 +35,8 @@ import { piConfigPath, primeAgentDir, primeConfigPath, + raycastAiDir, + raycastConfigPath, zcodeConfigPath, zcodeHomeDir, type ExportClientId, @@ -261,6 +263,22 @@ export const INTEGRATION_CLIENTS: Record join(asideHomeDir(env, home), "u"), }, + raycast: { + id: "raycast", + configPath: (env = process.env, home = homedir()) => raycastConfigPath(env, home), + /* + * The `ai` directory, not `Raycast.app`. Raycast creates it only when the + * user clicks "Reveal Providers Config" in Settings > AI, which is exactly + * the signal that Custom Providers is reachable on this install; an app + * bundle alone says nothing about the plan or the feature. + * + * No `sourcePreservingYaml`: that patcher handles block-map leaves only, + * and our entry is a SEQUENCE item, so the file is re-rendered through + * `renderYaml` (block style). The `[id=opencodex]` selector keeps the user's + * other providers in place across that re-render. + */ + detectDir: (env = process.env, home = homedir()) => raycastAiDir(env, home), + }, }; export const INTEGRATION_CLIENT_IDS: readonly IntegrationClientId[] = diff --git a/src/integrations/state.ts b/src/integrations/state.ts index 008f46fbf1..0249987027 100644 --- a/src/integrations/state.ts +++ b/src/integrations/state.ts @@ -12,6 +12,7 @@ import { ClientPathError, EXPORT_CLIENTS, opencodeProxyBaseUrl, type ExportModel import type { OcxConfig } from "../types"; import { PARSE_FAILED, loadTarget, parseConfig, type IntegrationIO } from "./config-io"; import { SNAPSHOT_RETENTION } from "./journal"; +import { AmbiguousSelectorError, parseSegment, selectIndex, type PathSegment } from "./merge"; import { canonicalContribution, fingerprint, semanticContribution, type OwnershipRecord } from "./ownership"; import { protectedContributionFingerprint, @@ -35,6 +36,7 @@ export type StateReason = | "unowned-key" /** A container we would have to write through holds a non-object value. */ | "blocked-container" + | "ambiguous-selector" /** A path selector we cannot resolve, e.g. a relative OPENCLAW_CONFIG_PATH. */ | "unresolvable-path"; @@ -52,11 +54,41 @@ export interface IntegrationStatus { retentionDegraded: boolean; } +function isPlainRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function assertNever(segment: never): never { + throw new Error(`unknown path segment ${JSON.stringify(segment)}`); +} + +/** The element a selector names, or `undefined` when none matches. */ +function selectElement(items: readonly unknown[], segment: PathSegment & { kind: "select" }): unknown { + return items[selectIndex(items, segment.field, segment.value)]; +} + +/** + * Same segment grammar as `setPath`: a plain key reads through a record, a + * `[field=value]` selector reads through an array. Because the classifier and + * the writer share this one function, status and mutation cannot disagree + * about which element is ours. + */ export function readPath(doc: unknown, path: readonly string[]): unknown { let cursor: unknown = doc; - for (const key of path) { - if (typeof cursor !== "object" || cursor === null || Array.isArray(cursor)) return undefined; - cursor = (cursor as Record)[key]; + for (const raw of path) { + const segment = parseSegment(raw); + switch (segment.kind) { + case "key": + if (!isPlainRecord(cursor)) return undefined; + cursor = cursor[segment.key]; + break; + case "select": + if (!Array.isArray(cursor)) return undefined; + cursor = selectElement(cursor, segment); + break; + default: + return assertNever(segment); + } if (cursor === undefined) return undefined; } return cursor; @@ -82,10 +114,35 @@ export function blockedContainerPath( doc: unknown, contribution: ManagedContribution, ): readonly string[] | null { + /* + * What a segment needs the value it walks through to BE: a record for a key, + * an array for a selector. `typeof null === "object"`, so null is excluded + * by both checks rather than walking straight into the dereference below. + */ + const holds = (segment: PathSegment, value: unknown): boolean => { + switch (segment.kind) { + case "key": + return isPlainRecord(value); + case "select": + return Array.isArray(value); + default: + return assertNever(segment); + } + }; + const step = (segment: PathSegment, value: unknown): unknown => { + switch (segment.kind) { + case "key": + return (value as Record)[segment.key]; + case "select": + return selectElement(value as readonly unknown[], segment); + default: + return assertNever(segment); + } + }; for (const fragment of contribution.fragments) { let cursor: unknown = doc; for (let depth = 0; depth < fragment.path.length - 1; depth += 1) { - const key = fragment.path[depth]!; + const segment = parseSegment(fragment.path[depth]!); /* * ONLY `undefined` means absent. A missing file parses as `{}`, so an * absent prefix reads `undefined` — but a parsed `null` is a value the @@ -94,14 +151,10 @@ export function blockedContainerPath( * "successful" apply. */ if (cursor === undefined) break; - // `typeof null === "object"`, so null has to be named explicitly or it - // walks straight into the dereference below. - if (cursor === null || typeof cursor !== "object" || Array.isArray(cursor)) { - return fragment.path.slice(0, depth); - } - const next = (cursor as Record)[key]; + if (!holds(segment, cursor)) return fragment.path.slice(0, depth); + const next = step(segment, cursor); if (next === undefined) break; - if (typeof next !== "object" || next === null || Array.isArray(next)) { + if (!holds(parseSegment(fragment.path[depth + 1]!), next)) { return fragment.path.slice(0, depth + 1); } cursor = next; @@ -239,8 +292,24 @@ export function classifyIntegration(input: { * Checked BEFORE `absent`: our leaf is missing in exactly this case, so the * absent branch would authorize an apply that replaces the user's value. */ - if (blockedContainerPath(input.parsed, input.contribution)) { - return { state: "unsafe", reason: "blocked-container" }; + try { + if (blockedContainerPath(input.parsed, input.contribution)) { + return { state: "unsafe", reason: "blocked-container" }; + } + // Check every selector before presence/fingerprint short-circuits, including + // paths an older ownership record may remove during refresh or disable. + const paths = [ + ...input.contribution.fragments.map(fragment => fragment.path), + ...(input.record?.fragmentPaths ?? []), + ]; + for (const path of paths) { + if (Array.isArray(path) && path.every(key => typeof key === "string")) { + readPath(input.parsed, path); + } + } + } catch (error) { + if (!(error instanceof AmbiguousSelectorError)) throw error; + return { state: "unsafe", reason: "ambiguous-selector" }; } if (!hasOurFragments(input.parsed, input.contribution)) return { state: "absent" }; diff --git a/src/integrations/writer.ts b/src/integrations/writer.ts index 23b3eaaad4..514fbc3220 100644 --- a/src/integrations/writer.ts +++ b/src/integrations/writer.ts @@ -27,7 +27,7 @@ import { refreshablePathsOf, semanticProtectedContributionFingerprint, } from "./ownership-policy"; -import { createdContainerPaths, mergeContribution, removeFragments } from "./merge"; +import { AmbiguousSelectorError, createdContainerPaths, mergeContribution, removeFragments } from "./merge"; import { INTEGRATION_CLIENTS, isLoopbackOnly, resolveIntegrationPaths, type IntegrationClientId } from "./registry"; import { classifyIntegration, exportContextOf } from "./state"; import type { IntegrationState } from "./state"; @@ -321,7 +321,9 @@ function applyOrRefreshIntegration( return refuse(clientId, "unsafe", "unsafe", classified.reason === "blocked-container" ? `${configPath} holds a value where opencodex would have to write a section, so applying would replace it` - : `${configPath} cannot be changed safely`); + : classified.reason === "ambiguous-selector" + ? `${configPath} has more than one entry matching a managed selector` + : `${configPath} cannot be changed safely`); } /* * An implicit catalog sync is refresh-only. Keeping this decision inside the @@ -352,36 +354,39 @@ function applyOrRefreshIntegration( * concludes the user owns it, and the replacement record forgets we made it * — so a later disable strands it forever. */ - const base = classified.state === "stale" && record - ? removeFragments(parsed, record.fragmentPaths, new Set(record.createdContainers ?? [])).doc - : classified.state === "conflict" && record - /* - * A forced overwrite of a `foreign-edit` conflict drops what the previous - * record owned for the same reason a stale refresh does: the replacement - * record covers the paths we are about to write, so a path the old record - * owned and the new one does not would be stranded forever, unremovable by - * any later disable. - * - * With NO record -- an `unowned-key` conflict -- there is nothing to drop and - * the merge runs against the user's document directly. That is correct: - * createdContainerPaths then attributes every container they already had to - * them, so a later disable removes our leaves and leaves their structure - * standing. - */ - ? removeFragments(parsed, record.fragmentPaths, new Set(record.createdContainers ?? [])).doc - : parsed; - // Computed against the document as it stands BEFORE the merge: afterwards - // every container exists and "did we create this?" is unanswerable. - const created = createdContainerPaths(base, contribution); /* * A document can hold a value its own format cannot round-trip through our * renderers. That used to throw straight out of the writer and reach the * user as a 500 with no path and no advice; it is a refusal like any other, - * and the file is untouched because this happens before any write. + * and the file is untouched because this happens before any write. The + * removal and merge sit inside the same guard: a sequence holding two + * entries our selector matches is equally unwritable, and equally untouched. */ - const nextDocument = mergeContribution(base, contribution); + let created: string[]; let text: string; try { + const base = classified.state === "stale" && record + ? removeFragments(parsed, record.fragmentPaths, new Set(record.createdContainers ?? [])).doc + : classified.state === "conflict" && record + /* + * A forced overwrite of a `foreign-edit` conflict drops what the previous + * record owned for the same reason a stale refresh does: the replacement + * record covers the paths we are about to write, so a path the old record + * owned and the new one does not would be stranded forever, unremovable by + * any later disable. + * + * With NO record -- an `unowned-key` conflict -- there is nothing to drop and + * the merge runs against the user's document directly. That is correct: + * createdContainerPaths then attributes every container they already had to + * them, so a later disable removes our leaves and leaves their structure + * standing. + */ + ? removeFragments(parsed, record.fragmentPaths, new Set(record.createdContainers ?? [])).doc + : parsed; + // Computed against the document as it stands BEFORE the merge: afterwards + // every container exists and "did we create this?" is unanswerable. + created = createdContainerPaths(base, contribution); + const nextDocument = mergeContribution(base, contribution); if (spec.sourcePreservingYaml && before !== null) { const value = sourcePreservingFragmentValue(contribution, spec.sourcePreservingYaml.path); const patched = value === undefined @@ -401,6 +406,10 @@ function applyOrRefreshIntegration( text = serializeDocument(nextDocument, exportSpec.format); } } catch (error) { + if (error instanceof AmbiguousSelectorError) { + return refuse(clientId, "unsafe", "unsafe", + `${configPath} holds more than one entry matching ours, so it was left alone`); + } if (!(error instanceof UnserializableValueError)) throw error; return refuse(clientId, "unsafe", "unsafe", `${configPath} contains something opencodex cannot rewrite safely (${error.message}), so it was left alone`); @@ -504,7 +513,9 @@ export function disableIntegration(input: IntegrationWriteInput): WriteOutcome { return refuse(clientId, "unsafe", "unsafe", classified.reason === "blocked-container" ? `${configPath} holds a value where opencodex would have to read a section, so nothing can be removed safely` - : `${configPath} cannot be changed safely`); + : classified.reason === "ambiguous-selector" + ? `${configPath} has more than one entry matching a managed selector` + : `${configPath} cannot be changed safely`); } /* @@ -527,11 +538,15 @@ export function disableIntegration(input: IntegrationWriteInput): WriteOutcome { return refuse(clientId, "unsafe", "unsafe", `${configPath} uses YAML source opencodex cannot patch without risking unrelated comments or formatting, so nothing was removed`); } - const { doc, removed } = removeFragments( - parsed, - record!.fragmentPaths, - new Set(prunableCreated), - ); + let doc: unknown; + let removed: boolean; + try { + ({ doc, removed } = removeFragments(parsed, record!.fragmentPaths, new Set(prunableCreated))); + } catch (error) { + if (!(error instanceof AmbiguousSelectorError)) throw error; + return refuse(clientId, "unsafe", "unsafe", + `${configPath} holds more than one entry matching ours, so nothing was removed`); + } if (!removed) { return { ok: true, changed: false, state: "absent", clientId, message: "nothing to remove" }; } diff --git a/src/lib/bounded-body.ts b/src/lib/bounded-body.ts index 4016a0a753..0975268560 100644 --- a/src/lib/bounded-body.ts +++ b/src/lib/bounded-body.ts @@ -212,13 +212,28 @@ export async function readBoundedResponseBytes( } } -function decodeUtf8(chunks: readonly Uint8Array[], fatal: boolean): string { +// Mark only exceptions thrown by our decoder, preserving their identity and TypeError contract. +// Timeout-path flushing may fail too; retain that origin so callers do not lose the deadline. +const decodeFailures = new WeakMap(); + +export function boundedBodyDecodeFailure(error: unknown): "invalid_utf8" | "timeout" | undefined { + return error !== null && typeof error === "object" ? decodeFailures.get(error) : undefined; +} + +function decodeUtf8(chunks: readonly Uint8Array[], fatal: boolean, timedOut = false): string { const decoder = new TextDecoder("utf-8", { fatal }); - let text = ""; - for (const chunk of chunks) text += decoder.decode(chunk, { stream: true }); - // Flush an incomplete trailing UTF-8 sequence deterministically. - text += decoder.decode(); - return text; + try { + let text = ""; + for (const chunk of chunks) text += decoder.decode(chunk, { stream: true }); + // Flush an incomplete trailing UTF-8 sequence deterministically. + text += decoder.decode(); + return text; + } catch (error) { + if (error !== null && typeof error === "object") { + decodeFailures.set(error, timedOut ? "timeout" : "invalid_utf8"); + } + throw error; + } } /** @@ -297,7 +312,7 @@ export async function readBoundedResponseBody( "TimeoutError", ); return { - text: decodeUtf8([retained.subarray(0, retainedBytes)], options.fatalUtf8 === true), + text: decodeUtf8([retained.subarray(0, retainedBytes)], options.fatalUtf8 === true, true), truncated: true, timedOut: true, totalTimedOut: outcome === TOTAL_TIMEOUT, diff --git a/src/oauth/anthropic-routing.ts b/src/oauth/anthropic-routing.ts index a029207be5..6b2eea5a3b 100644 --- a/src/oauth/anthropic-routing.ts +++ b/src/oauth/anthropic-routing.ts @@ -10,9 +10,10 @@ * Intentionally narrower than the Codex pool: no mid-session quota rotation, * soft-avoid ladders, or probe leases. Anthropic OAuth is ToS-sensitive. * - * Affinity is process-local (lost on restart). Cooldown uses Retry-After when present, - * otherwise a default backoff. 401/403 credential failures should set needsReauth on the - * store (existing OAuth path) so the account is excluded from eligibility. + * Affinity is process-local (lost on restart). Cooldown uses Retry-After when present, else + * the reset time of whichever rate-limit window upstream reports as rejected, else a default + * backoff. 401/403 credential failures should set needsReauth on the store (existing OAuth + * path) so the account is excluded from eligibility. */ import { createHash } from "node:crypto"; import { captureOAuthAccountSelection, commitOAuthAccountSelection, credentialGeneration, getAccountSet, getAccountCredential, getAccountCredentialWithStatus } from "./store"; @@ -33,9 +34,16 @@ import type { OcxAccountPoolQuotaWindow, OcxAccountPoolRotationStrategy, OcxConf import { sweepExpiredOnWrite } from "../lib/state-store-sweeper"; import { retainedUtf8Bytes } from "../lib/admission"; +/** + * The read side of a `Headers` object, so a caller can pass the live upstream response's + * headers without this module importing anything from the server layer -- and so a test can + * hand it a plain `new Headers({...})`. + */ +export type AnthropicRateLimitHeaders = Pick; + const PROVIDER = "anthropic"; +/** Backoff only when upstream supplies no usable deadline. */ const DEFAULT_COOLDOWN_MS = 60_000; -const MAX_COOLDOWN_MS = 15 * 60_000; const AFFINITY_IDLE_TTL_MS = 24 * 60 * 60_000; const MAX_AFFINITY_ENTRIES = 2_000; const MAX_AFFINITY_COMPONENT_BYTES = 512; @@ -58,9 +66,19 @@ export interface AnthropicAccountPoolConfig { quotaWindow?: OcxAccountPoolQuotaWindow; } +/** + * Where a cooldown's length came from. Same vocabulary as `CodexCooldownSource`, because it + * answers the same question for the same reason: `retry-after` is upstream answering THIS + * refusal, `reset-derived` is upstream stating when the spent window reopens, and `default` + * is our own guess. The dashboard renders the first as a rate limit and the rest as quota, + * which is exactly the distinction a reset-derived cooldown carries -- collapsing it into + * `retry-after` would report a drained five-hour window as request-rate throttling. + */ +type AnthropicCooldownSource = "retry-after" | "reset-derived" | "default"; + interface AccountHealth { cooldownUntil: number; - cooldownSource: "retry-after" | "default"; + cooldownSource: AnthropicCooldownSource; } interface AffinityEntry { @@ -112,19 +130,38 @@ export function anthropicQuotaWindow(config: AnthropicAccountPoolConfig): OcxAcc return normalizeAccountPoolQuotaWindow(config.quotaWindow); } +/** Accept upstream deadlines within the runtime's date range, without a policy ceiling. */ +function delayUntil(timestamp: number, now: number): number | undefined { + const delay = timestamp - now; + return Number.isFinite(new Date(timestamp).getTime()) && Number.isFinite(delay) && delay > 0 + ? delay : undefined; +} + function parseRetryAfterMs(value: string | null | undefined, now: number): number | undefined { const text = value?.trim(); if (!text) return undefined; if (/^\d+(?:\.\d+)?$/.test(text)) { const seconds = Number(text); - if (Number.isFinite(seconds) && seconds > 0) { - return Math.min(Math.max(Math.ceil(seconds * 1000), 1), MAX_COOLDOWN_MS); - } + if (!Number.isFinite(seconds) || seconds <= 0) return undefined; + return delayUntil(now + Math.max(Math.ceil(seconds * 1000), 1), now); } - const timestamp = Date.parse(text); - if (!Number.isFinite(timestamp)) return undefined; - const delay = timestamp - now; - return delay > 0 ? Math.min(delay, MAX_COOLDOWN_MS) : undefined; + return delayUntil(Date.parse(text), now); +} + +/** Only rejected windows constrain recovery; all must reopen, so take the latest reset. */ +function parseRateLimitResetMs(headers: AnthropicRateLimitHeaders | null | undefined, now: number): number | undefined { + if (!headers) return undefined; + let latest: number | undefined; + for (const window of ["5h", "7d"] as const) { + if (headers.get(`anthropic-ratelimit-unified-${window}-status`)?.trim() !== "rejected") continue; + const resetSeconds = Number(headers.get(`anthropic-ratelimit-unified-${window}-reset`)?.trim()); + if (!Number.isFinite(resetSeconds) || resetSeconds <= 0) continue; + const resetAt = resetSeconds * 1000; + if (delayUntil(resetAt, now) === undefined) continue; + if (latest === undefined || resetAt > latest) latest = resetAt; + } + if (latest === undefined) return undefined; + return latest - now; } export function getAnthropicAccountHealthSnapshot( @@ -669,6 +706,7 @@ export function rotateAnthropicAccountOn429( retryAfterHeader: string | null | undefined, sessionKey?: string | null, now = Date.now(), + rateLimitHeaders?: AnthropicRateLimitHeaders | null, ): string | null { // Reactive 429 failover is NOT gated on the pool flag. That flag buys PROACTIVE routing -- // session affinity, quota-ranked new-session selection, autoSwitchThreshold, strategy -- all @@ -678,11 +716,18 @@ export function rotateAnthropicAccountOn429( // Presence is the activation rule, the same one an apiKeyPool of two keys already uses. if (!isAnthropicAccountPoolEnabled(config) && !hasAnthropicFailoverQuorum(now)) return null; + // Retry-After first: it is the header written FOR this decision. The rejected window's + // reset is the fallback, because a 429 that omits Retry-After still carries it -- and + // without that fallback such a refusal cools for the 60s default and the exhausted + // account is back in the rotation a minute later. const parsedRetry = parseRetryAfterMs(retryAfterHeader, now); - const cooldownMs = parsedRetry ?? DEFAULT_COOLDOWN_MS; + const resetDerived = parsedRetry === undefined ? parseRateLimitResetMs(rateLimitHeaders, now) : undefined; + const cooldownMs = parsedRetry ?? resetDerived ?? DEFAULT_COOLDOWN_MS; upstreamHealth.set(failedAccountId, { cooldownUntil: now + cooldownMs, - cooldownSource: parsedRetry ? "retry-after" : "default", + cooldownSource: parsedRetry !== undefined + ? "retry-after" + : resetDerived !== undefined ? "reset-derived" : "default", }); sweepExpiredOnWrite(now); clearAnthropicSessionAffinityForAccount(failedAccountId); diff --git a/src/oauth/health.ts b/src/oauth/health.ts index 4c997c47cc..011ebd8f41 100644 --- a/src/oauth/health.ts +++ b/src/oauth/health.ts @@ -184,6 +184,9 @@ export function projectStoredOAuthAccountHealth( needsReauth: account.needsReauth === true, reauthReason: account.needsReauth === true ? "refresh_failed" : undefined, cooldownUntilMs: anthropicSnap?.cooldownUntil, + // Same mapping as the Codex pool's `cooldownReasonFromSource`: only a Retry-After is + // request-rate throttling. A reset-derived cooldown means a usage window is spent, which + // is quota, and reporting it as a rate limit would tell the operator to retry shortly. cooldownReason: anthropicSnap?.cooldownSource === "retry-after" ? "rate_limit" : anthropicSnap ? "quota" : undefined, warningReason: detectOAuthWarning(provider, account, opts.observeOnly === true, now), now, diff --git a/src/providers/quota.ts b/src/providers/quota.ts index 7136cd3c70..71644a9eae 100644 --- a/src/providers/quota.ts +++ b/src/providers/quota.ts @@ -1552,6 +1552,59 @@ type AccountQuotaCacheEntry = { identity?: string; isCurrent?: () => boolean; }; +/** Expired measurements become unknown; missing reset evidence never implies a fresh allowance. */ +function normalizeAnthropicQuota(quota: ProviderQuota | null | undefined, now: number): ProviderQuota | null { + if (!quota) return null; + const validReset = (resetAt: unknown): resetAt is number => typeof resetAt === "number" + && Number.isFinite(resetAt) && resetAt > 0 && Number.isFinite(new Date(resetAt).getTime()); + let result = quota; + for (const [percent, reset] of [ + ["fiveHourPercent", "fiveHourResetAt"], + ["weeklyPercent", "weeklyResetAt"], + ["monthlyPercent", "monthlyResetAt"], + ] as const) { + const resetAt = quota[reset]; + if (resetAt === undefined) continue; + const valid = validReset(resetAt); + if (valid && resetAt > now) continue; + if (result === quota) result = { ...quota }; + if (valid) delete result[percent]; + delete result[reset]; + } + // Persisted rows validate only the outer quota object, so custom data may be malformed. + if (quota.customWindows !== undefined) { + const windows = Array.isArray(quota.customWindows) ? quota.customWindows : []; + const retained: ProviderQuotaWindow[] = []; + let changed = !Array.isArray(quota.customWindows); + for (const window of windows) { + if (!window || typeof window !== "object" || typeof window.label !== "string" || !window.label.trim() + || typeof window.percent !== "number" || !Number.isFinite(window.percent) + || window.percent < 0 || window.percent > 100) { + changed = true; + continue; + } + if (validReset(window.resetAt) && window.resetAt <= now) { + changed = true; + continue; + } + if (window.resetAt !== undefined && !validReset(window.resetAt)) { + const normalized = { ...window }; + delete normalized.resetAt; + retained.push(normalized); + changed = true; + } else { + retained.push(window); + } + } + if (changed) { + if (result === quota) result = { ...quota }; + if (retained.length) result.customWindows = retained; + else delete result.customWindows; + } + } + return hasQuotaRows(result) ? result : null; +} + const accountQuotaCache = new Map(); let explicitAccountEpoch = 0; @@ -1568,14 +1621,23 @@ function hydrateAccountQuotaCache(): void { if (diskHydrated) return; diskHydrated = true; for (const [key, quota] of readPersistedAccountQuotas()) { - if (!accountQuotaCache.has(key)) accountQuotaCache.set(key, { ts: quota.updatedAt, quota }); + // Disk stores observation time, not the Anthropic usage probe's clock. + if (!accountQuotaCache.has(key)) { + const anthropic = key.startsWith("anthropic\u0000"); + accountQuotaCache.set(key, { + ts: anthropic ? 0 : quota.updatedAt, + quota: anthropic ? normalizeAnthropicQuota(quota, Date.now()) : quota, + }); + } } } function persistAccountQuotaCache(): void { schedulePersistAccountQuotas(function* () { + const now = Date.now(); for (const [key, entry] of accountQuotaCache) { - if (entry.quota) yield [key, entry.quota] as [string, ProviderQuota]; + const quota = key.startsWith("anthropic\u0000") ? normalizeAnthropicQuota(entry.quota, now) : entry.quota; + if (quota) yield [key, quota] as [string, ProviderQuota]; } }); } @@ -1625,7 +1687,7 @@ function accountCacheKey(provider: string, accountId: string): string { export function getCachedProviderAccountQuota(provider: string, accountId: string): ProviderQuota | null { const entry = accountQuotaCache.get(accountCacheKey(provider, accountId)); if (entry?.isCurrent && !entry.isCurrent()) return null; - return entry?.quota ?? null; + return provider === "anthropic" ? normalizeAnthropicQuota(entry?.quota, Date.now()) : entry?.quota ?? null; } /** Test-only: seed or clear the per-account quota cache without probing upstream. */ @@ -1642,6 +1704,68 @@ export function setCachedProviderAccountQuotaForTests( accountQuotaCache.set(key, { ts: Date.now(), quota }); } +/** Unified headers report utilization fractions and epoch-second reset times. */ +function anthropicHeaderResetAt(value: string | null): number | undefined { + const seconds = toFiniteNumber(value); + if (seconds === undefined || seconds <= 0) return undefined; + const timestamp = seconds * 1000; + return Number.isFinite(new Date(timestamp).getTime()) ? timestamp : undefined; +} + +export function parseAnthropicRateLimitHeaders(headers: Headers): ProviderQuota | null { + const fiveHourPercent = normalizeUtilizationFraction(headers.get("anthropic-ratelimit-unified-5h-utilization")); + const weeklyPercent = normalizeUtilizationFraction(headers.get("anthropic-ratelimit-unified-7d-utilization")); + if (fiveHourPercent === undefined && weeklyPercent === undefined) return null; + const fiveHourResetAt = anthropicHeaderResetAt(headers.get("anthropic-ratelimit-unified-5h-reset")); + const weeklyResetAt = anthropicHeaderResetAt(headers.get("anthropic-ratelimit-unified-7d-reset")); + return { + ...(fiveHourPercent !== undefined ? { fiveHourPercent } : {}), + ...(fiveHourPercent !== undefined && fiveHourResetAt !== undefined ? { fiveHourResetAt } : {}), + ...(weeklyPercent !== undefined ? { weeklyPercent } : {}), + ...(weeklyPercent !== undefined && weeklyResetAt !== undefined ? { weeklyResetAt } : {}), + updatedAt: Date.now(), + }; +} + +/** Reject unknown scales; round fraction conversion for persisted/displayed percentages. */ +function normalizeUtilizationFraction(value: string | null): number | undefined { + const numeric = toFiniteNumber(value); + if (numeric === undefined || numeric < 0 || numeric > 1) return undefined; + return Math.round(numeric * 10_000) / 100; +} + +/** + * Merge serving-account observations without advancing the usage probe's clock or + * erasing model-specific windows. The caller owns credential attribution; this guard + * prevents a retired account key from being revived by an older config generation. + */ +export function recordAnthropicAccountQuotaFromHeaders( + accountId: string, + headers: Headers, + writerGeneration: number, +): void { + if (!accountId) return; + const observed = parseAnthropicRateLimitHeaders(headers); + if (!observed) return; + const key = accountCacheKey("anthropic", accountId); + if (!mayCommitAccountQuotaKey(key, writerGeneration)) return; + // Hydrate before writing, for the same reason `recordPassiveAccountQuota` does: this write + // arrives unprompted from the request path, and `persistAccountQuotaCache` serializes the + // whole map. Landing before any reader has hydrated would persist this single row and erase + // every other provider's saved row. + hydrateAccountQuotaCache(); + const previous = accountQuotaCache.get(key); + accountQuotaCache.set(key, { + ...previous, + // Headers do not prove that the last usage probe succeeded. + ts: previous?.ts ?? 0, + quota: normalizeAnthropicQuota({ + ...normalizeAnthropicQuota(previous?.quota, observed.updatedAt), ...observed, + }, observed.updatedAt), + }); + persistAccountQuotaCache(); +} + /** * Providers whose per-account quota is OBSERVED in-band, never probed. * @@ -1714,7 +1838,11 @@ export function readPassiveProviderAccountQuotas(provider: string): ProviderAcco export function sweepExpiredProviderAccountQuotaRows(now = Date.now()): number { let removed = 0; for (const [key, entry] of accountQuotaCache) { - if (entry.ts + ACCOUNT_QUOTA_TTL_MS > now) continue; + // Anthropic observations extend retention, never the usage probe's eligibility clock. + const retainedAt = key.startsWith("anthropic\u0000") + ? Math.max(entry.ts, entry.quota?.updatedAt ?? 0) + : entry.ts; + if (retainedAt + ACCOUNT_QUOTA_TTL_MS > now) continue; accountQuotaCache.delete(key); removed += 1; } @@ -1907,10 +2035,13 @@ async function fetchAccountQuota( ): Promise { if (!supportsPerAccountQuota(provider)) return { ts: Date.now(), quota: null, unavailable: true }; if (explicitAccountReader(provider)) return fetchExplicitAccountQuota(provider, accountId, forceRefresh, providerConfig); + if (provider === "anthropic") hydrateAccountQuotaCache(); const key = accountCacheKey(provider, accountId); const writerGeneration = captureConfigGeneration(); const cached = accountQuotaCache.get(key); - if (!forceRefresh && cached && Date.now() - cached.ts < ACCOUNT_QUOTA_TTL_MS) return cached; + if (!forceRefresh && cached && Date.now() - cached.ts < ACCOUNT_QUOTA_TTL_MS) { + return provider === "anthropic" ? { ...cached, quota: normalizeAnthropicQuota(cached.quota, Date.now()) } : cached; + } const joinable = accountQuotaInflight.get(key); if (joinable) return joinable; @@ -1947,7 +2078,9 @@ async function fetchAccountQuota( // negative-cache instead of re-probing on every GUI poll. const entry: AccountQuotaCacheEntry = { ts: Date.now(), - quota: cached?.quota ?? null, + // Settle once for all joiners against observations committed during the probe. + quota: provider === "anthropic" + ? normalizeAnthropicQuota(accountQuotaCache.get(key)?.quota, Date.now()) : cached?.quota ?? null, unavailable: true, }; if (mayCommitAccountQuotaKey(key, writerGeneration)) { @@ -1957,7 +2090,9 @@ async function fetchAccountQuota( } return entry; } - const entry: AccountQuotaCacheEntry = { ts: Date.now(), quota }; + const entry: AccountQuotaCacheEntry = { + ts: Date.now(), quota: provider === "anthropic" ? normalizeAnthropicQuota(quota, Date.now()) : quota, + }; if (mayCommitAccountQuotaKey(key, writerGeneration)) { accountQuotaCache.set(key, entry); // Exhaustion state rides the SAME commit guard as the quota row: a probe from a @@ -1969,7 +2104,8 @@ async function fetchAccountQuota( } catch { const entry: AccountQuotaCacheEntry = { ts: Date.now(), - quota: cached?.quota ?? null, + quota: provider === "anthropic" + ? normalizeAnthropicQuota(accountQuotaCache.get(key)?.quota, Date.now()) : cached?.quota ?? null, unavailable: true, }; if (mayCommitAccountQuotaKey(key, writerGeneration)) { @@ -2001,7 +2137,7 @@ export async function fetchProviderAccountQuotas( const entry = await fetchAccountQuota(provider, account.id, forceRefresh, providerConfig); const result: ProviderAccountQuota = { accountId: account.id, - quota: entry.quota, + quota: provider === "anthropic" ? normalizeAnthropicQuota(entry.quota, Date.now()) : entry.quota, ...(entry.unavailable ? { unavailable: true as const } : {}), }; if (!explicitAccountReader(provider)) return result; diff --git a/src/providers/registry.ts b/src/providers/registry.ts index 82f70a6a6a..ef7cb59e00 100644 --- a/src/providers/registry.ts +++ b/src/providers/registry.ts @@ -2544,6 +2544,37 @@ export const PROVIDER_REGISTRY: readonly ProviderRegistryEntry[] = [ // yields an empty picker at runtime. note: "Domestic BigModel Coding Plan endpoint (open.bigmodel.cn)", }, + // Narrowed carry of #3641: the official Codex example declares a local static catalog, + // not an HTTP /models contract. Keep Responses separate from the Chat endpoint above. + // Source: https://docs.bigmodel.cn/cn/coding-plan/tool/codex.md (checked 2026-09-07). + { + id: "zhipu-bigmodel-responses", + label: "Zhipu AI — BigModel Coding Plan (Responses)", + baseUrl: "https://open.bigmodel.cn/api/v1", + adapter: "openai-responses", + authKind: "key", + dashboardUrl: "https://bigmodel.cn/console/usercenter/apikeys", + defaultModel: "glm-5.3", + models: ["glm-5.3", "glm-5-turbo"], + liveModels: false, + // The local Codex catalog does not establish an authenticated HTTP /models contract. + apiKeyValidation: "unknown", + jawcodeBundle: "zai", + // A pre-existing same-named custom provider must retain its destination and key boundary. + preserveCustomDestination: true, + modelContextWindows: { "glm-5.3": 1_048_576, "glm-5-turbo": 204_800 }, + modelInputModalities: { "glm-5.3": ["text"], "glm-5-turbo": ["text"] }, + modelReasoningEfforts: { + "glm-5.3": ZAI_GLM_53_REASONING_EFFORTS, + // Explicitly empty: Turbo must not inherit the generic selectable effort ladder. + "glm-5-turbo": [], + }, + modelDefaultReasoningEfforts: { "glm-5.3": "max", "glm-5-turbo": "max" }, + modelSupportsReasoningSummaries: { "glm-5.3": true, "glm-5-turbo": true }, + // Responses replay uses this provider-level flag, not the Chat-path model list. + preserveResponsesReasoningContent: true, + note: "Domestic BigModel Coding Plan Responses endpoint; static model roster", + }, { id: "nanogpt", label: "NanoGPT", baseUrl: "https://nano-gpt.com/api/v1", adapter: "openai-chat", authKind: "key", dashboardUrl: "https://nano-gpt.com/api" }, { id: "synthetic", label: "Synthetic", baseUrl: "https://api.synthetic.new/openai/v1", adapter: "openai-chat", authKind: "key", dashboardUrl: "https://synthetic.new" }, // SiliconFlow publishes an OpenAI-compatible chat endpoint and a dynamic model catalog. Do not diff --git a/src/responses/parser.ts b/src/responses/parser.ts index a81a693a4a..396f2170b2 100644 --- a/src/responses/parser.ts +++ b/src/responses/parser.ts @@ -126,6 +126,12 @@ export function parseRequest( } return holder; }; + const preservePendingReplay = () => { + const replay = pendingReasoning.filter(entry => entry.envelopeSigned || entry.part.redacted?.length); + if (replay.length > 0) { + ensureAssistantPlaceholder(messages, data.model, now).content.push(...replay.map(entry => entry.part)); + } + }; // Tool specs surfaced by a prior tool_search (deferred tools, e.g. subagents). Codex does not // re-list these in `tools`, but chat models can only call listed tools — so we re-inject them. const loadedToolSpecs: unknown[] = []; @@ -148,6 +154,12 @@ export function parseRequest( const effectiveType = (item as { type?: string }).type ?? ("role" in item ? "message" : undefined); const itemRole = (item as { role?: string }).role; const externalTaskInput = effectiveType === "function_call_output" ? externalTaskInputContent(item) : undefined; + // A signed/opaque assistant-only turn still owns its replay blocks, even + // without a following assistant text or tool call to drain the pending list. + if (effectiveType === "agent_message" || externalTaskInput !== undefined + || (effectiveType === "message" && ["user", "developer", "system"].includes(itemRole ?? ""))) { + preservePendingReplay(); + } // Raw protocol items do not map one-to-one onto context messages. Capture the boundary while // both representations are available so later metadata can stay before conversation in both. if ( @@ -269,7 +281,7 @@ export function parseRequest( const envelope = typeof reasoning.encrypted_content === "string" ? decodeReasoningEnvelope(reasoning.encrypted_content) : null; - const thinkingText = envelope?.txt || text; + const thinkingText = envelope?.txt ?? text; // Kiro reasoning round-trip: a krc-only item carries nothing renderable — it is provider // state for the assistant turn that ALREADY closed, because Kiro emits its @@ -285,7 +297,7 @@ export function parseRequest( // Native/non-ocxr1 encrypted-only reasoning is opaque here. Do not create a detached // assistant turn or invent replayable plaintext/signatures from the encrypted payload. - if (thinkingText.length > 0) { + if (thinkingText.length > 0 || envelope?.sig || envelope?.red?.length) { const part: OcxThinkingContent = { type: "thinking", thinking: thinkingText, @@ -296,7 +308,7 @@ export function parseRequest( const envelopeSigned = typeof envelope?.sig === "string"; const previous = pendingReasoning[pendingReasoning.length - 1]; - if (!envelopeSigned && previous && !previous.envelopeSigned) { + if (!envelopeSigned && !part.redacted && previous && !previous.envelopeSigned && !previous.part.redacted) { previous.part = { ...part, thinking: `${previous.part.thinking}\n${part.thinking}`, @@ -466,6 +478,7 @@ export function parseRequest( } } } + preservePendingReplay(); if (data.previous_response_id && continuationConversationMessageIndex === undefined) { continuationConversationMessageIndex = messages.length; } diff --git a/src/responses/reasoning-envelope.ts b/src/responses/reasoning-envelope.ts index 1735f775fb..2a56563578 100644 --- a/src/responses/reasoning-envelope.ts +++ b/src/responses/reasoning-envelope.ts @@ -50,10 +50,11 @@ export function decodeReasoningEnvelope(encryptedContent: string): ReasoningEnve if (red.length > 0) envelope.red = red; } const txt = (parsed as { txt?: unknown }).txt; - if (typeof txt === "string" && txt.length > 0) envelope.txt = txt; + const hasTxt = typeof txt === "string"; + if (hasTxt) envelope.txt = txt; const krc = (parsed as { krc?: unknown }).krc; if (typeof krc === "string" && krc.length > 0) envelope.krc = krc; - return envelope.sig || envelope.red || envelope.txt || envelope.krc ? envelope : null; + return envelope.sig || envelope.red || hasTxt || envelope.krc ? envelope : null; } catch { return null; } diff --git a/src/server/grok-responses-control-frame.ts b/src/server/grok-responses-control-frame.ts new file mode 100644 index 0000000000..e910daf99d --- /dev/null +++ b/src/server/grok-responses-control-frame.ts @@ -0,0 +1,43 @@ +import { sseDataPayload, type SseBlockRewrite } from "./sse-payload-rewrite"; + +const GROK_CONTROL_FRAME_TYPES: Record = { + "codex.rate_limits": true, + "codex.response.metadata": true, +}; + +/** + * Hide Codex-only control frames from Grok's strict Responses decoder. + * + * The inspection branch still sees these frames before this client-facing + * rewrite, so quota accounting and response metadata remain available to the + * proxy while Grok receives only its declared Responses event variants. + */ +export function createGrokResponsesControlFrameBlockRewrite(): SseBlockRewrite { + return (block) => { + let eventName = ""; + // SSE overwrites the event type on every event field, including empty resets. + // Like sseDataPayload, remove only one optional ASCII space after the colon. + for (const line of block.split(/\r?\n/)) { + if (line === "event") eventName = ""; + else if (line.startsWith("event:")) { + const value = line.slice("event:".length); + eventName = value.startsWith(" ") ? value.slice(1) : value; + } + } + if (GROK_CONTROL_FRAME_TYPES[eventName] === true) return []; + + const payload = sseDataPayload(block); + if (payload === null || payload === "[DONE]") return [block]; + + let event: unknown; + try { + event = JSON.parse(payload); + } catch { + return [block]; + } + if (!event || typeof event !== "object" || Array.isArray(event) || !("type" in event)) return [block]; + return typeof event.type === "string" && GROK_CONTROL_FRAME_TYPES[event.type] === true + ? [] + : [block]; + }; +} diff --git a/src/server/management/config-routes.ts b/src/server/management/config-routes.ts index ac6929c968..4d551a886d 100644 --- a/src/server/management/config-routes.ts +++ b/src/server/management/config-routes.ts @@ -161,7 +161,7 @@ interface ClientIntegrationSyncOutcome { } /** - * Re-inject native clients that are switched ON and file integrations whose + * Re-inject native clients that are switched ON and every file integration whose * OpenCodex ownership record is the operator's durable opt-in. * * Only Codex used to run here, so a catalog change reached Codex and nothing else: a Grok @@ -169,6 +169,10 @@ interface ClientIntegrationSyncOutcome { * next `ocx start`. The startup path already gates each client on its own toggle * (`src/cli/index.ts`), and this is that same fan-out for the on-demand command. * + * File integrations use the catalog-refresh coordinator so owned blocks are + * updated without claiming unowned files. Aside remains on its multi-profile + * server-owned path inside that coordinator. + * * A client that is OFF or never connected is omitted from the result rather than reported as skipped — the * caller has to be able to tell "not touched" from "tried and failed". A client that fails * does not fail the sync: Codex is the one that matters for routing, and a broken Grok file @@ -233,7 +237,7 @@ export async function syncEnabledClientIntegrations( }, config, port, - }, ["mcode", "pi", "aside"])); + }, ["mcode", "pi", "aside", "raycast"])); return out; } diff --git a/src/server/management/integration-routes.ts b/src/server/management/integration-routes.ts index b332718e07..43c0e6a98c 100644 --- a/src/server/management/integration-routes.ts +++ b/src/server/management/integration-routes.ts @@ -22,6 +22,7 @@ import { isIntegrationClientId, type IntegrationClientId, } from "../../integrations/registry"; +import { detectRaycast, type RaycastInstall } from "../../integrations/raycast-detect"; import { readIntegrationState } from "../../integrations/state"; import { createIntegrationStateStore, type IntegrationStateStore } from "../../integrations/store"; import { @@ -58,6 +59,13 @@ type RestoreResult = Awaited>; export type IntegrationStateEnvelope = { clientId: IntegrationClientId; + /** + * Raycast only, and only on the single-client read. Custom Providers is a + * Pro feature, so a file that is `current` can still be one Raycast ignores; + * this is the fact that lets status and the GUI say so. It is not part of + * the shared `IntegrationStatus`, which describes the file, not the app. + */ + raycast?: RaycastInstall; } & IntegrationStateRecord; export interface IntegrationStateListEnvelope { @@ -141,6 +149,17 @@ export function setIntegrationPathTestHooks(hooks: { env?: NodeJS.ProcessEnv; ho integrationPathTestHooks = hooks; } +/** + * Raycast detection override for tests. The real detector spawns `defaults` and + * reads the developer's own subscription state, which is exactly the kind of + * host fact a route test must not depend on. + */ +let raycastDetectTestHook: (() => RaycastInstall) | null = null; + +export function setRaycastDetectTestHook(hook: (() => RaycastInstall) | null): void { + raycastDetectTestHook = hook; +} + /** The `env`/`home` overrides, spread into every registry-resolving call. */ function pathOverrides(): { env?: NodeJS.ProcessEnv; home?: string } { return { @@ -177,7 +196,10 @@ export function setIntegrationMutationFlightTestHooks( setIntegrationMutationFlightTestHook(hooks?.run ?? null); // Path overrides are part of the same isolation contract: clearing flights // while leaving a temp home bound would let the next suite write real files. - if (hooks === null) integrationPathTestHooks = null; + if (hooks === null) { + integrationPathTestHooks = null; + raycastDetectTestHook = null; + } } /** @@ -633,7 +655,12 @@ export async function handleIntegrationRoutes(ctx: ManagementContext): Promise= 0 + && Number.isFinite(limit) && limit >= 0 + ? ` [measurement=${category}; bytes=${bytes}]` : ""; + super(`Decompressed request body exceeds ${Number.isFinite(limit) ? limit : "unknown"} bytes${suffix}`); + this.measurement = category; } } -function assertBodySizeWithinLimit(body: Uint8Array, maxBytes: number): Uint8Array { - if (body.byteLength > maxBytes) throw new DecompressedBodyTooLargeError(body.byteLength, maxBytes); +function assertBodySizeWithinLimit( + body: Uint8Array, + maxBytes: number, + measurement: BodySizeMeasurement = "decoded_exact", +): Uint8Array { + if (body.byteLength > maxBytes) throw new DecompressedBodyTooLargeError(body.byteLength, maxBytes, measurement); return body; } @@ -112,7 +137,7 @@ async function readRequestBodyBytesCapped( if (!value || value.byteLength === 0) continue; if (value.byteLength > maxBytes - retainedBytes) { - const error = new DecompressedBodyTooLargeError(retainedBytes + value.byteLength, maxBytes); + const error = new DecompressedBodyTooLargeError(retainedBytes + value.byteLength, maxBytes, "observed_wire_lower_bound"); cancel(error); throw error; } @@ -173,7 +198,8 @@ export function decodeRequestBody( else throw new UnsupportedContentEncodingError(encoding); } catch (err) { if ((err as NodeJS.ErrnoException | null)?.code === "ERR_BUFFER_TOO_LARGE") { - throw new DecompressedBodyTooLargeError(maxBytes + 1, maxBytes); + // Inflation stopped at the cap; the full decoded size was never measured. + throw new DecompressedBodyTooLargeError(maxBytes + 1, maxBytes, "decoded_lower_bound"); } throw err; } @@ -198,7 +224,7 @@ export async function readBoundedJsonRequestBody( // Reject an honest oversized declaration before reading. Missing, malformed, // and dishonest declarations remain bounded by the streaming reader below. if (declaredLength !== null && declaredLength > maxBytes) { - const error = new DecompressedBodyTooLargeError(declaredLength, maxBytes); + const error = new DecompressedBodyTooLargeError(declaredLength, maxBytes, "declared_wire"); cancelStreamWithoutWaiting(req.body, error); throw error; } @@ -211,7 +237,7 @@ export async function readBoundedJsonRequestBody( } finally { releaseReservation?.(); } - assertBodySizeWithinLimit(raw, maxBytes); + assertBodySizeWithinLimit(raw, maxBytes, "observed_wire_lower_bound"); const releaseRaw = budget?.observeAcceptedRequestCopy(raw.byteLength); let releaseDecoded: (() => void) | undefined; let releaseText: (() => void) | undefined; diff --git a/src/server/responses/agent-task-recovery-cache.ts b/src/server/responses/agent-task-recovery-cache.ts index 93d0c1778b..398a0feba4 100644 --- a/src/server/responses/agent-task-recovery-cache.ts +++ b/src/server/responses/agent-task-recovery-cache.ts @@ -2,6 +2,20 @@ const MAX_CACHE_BYTES = 8 * 1024 * 1024; const MAX_CONCURRENT_RECOVERIES = 32; const CACHE_TTL_MS = 15 * 60 * 1000; +export type AgentTaskRecoveryResolutionFailureReason = + | "recovery_unavailable" + | "caller_cancelled" + | "recovery_http_rejected" + | "recovery_timeout" + | "recovery_aborted" + | "recovery_transport_error" + | "recovery_invalid_output"; + +/** Shared flights carry bounded failures; only successful plaintext enters the cache. */ +export type AgentTaskRecoveryResolution = + | { readonly recovered: true; readonly assignment: string } + | { readonly recovered: false; readonly reason: AgentTaskRecoveryResolutionFailureReason }; + interface RecoveryCacheEntry { assignment: string; bytes: number; @@ -11,7 +25,7 @@ interface RecoveryCacheEntry { interface RecoveryFlight { controller: AbortController; - promise: Promise; + promise: Promise; waiters: number; settled: boolean; } @@ -63,7 +77,7 @@ function insertRecoveryCacheEntry(key: string, assignment: string, maxEntries: n function startRecoveryFlight( key: string, maxEntries: number, - request: (signal: AbortSignal) => Promise, + request: (signal: AbortSignal) => Promise, ): RecoveryFlight | null { const active = RECOVERY_FLIGHTS.get(key); if (active) return active; @@ -72,15 +86,15 @@ function startRecoveryFlight( const controller = new AbortController(); const flight: RecoveryFlight = { controller, - promise: Promise.resolve(null), + promise: Promise.resolve({ recovered: false, reason: "recovery_unavailable" }), waiters: 0, settled: false, }; flight.promise = request(controller.signal) - .then((assignment) => { - if (!assignment || controller.signal.aborted) return null; - insertRecoveryCacheEntry(key, assignment, maxEntries); - return assignment; + .then((result): AgentTaskRecoveryResolution => { + if (controller.signal.aborted) return { recovered: false, reason: "recovery_aborted" }; + if (result.recovered) insertRecoveryCacheEntry(key, result.assignment, maxEntries); + return result; }) .finally(() => { flight.settled = true; @@ -93,14 +107,14 @@ function startRecoveryFlight( async function waitForRecoveryFlight( flight: RecoveryFlight, abortSignal?: AbortSignal, -): Promise { - if (abortSignal?.aborted) return null; +): Promise { + if (abortSignal?.aborted) return { recovered: false, reason: "caller_cancelled" }; flight.waiters += 1; let onAbort: (() => void) | undefined; try { if (!abortSignal) return await flight.promise; - const cancelled = new Promise((resolve) => { - onAbort = () => resolve(null); + const cancelled = new Promise((resolve) => { + onAbort = () => resolve({ recovered: false, reason: "caller_cancelled" }); abortSignal.addEventListener("abort", onAbort, { once: true }); if (abortSignal.aborted) onAbort(); }); @@ -120,12 +134,27 @@ export async function resolveCachedAgentTaskRecovery( request: (signal: AbortSignal) => Promise, abortSignal?: AbortSignal, ): Promise { - if (abortSignal?.aborted) return null; + const result = await resolveCachedAgentTaskRecoveryWithResult(key, maxEntries, async signal => { + const assignment = await request(signal); + return assignment + ? { recovered: true, assignment } + : { recovered: false, reason: "recovery_unavailable" }; + }, abortSignal); + return result.recovered ? result.assignment : null; +} + +export async function resolveCachedAgentTaskRecoveryWithResult( + key: string, + maxEntries: number, + request: (signal: AbortSignal) => Promise, + abortSignal?: AbortSignal, +): Promise { + if (abortSignal?.aborted) return { recovered: false, reason: "caller_cancelled" }; sweepRecoveryCache(Date.now(), maxEntries); const cached = RECOVERY_CACHE.get(key)?.assignment; - if (cached) return cached; + if (cached) return { recovered: true, assignment: cached }; const flight = startRecoveryFlight(key, maxEntries, request); - return flight ? waitForRecoveryFlight(flight, abortSignal) : null; + return flight ? waitForRecoveryFlight(flight, abortSignal) : { recovered: false, reason: "recovery_unavailable" }; } export function discardCachedAgentTaskRecovery(key: string): void { diff --git a/src/server/responses/agent-task-recovery.ts b/src/server/responses/agent-task-recovery.ts index 22b7a4e66b..a15a2563ca 100644 --- a/src/server/responses/agent-task-recovery.ts +++ b/src/server/responses/agent-task-recovery.ts @@ -1,14 +1,16 @@ import { createHash, createHmac, randomBytes } from "node:crypto"; import { decodeJwtPayload, extractAccountId } from "../../oauth/chatgpt"; import type { OcxConfig } from "../../types"; -import { readBoundedResponseBody } from "../../lib/bounded-body"; +import { boundedBodyDecodeFailure, readBoundedResponseBody } from "../../lib/bounded-body"; import { isApiAuthRequired, isProxyAdmissionSecret } from "../auth-cors"; import { structurallyValidFernetTokens } from "./encrypted-payload"; import { cachedAgentTaskRecovery, discardCachedAgentTaskRecovery, resetAgentTaskRecoveryCache, - resolveCachedAgentTaskRecovery, + resolveCachedAgentTaskRecoveryWithResult, + type AgentTaskRecoveryResolution, + type AgentTaskRecoveryResolutionFailureReason, } from "./agent-task-recovery-cache"; /** Experimental opt-in normalization through ChatGPT's fixed Codex endpoint. */ @@ -44,9 +46,8 @@ export interface AgentTaskRecoveryOptions { export type AgentTaskRecoveryFailureReason = | "unsupported_envelope" | "admission_denied" - // Includes cache capacity rejection; does not imply an upstream request was attempted. - | "recovery_unavailable" - | "caller_cancelled" + // recovery_unavailable includes capacity rejection, which does not imply an upstream attempt. + | AgentTaskRecoveryResolutionFailureReason | "input_changed"; export type AgentTaskRecoveryResult = @@ -436,7 +437,7 @@ async function requestRecovery( envelope: AgentEnvelope, options: AgentTaskRecoveryOptions, abortSignal?: AbortSignal, -): Promise { +): Promise { const controller = new AbortController(); const timeout = setTimeout( () => controller.abort(new DOMException("Agent task recovery timed out", "TimeoutError")), @@ -454,8 +455,11 @@ async function requestRecovery( redirect: "error", }); if (!response.ok) { - try { await response.body?.cancel(); } catch { /* already closed */ } - return null; + // A rejected or never-settling cancellation must not extend the recovery deadline. + try { void response.body?.cancel().catch(() => undefined); } catch { /* already closed */ } + if (abortSignal?.aborted) return { recovered: false, reason: "recovery_aborted" }; + if (controller.signal.aborted) return { recovered: false, reason: "recovery_timeout" }; + return { recovered: false, reason: "recovery_http_rejected" }; } const body = await readBoundedResponseBody(response, { signal, @@ -465,10 +469,18 @@ async function requestRecovery( inactivityTimeoutMs: options.timeoutMs ?? 45_000, firstByteTimeoutMs: options.timeoutMs ?? 45_000, }); - if (body.truncated || body.oversized || body.timedOut || !body.displaySafe) return null; - return assignmentFromRecoverySse(body.text, envelope); - } catch { - return null; + if (abortSignal?.aborted) return { recovered: false, reason: "recovery_aborted" }; + if (controller.signal.aborted || body.timedOut) return { recovered: false, reason: "recovery_timeout" }; + if (body.truncated || body.oversized || !body.displaySafe) return { recovered: false, reason: "recovery_invalid_output" }; + const assignment = assignmentFromRecoverySse(body.text, envelope); + return assignment === null + ? { recovered: false, reason: "recovery_invalid_output" } + : { recovered: true, assignment }; + } catch (error) { + if (abortSignal?.aborted) return { recovered: false, reason: "recovery_aborted" }; + const decodeFailure = boundedBodyDecodeFailure(error); + if (controller.signal.aborted || decodeFailure === "timeout") return { recovered: false, reason: "recovery_timeout" }; + return { recovered: false, reason: decodeFailure === "invalid_utf8" ? "recovery_invalid_output" : "recovery_transport_error" }; } finally { clearTimeout(timeout); } @@ -497,23 +509,23 @@ export async function recoverEncryptedAgentTaskWithResult( const admitted = admittedRecovery(req, input, config, context.parentThreadId); if (!admitted.admitted) return { recovered: false, reason: admitted.reason }; const { admission, cacheKey, envelope } = admitted.recovery; - const assignment = await resolveCachedAgentTaskRecovery( + const result = await resolveCachedAgentTaskRecoveryWithResult( cacheKey, options.cacheEntries ?? 200, signal => requestRecovery(admission, envelope, options, signal), context.abortSignal, ); - if (!assignment) { + if (!result.recovered) { return { recovered: false, - reason: context.abortSignal?.aborted ? "caller_cancelled" : "recovery_unavailable", + reason: context.abortSignal?.aborted ? "caller_cancelled" : result.reason, }; } if (context.abortSignal?.aborted) { discardCachedAgentTaskRecovery(cacheKey); return { recovered: false, reason: "caller_cancelled" }; } - if (!injectAssignment(input, envelope, assignment)) { + if (!injectAssignment(input, envelope, result.assignment)) { discardCachedAgentTaskRecovery(cacheKey); return { recovered: false, reason: "input_changed" }; } diff --git a/src/server/responses/core.ts b/src/server/responses/core.ts index 3c539c6d8e..312af7ac43 100644 --- a/src/server/responses/core.ts +++ b/src/server/responses/core.ts @@ -230,7 +230,7 @@ import { } from "../../providers/request-pacing"; import { slugsEquivalent } from "../../providers/slug-codec"; import { isMuseSubscriptionUsagePayload, parseMuseSubscriptionUsage } from "../../providers/muse-subscription-usage"; -import { hasPassiveAccountQuota, recordPassiveAccountQuota } from "../../providers/quota"; +import { hasPassiveAccountQuota, recordAnthropicAccountQuotaFromHeaders, recordPassiveAccountQuota } from "../../providers/quota"; import { captureConfigGeneration } from "../../lib/state-store-sweeper"; import { applyOpenAiVirtualModel, resolveOpenAiCompactModel } from "../../providers/openai-virtual-models"; import { isUsageDebugEnabled } from "../../usage/debug"; @@ -374,6 +374,7 @@ import { type UpstreamHostAdmissionLease, } from "../../codex/upstream-host-health"; import { createGrokResponsesSparseTerminalBlockRewrite } from "../grok-responses-snapshot-repair"; +import { createGrokResponsesControlFrameBlockRewrite } from "../grok-responses-control-frame"; import { createResponsesSnapshotBlockRewrite, hasResponsesSnapshotRepair, @@ -3946,7 +3947,27 @@ async function handleResponsesInner( for (let attempt = 0; attempt < 3; attempt++) { if (selectionIsCurrent(requestBindings.get(wireRequest))) { const fetchImpl = (route.provider as OcxProviderConfig & { fetch?: typeof globalThis.fetch }).fetch ?? execute; - return fetchImpl(destination, dispatchInit); + const binding = requestBindings.get(wireRequest); + const snapshot = route.providerName === "anthropic" && anthropicPoolAccountId && binding?.kind === "oauth" + ? binding.snapshot : undefined; + const writerGeneration = snapshot ? captureConfigGeneration() : 0; + const sentHeaders = snapshot ? new Headers(dispatchInit.headers) : undefined; + const ownsBearer = snapshot !== undefined + && sentHeaders?.get("authorization") === `Bearer ${snapshot.accessToken}` + && !sentHeaders?.has("x-api-key"); + const response = await fetchImpl(destination, dispatchInit); + // Observe each physical response before retries replace it. The binding belongs to + // this dispatch, so a manual switch cannot file A's headers against B. Header + // overrides and credential replacement make ownership unprovable: skip those writes. + if (ownsBearer && snapshot) { + try { + const current = getAccountCredentialWithStatus("anthropic", snapshot.accountId); + if (current && !current.needsReauth && credentialGeneration(current.credential) === snapshot.generation) { + recordAnthropicAccountQuotaFromHeaders(snapshot.accountId, response.headers, writerGeneration); + } + } catch { /* best-effort observation cannot fail the response */ } + } + return response; } const nextAdapter = await refreshDispatchAdapter(requestParsed); const rebuilt = await nextAdapter.buildRequest(requestParsed, { @@ -5494,9 +5515,9 @@ async function handleResponsesInner( // Grok Build renders deltas live but reconstructs its durable assistant // turn from the completed response snapshot. Native Responses streams // may instead carry the complete items in output_item.done, so the - // explicit Grok compatibility marker enables strict terminal-only repair. + // explicit Grok compatibility marker enables strict client compatibility rewrites. // The provider's broader snapshot/lifecycle repair remains opt-in. - const grokClientSnapshotRepairEnabled = logCtx.surface === "grok"; + const grokClientCompatibilityEnabled = logCtx.surface === "grok"; const snapshotRepairEnabled = hasResponsesSnapshotRepair(route.provider.responsesSnapshotRepair); const githubCopilotRepairEnabled = route.providerName === "github-copilot"; const responseModelRewrite = parsed._responseModelId !== undefined @@ -5545,7 +5566,10 @@ async function handleResponsesInner( githubCopilotRepairEnabled ? createGithubCopilotResponsesBlockRewrite(translatorBudget) : undefined, - grokClientSnapshotRepairEnabled + grokClientCompatibilityEnabled + ? createGrokResponsesControlFrameBlockRewrite() + : undefined, + grokClientCompatibilityEnabled ? createGrokResponsesSparseTerminalBlockRewrite(translatorBudget) : undefined, snapshotRepairEnabled @@ -5956,7 +5980,10 @@ async function handleResponsesInner( const imgPlan = !routedCompaction ? await planImageBridge(config, parsed, route.provider) : undefined; const vidPlan = !routedCompaction ? await planVideoBridge(config, parsed, route.provider) : undefined; const canRunWebSearch = !!wsPlan && !adapter.runTurn; - const rotateSidecarProviderOn429 = async (retryAfter: string | null): Promise => { + const rotateSidecarProviderOn429 = async ( + retryAfter: string | null, + responseHeaders?: Headers, + ): Promise => { const rotated = rotateProviderTransportOn429(config, route.providerName, route.provider, { retryAfter, now: Date.now(), @@ -6000,6 +6027,8 @@ async function handleResponsesInner( anthropicPoolAccountId, retryAfter, anthropicSessionKey, + Date.now(), + responseHeaders, ); if (!nextAccountId) return null; try { @@ -7032,6 +7061,8 @@ async function handleResponsesInner( anthropicPoolAccountId, upstreamResponse.headers.get("retry-after"), anthropicSessionKey, + Date.now(), + upstreamResponse.headers, ); if (!nextAccountId) break; try { void upstreamResponse.body?.cancel().catch(() => {}); } catch { /* already consumed/closed */ } @@ -7445,6 +7476,8 @@ async function handleResponsesInner( anthropicPoolAccountId, response.headers.get("retry-after"), anthropicSessionKey, + Date.now(), + response.headers, ); if (nextAccountId) { try { void response.body?.cancel().catch(() => {}); } catch { /* already closed */ } diff --git a/src/web-search/loop.ts b/src/web-search/loop.ts index 3a2c5e99b4..0c957e1c17 100644 --- a/src/web-search/loop.ts +++ b/src/web-search/loop.ts @@ -309,8 +309,16 @@ export interface WebSearchLoopDeps { * 429 failover hook: rotate the provider's active credential and return a rebuilt adapter, * or null when the pool is exhausted. Async hooks support OAuth refresh; existing synchronous * key-pool hooks remain valid. + * + * `responseHeaders` carries the whole refusal, not just Retry-After, because an Anthropic + * 429 states the window's reset epoch even when it omits Retry-After -- and a rotation that + * cannot see it cools the drained account for the short default instead of until the window + * actually reopens. Optional so existing callers keep compiling. */ - on429?: (retryAfterHeader: string | null) => ProviderAdapter | null | Promise; + on429?: ( + retryAfterHeader: string | null, + responseHeaders?: Headers, + ) => ProviderAdapter | null | Promise; /** Opt-in same-target 429 policy (key-auth providers). When present, 429 replays on the SAME key before on429 rotation. */ retryOn429Policy?: Required | null; /** Called only when the final bridged Responses stream reaches completed or incomplete. */ @@ -521,7 +529,7 @@ export async function runWithWebSearch(deps: WebSearchLoopDeps): Promise }[]; + +beforeEach(() => { + home = ""; + originalFetch = globalThis.fetch; + unexpectedGlobalFetches = 0; + globalThis.fetch = (async () => { + unexpectedGlobalFetches += 1; + throw new Error("Unexpected global fetch in Anthropic quota dispatch test"); + }) as typeof fetch; + home = mkdtempSync(join(tmpdir(), "ocx-anthropic-quota-dispatch-")); + process.env.OPENCODEX_HOME = home; + sent = []; + clearAnthropicAccountPoolState(); + forgetAnthropicFailoverQuorum(); + clearGenericFailoverHealth(); + clearAccountQuotaCache(); + resetProviderQuotaReconcileStateForTests(); + clearResponseStateForTests(); +}); + +afterEach(() => { + try { + // Provider code may catch the guard's rejection; the attempted network call still fails the test. + expect(unexpectedGlobalFetches).toBe(0); + } finally { + try { + // Cancel the debounced persistence before restoring the real home. + clearAccountQuotaCache(); + clearAnthropicAccountPoolState(); + forgetAnthropicFailoverQuorum(); + clearGenericFailoverHealth(); + resetProviderQuotaReconcileStateForTests(); + clearResponseStateForTests(); + } finally { + globalThis.fetch = originalFetch; + if (originalHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = originalHome; + if (home) removeTreeWithRetry(home); + } + } +}); + +function credential(index: number) { + return { + access: `synthetic-anthropic-access-${index}`, + refresh: `synthetic-anthropic-refresh-${index}`, + expires: Date.now() + 3_600_000, + accountId: `synthetic-account-${index}`, + }; +} + +async function seed(count = 2): Promise { + for (let index = 0; index < count; index++) { + await saveCredential("anthropic", credential(index)); + } + const ids = getAccountSet("anthropic")!.accounts.map(account => account.id); + await setActiveAccount("anthropic", ids[0]!); + return ids; +} + +function quotaHeaders(fiveHour: string, weekly: string): Record { + return { + "anthropic-ratelimit-unified-5h-utilization": fiveHour, + "anthropic-ratelimit-unified-7d-utilization": weekly, + }; +} + +function limited(fiveHour = "1", weekly = "0.61"): Response { + return Response.json({ type: "error", error: { type: "rate_limit_error", message: "synthetic quota exhausted" } }, { + status: 429, + headers: { ...quotaHeaders(fiveHour, weekly), "retry-after": "30" }, + }); +} + +function answer(stream: boolean, fiveHour = "0.23", weekly = "0.47", text = "The answer is complete."): Response { + const usage = { input_tokens: 8, output_tokens: 6 }; + const message = { id: "msg_synthetic", type: "message", role: "assistant", model: "claude-sonnet-4-5", content: [{ type: "text", text }], stop_reason: "end_turn", usage }; + if (!stream) return Response.json(message, { headers: quotaHeaders(fiveHour, weekly) }); + const frames = [ + { type: "message_start", message: { ...message, content: [], stop_reason: null } }, + { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }, + { type: "content_block_delta", index: 0, delta: { type: "text_delta", text } }, + { type: "content_block_stop", index: 0 }, + { type: "message_delta", delta: { stop_reason: "end_turn" }, usage }, + { type: "message_stop" }, + ]; + return new Response(frames.map(frame => `event: ${frame.type}\ndata: ${JSON.stringify(frame)}\n\n`).join(""), { + headers: { ...quotaHeaders(fiveHour, weekly), "content-type": "text/event-stream" }, + }); +} + +function configFor(reply: (body: Record) => Response | Promise, headers?: Record): OcxConfig { + const transport = (async (_input, init) => { + const wireHeaders = new Headers(init?.headers); + const body = JSON.parse(String(init?.body)) as Record; + sent.push({ authorization: wireHeaders.get("authorization"), apiKey: wireHeaders.get("x-api-key"), body }); + return reply(body); + }) as typeof fetch; + const provider: OcxProviderConfig & { fetch: typeof fetch } = { + adapter: "anthropic", baseUrl: "https://anthropic-quota.test", authMode: "oauth", + models: ["claude-sonnet-4-5"], fetch: transport, ...(headers ? { headers } : {}), + }; + return { + port: 0, defaultProvider: "anthropic", + anthropicAccountPool: { enabled: false, strategy: "round-robin" }, + providers: { anthropic: provider }, + }; +} + +function post(config: OcxConfig, body: Record = {}) { + return handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "anthropic/claude-sonnet-4-5", input: "Answer briefly", stream: false, ...body }), + }), config, { model: "", provider: "" }); +} + +function expectQuota(id: string, fiveHourPercent: number, weeklyPercent: number) { + expect(getCachedProviderAccountQuota("anthropic", id)).toMatchObject({ fiveHourPercent, weeklyPercent }); +} + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise(done => { resolve = done; }); + return { promise, resolve }; +} + +test("main A429 -> B200 records both physical responses against their sending accounts", async () => { + const [a, b] = await seed(); + const config = configFor(body => { + if (sent.length === 1) return limited(); + expect(sent.length).toBe(2); + // A must already be measured before the replacement response exists. + expectQuota(a!, 100, 61); + expect(getCachedProviderAccountQuota("anthropic", b!)).toBeNull(); + return answer(body.stream === true); + }); + const response = await post(config); + const responseText = await response.text(); + expect(response.status).toBe(200); + expect(responseText).toContain("The answer is complete."); + expect(sent.map(row => row.authorization)).toEqual([`Bearer ${credential(0).access}`, `Bearer ${credential(1).access}`]); + expectQuota(a!, 100, 61); + expectQuota(b!, 23, 47); +}); + +test("terminal 429 after both accounts are exhausted records both refused physical responses", async () => { + const [a, b] = await seed(); + const response = await post(configFor(() => { + if (sent.length === 1) return limited(); + expect(sent.length).toBe(2); + expectQuota(a!, 100, 61); + return limited("0.89", "1"); + })); + await response.text(); + expect(response.status).toBe(429); + expect(sent.map(row => row.authorization)).toEqual([`Bearer ${credential(0).access}`, `Bearer ${credential(1).access}`]); + expectQuota(a!, 100, 61); + expectQuota(b!, 89, 100); +}); + +test("manual active switch while A is pending keeps A's measurement off B", async () => { + const [a, b] = await seed(); + const entered = deferred(); + const returned = deferred(); + const config = configFor(() => { entered.resolve(); return returned.promise; }); + const pending = post(config); + await entered.promise; + let response!: Response; + try { + expect(sent[0]!.authorization).toBe(`Bearer ${credential(0).access}`); + expect(await setActiveAccount("anthropic", b!)).toBe(true); + } finally { + returned.resolve(answer(false, "0.37", "0.53")); + response = await pending; + await response.text(); + } + expect(response.status).toBe(200); + expect(sent).toHaveLength(1); + expect(getAccountSet("anthropic")!.activeAccountId).toBe(b!); + expectQuota(a!, 37, 53); + expect(getCachedProviderAccountQuota("anthropic", b!)).toBeNull(); +}); + +test("credential replacement while A is pending skips its old-generation response", async () => { + const [a, b] = await seed(); + const entered = deferred(); + const returned = deferred(); + const pending = post(configFor(() => { entered.resolve(); return returned.promise; })); + await entered.promise; + let response!: Response; + try { + expect(sent[0]!.authorization).toBe(`Bearer ${credential(0).access}`); + await saveAccountCredential("anthropic", a!, { ...credential(0), access: "synthetic-replacement-access", refresh: "synthetic-replacement-refresh" }); + } finally { + returned.resolve(answer(false)); + response = await pending; + await response.text(); + } + expect(response.status).toBe(200); + expect(sent).toHaveLength(1); + expect(getAccountSet("anthropic")!.accounts.find(row => row.id === a)!.credential.access).toBe("synthetic-replacement-access"); + expect(getCachedProviderAccountQuota("anthropic", a!)).toBeNull(); + expect(getCachedProviderAccountQuota("anthropic", b!)).toBeNull(); +}); + +const overriddenHeaders: { label: string; headers: Record; authorization: string; apiKey: string | null }[] = [ + { label: "overridden bearer", headers: { Authorization: "Bearer synthetic-override" }, authorization: "Bearer synthetic-override", apiKey: null }, + { label: "additional x-api-key", headers: { "x-api-key": "synthetic-api-key" }, authorization: `Bearer ${credential(0).access}`, apiKey: "synthetic-api-key" }, +]; +test.each(overriddenHeaders)("$label skips quota attribution even when a selected OAuth account exists", async ({ headers, authorization, apiKey }) => { + const ids = await seed(); + const response = await post(configFor(body => answer(body.stream === true), headers)); + await response.text(); + expect(response.status).toBe(200); + expect(sent).toHaveLength(1); + expect(sent[0]).toMatchObject({ authorization, apiKey }); + for (const id of ids) expect(getCachedProviderAccountQuota("anthropic", id)).toBeNull(); +}); + +test("real web-search routed loop records A429 and B200 through fetchForRequest", async () => { + const [a, b] = await seed(); + const config = configFor(body => { + // The search loop forces upstream streaming although the client asks for JSON. + expect(body.stream).toBe(true); + if (sent.length === 1) return limited(); + expect(sent.length).toBe(2); + expectQuota(a!, 100, 61); + return answer(true); + }); + config.webSearchSidecar = { backend: "anthropic", enabled: true }; + const response = await post(config, { tools: [{ type: "web_search" }] }); + const responseText = await response.text(); + expect(response.status).toBe(200); + expect(responseText).toContain("The answer is complete."); + expect(sent.map(row => row.authorization)).toEqual([`Bearer ${credential(0).access}`, `Bearer ${credential(1).access}`]); + expectQuota(a!, 100, 61); + expectQuota(b!, 23, 47); +}); + +test("real terminal continuation records A429 before retrying the continuation on B", async () => { + const [a, b] = await seed(); + const config = configFor(body => { + // The real guard recognizes an actionable request plus a short execution announcement, + // with available tools and no tool call. A normal completed answer does not trigger it. + if (sent.length === 1) return answer(body.stream === true, "0.11", "0.31", "I will modify the file now."); + if (sent.length === 2) { + expectQuota(a!, 11, 31); + return limited(); + } + expect(sent.length).toBe(3); + expectQuota(a!, 100, 61); + return answer(body.stream === true); + }); + const response = await post(config, { + input: "Please modify the file now", + tools: [{ type: "function", name: "read_file", description: "read a file", parameters: { type: "object" } }], + }); + const responseText = await response.text(); + expect(response.status).toBe(200); + expect(responseText).toContain("The answer is complete."); + expect(sent.map(row => row.authorization)).toEqual([`Bearer ${credential(0).access}`, `Bearer ${credential(0).access}`, `Bearer ${credential(1).access}`]); + expectQuota(a!, 100, 61); + expectQuota(b!, 23, 47); +}); + +test("real image bridge routed loop records A429 and B200 through fetchForRequest", async () => { + const [a, b] = await seed(); + const config = configFor(body => { + expect(body.stream).toBe(true); + // Only the bridge installs this synthetic tool for the hosted image_generation input. + expect(body.tools).toEqual(expect.arrayContaining([expect.objectContaining({ name: "custom_image_gen" })])); + if (sent.length === 1) return limited(); + expect(sent.length).toBe(2); + expectQuota(a!, 100, 61); + return answer(true); + }); + config.images = { bridgeEnabled: true }; + config.providers.xai = { + adapter: "openai-chat", baseUrl: "https://api.x.ai/v1", authMode: "key", apiKey: "synthetic-image-key", + }; + const response = await post(config, { stream: true, tools: [{ type: "image_generation" }] }); + const responseText = await response.text(); + expect(response.status).toBe(200); + expect(responseText).toContain("The answer is complete."); + expect(sent.map(row => row.authorization)).toEqual([`Bearer ${credential(0).access}`, `Bearer ${credential(1).access}`]); + expectQuota(a!, 100, 61); + expectQuota(b!, 23, 47); +}); diff --git a/tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts b/tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts new file mode 100644 index 0000000000..f1ad70542e --- /dev/null +++ b/tests/adapters/anthropic/anthropic-ratelimit-headers.test.ts @@ -0,0 +1,818 @@ +/** Anthropic response observations must preserve account usage and probe semantics. */ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + clearAnthropicAccountCooldown, + clearAnthropicAccountPoolState, + forgetAnthropicFailoverQuorum, + getAnthropicAccountHealthSnapshot, + rotateAnthropicAccountOn429, + resetAnthropicRoutingForManualSelection, + resolveAnthropicAccountForSession, +} from "../../../src/oauth/anthropic-routing"; +import { projectStoredOAuthAccountHealth } from "../../../src/oauth/health"; +import { quotaEvidenceForCandidate } from "../../../src/routing/quota"; +import { + clearAccountQuotaCache, + fetchProviderAccountQuotas, + getCachedProviderAccountQuota, + parseAnthropicRateLimitHeaders, + recordAnthropicAccountQuotaFromHeaders, + reconcileProviderAccountQuotaRows, + resetProviderQuotaReconcileStateForTests, + setCachedProviderAccountQuotaForTests, + sweepExpiredProviderAccountQuotaRows, +} from "../../../src/providers/quota"; +import { getAccountSet, saveCredential, setActiveAccount } from "../../../src/oauth/store"; +import { clearPoolRotationState } from "../../../src/codex/pool-rotation"; +import { removeTreeWithRetry } from "../../helpers/remove-tree"; +import type { OcxConfig } from "../../../src/types"; + +const originalHome = process.env.OPENCODEX_HOME; +const originalFetch = globalThis.fetch; +const originalNow = Date.now; +let home: string; + +beforeEach(() => { + globalThis.fetch = (async () => { throw new Error("Unexpected network request in quota test"); }) as typeof fetch; + home = mkdtempSync(join(tmpdir(), "ocx-anthropic-ratelimit-")); + process.env.OPENCODEX_HOME = home; + clearAnthropicAccountPoolState(); + clearPoolRotationState(); + clearAccountQuotaCache(); + // `lastReconciledGeneration` is module-global and survives a cache clear, so the fence case + // below would otherwise raise the floor for every test that runs after it in this file. + resetProviderQuotaReconcileStateForTests(); + forgetAnthropicFailoverQuorum(); +}); + +afterEach(() => { + globalThis.fetch = originalFetch; + Date.now = originalNow; + clearAnthropicAccountPoolState(); + clearPoolRotationState(); + // The argument-less form, deliberately: only it calls cancelPendingAccountQuotaPersist. + // The observer ends in a 250ms-debounced write that resolves OPENCODEX_HOME at fire time, + // so a provider-scoped clear would leave that write to land in whatever home is current a + // quarter second later — the next test's sandbox, or the developer's real one. + clearAccountQuotaCache(); + resetProviderQuotaReconcileStateForTests(); + forgetAnthropicFailoverQuorum(); + if (originalHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = originalHome; + removeTreeWithRetry(home); +}); + +/** The store assigns its own slot ids, so the seeded `accountId` is never the cache key. */ +async function seed(count: number): Promise { + for (let i = 0; i < count; i++) { + await saveCredential("anthropic", { + access: `access-${i}`, + refresh: `refresh-${i}`, + expires: Date.now() + 3_600_000, + accountId: `uuid-${i}`, + email: `user${i}@example.test`, + } as never); + } + return getAccountSet("anthropic")?.accounts.map(a => a.id) ?? []; +} + +function poolEnabled(): OcxConfig { + return { + port: 0, + defaultProvider: "anthropic", + providers: { + anthropic: { adapter: "anthropic", baseUrl: "https://api.anthropic.com", authMode: "oauth" }, + }, + anthropicAccountPool: { enabled: true }, + } as OcxConfig; +} + +/** A real 429 from a drained five-hour window, captured from api.anthropic.com. */ +function drainedFiveHour(resetEpochSeconds: number): Headers { + return new Headers({ + "anthropic-ratelimit-unified-status": "rejected", + "anthropic-ratelimit-unified-5h-status": "rejected", + "anthropic-ratelimit-unified-5h-reset": String(resetEpochSeconds), + "anthropic-ratelimit-unified-5h-utilization": "1.0", + "anthropic-ratelimit-unified-7d-status": "allowed", + "anthropic-ratelimit-unified-7d-reset": String(resetEpochSeconds + 86_400), + "anthropic-ratelimit-unified-7d-utilization": "0.36", + }); +} + +describe("Anthropic cooldown honours the stated window", () => { + test("a multi-hour Retry-After is not truncated to the guessed-backoff ceiling", async () => { + const start = Date.now(); + const ids = await seed(2); + // 7999s is what a drained five-hour window actually answers; the old 15-minute clamp + // turned a single refusal into sixteen wasted retries before the window reopened. + rotateAnthropicAccountOn429(poolEnabled(), ids[0]!, "7999", null, start); + const health = getAnthropicAccountHealthSnapshot(ids[0]!, start); + expect(health?.cooldownUntil).toBe(start + 7_999_000); + expect(health?.cooldownSource).toBe("retry-after"); + }); + + test("a week-long Retry-After retains its stated deadline", async () => { + const start = Date.now(); + const ids = await seed(2); + rotateAnthropicAccountOn429(poolEnabled(), ids[0]!, "604800", null, start); + expect(getAnthropicAccountHealthSnapshot(ids[0]!, start)?.cooldownUntil) + .toBe(start + 604_800_000); + }); + + test("an HTTP-date Retry-After is honoured beyond six hours", async () => { + const start = Date.now(); + const ids = await seed(2); + // RFC 9110 allows either form, and both are upstream STATING when it will serve again -- + // the date branch had its own clamp and would have kept the 15-minute truncation. + rotateAnthropicAccountOn429(poolEnabled(), ids[0]!, new Date(start + 2 * 60 * 60_000).toUTCString(), null, start); + const cooldown = getAnthropicAccountHealthSnapshot(ids[0]!, start)?.cooldownUntil; + // toUTCString drops sub-second precision, so the deadline lands within a second of target. + expect(cooldown).toBeGreaterThan(start + 2 * 60 * 60_000 - 1_000); + expect(cooldown).toBeLessThanOrEqual(start + 2 * 60 * 60_000); + + const reset = Math.floor(start / 1000) * 1000 + 48 * 60 * 60_000; + rotateAnthropicAccountOn429(poolEnabled(), ids[1]!, new Date(reset).toUTCString(), null, start); + expect(getAnthropicAccountHealthSnapshot(ids[1]!, start)?.cooldownUntil).toBe(reset); + }); + + test("a 429 without Retry-After cools until the rejected window reopens", async () => { + const start = Date.now(); + const ids = await seed(2); + // The wire carries whole seconds, so the reset is built from an epoch second and the + // expectation is derived from the same value rather than from `start + 90min` — an + // assertion on the un-truncated millisecond would be testing the fixture, not the code. + const resetEpochSeconds = Math.floor((start + 90 * 60_000) / 1000); + // Retry-After is not guaranteed on an Anthropic 429; the rejected window's reset is. + // Without reading it this refusal cooled for the 60s default and the drained account + // was back in the rotation a minute later. + rotateAnthropicAccountOn429(poolEnabled(), ids[0]!, null, null, start, drainedFiveHour(resetEpochSeconds)); + const health = getAnthropicAccountHealthSnapshot(ids[0]!, start); + expect(health?.cooldownUntil).toBe(resetEpochSeconds * 1000); + // Its own source, not "retry-after": the dashboard renders that one as request-rate + // throttling, and a spent five-hour window is quota. Same vocabulary the Codex pool uses. + expect(health?.cooldownSource).toBe("reset-derived"); + }); + + test("an ALLOWED window's reset never cools the account", async () => { + const start = Date.now(); + const ids = await seed(2); + // Every response names when the current period ends, including a healthy one. Treating + // that as a cooldown would bench an account with 4% used for the rest of its window. + const healthy = new Headers({ + "anthropic-ratelimit-unified-status": "allowed", + "anthropic-ratelimit-unified-5h-status": "allowed", + "anthropic-ratelimit-unified-5h-reset": String(Math.floor((start + 3 * 60 * 60_000) / 1000)), + "anthropic-ratelimit-unified-5h-utilization": "0.04", + }); + rotateAnthropicAccountOn429(poolEnabled(), ids[0]!, null, null, start, healthy); + const health = getAnthropicAccountHealthSnapshot(ids[0]!, start); + expect(health?.cooldownUntil).toBe(start + 60_000); + expect(health?.cooldownSource).toBe("default"); + }); + + test("both windows rejected cools until the LAST one reopens", async () => { + const start = Date.now(); + const ids = await seed(2); + // The limiter is AND-composed: upstream refuses while ANY window rejects. An account whose + // 5-hour bucket rolls in three minutes is still refused for the days its weekly window + // needs, so cooling to the earliest reset would re-offer it every three minutes until the + // weekly window finally reopens -- the exact loop this path exists to end. + const fiveHourReset = Math.floor((start + 3 * 60_000) / 1000); + const weeklyReset = Math.floor((start + 5 * 24 * 60 * 60_000) / 1000); + const bothDrained = new Headers({ + "anthropic-ratelimit-unified-status": "rejected", + "anthropic-ratelimit-unified-5h-status": "rejected", + "anthropic-ratelimit-unified-5h-reset": String(fiveHourReset), + "anthropic-ratelimit-unified-7d-status": "rejected", + "anthropic-ratelimit-unified-7d-reset": String(weeklyReset), + }); + rotateAnthropicAccountOn429(poolEnabled(), ids[0]!, null, null, start, bothDrained); + expect(getAnthropicAccountHealthSnapshot(ids[0]!, start)?.cooldownUntil).toBe(weeklyReset * 1000); + }); + + test("a reset-derived cooldown surfaces as quota, a Retry-After as a rate limit", async () => { + const start = Date.now(); + const ids = await seed(2); + const account = getAccountSet("anthropic")!.accounts.find(a => a.id === ids[0]!)!; + // The distinction is not cosmetic: the dashboard tells an operator to wait out a rate + // limit and to switch accounts on spent quota. A drained five-hour window is the second. + rotateAnthropicAccountOn429( + poolEnabled(), + ids[0]!, + null, + null, + start, + drainedFiveHour(Math.floor((start + 90 * 60_000) / 1000)), + ); + expect(projectStoredOAuthAccountHealth("anthropic", account, start)).toMatchObject({ + status: "cooldown", + reason: "quota", + }); + + clearAnthropicAccountCooldown(ids[0]!); + rotateAnthropicAccountOn429(poolEnabled(), ids[0]!, "300", null, start); + expect(projectStoredOAuthAccountHealth("anthropic", account, start)).toMatchObject({ + status: "cooldown", + reason: "rate_limit", + }); + }); + + test("Retry-After wins over the header reset", async () => { + const start = Date.now(); + const ids = await seed(2); + // Retry-After is written for this decision; the reset epoch is a fallback for the + // refusals that omit it. A disagreement must not silently prefer the fallback. + rotateAnthropicAccountOn429( + poolEnabled(), + ids[0]!, + "120", + null, + start, + drainedFiveHour(Math.floor((start + 4 * 60 * 60_000) / 1000)), + ); + expect(getAnthropicAccountHealthSnapshot(ids[0]!, start)?.cooldownUntil).toBe(start + 120_000); + }); +}); + +describe("Anthropic rate-limit headers feed the routing cache", () => { + test("utilization is read as a fraction, not as a percent", () => { + // The header sends 0.74 for a 74%-spent window while the probe endpoint sends 74.0 for + // the same account. Passing the header value through unscaled would file the emptiest + // account as the freshest and route every new session straight at it. + const quota = parseAnthropicRateLimitHeaders(new Headers({ + "anthropic-ratelimit-unified-5h-utilization": "0.42", + "anthropic-ratelimit-unified-7d-utilization": "0.74", + })); + expect(quota?.fiveHourPercent).toBe(42); + expect(quota?.weeklyPercent).toBe(74); + }); + + test("reset epochs are promoted from seconds to milliseconds", () => { + const quota = parseAnthropicRateLimitHeaders(new Headers({ + "anthropic-ratelimit-unified-5h-utilization": "0.5", + "anthropic-ratelimit-unified-5h-reset": "1788717000", + })); + expect(quota?.fiveHourResetAt).toBe(1_788_717_000_000); + }); + + test("a header set with no utilization yields no measurement", () => { + // A renamed or dropped header must degrade to "unmeasured", which the router already + // has a defined behaviour for -- never to a fabricated zero, which reads as a fresh + // account and would pull traffic toward whichever account stopped reporting. + expect(parseAnthropicRateLimitHeaders(new Headers({ + "anthropic-ratelimit-unified-5h-reset": "1788717000", + }))).toBeNull(); + }); + + test("a utilization above 1 is rejected rather than clamped", () => { + // Above one is a wire change, not a full window. Inventing 100 from it would cool a + // healthy account on a misread. + expect(parseAnthropicRateLimitHeaders(new Headers({ + "anthropic-ratelimit-unified-5h-utilization": "42", + }))).toBeNull(); + }); + + test("an observed turn makes the serving account's usage known to the router", async () => { + const ids = await seed(2); + // Before the observation the account has no reading at all, which is what left a + // two-account pool scoring both at UNKNOWN_USAGE_SCORE and picking between them blind. + expect(getCachedProviderAccountQuota("anthropic", ids[0]!)).toBeNull(); + recordAnthropicAccountQuotaFromHeaders(ids[0]!, drainedFiveHour(Math.floor(Date.now() / 1000) + 3600), 0); + expect(getCachedProviderAccountQuota("anthropic", ids[0]!)?.fiveHourPercent).toBe(100); + // The other account stays unmeasured: an observation is attributed to the account that + // served the turn, never spread across the roster. + expect(getCachedProviderAccountQuota("anthropic", ids[1]!)).toBeNull(); + }); + + test("headers with nothing parseable leave the previous reading intact", async () => { + const ids = await seed(1); + recordAnthropicAccountQuotaFromHeaders(ids[0]!, new Headers({ + "anthropic-ratelimit-unified-5h-utilization": "0.25", + }), 0); + recordAnthropicAccountQuotaFromHeaders(ids[0]!, new Headers({ "content-type": "application/json" }), 0); + // A response that says nothing about quota is not evidence that the quota is gone. + expect(getCachedProviderAccountQuota("anthropic", ids[0]!)?.fiveHourPercent).toBe(25); + }); + + test("an empty account id writes nothing", () => { + // API-key providers and single-account installs below failover quorum reach the observer + // with no account to attribute; that is an ordinary state, not an error. Asserting only + // that it does not throw would pass with the guard deleted -- an empty-string cache key + // is perfectly writable -- so this asserts the absence of the row instead. + recordAnthropicAccountQuotaFromHeaders("", drainedFiveHour(Math.floor(Date.now() / 1000) + 3600), 0); + expect(getCachedProviderAccountQuota("anthropic", "")).toBeNull(); + }); + + test("a stale writer generation is refused", async () => { + const ids = await seed(1); + // The fence exists because a turn is a long await: an account or config change that lands + // mid-turn must not be overwritten by a measurement taken before it. Every other test here + // passes 0, which a fresh worker always accepts, so without this case the parameter is + // carried but never actually exercised as a fence. + reconcileProviderAccountQuotaRows({ + generation: 5, + providerNames: new Set(), + comboIds: new Set(), + comboTargets: new Set(), + codexAccountIds: new Set(), + oauthAccountKeys: new Set(), + configRoots: new Set(), + }); + recordAnthropicAccountQuotaFromHeaders(ids[0]!, new Headers({ + "anthropic-ratelimit-unified-5h-utilization": "0.5", + }), 1); + expect(getCachedProviderAccountQuota("anthropic", ids[0]!)).toBeNull(); + }); + + test("an observation keeps the model-scoped bars the probe filled", async () => { + const ids = await seed(1); + // The probe reports per-model weekly limits (Opus, Sonnet, Fable) that no header carries. + // They are read by the manual-preference exhaustion check and by `headroomOf`, so a + // wholesale replace would not merely blank the dashboard: it would route an Opus request + // to an account whose Opus allowance is spent. + setCachedProviderAccountQuotaForTests("anthropic", ids[0]!, { + fiveHourPercent: 10, + weeklyPercent: 20, + customWindows: [{ label: "Opus", percent: 96 }], + updatedAt: Date.now(), + }); + recordAnthropicAccountQuotaFromHeaders(ids[0]!, new Headers({ + "anthropic-ratelimit-unified-5h-utilization": "0.41", + }), 0); + const quota = getCachedProviderAccountQuota("anthropic", ids[0]!); + expect(quota?.fiveHourPercent).toBe(41); + // Untouched by this observation, not erased by it. + expect(quota?.weeklyPercent).toBe(20); + expect(quota?.customWindows).toEqual([{ label: "Opus", percent: 96 }]); + }); + + test("a percent that is not exactly representable is rounded, not left as an artifact", () => { + // `0.29 * 100` is 28.999999999999996 in binary floating point, and the CLI interpolates the + // percent raw. A user reading `5h 28.999999999999996%` would reasonably file a bug. + expect(parseAnthropicRateLimitHeaders(new Headers({ + "anthropic-ratelimit-unified-5h-utilization": "0.29", + }))?.fiveHourPercent).toBe(29); + }); +}); + +describe("Anthropic observation and probe clocks", () => { + function observe(accountId: string, percent = "0.41"): void { + recordAnthropicAccountQuotaFromHeaders(accountId, new Headers({ + "anthropic-ratelimit-unified-5h-utilization": percent, + }), 0); + } + + function usageResponse(): Response { + return Response.json({ five_hour: { utilization: 12 }, seven_day_opus: { utilization: 63 } }); + } + + test("a cold header-only row does not defer the first usage probe", async () => { + const [id] = await seed(1); + let calls = 0; + globalThis.fetch = (async () => { calls++; return usageResponse(); }) as typeof fetch; + observe(id!); + expect(getCachedProviderAccountQuota("anthropic", id!)?.fiveHourPercent).toBe(41); + const [row] = await fetchProviderAccountQuotas("anthropic"); + expect(calls).toBe(1); + expect(row?.quota).toMatchObject({ fiveHourPercent: 12, customWindows: [{ label: "Opus", percent: 63 }] }); + expect(row?.unavailable).toBeUndefined(); + }); + + test("fresh header observations survive sweeping until their own TTL expires", async () => { + const [id] = await seed(1); + const observedAt = originalNow(); + Date.now = () => observedAt; + observe(id!); + expect(sweepExpiredProviderAccountQuotaRows(observedAt + 1)).toBe(0); + expect(getCachedProviderAccountQuota("anthropic", id!)?.fiveHourPercent).toBe(41); + expect(sweepExpiredProviderAccountQuotaRows(observedAt + 10 * 60_000 - 1)).toBe(0); + expect(sweepExpiredProviderAccountQuotaRows(observedAt + 10 * 60_000)).toBe(1); + expect(getCachedProviderAccountQuota("anthropic", id!)).toBeNull(); + }); + + test("headers preserve the probe TTL instead of renewing it", async () => { + const [id] = await seed(1); + let now = originalNow(); + Date.now = () => now; + let calls = 0; + globalThis.fetch = (async () => { calls++; return usageResponse(); }) as typeof fetch; + await fetchProviderAccountQuotas("anthropic"); + now += 9 * 60_000; + observe(id!); + expect((await fetchProviderAccountQuotas("anthropic"))[0]?.quota?.fiveHourPercent).toBe(41); + expect(calls).toBe(1); + now += 60_001; + await fetchProviderAccountQuotas("anthropic"); + expect(calls).toBe(2); + }); + + for (const observeAfterRestart of [false, true]) { + test(`restart keeps Anthropic probes due with new headers: ${observeAfterRestart}`, async () => { + const [id] = await seed(1); + const updatedAt = Date.now(); + const saved = { fiveHourPercent: 41, customWindows: [{ label: "Opus", percent: 63 }], updatedAt }; + writeFileSync(join(home, "provider-account-quota-cache.json"), JSON.stringify({ + version: 1, + rows: { [`anthropic\u0000${id}`]: saved, "kiro\u0000other": { monthlyPercent: 17, updatedAt } }, + })); + clearAccountQuotaCache(); + // Cover both dashboard-first and response-first hydration after restart. + if (observeAfterRestart) observe(id!, "0.52"); + let calls = 0; + globalThis.fetch = (async () => { calls++; return new Response("busy", { status: 429 }); }) as typeof fetch; + const [row] = await fetchProviderAccountQuotas("anthropic"); + expect(calls).toBe(1); + expect(row?.quota).toMatchObject({ fiveHourPercent: observeAfterRestart ? 52 : 41, customWindows: saved.customWindows }); + expect(getCachedProviderAccountQuota("kiro", "other")?.monthlyPercent).toBe(17); + expect(row?.unavailable).toBe(true); + }); + } + + for (const [failure, warm] of [["http", true], ["network", true], ["http", false]] as const) { + test(`joined ${failure} probe failures preserve in-flight headers (warm cache: ${warm})`, async () => { + const [id] = await seed(1); + if (warm) setCachedProviderAccountQuotaForTests("anthropic", id!, { + fiveHourPercent: 10, weeklyPercent: 20, customWindows: [{ label: "Opus", percent: 63 }], updatedAt: Date.now(), + }); + let started!: () => void; + const dispatched = new Promise(resolve => { started = resolve; }); + let finish!: (response: Response) => void; + let fail!: (error: Error) => void; + const response = new Promise((resolve, reject) => { finish = resolve; fail = reject; }); + let calls = 0; + globalThis.fetch = (async () => { calls++; started(); return response; }) as typeof fetch; + const first = fetchProviderAccountQuotas("anthropic", true); + await dispatched; + const second = fetchProviderAccountQuotas("anthropic", true); + observe(id!); + const latest = getCachedProviderAccountQuota("anthropic", id!); + if (failure === "http") finish(new Response("busy", { status: 429 })); + else fail(new Error("offline")); + const [a, b] = await Promise.all([first, second]); + expect(calls).toBe(1); + expect(a).toEqual(b); + expect(a[0]?.quota).toEqual(latest); + expect(a[0]?.quota?.fiveHourPercent).toBe(41); + if (warm) expect(a[0]?.quota).toMatchObject({ weeklyPercent: 20, customWindows: [{ label: "Opus", percent: 63 }] }); + expect(a[0]?.unavailable).toBe(true); + expect(getCachedProviderAccountQuota("anthropic", id!)).toEqual(latest); + // A later partial observation cannot claim that the failed usage probe succeeded. + observe(id!, "0.53"); + const [cached] = await fetchProviderAccountQuotas("anthropic"); + expect(cached?.unavailable).toBe(true); + expect(cached?.quota?.fiveHourPercent).toBe(53); + expect(calls).toBe(1); + globalThis.fetch = (async () => usageResponse()) as typeof fetch; + expect((await fetchProviderAccountQuotas("anthropic", true))[0]?.unavailable).toBeUndefined(); + }); + } +}); + +describe("Anthropic malformed deadlines and partial windows", () => { + for (const invalid of ["NaN", "Infinity", "1e309", "1e308", "8640000000001", "not-a-date", "-1", "0"]) { + test(`invalid reset ${invalid} cannot establish a cooldown deadline`, async () => { + const start = Date.now(); + const [id] = await seed(1); + const headers = new Headers({ + "anthropic-ratelimit-unified-7d-status": "rejected", + "anthropic-ratelimit-unified-7d-reset": invalid, + "anthropic-ratelimit-unified-7d-utilization": "0.74", + }); + rotateAnthropicAccountOn429(poolEnabled(), id!, null, null, start, headers); + expect(getAnthropicAccountHealthSnapshot(id!, start)).toMatchObject({ + cooldownUntil: start + 60_000, cooldownSource: "default", + }); + expect(parseAnthropicRateLimitHeaders(headers)?.weeklyResetAt).toBeUndefined(); + }); + } + + test("overflowing Retry-After falls back to a valid rejected reset", async () => { + const start = Date.now(); + const [id] = await seed(1); + const reset = Math.floor(start / 1000) + 432_000; + for (const invalid of ["9".repeat(400), "8640000000001", "invalid-date"]) { + rotateAnthropicAccountOn429(poolEnabled(), id!, invalid, null, start, drainedFiveHour(reset)); + expect(getAnthropicAccountHealthSnapshot(id!, start)).toMatchObject({ + cooldownUntil: reset * 1000, cooldownSource: "reset-derived", + }); + } + }); + + test("a malformed weekly deadline cannot hide a valid five-hour reset", async () => { + const start = Date.now(); + const [id] = await seed(1); + const reset = Math.floor(start / 1000) + 180; + const headers = drainedFiveHour(reset); + headers.set("anthropic-ratelimit-unified-7d-status", "rejected"); + headers.set("anthropic-ratelimit-unified-7d-reset", "1e308"); + rotateAnthropicAccountOn429(poolEnabled(), id!, null, null, start, headers); + expect(getAnthropicAccountHealthSnapshot(id!, start)?.cooldownUntil).toBe(reset * 1000); + }); + + test("partial zero utilization preserves other and model-specific windows", async () => { + const [id] = await seed(1); + const customWindows = [{ label: "Opus", percent: 63 }]; + setCachedProviderAccountQuotaForTests("anthropic", id!, { + fiveHourPercent: 10, weeklyPercent: 20, weeklyResetAt: 1_800_000_000_000, customWindows, updatedAt: Date.now(), + }); + recordAnthropicAccountQuotaFromHeaders(id!, new Headers({ + "anthropic-ratelimit-unified-5h-utilization": "0", + "anthropic-ratelimit-unified-7d-utilization": "NaN", + "anthropic-ratelimit-unified-7d-reset": "1e308", + }), 0); + expect(getCachedProviderAccountQuota("anthropic", id!)).toMatchObject({ + fiveHourPercent: 0, weeklyPercent: 20, weeklyResetAt: 1_800_000_000_000, customWindows, + }); + }); +}); + +describe("Anthropic known-reset expiry", () => { + const start = 1_800_000_000_000; + let now: number; + + beforeEach(() => { + now = start; + Date.now = () => now; + }); + + function observe(id: string, headers: Record = { + "anthropic-ratelimit-unified-5h-utilization": "0.41", + }): void { + recordAnthropicAccountQuotaFromHeaders(id, new Headers(headers), 0); + } + + test("headers expire only known elapsed custom windows without mutating their source", async () => { + const [id] = await seed(1); + const saved = { + fiveHourPercent: 10, + customWindows: [ + { label: "Opus", percent: 100, resetAt: start + 60_000 }, + { label: "Sonnet", percent: 90, resetAt: start + 600_000 }, + { label: "Fable", percent: 70 }, + { label: "Unknown reset", percent: 60, resetAt: 0 }, + ], + updatedAt: start, + }; + setCachedProviderAccountQuotaForTests("anthropic", id!, saved); + now += 120_000; + observe(id!); + const quota = getCachedProviderAccountQuota("anthropic", id!); + const retained = [saved.customWindows[1], saved.customWindows[2], { label: "Unknown reset", percent: 60 }]; + expect(quota?.customWindows).toEqual(retained); + expect(quota?.fiveHourPercent).toBe(41); + expect(quota?.updatedAt).toBe(now); + expect(saved.customWindows).toHaveLength(4); + expect(saved.updatedAt).toBe(start); + now += 30_000; + observe(id!); + expect(getCachedProviderAccountQuota("anthropic", id!)?.customWindows).toEqual(retained); + }); + + test("custom windows reject empty labels and invalid percentages while preserving valid objects", async () => { + const [id] = await seed(1); + const valid = [{ label: "Opus", percent: 0 }, { label: "Sonnet", percent: 100, resetAt: start + 60_000 }]; + const saved = { customWindows: [ + ...valid, + { label: "", percent: 50 }, { label: " ", percent: 50 }, + { label: "negative", percent: -1 }, { label: "too high", percent: 101 }, + { label: "not finite", percent: Number.NaN }, { label: "infinite", percent: Infinity }, + ], updatedAt: start }; + setCachedProviderAccountQuotaForTests("anthropic", id!, saved); + const normalized = getCachedProviderAccountQuota("anthropic", id!); + expect(normalized?.customWindows).toEqual(valid); + expect(normalized?.customWindows?.[0]).toBe(valid[0]); + expect(saved.customWindows).toHaveLength(8); + setCachedProviderAccountQuotaForTests("anthropic", id!, normalized!); + expect(getCachedProviderAccountQuota("anthropic", id!)).toBe(normalized); + }); + + test("invalid reset metadata is removed without discarding valid usage", async () => { + const [id] = await seed(1); + const invalidResets = [0, -1, Number.NaN, Infinity, 8_640_000_000_000_001]; + const saved = { + fiveHourPercent: 40, fiveHourResetAt: 0, + weeklyPercent: 50, weeklyResetAt: Infinity, + monthlyPercent: 60, monthlyResetAt: 8_640_000_000_000_001, + customWindows: invalidResets.map((resetAt, index) => ({ label: `window-${index}`, percent: 70, resetAt })), + updatedAt: start, + }; + setCachedProviderAccountQuotaForTests("anthropic", id!, saved); + const normalized = getCachedProviderAccountQuota("anthropic", id!); + expect(normalized).toEqual({ + fiveHourPercent: 40, weeklyPercent: 50, monthlyPercent: 60, + customWindows: invalidResets.map((_, index) => ({ label: `window-${index}`, percent: 70 })), + updatedAt: start, + }); + expect(saved.customWindows[0]?.resetAt).toBe(0); + expect(saved.fiveHourResetAt).toBe(0); + setCachedProviderAccountQuotaForTests("anthropic", id!, normalized!); + expect(getCachedProviderAccountQuota("anthropic", id!)).toBe(normalized); + }); + + for (const [percent, reset, observedWindow] of [ + ["fiveHourPercent", "fiveHourResetAt", "7d"], + ["weeklyPercent", "weeklyResetAt", "5h"], + ["monthlyPercent", "monthlyResetAt", "5h"], + ] as const) { + test(`partial headers remove the expired ${percent} pair without inventing zero`, async () => { + const [id] = await seed(1); + setCachedProviderAccountQuotaForTests("anthropic", id!, { + [percent]: 100, [reset]: start + 60_000, updatedAt: start, + }); + now += 60_000; + observe(id!, { [`anthropic-ratelimit-unified-${observedWindow}-utilization`]: "0.2" }); + const quota = getCachedProviderAccountQuota("anthropic", id!); + expect(quota).not.toBeNull(); + expect(quota?.[percent]).toBeUndefined(); + expect(quota?.[reset]).toBeUndefined(); + }); + } + + test("standard windows without reset evidence remain known", async () => { + const [id] = await seed(1); + setCachedProviderAccountQuotaForTests("anthropic", id!, { weeklyPercent: 100, updatedAt: start }); + now += 120_000; + observe(id!); + expect(getCachedProviderAccountQuota("anthropic", id!)?.weeklyPercent).toBe(100); + }); + + test("a reset-only header cannot extend retained usage even before the original reset", async () => { + const [id] = await seed(1); + setCachedProviderAccountQuotaForTests("anthropic", id!, { + fiveHourPercent: 10, weeklyPercent: 100, weeklyResetAt: start + 60_000, updatedAt: start, + }); + now += 30_000; + observe(id!, { + "anthropic-ratelimit-unified-5h-utilization": "0.2", + "anthropic-ratelimit-unified-7d-utilization": "invalid", + "anthropic-ratelimit-unified-7d-reset": String((start + 600_000) / 1000), + }); + expect(getCachedProviderAccountQuota("anthropic", id!)?.weeklyResetAt).toBe(start + 60_000); + now += 30_000; + expect(getCachedProviderAccountQuota("anthropic", id!)?.weeklyPercent).toBeUndefined(); + expect(getCachedProviderAccountQuota("anthropic", id!)?.weeklyResetAt).toBeUndefined(); + observe(id!, { + "anthropic-ratelimit-unified-7d-utilization": "0.3", + "anthropic-ratelimit-unified-7d-reset": String((start + 600_000) / 1000), + }); + expect(getCachedProviderAccountQuota("anthropic", id!)).toMatchObject({ + weeklyPercent: 30, weeklyResetAt: start + 600_000, + }); + }); + + test("idle cache reads cross a reset without another observation or probe", async () => { + const [id] = await seed(1); + const quota = { customWindows: [{ label: "Opus", percent: 100, resetAt: start + 60_000 }], updatedAt: start }; + setCachedProviderAccountQuotaForTests("anthropic", id!, quota); + setCachedProviderAccountQuotaForTests("kiro", "untouched", quota); + const candidate = { provider: "anthropic", model: "claude-opus-4-6", accountRef: id! }; + now += 59_999; + expect(getCachedProviderAccountQuota("anthropic", id!)).toEqual(quota); + expect(quotaEvidenceForCandidate(candidate)).toMatchObject({ known: true, exhausted: true, headroom: 0 }); + now++; + expect(getCachedProviderAccountQuota("anthropic", id!)).toBeNull(); + expect(quotaEvidenceForCandidate(candidate)).toEqual({ known: false }); + const [row] = await fetchProviderAccountQuotas("anthropic"); + expect(row?.quota).toBeNull(); + expect(row?.unavailable).toBeUndefined(); + expect(getCachedProviderAccountQuota("kiro", "untouched")).toBe(quota); + }); + + test("expired Opus evidence stops suppressing an otherwise healthy manual selection", async () => { + const [a, b] = await seed(2); + setCachedProviderAccountQuotaForTests("anthropic", a!, { + fiveHourPercent: 30, customWindows: [{ label: "Opus", percent: 100, resetAt: start + 60_000 }], updatedAt: start, + }); + setCachedProviderAccountQuotaForTests("anthropic", b!, { fiveHourPercent: 11, updatedAt: start }); + await setActiveAccount("anthropic", a!); + resetAnthropicRoutingForManualSelection(a!); + const config = poolEnabled(); + config.anthropicAccountPool = { enabled: true, strategy: "quota", autoSwitchThreshold: 20 }; + const candidate = { provider: "anthropic", model: "claude-opus-4-6", accountRef: a! }; + expect(resolveAnthropicAccountForSession(null, config, now).accountId).toBe(b); + expect(quotaEvidenceForCandidate(candidate)).toMatchObject({ known: true, exhausted: true, headroom: 0 }); + now += 60_000; + expect(resolveAnthropicAccountForSession(null, config, now)).toMatchObject({ accountId: a, reason: "manual" }); + expect(quotaEvidenceForCandidate(candidate)).toMatchObject({ known: true, exhausted: false, headroom: 0.7 }); + }); + + for (const failure of ["http", "network"] as const) { + test(`joined ${failure} failures remove windows expiring during the shared probe`, async () => { + const [id] = await seed(1); + setCachedProviderAccountQuotaForTests("anthropic", id!, { + fiveHourPercent: 10, weeklyPercent: 100, weeklyResetAt: start + 60_000, + customWindows: [{ label: "Opus", percent: 100, resetAt: start + 60_000 }, { label: "Fable", percent: 63 }], + updatedAt: start, + }); + let started!: () => void; + const dispatched = new Promise(resolve => { started = resolve; }); + let finish!: (response: Response) => void; + let fail!: (error: Error) => void; + const response = new Promise((resolve, reject) => { finish = resolve; fail = reject; }); + let calls = 0; + globalThis.fetch = (async () => { calls++; started(); return response; }) as typeof fetch; + const first = fetchProviderAccountQuotas("anthropic", true); + await dispatched; + const second = fetchProviderAccountQuotas("anthropic", true); + now += 30_000; + observe(id!); + now += 30_000; + if (failure === "http") finish(new Response("busy", { status: 429 })); + else fail(new Error("offline")); + const [a, b] = await Promise.all([first, second]); + expect(calls).toBe(1); + expect(a).toEqual(b); + expect(a[0]?.unavailable).toBe(true); + expect(a[0]?.quota).toEqual({ fiveHourPercent: 41, customWindows: [{ label: "Fable", percent: 63 }], updatedAt: start + 30_000 }); + expect(getCachedProviderAccountQuota("anthropic", id!)).toEqual(a[0]?.quota); + expect((await fetchProviderAccountQuotas("anthropic"))[0]).toEqual(a[0]); + expect(calls).toBe(1); + }); + } + + test("restart cannot revive expired bars from a recently updated disk row", async () => { + const [id] = await seed(1); + now += 120_000; + writeFileSync(join(home, "provider-account-quota-cache.json"), JSON.stringify({ version: 1, rows: { + [`anthropic\u0000${id}`]: { + fiveHourPercent: 41, weeklyPercent: 100, weeklyResetAt: start + 60_000, + customWindows: [{ label: "Opus", percent: 100, resetAt: start + 60_000 }, { label: "Fable", percent: 63 }], + updatedAt: now, + }, + } })); + clearAccountQuotaCache(); + let calls = 0; + globalThis.fetch = (async () => { calls++; return new Response("busy", { status: 429 }); }) as typeof fetch; + const [row] = await fetchProviderAccountQuotas("anthropic"); + expect(calls).toBe(1); + expect(row?.unavailable).toBe(true); + expect(row?.quota).toEqual({ fiveHourPercent: 41, customWindows: [{ label: "Fable", percent: 63 }], updatedAt: now }); + }); + + for (const malformed of [null, {}, [null, "bad", { label: "invalid", percent: "100" }]]) { + test(`malformed persisted custom windows stay unknown without breaking other rows: ${JSON.stringify(malformed)}`, async () => { + const [id] = await seed(1); + writeFileSync(join(home, "provider-account-quota-cache.json"), JSON.stringify({ version: 1, rows: { + [`anthropic\u0000${id}`]: { customWindows: malformed, updatedAt: now }, + "kiro\u0000untouched": { monthlyPercent: 17, updatedAt: now }, + } })); + clearAccountQuotaCache(); + let calls = 0; + globalThis.fetch = (async () => { calls++; return new Response("busy", { status: 429 }); }) as typeof fetch; + const [row] = await fetchProviderAccountQuotas("anthropic"); + expect(calls).toBe(1); + expect(row?.quota).toBeNull(); + expect(row?.unavailable).toBe(true); + expect(getCachedProviderAccountQuota("kiro", "untouched")).toEqual({ monthlyPercent: 17, updatedAt: now }); + }); + } + + test("persisted nonnumeric reset metadata does not erase otherwise valid windows", async () => { + const [id] = await seed(1); + writeFileSync(join(home, "provider-account-quota-cache.json"), JSON.stringify({ version: 1, rows: { + [`anthropic\u0000${id}`]: { + weeklyPercent: 80, weeklyResetAt: "unknown", + customWindows: [{ label: "Opus", percent: 70, resetAt: null }, { label: "Sonnet", percent: 60, resetAt: "later" }], + updatedAt: now, + }, + } })); + clearAccountQuotaCache(); + globalThis.fetch = (async () => new Response("busy", { status: 429 })) as typeof fetch; + const [row] = await fetchProviderAccountQuotas("anthropic"); + expect(row?.quota).toEqual({ weeklyPercent: 80, + customWindows: [{ label: "Opus", percent: 70 }, { label: "Sonnet", percent: 60 }], updatedAt: now }); + expect(row?.unavailable).toBe(true); + }); + + test("fresh utilization without a reset does not inherit an expired reset", async () => { + const [id] = await seed(1); + setCachedProviderAccountQuotaForTests("anthropic", id!, { + fiveHourPercent: 100, fiveHourResetAt: start + 60_000, updatedAt: start, + }); + now += 60_000; + observe(id!); + expect(getCachedProviderAccountQuota("anthropic", id!)).toEqual({ fiveHourPercent: 41, updatedAt: now }); + }); + + test("deferred persistence evaluates expiry at write time and leaves other providers intact", async () => { + const [id] = await seed(1); + const saved = { weeklyPercent: 100, weeklyResetAt: start + 60_000, updatedAt: start }; + setCachedProviderAccountQuotaForTests("anthropic", id!, saved); + setCachedProviderAccountQuotaForTests("kiro", "untouched", saved); + let flush!: () => void; + const timer = spyOn(globalThis, "setTimeout").mockImplementation(((callback: () => void) => { + flush = callback; + return 0 as unknown as ReturnType; + }) as typeof setTimeout); + try { observe(id!); } finally { timer.mockRestore(); } + now += 60_000; + flush(); + const disk = JSON.parse(readFileSync(join(home, "provider-account-quota-cache.json"), "utf8")); + expect(disk.rows[`anthropic\u0000${id}`]).toEqual({ fiveHourPercent: 41, updatedAt: start }); + expect(disk.rows["kiro\u0000untouched"]).toEqual(saved); + }); +}); diff --git a/tests/adapters/anthropic/anthropic-sidecar-account-failover.test.ts b/tests/adapters/anthropic/anthropic-sidecar-account-failover.test.ts index 31b2389fb8..8d094db631 100644 --- a/tests/adapters/anthropic/anthropic-sidecar-account-failover.test.ts +++ b/tests/adapters/anthropic/anthropic-sidecar-account-failover.test.ts @@ -8,10 +8,11 @@ import { afterAll, afterEach, beforeAll, beforeEach, expect, mock, test } from " import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import type { ProviderAdapter } from "../../../src/adapters/base"; +import type { AdapterRequest, IncomingMeta, ProviderAdapter } from "../../../src/adapters/base"; import { clearAnthropicAccountPoolState } from "../../../src/oauth/anthropic-routing"; import { clearGenericFailoverHealth } from "../../../src/oauth/generic-account-failover"; import { getAccountSet, saveCredential, setActiveAccount } from "../../../src/oauth/store"; +import { clearAccountQuotaCache, getCachedProviderAccountQuota, resetProviderQuotaReconcileStateForTests } from "../../../src/providers/quota"; import type { OcxConfig, OcxParsedRequest, OcxProviderConfig } from "../../../src/types"; import { removeTreeWithRetry } from "../../helpers/remove-tree"; @@ -66,15 +67,24 @@ beforeAll(async () => { runWithWebSearch: async (args: { parsed: OcxParsedRequest; adapter: ProviderAdapter; + incomingMeta: IncomingMeta; + fetchForRequest: (request: AdapterRequest, parsed: OcxParsedRequest) => typeof fetch; on429?: (retryAfter: string | null) => Promise; }) => { - const first = await args.adapter.buildRequest(args.parsed); - observedKeys.push(new Headers(first.headers).get("authorization") ?? ""); - const rotated = await args.on429?.("30"); + // This is a dispatch seam test. The real loop is covered in anthropic-quota-dispatch. + const first = await args.adapter.buildRequest(args.parsed, args.incomingMeta); + const refused = await args.fetchForRequest(first, args.parsed)(first.url, { + method: first.method, headers: first.headers, body: first.body, + }); + expect(refused.status).toBe(429); + const retryAfter = refused.headers.get("retry-after"); + await refused.body?.cancel(); + const rotated = await args.on429?.(retryAfter); if (!rotated) throw new Error("Anthropic sidecar did not rotate after 429"); - const second = await rotated.buildRequest(args.parsed); - observedKeys.push(new Headers(second.headers).get("authorization") ?? ""); - return new Response("sidecar-ok", { status: 200 }); + const second = await rotated.buildRequest(args.parsed, args.incomingMeta); + return args.fetchForRequest(second, args.parsed)(second.url, { + method: second.method, headers: second.headers, body: second.body, + }); }, })); @@ -88,11 +98,15 @@ beforeEach(() => { sidecarMode = false; clearAnthropicAccountPoolState(); clearGenericFailoverHealth(); + clearAccountQuotaCache(); + resetProviderQuotaReconcileStateForTests(); }); afterEach(() => { clearAnthropicAccountPoolState(); clearGenericFailoverHealth(); + clearAccountQuotaCache(); + resetProviderQuotaReconcileStateForTests(); removeTreeWithRetry(testHome); }); @@ -102,7 +116,7 @@ afterAll(() => { mock.restore(); }); -test("Anthropic web-search sidecar rotates on 429 when proactive pooling is disabled", async () => { +test("Anthropic sidecar dispatch seam records A429 and B200 when proactive pooling is disabled", async () => { sidecarMode = true; for (let index = 0; index < 2; index += 1) { await saveCredential("anthropic", { @@ -110,7 +124,7 @@ test("Anthropic web-search sidecar rotates on 429 when proactive pooling is disa refresh: `anthropic-refresh-${index}`, expires: Date.now() + 3_600_000, accountId: `anthropic-account-${index}`, - } as never, { addAccount: true }); + }); } const ids = getAccountSet("anthropic")!.accounts.map(account => account.id); await setActiveAccount("anthropic", ids[0]!); @@ -125,6 +139,27 @@ test("Anthropic web-search sidecar rotates on 429 when proactive pooling is disa baseUrl: "https://anthropic-sidecar.test/v1", authMode: "oauth", models: ["model"], + fetch: (async (_input, init) => { + observedKeys.push(new Headers(init?.headers).get("authorization") ?? ""); + if (observedKeys.length === 1) { + return new Response("rate limited", { + status: 429, + headers: { + "retry-after": "30", + "anthropic-ratelimit-unified-5h-utilization": "1", + "anthropic-ratelimit-unified-7d-utilization": "0.61", + }, + }); + } + expect(observedKeys).toHaveLength(2); + expect(getCachedProviderAccountQuota("anthropic", ids[0]!)).toMatchObject({ fiveHourPercent: 100, weeklyPercent: 61 }); + return new Response("sidecar-ok", { + headers: { + "anthropic-ratelimit-unified-5h-utilization": "0.23", + "anthropic-ratelimit-unified-7d-utilization": "0.47", + }, + }); + }) as typeof fetch, }, }, } as unknown as OcxConfig; @@ -146,4 +181,6 @@ test("Anthropic web-search sidecar rotates on 429 when proactive pooling is disa "Bearer anthropic-access-0", "Bearer anthropic-access-1", ]); + expect(getCachedProviderAccountQuota("anthropic", ids[0]!)).toMatchObject({ fiveHourPercent: 100, weeklyPercent: 61 }); + expect(getCachedProviderAccountQuota("anthropic", ids[1]!)).toMatchObject({ fiveHourPercent: 23, weeklyPercent: 47 }); }); diff --git a/tests/adapters/anthropic/anthropic-thinking-signature.test.ts b/tests/adapters/anthropic/anthropic-thinking-signature.test.ts index 68c972a742..86ca82b412 100644 --- a/tests/adapters/anthropic/anthropic-thinking-signature.test.ts +++ b/tests/adapters/anthropic/anthropic-thinking-signature.test.ts @@ -4,7 +4,12 @@ import { createAnthropicAdapter as createAnthropicAdapterProduction } from "../. import { parseRequest } from "../../../src/responses/parser"; import { encodeReasoningEnvelope, decodeReasoningEnvelope, OCX_REASONING_PREFIX } from "../../../src/responses/reasoning-envelope"; import type { AdapterEvent, OcxProviderConfig, OcxThinkingContent } from "../../../src/types"; -import { withTestTranslatorBudget } from "../../helpers/translator-budget"; +import { createTestTranslatorBudget, withTestTranslatorBudget } from "../../helpers/translator-budget"; + +import { anthropicToResponsesBody } from "../../../src/claude/inbound"; +import { collectAnthropicMessage, responsesSseToAnthropicSse, responsesJsonToAnthropicMessage } from "../../../src/claude/outbound"; +import { createGoogleAdapter } from "../../../src/adapters/google"; +import { sanitizeReasoningInputContent } from "../../../src/adapters/openai-responses"; const createAnthropicAdapter = (...args: Parameters) => withTestTranslatorBudget(createAnthropicAdapterProduction(...args)); @@ -127,11 +132,11 @@ describe("bridge ocxr1 envelope emission", () => { ...baseEvents, ], "claude-x"); const output = response.output as Record[]; - const reasoning = output.find(i => i.type === "reasoning"); - expect(reasoning).toBeDefined(); - const env = decodeReasoningEnvelope(reasoning!.encrypted_content as string); - expect(env?.sig).toBe("RealSig1234567890=="); - expect(env?.red).toEqual(["RED1"]); + const reasoning = output.filter(i => i.type === "reasoning"); + expect(reasoning.map(item => decodeReasoningEnvelope(item.encrypted_content as string))).toEqual([ + { red: ["RED1"] }, + { sig: "RealSig1234567890==" }, + ]); }); test("redacted-only turn still emits an envelope reasoning item (SSE)", async () => { @@ -326,3 +331,174 @@ describe("passthrough scrub of ocxr1 envelopes", () => { expect(req.body ?? "").toContain('"rs_1"'); // reasoning item itself survives }); }); + + +describe("Claude / Responses / intended Anthropic replay fidelity", () => { + // Synthetic fixtures prove transport fidelity only, never upstream signature validity. + const first = { type: "thinking", thinking: "first\nexact", signature: "FirstSyntheticSignature123456==" }; + const second = { type: "thinking", thinking: "second", signature: "SecondSyntheticSignature123456==" }; + const empty = { type: "thinking", thinking: "", signature: "EmptySyntheticSignature123456==" }; + const before = { type: "redacted_thinking", data: "opaque-before" }; + const middle = { type: "redacted_thinking", data: "opaque-middle" }; + const after = { type: "redacted_thinking", data: "opaque-after" }; + const tool = { type: "tool_use", id: "toolu_replay", name: "lookup", input: { q: "x" } }; + const cases = [ + { name: "consecutive signed blocks", blocks: [first, second, tool] }, + { name: "opaque blocks in source order", blocks: [before, first, middle, second, after, tool] }, + { name: "empty signed block", blocks: [empty, tool] }, + { name: "consecutive empty signed blocks", blocks: [empty, { ...empty, signature: "OtherEmptySyntheticSignature123456==" }, tool] }, + { name: "redacted-only tool turn", blocks: [before, after, tool] }, + ]; + + for (const fixture of cases) { + for (const streaming of [true, false]) { + test(`${fixture.name}: ${streaming ? "SSE" : "JSON"} full chain preserves exact blocks`, async () => { + const adapter = createAnthropicAdapter(provider, "none"); + let events: AdapterEvent[]; + if (streaming) { + const frames = [frame("message_start", { message: { usage: { input_tokens: 1, output_tokens: 0 } } })]; + fixture.blocks.forEach((block, index) => { + frames.push(frame("content_block_start", { index, content_block: block.type === "thinking" + ? { type: "thinking", thinking: "", signature: "" } + : block.type === "tool_use" ? { ...tool, input: {} } : block })); + if ("thinking" in block) { + // Omitted thinking has no thinking_delta on the actual wire. + if (block.thinking) frames.push(frame("content_block_delta", { index, delta: { type: "thinking_delta", thinking: block.thinking } })); + frames.push(frame("content_block_delta", { index, delta: { type: "signature_delta", signature: block.signature } })); + } else if (block.type === "tool_use") { + frames.push(frame("content_block_delta", { index, delta: { type: "input_json_delta", partial_json: JSON.stringify(tool.input) } })); + } + frames.push(frame("content_block_stop", { index })); + }); + frames.push(frame("message_delta", { delta: { stop_reason: "tool_use" }, usage: { output_tokens: 1 } }), frame("message_stop", {})); + events = await collect(adapter.parseStream(sseResponse(frames))); + } else { + events = await adapter.parseResponse!(new Response(JSON.stringify({ + id: "msg_fixture", type: "message", role: "assistant", model: "claude-x", + content: fixture.blocks, stop_reason: "tool_use", usage: { input_tokens: 1, output_tokens: 1 }, + }))); + } + let message: Record; + if (streaming) { + async function* upstream() { yield* events; } + const budget = createTestTranslatorBudget(); + message = await collectAnthropicMessage(responsesSseToAnthropicSse( + bridgeToResponsesSSE(upstream(), "claude-x"), "claude-x", { translatorBudget: budget }, + ), "claude-x", budget); + } else { + message = responsesJsonToAnthropicMessage(buildResponseJSON(events, "claude-x"), "claude-x"); + } + expect(message.content).toEqual(fixture.blocks); + const parsed = parseRequest(anthropicToResponsesBody({ + model: "anthropic/claude-x", messages: [ + { role: "user", content: "question" }, + { role: "assistant", content: message.content }, + { role: "user", content: [{ type: "tool_result", tool_use_id: tool.id, content: "result" }] }, + ], + })); + const request = await adapter.buildRequest(parsed); + const replay = JSON.parse(request.body as string) as { messages: Array<{ role: string; content: unknown }> }; + expect(replay.messages).toEqual([ + { role: "user", content: "question" }, + { role: "assistant", content: fixture.blocks }, + { role: "user", content: [{ type: "tool_result", tool_use_id: tool.id, content: "result" }] }, + ]); + }); + } + } + + test("signature updates replace rather than concatenate, across heartbeats", async () => { + // Both official SDKs assign signature_delta.signature instead of appending it: + // anthropic-sdk-typescript/src/lib/MessageStream.ts and + // anthropic-sdk-python/src/anthropic/lib/streaming/_messages.py. + const adapter = createAnthropicAdapter(provider); + const events = await collect(adapter.parseStream(sseResponse([ + frame("content_block_start", { index: 0, content_block: { type: "thinking", thinking: "", signature: "" } }), + frame("content_block_delta", { index: 0, delta: { type: "thinking_delta", thinking: "first" } }), + frame("content_block_delta", { index: 0, delta: { type: "signature_delta", signature: "old" } }), + ": heartbeat\n\n", + frame("content_block_delta", { index: 0, delta: { type: "signature_delta", signature: "FirstSyntheticSignature123456==" } }), + frame("content_block_stop", { index: 0 }), + frame("content_block_start", { index: 1, content_block: { type: "thinking", thinking: "", signature: "" } }), + frame("content_block_delta", { index: 1, delta: { type: "thinking_delta", thinking: "second" } }), + frame("content_block_delta", { index: 1, delta: { type: "signature_delta", signature: "SecondSyntheticSignature123456==" } }), + frame("content_block_stop", { index: 1 }), + frame("message_stop", {}), + ]))); + async function* upstream() { yield* events; } + const streamed = sseItems(await drainSse(bridgeToResponsesSSE(upstream(), "claude-x"))); + const buffered = buildResponseJSON(events, "claude-x").output as Record[]; + for (const items of [streamed, buffered]) { + expect(items.map(item => ({ summary: item.summary, envelope: decodeReasoningEnvelope(item.encrypted_content as string) }))).toEqual([ + { summary: [{ type: "summary_text", text: "first" }], envelope: { sig: "FirstSyntheticSignature123456==" } }, + { summary: [{ type: "summary_text", text: "second" }], envelope: { sig: "SecondSyntheticSignature123456==" } }, + ]); + } + }); + + test("signed/opaque-only assistant turns survive a user boundary and end of input", () => { + for (const continuation of [[], [{ role: "user", content: "next" }]]) { + const parsed = parseRequest(anthropicToResponsesBody({ model: "anthropic/claude-x", messages: [ + { role: "assistant", content: [empty, before, after] }, ...continuation, + ] })); + const assistant = parsed.context.messages.find(message => message.role === "assistant"); + expect(assistant?.content).toEqual([ + expect.objectContaining({ type: "thinking", thinking: "", signature: empty.signature }), + expect.objectContaining({ type: "thinking", thinking: "", redacted: [before.data] }), + expect.objectContaining({ type: "thinking", thinking: "", redacted: [after.data] }), + ]); + } + }); + + test("locally hidden signed text remains exact on Responses replay without being exposed to Claude", async () => { + const events: AdapterEvent[] = [ + { type: "thinking_delta", thinking: "hidden exact\ntext" }, + { type: "thinking_signature", signature: first.signature }, + { type: "text_delta", text: "answer" }, + { type: "done", usage: { inputTokens: 1, outputTokens: 1 } }, + ]; + async function* upstream() { yield* events; } + const items = sseItems(await drainSse(bridgeToResponsesSSE(upstream(), "claude-x", undefined, undefined, undefined, undefined, 2000, { hideThinkingSummary: true }))); + const response = buildResponseJSON(events, "claude-x", { hideThinkingSummary: true }); + for (const output of [items, response.output as Record[]]) { + const reasoning = output.find(item => item.type === "reasoning")!; + expect(reasoning.summary).toEqual([]); + expect(decodeReasoningEnvelope(reasoning.encrypted_content as string)).toEqual({ sig: first.signature, txt: "hidden exact\ntext" }); + const request = await createAnthropicAdapter(provider, "none").buildRequest(parseRequest({ model: "anthropic/claude-x", input: output })); + const replay = JSON.parse(request.body as string) as { messages: Array<{ content: unknown }> }; + expect(replay.messages[0].content).toEqual([ + { type: "thinking", thinking: "hidden exact\ntext", signature: first.signature }, + { type: "text", text: "answer" }, + ]); + // Deliberate existing limitation: no new signed carrier and no hidden-text disclosure. + expect(JSON.stringify(responsesJsonToAnthropicMessage({ output }, "claude-x"))).not.toContain("hidden exact"); + } + expect(() => anthropicToResponsesBody({ model: "m", messages: [{ role: "assistant", content: [ + { type: "thinking", thinking: "", signature: encodeReasoningEnvelope({ sig: first.signature, txt: "hidden exact" }) }, + ] }] })).toThrow(/continuity/); + }); + + test("explicitly empty signed envelope text does not fall back to a different summary", () => { + const parsed = parseRequest({ model: "m", input: [ + { type: "reasoning", summary: [{ type: "summary_text", text: "different summary" }], encrypted_content: encodeReasoningEnvelope({ sig: empty.signature, txt: "" }) }, + ] }); + expect(parsed.context.messages[0]?.content).toEqual([ + { type: "thinking", thinking: "", signature: empty.signature }, + ]); + }); + + test("opaque Anthropic payloads do not become Google signatures or native Responses encryption", async () => { + const body = anthropicToResponsesBody({ model: "google/gemini-test", messages: [ + { role: "assistant", content: [empty, before, tool] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: tool.id, content: "result" }] }, + ] }); + const google = withTestTranslatorBudget(createGoogleAdapter({ adapter: "google", baseUrl: "https://generativelanguage.googleapis.com", apiKey: "synthetic" })); + const request = await google.buildRequest(parseRequest(body)); + for (const output of [request.body as string, JSON.stringify(sanitizeReasoningInputContent(body))]) { + expect(output).not.toContain(empty.signature); + expect(output).not.toContain(before.data); + expect(output).not.toContain("ocxr1:"); + } + expect(parseRequest({ model: "m", input: [{ type: "reasoning", summary: [], encrypted_content: "native-opaque" }] }).context.messages).toEqual([]); + }); +}); diff --git a/tests/ci-workflows/ci-workflows.test.ts b/tests/ci-workflows/ci-workflows.test.ts index ec2c919c45..c967f9d4c0 100644 --- a/tests/ci-workflows/ci-workflows.test.ts +++ b/tests/ci-workflows/ci-workflows.test.ts @@ -506,17 +506,21 @@ describe("GitHub Actions hardening", () => { // allowlist. PRs always create the workflow and aggregate check; this list // decides whether the costly jobs run. Pin the entire list on both paths. const ciPaths = [ + ".dockerignore", ".gitattributes", ".github/workflows/ci.yml", ".github/workflows/enforce-pr-target.yml", ".github/workflows/release.yml", ".github/workflows/stale-needs-info.yml", ".npmignore", + "Dockerfile", "LICENSE", "README.md", "assets/**", "bin/**", "bun.lock", + "compose.yaml", + "docker/**", "gui/**", "package.json", "scripts/**", @@ -563,7 +567,7 @@ describe("GitHub Actions hardening", () => { expect(scopeIndex).toBeGreaterThan(filterIndex); const scopedCondition = "github.event_name != 'pull_request' || needs.changes.outputs.ci == 'true'"; - for (const jobName of ["test", "storage-policy", "gates", "platform-macos", "keyring-smoke"]) { + for (const jobName of ["test", "storage-policy", "gates", "platform-macos", "keyring-smoke", "docker-smoke"]) { const job = ci.jobs?.[jobName] as { needs?: string; if?: string } | undefined; expect(`${jobName}:${job?.needs}`).toBe(`${jobName}:changes`); expect(`${jobName}:${job?.if}`).toBe(`${jobName}:${scopedCondition}`); @@ -573,6 +577,34 @@ describe("GitHub Actions hardening", () => { expect(macosControlIf?.if).toBe("github.event_name == 'workflow_dispatch'"); }); + test("Docker smoke executes the source-build lifecycle and gates its result", async () => { + const ci = Bun.YAML.parse(await readText(".github/workflows/ci.yml")) as { + jobs?: Record; + steps?: Array<{ name?: string; run?: string; if?: string; "continue-on-error"?: boolean }>; + }>; + }; + const smoke = ci.jobs?.["docker-smoke"]; + expect(smoke?.["runs-on"]).toBe("ubuntu-latest"); + expect(smoke?.["timeout-minutes"]).toBe(20); + expect(smoke?.["continue-on-error"]).toBeUndefined(); + expect(smoke?.permissions).toBeUndefined(); // Inherits workflow contents:read. + const execution = smoke?.steps?.find(step => + hasExactShellCommand(step.run, "bun scripts/ci/docker-smoke.ts")); + expect(execution).toBeDefined(); + expect(execution?.if).toBeUndefined(); + expect(execution?.["continue-on-error"]).toBeUndefined(); + expect(ci.jobs?.ci?.needs).toContain("docker-smoke"); + const typecheck = ci.jobs?.gates?.steps?.find(step => step.name === "Typecheck"); + expect(hasExactShellCommand(typecheck?.run, + "bun x tsc --ignoreConfig --noEmit --strict --target ESNext --module ESNext --moduleResolution bundler --types bun-types --skipLibCheck scripts/ci/docker-smoke.ts", + )).toBe(true); + }); + test("cross-platform CI keeps the GUI lint and build gates", async () => { // Review finding (PR #97): the GUI build gate was silently dropped once; assert the // enhanced gate (PR #99) stays wired so broken GUI builds cannot merge unnoticed. diff --git a/tests/claude-integration/claude-code-thought-signature-scope.test.ts b/tests/claude-integration/claude-code-thought-signature-scope.test.ts index eb544dce97..b3d981c327 100644 --- a/tests/claude-integration/claude-code-thought-signature-scope.test.ts +++ b/tests/claude-integration/claude-code-thought-signature-scope.test.ts @@ -125,4 +125,16 @@ describe("Claude Code Anthropic inbound reasoning-replay scope", () => { const parsed = await drive({ promptCacheKey: " ", promptCacheKeyIsSharedCohort: false }); expect(parsed._reasoningReplayScope).toBeUndefined(); }); + + test("distinct session identities remain distinct and bounded", async () => { + const first = await drive({ promptCacheKey: "session-a", promptCacheKeyIsSharedCohort: false }); + const second = await drive({ promptCacheKey: "session-b", promptCacheKeyIsSharedCohort: false }); + const a = first._reasoningReplayScope?.clientThreadId; + const b = second._reasoningReplayScope?.clientThreadId; + expect(a).toBeDefined(); + expect(b).toBeDefined(); + expect(a).not.toBe(b); + expect(a).toBe("session-a"); + expect(b).toBe("session-b"); + }); }); diff --git a/tests/claude-integration/claude-inbound.test.ts b/tests/claude-integration/claude-inbound.test.ts index 32207c9019..7227bbf2f1 100644 --- a/tests/claude-integration/claude-inbound.test.ts +++ b/tests/claude-integration/claude-inbound.test.ts @@ -84,12 +84,12 @@ describe("claude inbound translation", () => { expect(tools[1]).toEqual({ type: "web_search" }); const input = body.input as Record[]; - // user text, assistant text (thinking dropped), function_call, function_call_output, user tail - expect(input.map(i => i.type ?? i.role)).toEqual(["message", "message", "function_call", "function_call_output", "message"]); - expect(input[1].content).toEqual([{ type: "output_text", text: "Reading it now." }]); - expect(input[2]).toMatchObject({ call_id: "toolu_01", name: "Read", arguments: JSON.stringify({ file_path: "/README.md" }) }); - expect(input[3]).toMatchObject({ call_id: "toolu_01", output: [{ type: "input_text", text: "# hello" }] }); - const tail = input[4].content as Record[]; + // user text, reasoning, assistant text, function_call, function_call_output, user tail + expect(input.map(i => i.type ?? i.role)).toEqual(["message", "reasoning", "message", "function_call", "function_call_output", "message"]); + expect(input[2].content).toEqual([{ type: "output_text", text: "Reading it now." }]); + expect(input[3]).toMatchObject({ call_id: "toolu_01", name: "Read", arguments: JSON.stringify({ file_path: "/README.md" }) }); + expect(input[4]).toMatchObject({ call_id: "toolu_01", output: [{ type: "input_text", text: "# hello" }] }); + const tail = input[5].content as Record[]; expect(tail[0]).toEqual({ type: "input_text", text: "now summarize" }); expect(tail[1]).toEqual({ type: "input_image", image_url: "data:image/png;base64,aWc=" }); }); diff --git a/tests/claude-integration/claude-outbound.test.ts b/tests/claude-integration/claude-outbound.test.ts index 299ce5135d..67380bb44a 100644 --- a/tests/claude-integration/claude-outbound.test.ts +++ b/tests/claude-integration/claude-outbound.test.ts @@ -13,6 +13,7 @@ import { TRANSLATOR_MAX_CALL_ARGUMENT_BYTES, type TranslatorBudget, } from "../../src/lib/translator-budget"; +import { decodeReasoningEnvelope, encodeReasoningEnvelope } from "../../src/responses/reasoning-envelope"; const streamBudgets = new WeakMap, TranslatorBudget>(); @@ -274,6 +275,8 @@ describe("claude outbound SSE", () => { "**A**\n\nOne.\n\n**B**\n\nTwo.", "Three.", ]); + expect(decodeReasoningEnvelope(thinkingBlocks[0].signature)?.txt) + .toBe("**A**\n\nOne.\n\n**B**\n\nTwo."); // Parity: the non-streaming translator joins the same summary parts identically. const json = responsesJsonToAnthropicMessage({ @@ -286,6 +289,152 @@ describe("claude outbound SSE", () => { expect(jsonThinking.thinking).toBe("**A**\n\nOne.\n\n**B**\n\nTwo."); }); + test("reasoning fallback buffering is bounded and releases its retained budget", async () => { + const budget = createTestTranslatorBudget({ maxTurnBytes: 8 * 1024 }); + let reasoningCommitted = 0; + let reasoningReleased = 0; + const trackedBudget: TranslatorBudget = { + openCall: id => budget.openCall(id), + closeCall: id => budget.closeCall(id), + reserveTransient(bytes, scope) { + const reservation = budget.reserveTransient(bytes, scope); + return { + commitRetained() { + reservation.commitRetained(); + if (scope.kind === "reasoning") reasoningCommitted += bytes; + }, + release: () => reservation.release(), + }; + }, + chargeRetained(bytes, scope) { + budget.chargeRetained(bytes, scope); + if (scope.kind === "reasoning") reasoningCommitted += bytes; + }, + releaseRetained(bytes, scope) { + budget.releaseRetained(bytes, scope); + if (scope.kind === "reasoning") reasoningReleased += bytes; + }, + observeAcceptedRequestCopy: bytes => budget.observeAcceptedRequestCopy(bytes), + observeExternallyCapped: (kind, bytes) => budget.observeExternallyCapped(kind, bytes), + snapshot: () => budget.snapshot(), + dispose: () => budget.dispose(), + }; + const frames = [ + sse("response.created", { response: { id: "resp_1", status: "in_progress" } }), + ...Array.from({ length: 32 }, (_, index) => sse("response.reasoning_text.delta", { + item_id: "rs_1", + content_index: 0, + delta: `${index}:` + "x".repeat(512), + })), + ]; + const events = await collectEvents(responsesSseToAnthropicSse( + streamFromChunks(frames), + "m", + { translatorBudget: trackedBudget }, + )); + + expect(events.at(-1)).toMatchObject({ + name: "error", + data: { error: { type: "request_too_large", code: "translation_buffer_limit" } }, + }); + expect(budget.snapshot().overflows).toBe(1); + expect(reasoningCommitted).toBeGreaterThan(0); + expect(reasoningReleased).toBe(reasoningCommitted); + }); + + for (const terminal of ["eof", "failed", "completed", "incomplete"] as const) { + for (const buffered of [false, true]) { + test(`closure-only reasoning overflow: ${terminal}, ${buffered ? "collector" : "stream"}`, async () => { + // All small deltas fit, including replacement reservations. Closing needs + // the retained 32 KiB text PLUS its base64 signature frame. Capture the + // generated stream before collection: concurrent collector retention can + // exceed a shared budget during ingestion instead of exercising closure. + // Collection below reuses this SAME budget, without resetting it. + const budget = createTestTranslatorBudget({ maxTurnBytes: 70 * 1024 }); + let reasoningBytes = 0; + let maxReasoningBytes = 0; + let reasoningBytesAtOverflow = -1; + const trackedBudget: TranslatorBudget = { + openCall: id => budget.openCall(id), + closeCall: id => budget.closeCall(id), + reserveTransient(bytes, scope) { + let reservation: ReturnType; + try { reservation = budget.reserveTransient(bytes, scope); } + catch (error) { reasoningBytesAtOverflow = reasoningBytes; throw error; } + return { + commitRetained() { + reservation.commitRetained(); + if (scope.kind === "reasoning") { + reasoningBytes += bytes; + maxReasoningBytes = Math.max(maxReasoningBytes, reasoningBytes); + } + }, + release: () => reservation.release(), + }; + }, + chargeRetained: (bytes, scope) => budget.chargeRetained(bytes, scope), + releaseRetained(bytes, scope) { + if (scope.kind === "reasoning") reasoningBytes -= bytes; + budget.releaseRetained(bytes, scope); + }, + observeAcceptedRequestCopy: bytes => budget.observeAcceptedRequestCopy(bytes), + observeExternallyCapped: (kind, bytes) => budget.observeExternallyCapped(kind, bytes), + snapshot: () => budget.snapshot(), + dispose: () => budget.dispose(), + }; + const text = "x".repeat(32 * 1024); + const frames = Array.from({ length: 128 }, () => sse("response.reasoning_text.delta", { + item_id: "rs_closure", content_index: 0, delta: text.slice(0, 256), + })); + if (terminal !== "eof") { + frames.push(sse(`response.${terminal}`, { response: terminal === "failed" + ? { error: { message: "upstream failure", status: 502 } } + : terminal === "incomplete" + ? { status: "incomplete", incomplete_details: { reason: "max_output_tokens" }, usage: {} } + : { status: "completed", usage: {} } })); + // Neither a repeated completion nor a later failure may add a terminal. + frames.push(sse("response.completed", { response: { status: "completed", usage: {} } })); + frames.push(sse("response.failed", { response: { error: { message: "late failure" } } })); + } + const stream = responsesSseToAnthropicSse(streamFromChunks(frames), "m", { + translatorBudget: trackedBudget, pingIntervalMs: 0, + }); + const captured = buffered ? await new Response(stream).text() : undefined; + const capturedFrames = captured?.split("\n\n").filter(Boolean).map(frame => `${frame}\n\n`); + const events = await collectEvents(capturedFrames ? streamFromChunks(capturedFrames) : stream); + const deltas = events.filter(event => event.data.delta?.type === "thinking_delta"); + expect(deltas.map(event => event.data.delta.thinking).join("")).toBe(text); + expect(events.filter(event => event.name === "error")).toHaveLength(1); + expect(events.at(-1)).toMatchObject({ name: "error", data: { type: "error", error: { + type: "request_too_large", code: "translation_buffer_limit", + } } }); + expect(JSON.stringify(events.at(-1)).length).toBeLessThan(1024); + expect(events.some(event => event.name === "message_stop" || event.name === "message_delta" || event.name === "content_block_stop")).toBe(false); + expect(events.some(event => event.data.delta?.type === "signature_delta")).toBe(false); + if (capturedFrames) { + expect(capturedFrames.join("")).toBe(captured); + expect(reasoningBytesAtOverflow).toBe(text.length); + expect(reasoningBytes).toBe(0); + expect(budget.snapshot().overflows).toBe(1); + // Feed the actual generated frames, without inventing an error event or + // collecting one huge chunk that introduces a different buffer limit. + const message = await collectAnthropicMessage(streamFromChunks(capturedFrames), "m", trackedBudget); + expect(message).toMatchObject({ type: "error", error: { + type: "request_too_large", code: "translation_buffer_limit", + } }); + expect(message).not.toHaveProperty("content"); + expect(message).not.toHaveProperty("stop_reason"); + } + // These prove failure happened after all text was retained, not while + // ingesting a delta, and the error path released the thinking reservation. + expect(reasoningBytesAtOverflow).toBe(text.length); + expect(maxReasoningBytes).toBeGreaterThanOrEqual(text.length); + expect(reasoningBytes).toBe(0); + expect(budget.snapshot().overflows).toBe(1); + }); + } + } + test("same-part deltas and index-free reasoning frames never get a separator", async () => { const samePart = [ sse("response.created", { response: { id: "resp_1", status: "in_progress" } }), @@ -1109,4 +1258,49 @@ describe("sanitizeWebSearchInput (#381)", () => { data: { error: { type: "request_too_large", code: "translation_buffer_limit" } }, }); }, 60_000); + + test("redacted-only reasoning emits a standalone redacted_thinking block", async () => { + const events = await collectEvents(responsesSseToAnthropicSse(streamFrom([ + sse("response.output_item.done", { + item: { type: "reasoning", id: "rs_red", encrypted_content: encodeReasoningEnvelope({ red: ["opaque"] }) }, + }), + sse("response.completed", { response: { status: "completed", usage: {} } }), + ].join("")), "m")); + expect(events.map(event => event.name)).toEqual([ + "message_start", "ping", "content_block_start", "content_block_stop", "message_delta", "message_stop", + ]); + expect(events[2].data.content_block).toEqual({ type: "redacted_thinking", data: "opaque" }); + }); + + test("redacted reasoning closes an open text block before opening its opaque block", async () => { + const events = await collectEvents(responsesSseToAnthropicSse(streamFrom([ + sse("response.output_text.delta", { delta: "text" }), + sse("response.output_item.done", { + item: { type: "reasoning", id: "rs_red", encrypted_content: encodeReasoningEnvelope({ red: ["opaque"] }) }, + }), + sse("response.completed", { response: { status: "completed", usage: {} } }), + ].join("")), "m")); + expect(events.filter(event => event.name === "content_block_start" || event.name === "content_block_stop") + .map(event => ({ name: event.name, index: event.data.index }))).toEqual([ + { name: "content_block_start", index: 0 }, + { name: "content_block_stop", index: 0 }, + { name: "content_block_start", index: 1 }, + { name: "content_block_stop", index: 1 }, + ]); + }); + + test("signature-only reasoning emits an empty thinking block with the genuine signature", async () => { + const events = await collectEvents(responsesSseToAnthropicSse(streamFrom([ + sse("response.output_item.done", { + item: { type: "reasoning", id: "rs_sig", encrypted_content: encodeReasoningEnvelope({ sig: "sig-only" }) }, + }), + sse("response.completed", { response: { status: "completed", usage: {} } }), + ].join("")), "m")); + expect(events.map(event => event.name)).toEqual([ + "message_start", "ping", "content_block_start", "content_block_delta", "content_block_stop", + "message_delta", "message_stop", + ]); + expect(events[2].data.content_block).toEqual({ type: "thinking", thinking: "", signature: "" }); + expect(events[3].data.delta).toEqual({ type: "signature_delta", signature: "sig-only" }); + }); }); diff --git a/tests/claude-integration/claude-source-envelope.test.ts b/tests/claude-integration/claude-source-envelope.test.ts new file mode 100644 index 0000000000..a78c9f1a15 --- /dev/null +++ b/tests/claude-integration/claude-source-envelope.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, test } from "bun:test"; +import { anthropicToResponsesBody } from "../../src/claude/inbound"; + +describe("Claude source envelope boundaries", () => { + test("nested tool results retain only bounded structured content", () => { + const body = anthropicToResponsesBody({ + model: "m", + messages: [ + { role: "assistant", content: [{ type: "tool_use", id: "call-1", name: "lookup", input: { q: "x" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "call-1", content: [ + { type: "text", text: "ok" }, + { type: "document", title: "report" }, + { type: "future_block", payload: "secret-payload" }, + ] }] }, + ], + }) as any; + expect(body.input.map((item: any) => item.type)).toEqual(["function_call", "function_call_output"]); + expect(body.input[1].output).toEqual([ + { type: "input_text", text: "ok" }, + { type: "input_text", text: "[document: report]" }, + ]); + expect(JSON.stringify(body)).not.toContain("secret-payload"); + }); + + test("malformed tool results fail closed instead of becoming an unpaired output", () => { + expect(() => anthropicToResponsesBody({ + model: "m", messages: [{ role: "user", content: [{ type: "tool_result", content: "secret-payload" }] }], + })).toThrow(/unknown|unpaired|tool/i); + }); +}); diff --git a/tests/cli/cli-export-command.test.ts b/tests/cli/cli-export-command.test.ts index 4c9808677a..6d8a513558 100644 --- a/tests/cli/cli-export-command.test.ts +++ b/tests/cli/cli-export-command.test.ts @@ -204,6 +204,24 @@ describe("ocx export --json (accept criterion 1)", () => { expect(parsed.provider.opencodex!.options.baseURL).not.toContain(":10100/"); }); + test("OpenCode export keeps the live port when saved listener settings point at a future port", async () => { + const code = await handleExportCommand(["--client", "opencode", "--json"], { + baseUrl: "http://127.0.0.1:10100", + configImpl: () => config({ + hostname: "0.0.0.0", + unauthenticatedLoopbackListener: { enabled: true, port: 10999 }, + }), + fetchImpl: (async input => { + expect(String(input)).toBe("http://127.0.0.1:10100/api/models"); + return Response.json(ROWS); + }) as typeof fetch, + }); + expect(code).toBe(0); + const parsed = JSON.parse(stdout()) as { provider: Record }; + expect(parsed.provider.opencodex!.options.baseURL).toBe("http://127.0.0.1:10100/v1"); + expect(parsed.provider.opencodex!.options.baseURL).not.toContain(":10999/"); + }); + test("disabled rows never reach the exported config", async () => { const proxy = fakeProxy(); const result = await run(["--client", "pi", "--json"], { baseUrl: proxy.baseUrl }); @@ -543,3 +561,51 @@ describe("export allowlist parity", () => { ], cfg).map(row => row.namespaced)).toEqual(["slash/org-model"]); }); }); + +describe("Raycast export uses the live management admission policy", () => { + for (const secondary of [false, true]) { + test(`live wildcard bind with secondary=${secondary} wins over saved loopback config`, async () => { + const oldHome = process.env.OPENCODEX_HOME; + const oldCodexHome = process.env.CODEX_HOME; + const root = tempDir(); + process.env.OPENCODEX_HOME = join(root, "ocx"); + process.env.CODEX_HOME = join(root, "codex"); + mkdirSync(process.env.CODEX_HOME, { recursive: true }); + try { + const liveConfig = config({ + hostname: "0.0.0.0", + providers: { mock: { + adapter: "openai-chat", baseUrl: "http://127.0.0.1/v1", + liveModels: false, models: ["fixture-model"], + } }, + ...(secondary ? { unauthenticatedLoopbackListener: { enabled: true, port: 10237 } } : {}), + }); + const proxy = managementProxy(liveConfig); + const out = join(root, "providers.yaml"); + writeFileSync(out, "keep existing export\n"); + const result = await run(["--client", "raycast", "--json", "--out", out, "--force"], { + baseUrl: proxy.baseUrl, + // Deliberately contradict both live bind and secondary port. + config: config({ unauthenticatedLoopbackListener: { enabled: true, port: 10999 } }), + }); + if (secondary) { + expect(result.code).toBe(0); + const document = JSON.parse(result.stdout) as { providers: Array<{ base_url: string }> }; + expect(document.providers[0]!.base_url).toBe("http://127.0.0.1:10237/v1"); + expect(readFileSync(out, "utf8")).toContain("10237/v1"); + expect(readFileSync(out, "utf8")).not.toContain("10999"); + } else { + expect(result.code).not.toBe(0); + expect(result.stdout).toBe(""); + expect(result.stderr).toContain("non_loopback"); + expect(readFileSync(out, "utf8")).toBe("keep existing export\n"); + } + } finally { + if (oldHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = oldHome; + if (oldCodexHome === undefined) delete process.env.CODEX_HOME; + else process.env.CODEX_HOME = oldCodexHome; + } + }); + } +}); diff --git a/tests/cli/cli-provider.test.ts b/tests/cli/cli-provider.test.ts index b83bc8d514..ea29c5535f 100644 --- a/tests/cli/cli-provider.test.ts +++ b/tests/cli/cli-provider.test.ts @@ -109,6 +109,80 @@ describe("ocx provider", () => { } }); + test("provider list --jsonl matches JSON configured records with escaped model values", () => { + const escapedModel = 'model-"quoted"\\path\nnext\r\ttab-한글'; + const { dir } = freshConfig({ + providers: { + openai: { + adapter: "openai-responses", + baseUrl: "https://chatgpt.com/backend-api/codex", + authMode: "forward", + }, + "custom.models-1": { + adapter: "openai-chat", + baseUrl: "https://models.example.test/v1", + defaultModel: escapedModel, + models: ["plain-model", escapedModel], + }, + }, + defaultProvider: "custom.models-1", + }); + try { + const result = runCli(["provider", "list", "--jsonl"], { OPENCODEX_HOME: dir }); + const json = runCli(["provider", "list", "--json"], { OPENCODEX_HOME: dir }); + expect(result.status).toBe(0); + expect(json.status).toBe(0); + // Keep every physical line: embedded newlines must be escaped, and only + // the final record terminator may produce an empty split element. + const lines = result.stdout.split(/\r?\n/); + expect(lines.pop()).toBe(""); + expect(lines).toHaveLength(2); + const records = lines.map(line => JSON.parse(line)); + const envelope = JSON.parse(json.stdout); + expect(records).toEqual(envelope.configured); + expect(envelope.registryCount).toBeGreaterThan(0); + expect(records).toEqual([ + { + name: "openai", + adapter: "openai-responses", + baseUrl: "https://chatgpt.com/backend-api/codex", + authMode: "forward", + defaultModel: null, + isDefault: false, + source: "registry", + models: [], + }, + { + name: "custom.models-1", + adapter: "openai-chat", + baseUrl: "https://models.example.test/v1", + authMode: "key", + defaultModel: escapedModel, + isDefault: true, + source: "custom", + models: ["plain-model", escapedModel], + }, + ]); + } finally { + removeTreeWithRetry(dir); + } + }); + + test.each([ + ["--json", "--jsonl"], + ["--jsonl", "--json"], + ])("provider list rejects %s %s without stdout", (first, second) => { + const { dir } = freshConfig(); + try { + const result = runCli(["provider", "list", first, second], { OPENCODEX_HOME: dir }); + expect(result.status).toBe(1); + expect(result.stdout).toBe(""); + expect(result.stderr).toContain("Use only one of --json or --jsonl"); + } finally { + removeTreeWithRetry(dir); + } + }); + test("provider add registry provider seeds config", () => { const { dir } = freshConfig(); try { diff --git a/tests/cli/cli-status-json.test.ts b/tests/cli/cli-status-json.test.ts index 31371baa33..10ab4f110e 100644 --- a/tests/cli/cli-status-json.test.ts +++ b/tests/cli/cli-status-json.test.ts @@ -10,9 +10,11 @@ import { fileURLToPath } from "node:url"; import { isConnectionRefused, isUncleanExitEvidence, proxyHealthFailureReason, resolveStatusPid, selectListenTarget } from "../../src/cli/status"; import * as statusFacade from "../../src/cli/status"; import * as statusProbes from "../../src/cli/status-probes"; +import { packageVersion } from "../../src/cli/help"; +import { getDefaultConfig } from "../../src/config"; import { findDeadPid } from "../helpers/dead-pid"; import { removeTreeWithRetry } from "../helpers/remove-tree"; -import { STORE_BUDGET_MS } from "../helpers/test-budget"; +import { INTERNAL_DEADLINE_MS, SPAWN_BUDGET_MS, STORE_BUDGET_MS } from "../helpers/test-budget"; import { inspectClientRotationRecoveryGate, readClientConnectionState } from "../../src/client/state"; import * as lifecycleLock from "../../src/client/lifecycle-lock"; import { writeDesktopDisconnectReceipt } from "../../src/claude/desktop-remote-store"; @@ -28,6 +30,84 @@ function runStatusJson(opencodexHome: string) { }); } +describe("status version skew projection", () => { + test.each([ + ["0.0.1", "the running proxy is older"], + ["999999.0.0", "this ocx on PATH is older"], + [packageVersion(), null], + [`${packageVersion()}+skew-fixture`, "neither can be identified as older"], + ["not-a-version", "neither can be identified as older"], + ["unknown", null], + ["0.0.0", null], + [undefined, null], + ] as const)("projects proxy %s in JSON and human output", async (proxyVersion, expected) => { + const home = mkdtempSync(join(tmpdir(), "ocx-status-skew-")); + const codexHome = join(home, "codex"); + let server: ReturnType | undefined; + try { + // Explicit CODEX_HOME must exist before the CLI imports codex/paths.ts. + mkdirSync(codexHome, { recursive: true }); + server = Bun.serve({ + hostname: "127.0.0.1", port: 0, + fetch(request) { + return new URL(request.url).pathname === "/healthz" + ? Response.json({ service: "opencodex", status: "ok", version: proxyVersion, uptime: 1 }) + : new Response("not found", { status: 404 }); + }, + }); + writeFileSync(join(home, "config.json"), JSON.stringify({ + ...getDefaultConfig(), port: server.port, hostname: "127.0.0.1", codexAutoStart: false, + })); + for (const json of [true, false]) { + // Async child execution lets the fixture answer the real identity/health probes. + const child = Bun.spawn([process.execPath, cliPath, "status", ...(json ? ["--json"] : [])], { + cwd: repoRoot, + env: { ...process.env, OPENCODEX_HOME: home, CODEX_HOME: codexHome }, + stdout: "pipe", stderr: "pipe", + }); + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + child.kill("SIGKILL"); + }, INTERNAL_DEADLINE_MS); + try { + const [stdout, stderr, exitCode] = await Promise.all([ + new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited, + ]); + expect(timedOut).toBe(false); + // Preserve both gates while surfacing the child error when startup fails. + expect({ exitCode, stderr }).toEqual({ exitCode: 0, stderr: "" }); + if (json) { + const parsed = JSON.parse(stdout); + expect(parsed.schemaVersion).toBe(1); + expect(Object.keys(parsed.versionSkew).sort()).toEqual(["cliVersion", "proxyVersion", "skewed", "warning"]); + expect(parsed.versionSkew.cliVersion).toBe(packageVersion()); + expect(parsed.versionSkew.proxyVersion).toBe(proxyVersion ?? null); + expect(parsed.versionSkew.skewed).toBe(expected !== null); + if (expected === null) expect(parsed.versionSkew.warning).toBeNull(); + else expect(parsed.versionSkew.warning).toContain(expected); + } else if (expected === null) { + expect(stdout).not.toContain("does not match the running proxy"); + } else { + expect(stdout).toContain(expected); + } + } finally { + clearTimeout(timer); + if (child.exitCode === null) child.kill("SIGKILL"); + await child.exited; + } + } + expect(existsSync(join(home, "ocx.pid"))).toBe(false); + } finally { + try { + await server?.stop(true); + } finally { + removeTreeWithRetry(home); + } + } + }, SPAWN_BUDGET_MS); +}); + function withRecoveryStatusFixture(work: (fixture: { home: string; lockDeps: { lockPath: string }; diff --git a/tests/cli/cli-version-skew.test.ts b/tests/cli/cli-version-skew.test.ts index 6e45f83c28..36fb6845f9 100644 --- a/tests/cli/cli-version-skew.test.ts +++ b/tests/cli/cli-version-skew.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { computeVersionSkew } from "../../src/cli/version-skew"; +import { computeVersionSkew, isConfirmedVersionMatch } from "../../src/cli/version-skew"; import { packageVersion } from "../../src/cli/help"; /** @@ -7,20 +7,83 @@ import { packageVersion } from "../../src/cli/help"; * build, and nothing surfaced it because the CLI never compared the two versions. */ describe("version skew detection", () => { - test("reports skew when the proxy reports a different version", () => { + test("directs an older CLI to upgrade or resolve PATH", () => { const skew = computeVersionSkew("2.35.0", "2.36.1"); expect(skew.skewed).toBe(true); expect(skew.cliVersion).toBe("2.35.0"); expect(skew.proxyVersion).toBe("2.36.1"); expect(skew.warning).toContain("2.35.0"); expect(skew.warning).toContain("2.36.1"); - expect(skew.warning).toContain("stale"); + expect(skew.warning).toContain("this ocx on PATH is older"); + expect(skew.warning).toContain("Upgrade the CLI or resolve PATH"); + expect(skew.warning).not.toContain("ocx service repair"); + }); + + test("#3464 directs a newer CLI to restart the older proxy", () => { + const skew = computeVersionSkew("2.42.0", "2.10.1-preview.20260805"); + expect(skew).toEqual({ + cliVersion: "2.42.0", + proxyVersion: "2.10.1-preview.20260805", + skewed: true, + warning: "CLI 2.42.0 does not match the running proxy 2.10.1-preview.20260805 — " + + "the running proxy is older than this CLI. Restart the proxy using the intended current installation. " + + "For a background service, run ocx service repair (ocx service restart is an alias).", + }); + expect(skew.warning).not.toContain("this ocx on PATH is older"); + }); + + test.each([ + ["2.43.0", "2.43.0-preview.1"], + ["2.43.0-preview.10", "2.43.0-preview.2"], + ["2.43.0-preview.beta", "2.43.0-preview.10"], + ["2.43.0-preview.1", "2.43.0-preview"], + ["2.43.0-beta", "2.43.0-alpha"], + ["2.44.0-preview.1", "2.43.0"], + ["10.0.0", "9.99.99"], + ["2.43.1", "2.43.0"], + ["2.43.0-preview.9007199254740993", "2.43.0-preview.9007199254740992"], + ])("orders %s above %s in both directions", (newer, older) => { + expect(computeVersionSkew(newer, older).warning).toContain("the running proxy is older"); + expect(computeVersionSkew(older, newer).warning).toContain("this ocx on PATH is older"); + }); + + test.each([ + ["2.43.0+build.1", "2.43.0+build.2"], + ["2.43.0", "2.43.0+build.1"], + ["2.43.0-preview.1+a", "2.43.0-preview.1+b"], + ["invalid", "2.43.0"], + ["2.43", "2.43.0"], + ["v2.43.0", "2.43.0"], + [" 2.43.0", "2.43.0"], + ["2.43.0 ", "2.43.0"], + ["2.43.0-preview.01", "2.43.0-preview.1"], + ["", "2.43.0"], + ])("keeps raw unequal %s / %s neutral in both directions", (left, right) => { + for (const [cli, proxy] of [[left, right], [right, left]]) { + const skew = computeVersionSkew(cli!, proxy!); + expect(skew.cliVersion).toBe(cli); + expect(skew.proxyVersion).toBe(proxy); + expect(skew.skewed).toBe(true); + expect(skew.warning).toContain("neither can be identified as older"); + expect(skew.warning).not.toContain("ocx service repair"); + expect(isConfirmedVersionMatch(skew)).toBe(false); + } + }); + + test.each(["unknown", "0.0.0"])("suppresses %s on either side without confirming a match", placeholder => { + for (const [cli, proxy] of [[placeholder, "2.43.0"], ["2.43.0", placeholder], [placeholder, placeholder]]) { + const skew = computeVersionSkew(cli!, proxy!); + expect(skew.skewed).toBe(false); + expect(skew.warning).toBeNull(); + expect(isConfirmedVersionMatch(skew)).toBe(false); + } }); test("stays quiet when the versions match", () => { const skew = computeVersionSkew("2.35.0", "2.35.0"); expect(skew.skewed).toBe(false); expect(skew.warning).toBeNull(); + expect(isConfirmedVersionMatch(skew)).toBe(true); }); test("stays quiet when nothing is live", () => { @@ -28,6 +91,7 @@ describe("version skew detection", () => { expect(skew.skewed).toBe(false); expect(skew.proxyVersion).toBeNull(); expect(skew.warning).toBeNull(); + expect(isConfirmedVersionMatch(skew)).toBe(false); }); test("suppresses the warning when the proxy reports the 0.0.0 placeholder", () => { diff --git a/tests/clients/aside-profile-identity.test.ts b/tests/clients/aside-profile-identity.test.ts new file mode 100644 index 0000000000..771966a1c4 --- /dev/null +++ b/tests/clients/aside-profile-identity.test.ts @@ -0,0 +1,132 @@ +import { expect, spyOn, test } from "bun:test"; +import * as fs from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { IntegrationIO } from "../../src/integrations/config-io"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +// Capture real delegates before spying. Only fixture inode values are controlled; +// existence, file type, link count, realpath and link resolution remain native. +const nativeLstat = fs.lstatSync; +const nativeStat = fs.statSync; +const FIRST_INODE = 2n ** 53n; +const SECOND_INODE = FIRST_INODE + 1n; + +test("Aside preserves high file identities without admitting shared targets or directory replacement", async () => { + const home = fs.mkdtempSync(join(tmpdir(), "ocx-aside-identity-")); + const root = join(home, ".aside"); + const paths = [0, 1].map(id => join(root, "u", String(id), "models.json")); + const identities = new Map(); + const reads = new Set(); + let observingBoundary = false; + const restoreSpies: Array<() => void> = []; + + function controlledStat(delegate: typeof fs.statSync, kind: "stat" | "lstat"): typeof fs.statSync { + // Preserve fs's overload contract: the native delegate determines the result + // type, including undefined for throwIfNoEntry:false and number vs bigint. + return ((path: fs.PathLike, options?: fs.StatOptions) => { + const stats = delegate(path, options); + const inode = typeof path === "string" ? identities.get(path) : undefined; + if (stats && inode !== undefined) { + if (observingBoundary) reads.add(`${kind}:${path}`); + // Mutate this fresh native result, retaining its prototype and method + // receiver. Spreading Stats would lose native isFile/isDirectory methods. + stats.ino = options?.bigint ? inode : Number(inode); + } + return stats; + }) as typeof fs.statSync; + } + + function observe(run: () => T): T { + reads.clear(); + observingBoundary = true; + try { return run(); } finally { observingBoundary = false; } + } + + try { + for (const id of [0, 1]) fs.mkdirSync(join(root, "u", String(id)), { recursive: true }); + fs.writeFileSync(join(root, "accounts.json"), JSON.stringify({ + currentAccountId: 0, accounts: [{ id: 0 }, { id: 1 }], + })); + for (const path of paths) fs.writeFileSync(path, "{}"); + // Controlled IDs must not hide a runtime lacking native BigInt stat support. + expect(typeof nativeStat(paths[0]!, { bigint: true }).ino).toBe("bigint"); + expect(typeof nativeLstat(paths[0]!, { bigint: true }).ino).toBe("bigint"); + const lstatSpy = spyOn(fs, "lstatSync"); + restoreSpies.push(() => lstatSpy.mockRestore()); + lstatSpy.mockImplementation(controlledStat(nativeLstat, "lstat")); + const statSpy = spyOn(fs, "statSync"); + restoreSpies.push(() => statSpy.mockRestore()); + statSpy.mockImplementation(controlledStat(nativeStat, "stat")); + + // Load after spies so the regression also covers the native named-import seam. + const { assertAsideProfileBoundary, guardAsideProfileIO, listAsideProfiles } = + await import("../../src/clients/aside-profiles"); + const [selected, peer] = listAsideProfiles({}, home); + if (!selected || !peer) throw new Error("fixture requires two profiles"); + const profiles = [selected, peer]; + expect(Number(FIRST_INODE)).toBe(Number(SECOND_INODE)); + expect(FIRST_INODE).not.toBe(SECOND_INODE); + expect(nativeStat(selected.configPath, { bigint: true }).dev) + .toBe(nativeStat(peer.configPath, { bigint: true }).dev); + // Distinct catalogs and directories are allowed even though their Number + // representations collide. + // Reads are recorded only DURING boundary calls, so a missed spy binding + // cannot silently turn this into a passing ordinary-filesystem test. + for (const target of ["configPath", "detectDir"] as const) { + identities.clear(); + identities.set(selected[target], FIRST_INODE); + identities.set(peer[target], SECOND_INODE); + for (const profile of profiles) { + const sibling = profile === selected ? peer : selected; + observe(() => expect(() => assertAsideProfileBoundary(profile, profiles, true)).not.toThrow()); + expect(reads.has(`lstat:${profile[target]}`)).toBe(true); + expect(reads.has(`stat:${sibling[target]}`)).toBe(true); + } + } + + identities.clear(); + identities.set(selected.detectDir, FIRST_INODE); + let delegatedReads = 0; + const io: IntegrationIO = { + readText: () => { delegatedReads++; return { kind: "text", text: "{}" }; }, + statKind: () => "file", + writeText: () => {}, removeFile: () => {}, mkdirp: () => {}, + now: () => 0, appendJournal: () => {}, putRecord: () => {}, dropRecord: () => {}, + }; + const guarded = observe(() => guardAsideProfileIO(selected, io, profiles)); + expect(reads.has(`lstat:${selected.detectDir}`)).toBe(true); + observe(() => expect(guarded.readText(selected.configPath)).toEqual({ kind: "text", text: "{}" })); + expect(reads.has(`lstat:${selected.detectDir}`)).toBe(true); + expect(delegatedReads).toBe(1); + identities.set(selected.detectDir, SECOND_INODE); + observe(() => expect(() => guarded.readText(selected.configPath)) + .toThrow("the account directory changed after the operation began.")); + expect(reads.has(`lstat:${selected.detectDir}`)).toBe(true); + expect(delegatedReads).toBe(1); + + // No synthetic IDs for these controls: real hardlinks and symlinks must + // continue to be refused by the same boundary, with native stat delegates. + identities.clear(); + fs.unlinkSync(peer.configPath); + fs.linkSync(selected.configPath, peer.configPath); + expect(nativeLstat(selected.configPath, { bigint: true }).nlink).toBe(2n); + for (const profile of profiles) { + expect(() => assertAsideProfileBoundary(profile, profiles, true)) + .toThrow("the model catalog is a link, shared file or non-regular file."); + } + fs.unlinkSync(peer.configPath); + fs.symlinkSync(selected.configPath, peer.configPath, "file"); + expect(nativeLstat(peer.configPath, { bigint: true }).isSymbolicLink()).toBe(true); + expect(() => assertAsideProfileBoundary(selected, profiles, true)) + .toThrow("account catalogs share a target."); + expect(() => assertAsideProfileBoundary(peer, profiles, true)) + .toThrow("the model catalog is a link, shared file or non-regular file."); + } finally { + observingBoundary = false; + identities.clear(); + reads.clear(); + for (const restore of restoreSpies.reverse()) restore(); + removeTreeWithRetry(home); + } +}); diff --git a/tests/clients/integrations-merge.test.ts b/tests/clients/integrations-merge.test.ts new file mode 100644 index 0000000000..6585d9f1e9 --- /dev/null +++ b/tests/clients/integrations-merge.test.ts @@ -0,0 +1,301 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import type { ExportModel, ManagedContribution } from "../../src/clients/config-export"; +import { + AmbiguousSelectorError, + createdContainerPaths, + deletePath, + parseSegment, + setPath, +} from "../../src/integrations/merge"; +import { INTEGRATION_CLIENTS } from "../../src/integrations/registry"; +import { blockedContainerPath, readIntegrationState, readPath } from "../../src/integrations/state"; +import { createIntegrationStateStore, type IntegrationStateStore } from "../../src/integrations/store"; +import { + applyIntegration, + disableIntegration, + overwriteIntegration, + refreshIntegration, + type IntegrationWriteInput, +} from "../../src/integrations/writer"; +import type { OcxConfig } from "../../src/types"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +/** + * The `[field=value]` path segment: one element of a sequence, addressed by a + * field rather than an index so the user's own reordering cannot move it under + * us. Plan: devlog/_plan/260904_raycast_integration/000_plan.md (WP1). + */ +const OURS = { id: "opencodex", name: "OpenCodex" }; +const THEIRS = { id: "lmstudio", name: "LM Studio" }; +const SELECT = ["providers", "[id=opencodex]"] as const; + +function contribution(path: readonly string[], value: unknown = OURS): ManagedContribution { + return { clientId: "raycast", fragments: [{ path, value }] }; +} + +describe("parseSegment", () => { + test("a selector splits into field and value; anything else is a key", () => { + expect(parseSegment("[id=opencodex]")).toEqual({ kind: "select", field: "id", value: "opencodex" }); + expect(parseSegment("[model_id=anthropic/claude-opus-5]")) + .toEqual({ kind: "select", field: "model_id", value: "anthropic/claude-opus-5" }); + expect(parseSegment("providers")).toEqual({ kind: "key", key: "providers" }); + // Near misses stay keys: a client whose map literally has such a key keeps working. + expect(parseSegment("[id=]")).toEqual({ kind: "key", key: "[id=]" }); + expect(parseSegment("[=x]")).toEqual({ kind: "key", key: "[=x]" }); + expect(parseSegment("[id=x")).toEqual({ kind: "key", key: "[id=x" }); + }); +}); + +describe("setPath with a selector", () => { + test("replaces the matching element in place and keeps siblings and order", () => { + const doc = { providers: [THEIRS, { id: "opencodex", name: "old" }, { id: "other" }], keep: true }; + const next = setPath(doc, SELECT, OURS) as typeof doc; + expect(next.providers).toEqual([THEIRS, OURS, { id: "other" }]); + expect(next.keep).toBe(true); + // The input is not mutated. + expect(doc.providers[1]).toEqual({ id: "opencodex", name: "old" }); + }); + + test("pushes when no element matches", () => { + const next = setPath({ providers: [THEIRS] }, SELECT, OURS) as { providers: unknown[] }; + expect(next.providers).toEqual([THEIRS, OURS]); + }); + + test("creates the array when absent, and createdContainerPaths reports it", () => { + expect(createdContainerPaths({}, contribution(SELECT))).toEqual(["providers"]); + expect(createdContainerPaths({ providers: {} }, contribution(SELECT))).toEqual(["providers"]); + expect(createdContainerPaths({ providers: [THEIRS] }, contribution(SELECT))).toEqual([]); + expect(setPath({}, SELECT, OURS)).toEqual({ providers: [OURS] }); + // A record where the array belongs is replaced, exactly as a scalar under a key is. + expect(setPath({ providers: {} }, SELECT, OURS)).toEqual({ providers: [OURS] }); + }); + + test("descends into a matched element, seeding one when absent", () => { + const path = ["providers", "[id=opencodex]", "name"]; + expect(setPath({ providers: [THEIRS] }, path, "X")) + .toEqual({ providers: [THEIRS, { id: "opencodex", name: "X" }] }); + expect(setPath({ providers: [OURS, THEIRS] }, path, "X")) + .toEqual({ providers: [{ id: "opencodex", name: "X" }, THEIRS] }); + // The element the selector would create is recorded, the existing array is not. + expect(createdContainerPaths({ providers: [THEIRS] }, contribution(path, "X"))) + .toEqual(["providers\u0000[id=opencodex]"]); + expect(createdContainerPaths({ providers: [OURS] }, contribution(path, "X"))).toEqual([]); + }); + + test("throws AmbiguousSelectorError when two elements match", () => { + const doc = { providers: [OURS, THEIRS, { id: "opencodex", name: "dupe" }] }; + expect(() => setPath(doc, SELECT, OURS)).toThrow(AmbiguousSelectorError); + expect(() => deletePath(doc, SELECT)).toThrow(AmbiguousSelectorError); + expect(() => readPath(doc, SELECT)).toThrow(AmbiguousSelectorError); + expect(() => createdContainerPaths(doc, contribution([...SELECT, "name"]))) + .toThrow(AmbiguousSelectorError); + }); +}); + +describe("deletePath with a selector", () => { + test("removes only the matching element and leaves siblings", () => { + const { doc, removed } = deletePath({ providers: [THEIRS, OURS, { id: "other" }], keep: 1 }, SELECT); + expect(removed).toBe(true); + expect(doc).toEqual({ providers: [THEIRS, { id: "other" }], keep: 1 }); + }); + + test("reports nothing removed when no element matches or the slot is not an array", () => { + expect(deletePath({ providers: [THEIRS] }, SELECT)).toEqual({ doc: { providers: [THEIRS] }, removed: false }); + expect(deletePath({ providers: {} }, SELECT)).toEqual({ doc: { providers: {} }, removed: false }); + expect(deletePath({}, SELECT)).toEqual({ doc: {}, removed: false }); + }); + + test("prunes an emptied array we created and keeps one we did not", () => { + const created = new Set(["providers"]); + expect(deletePath({ providers: [OURS], keep: 1 }, SELECT, created).doc).toEqual({ keep: 1 }); + expect(deletePath({ providers: [OURS], keep: 1 }, SELECT).doc).toEqual({ providers: [], keep: 1 }); + // A sibling keeps the array alive even when we created it. + expect(deletePath({ providers: [OURS, THEIRS] }, SELECT, created).doc).toEqual({ providers: [THEIRS] }); + }); + + test("a leaf inside a selected element is removed without touching the element", () => { + const path = ["providers", "[id=opencodex]", "name"]; + const created = new Set(["providers", "providers\u0000[id=opencodex]"]); + // The seeded element keeps its selector field, so it is never empty and the prune walk + // stops at it. No client owns a leaf inside a selected element today; when one does, it + // decides whether a `{ id }` husk is residue worth a dedicated rule. + expect(deletePath({ providers: [{ id: "opencodex", name: "X" }] }, path, created).doc) + .toEqual({ providers: [{ id: "opencodex" }] }); + expect(deletePath({ providers: [{ id: "opencodex", name: "X", extra: 1 }] }, path, created).doc) + .toEqual({ providers: [{ id: "opencodex", extra: 1 }] }); + }); +}); + +describe("readPath and blockedContainerPath with a selector", () => { + test("readPath finds the element through a selector", () => { + const doc = { providers: [THEIRS, OURS] }; + expect(readPath(doc, SELECT)).toEqual(OURS); + expect(readPath(doc, ["providers", "[id=opencodex]", "name"])).toBe("OpenCodex"); + expect(readPath(doc, ["providers", "[id=missing]"])).toBeUndefined(); + expect(readPath({ providers: {} }, SELECT)).toBeUndefined(); + expect(readPath({ providers: "x" }, SELECT)).toBeUndefined(); + }); + + test("blockedContainerPath blocks a non-array where the selector expects one", () => { + expect(blockedContainerPath({ providers: {} }, contribution(SELECT))).toEqual(["providers"]); + expect(blockedContainerPath({ providers: "x" }, contribution(SELECT))).toEqual(["providers"]); + expect(blockedContainerPath({ providers: null }, contribution(SELECT))).toEqual(["providers"]); + expect(blockedContainerPath({ providers: [THEIRS] }, contribution(SELECT))).toBeNull(); + expect(blockedContainerPath({}, contribution(SELECT))).toBeNull(); + // Reading through a matched element continues the walk: a scalar element is blocked, + // a record one is fine, an absent one is simply not there yet. + const deep = ["providers", "[id=opencodex]", "name"]; + expect(blockedContainerPath({ providers: [OURS] }, contribution(deep, "X"))).toBeNull(); + expect(blockedContainerPath({ providers: [THEIRS] }, contribution(deep, "X"))).toBeNull(); + expect(blockedContainerPath({ providers: [{ id: "opencodex", name: 1 }] }, contribution(["providers", "[id=opencodex]", "name", "leaf"], "X"))) + .toEqual(["providers", "[id=opencodex]", "name"]); + }); +}); + +describe("plain-key paths are unchanged", () => { + test("setPath, deletePath, readPath, createdContainerPaths and blockedContainerPath behave as before", () => { + const path = ["providers", "opencodex", "api_key"]; + expect(setPath({}, path, "k")).toEqual({ providers: { opencodex: { api_key: "k" } } }); + expect(setPath({ providers: "x" }, path, "k")).toEqual({ providers: { opencodex: { api_key: "k" } } }); + expect(setPath({ providers: [1] }, path, "k")).toEqual({ providers: { opencodex: { api_key: "k" } } }); + expect(setPath({ providers: { other: 1 } }, path, "k")) + .toEqual({ providers: { other: 1, opencodex: { api_key: "k" } } }); + expect(createdContainerPaths({}, contribution(path, "k"))).toEqual(["providers", "providers\u0000opencodex"]); + expect(createdContainerPaths({ providers: { other: 1 } }, contribution(path, "k"))).toEqual(["providers\u0000opencodex"]); + + const created = new Set(["providers", "providers\u0000opencodex"]); + expect(deletePath({ providers: { opencodex: { api_key: "k" } } }, path, created)).toEqual({ doc: {}, removed: true }); + expect(deletePath({ providers: { opencodex: { api_key: "k" } } }, path)).toEqual({ doc: { providers: { opencodex: {} } }, removed: true }); + expect(deletePath({ providers: { opencodex: { api_key: "k", other: 1 } }, x: 1 }, path, created)) + .toEqual({ doc: { providers: { opencodex: { other: 1 } }, x: 1 }, removed: true }); + expect(deletePath({ providers: {} }, path)).toEqual({ doc: { providers: {} }, removed: false }); + expect(deletePath({ providers: [] }, path)).toEqual({ doc: { providers: [] }, removed: false }); + expect(deletePath({ providers: { opencodex: "x" } }, path)).toEqual({ doc: { providers: { opencodex: "x" } }, removed: false }); + expect(deletePath({ providers: { opencodex: { api_key: null } } }, path, created)).toEqual({ doc: {}, removed: true }); + + expect(readPath({ providers: { opencodex: { api_key: "k" } } }, path)).toBe("k"); + expect(readPath({ providers: [OURS] }, ["providers", "0"])).toBeUndefined(); + expect(readPath({ providers: null }, path)).toBeUndefined(); + + expect(blockedContainerPath({ providers: ["x"] }, contribution(path, "k"))).toEqual(["providers"]); + expect(blockedContainerPath({ providers: { opencodex: null } }, contribution(path, "k"))).toEqual(["providers", "opencodex"]); + expect(blockedContainerPath(null, contribution(path, "k"))).toEqual([]); + expect(blockedContainerPath({ providers: { opencodex: {} } }, contribution(path, "k"))).toBeNull(); + expect(blockedContainerPath(undefined, contribution(path, "k"))).toBeNull(); + }); +}); + +/** + * End to end through the real writer: Raycast is the first client whose + * fragment path carries a selector, so this is where status and mutation are + * shown agreeing on which sequence element is ours. + */ +describe("raycast writer round trip", () => { + const TEST_ENV = {} as NodeJS.ProcessEnv; + const MODELS: ExportModel[] = [ + { namespaced: "anthropic/claude-opus-4-8", provider: "anthropic", id: "claude-opus-4-8", contextWindow: 200_000 }, + ]; + const CONFIG: OcxConfig = { + port: 10100, + hostname: "127.0.0.1", + defaultProvider: "mock", + providers: { mock: { adapter: "openai-chat", baseUrl: "http://127.0.0.1/v1" } }, + } as unknown as OcxConfig; + let home: string; + let store: IntegrationStateStore; + + beforeEach(() => { + const base = mkdtempSync(join(tmpdir(), "ocx-integrations-merge-")); + home = join(base, "home"); + mkdirSync(home, { recursive: true }); + store = createIntegrationStateStore(join(base, "store", "integrations")); + }); + + afterEach(() => { + removeTreeWithRetry(dirname(home)); + }); + + function installRaycast(): string { + const spec = INTEGRATION_CLIENTS.raycast; + mkdirSync(spec.detectDir(TEST_ENV, home), { recursive: true }); + const configPath = spec.configPath(TEST_ENV, home); + mkdirSync(dirname(configPath), { recursive: true }); + return configPath; + } + + function input(): IntegrationWriteInput { + return { clientId: "raycast", models: MODELS, config: CONFIG, port: 10100, env: TEST_ENV, home, store }; + } + + test("apply appends beside the user's provider, disable removes only ours", () => { + const configPath = installRaycast(); + writeFileSync(configPath, Bun.YAML.stringify({ providers: [THEIRS] })); + + expect(readIntegrationState(input())).toMatchObject({ state: "absent" }); + expect(applyIntegration(input())).toMatchObject({ ok: true, changed: true }); + const applied = Bun.YAML.parse(readFileSync(configPath, "utf8")) as { providers: Array<{ id: string }> }; + expect(applied.providers.map(item => item.id)).toEqual(["lmstudio", "opencodex"]); + expect(readIntegrationState(input())).toMatchObject({ state: "current" }); + + expect(disableIntegration(input())).toMatchObject({ ok: true, changed: true }); + // The user's array was there before us, so it survives with their entry intact. + expect(Bun.YAML.parse(readFileSync(configPath, "utf8"))).toEqual({ providers: [THEIRS] }); + expect(readIntegrationState(input())).toMatchObject({ state: "absent" }); + }); + + test("a providers map instead of a sequence is unsafe for status and writer alike", () => { + const configPath = installRaycast(); + writeFileSync(configPath, Bun.YAML.stringify({ providers: { opencodex: {} } })); + expect(readIntegrationState(input())).toMatchObject({ state: "unsafe", reason: "blocked-container" }); + expect(applyIntegration(input())).toMatchObject({ ok: false, reason: "unsafe" }); + expect(Bun.YAML.parse(readFileSync(configPath, "utf8"))).toEqual({ providers: { opencodex: {} } }); + }); + + for (const recorded of [false, true]) { + for (const count of [0, 1, 2]) { + test(`${count} matching rows with record=${recorded} agree across status and mutation`, () => { + const configPath = installRaycast(); + writeFileSync(configPath, Bun.YAML.stringify({ providers: [THEIRS] })); + let managed: unknown = OURS; + if (recorded) { + expect(applyIntegration(input())).toMatchObject({ ok: true }); + const applied = Bun.YAML.parse(readFileSync(configPath, "utf8")) as { providers: unknown[] }; + managed = applied.providers[1]; + } + // For one owned row retain the writer's exact bytes, so this exercises + // current rather than an unrelated whole-file formatting conflict. + if (!recorded || count !== 1) { + writeFileSync(configPath, Bun.YAML.stringify({ + providers: [THEIRS, ...Array.from({ length: count }, () => managed)], + })); + } + const text = readFileSync(configPath, "utf8"); + const records = store.readRecords(); + const operations = store.listOperations("raycast"); + const expected = count === 0 ? "absent" : count === 2 ? "unsafe" : recorded ? "current" : "conflict"; + expect(readIntegrationState(input()).state).toBe(expected); + if (count === 2) { + expect(readIntegrationState(input()).reason).toBe("ambiguous-selector"); + for (const mutate of [applyIntegration, refreshIntegration, disableIntegration, overwriteIntegration]) { + expect(mutate(input())).toMatchObject({ ok: false, state: "unsafe", reason: "unsafe" }); + expect(readFileSync(configPath, "utf8")).toBe(text); + expect(store.readRecords()).toEqual(records); + expect(store.listOperations("raycast")).toEqual(operations); + } + } else if (count === 0) { + expect(refreshIntegration(input())).toMatchObject({ ok: true, changed: false, state: "absent" }); + expect(readFileSync(configPath, "utf8")).toBe(text); + } else if (recorded) { + expect(applyIntegration(input())).toMatchObject({ ok: true, changed: false, state: "current" }); + } else { + expect(applyIntegration(input())).toMatchObject({ ok: false, reason: "conflict" }); + expect(disableIntegration(input())).toMatchObject({ ok: false, reason: "conflict" }); + expect(readFileSync(configPath, "utf8")).toBe(text); + } + }); + } + } +}); diff --git a/tests/clients/integrations-state.test.ts b/tests/clients/integrations-state.test.ts index 872e9b3824..56093b3dd6 100644 --- a/tests/clients/integrations-state.test.ts +++ b/tests/clients/integrations-state.test.ts @@ -775,9 +775,9 @@ describe("installation detection is independent of config state", () => { * from. Rationale and the per-client table: 020 §1 amendment. */ describe("the loopback-only set is one fact, read through one seam", () => { - test("omp, pi, kimi, gajae, dsh, mcode, zcode, prime and aside are loopback-only and nobody else is", () => { + test("omp, pi, kimi, gajae, dsh, mcode, zcode, prime, aside and raycast are loopback-only and nobody else is", () => { const loopbackOnly = INTEGRATION_CLIENT_IDS.filter(id => isLoopbackOnly(id)); - expect(loopbackOnly).toEqual(["pi", "omp", "kimi", "gajae", "dsh", "mcode", "zcode", "prime", "aside"]); + expect(loopbackOnly).toEqual(["pi", "omp", "kimi", "gajae", "dsh", "mcode", "zcode", "prime", "aside", "raycast"]); }); test("the registry restates nothing — it reads the export spec", () => { diff --git a/tests/clients/raycast-client.test.ts b/tests/clients/raycast-client.test.ts new file mode 100644 index 0000000000..d84123f458 --- /dev/null +++ b/tests/clients/raycast-client.test.ts @@ -0,0 +1,314 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + EXPORT_CLIENTS, + OPENCODE_PROVIDER_ID, + buildClientConfig, + buildClientConfigText, + buildClientContribution, + raycastAiDir, + raycastConfigPath, + summarizeRaycast, + type ExportContext, + type ExportModel, + type RaycastGeneratedConfig, +} from "../../src/clients/config-export"; +import { exportPresentationLabel } from "../../src/clients/model-presentation"; +import { refreshOwnedCatalogIntegrations } from "../../src/integrations/catalog-refresh"; +import { INTEGRATION_CLIENTS } from "../../src/integrations/registry"; +import { createIntegrationStateStore, type IntegrationStateStore } from "../../src/integrations/store"; +import { applyIntegration, disableIntegration, refreshIntegration } from "../../src/integrations/writer"; +import type { OcxConfig } from "../../src/types"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const CONFIG = { + port: 10100, + hostname: "127.0.0.1", + defaultProvider: "mock", + providers: { mock: { adapter: "openai-chat", baseUrl: "http://127.0.0.1/v1" } }, +} as OcxConfig; + +// One model per cell of the vision x reasoning matrix, so every ability +// branch is exercised by a row that differs from its neighbours in one axis. +const MODELS: ExportModel[] = [ + { namespaced: "anthropic/claude-opus-5", provider: "anthropic", id: "claude-opus-5", contextWindow: 200_000, inputModalities: ["text", "image"] }, + { namespaced: "openai/gpt-5.6-sol", provider: "openai", id: "gpt-5.6-sol", contextWindow: 922_000, reasoningEfforts: ["low", "medium", "high"] }, + { namespaced: "mystery/model", provider: "mystery", id: "model" }, + { namespaced: "google/gemini-3-pro", provider: "google", id: "gemini-3-pro", contextWindow: 1_048_576, inputModalities: ["text", "image"], reasoningEfforts: ["low", "high"] }, +]; + +function context(models: readonly ExportModel[] = MODELS): ExportContext { + return { baseUrl: "http://127.0.0.1:10100/v1", config: CONFIG, models }; +} + +// A provider the user wrote by hand: the merge must carry it through every +// apply, refresh and disable untouched. +const LMSTUDIO = { id: "lmstudio", name: "LM Studio", base_url: "http://localhost:1234/v1", models: [] }; +const USER_SEED = [ + "providers:", + " - id: lmstudio", + " name: LM Studio", + " base_url: http://localhost:1234/v1", + " models: []", + "", +].join(String.fromCharCode(10)); + +function ourProvider(document: RaycastGeneratedConfig) { + return document.providers.find(provider => provider.id === OPENCODE_PROVIDER_ID)!; +} + +function abilitiesOf(document: RaycastGeneratedConfig, id: string): Record { + const model = ourProvider(document).models.find(entry => entry.id === id)!; + return Object.fromEntries(Object.entries(model.abilities).map(([name, ability]) => [name, ability.supported])); +} + +let home: string; +let store: IntegrationStateStore; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "ocx-raycast-")); + store = createIntegrationStateStore(mkdtempSync(join(tmpdir(), "ocx-raycast-store-"))); +}); + +afterEach(() => { + removeTreeWithRetry(home); + removeTreeWithRetry(store.root); +}); + +/** Raycast "installed" for our purposes: the `ai` directory exists. */ +function installRaycast(seed?: string): string { + const spec = INTEGRATION_CLIENTS.raycast; + mkdirSync(spec.detectDir({}, home), { recursive: true }); + const configPath = spec.configPath({}, home); + if (seed !== undefined) writeFileSync(configPath, seed); + return configPath; +} + +function readProviders(configPath: string): RaycastGeneratedConfig { + return Bun.YAML.parse(readFileSync(configPath, "utf8")) as RaycastGeneratedConfig; +} + +function request(models: readonly ExportModel[] = MODELS) { + return { clientId: "raycast" as const, models, config: CONFIG, port: 10100, env: {}, home, store }; +} + +describe("Raycast client config", () => { + /* + * The shape is Raycast's, not ours: `providers` is a SEQUENCE, `base_url` + * ends in `/v1` without `/chat/completions`, and there is no `api_keys` at + * all because a loopback bind is unauthenticated. Every model carries all + * five abilities so Raycast never has to guess at a missing one. + */ + test("emits one provider element with the documented field vocabulary", () => { + const document = buildClientConfig("raycast", context()) as RaycastGeneratedConfig; + expect(Object.keys(document)).toEqual(["providers"]); + expect(document.providers.map(provider => provider.id)).toEqual([OPENCODE_PROVIDER_ID]); + + const provider = ourProvider(document); + expect(Object.keys(provider)).toEqual(["id", "name", "base_url", "models"]); + expect(provider.name).toBe("OpenCodex"); + expect(provider.base_url).toBe("http://127.0.0.1:10100/v1"); + expect(Object.keys(provider)).not.toContain("api_keys"); + + for (const model of provider.models) { + expect(Object.keys(model.abilities)).toEqual(["temperature", "vision", "system_message", "tools", "reasoning_effort"]); + } + const claude = provider.models.find(model => model.id === "anthropic/claude-opus-5")!; + // Raycast shows `name` verbatim with no provider suffix; capability tables + // supply the product label when ExportModel has no operator override. + expect(claude.name).toBe("Claude Opus 5"); + expect(claude.context).toBe(200_000); + // No authoritative window means the key is absent, not zero or null. + const unknown = provider.models.find(model => model.id === "mystery/model")!; + expect("context" in unknown).toBe(false); + }); + + test("summarizes unknown file shapes without trusting parsed YAML", () => { + const empty = { modelCount: 0, modelsWithoutLimits: 0 }; + for (const document of [undefined, null, false, 42, "providers", [], {}, + { providers: null }, { providers: {} }, { providers: "bad" }, + { providers: [null, false, "bad", [], {}] }, + ...[undefined, null, false, 42, "bad", {}].map(models => ({ providers: [{ id: "opencodex", models }] })), + { providers: [{ id: "opencodex", models: [] }, { id: "opencodex", models: [] }] }, + ]) expect(summarizeRaycast(document)).toEqual(empty); + expect(summarizeRaycast({ providers: [null, { id: "foreign", models: "bad" }, { + id: "opencodex", models: [null, false, 1, "bad", [], {}, { id: "x" }, + { id: "", name: "empty id" }, { id: "x", name: 1 }, + { id: "known", name: "Known", context: 1000 }, + { id: "unknown", name: "Unknown" }, + { id: "invalid", name: "Invalid", context: "1000" }, + { id: "negative", name: "Negative", context: -1 }, + ], + }] })).toEqual({ modelCount: 4, modelsWithoutLimits: 3 }); + }); + + test("uses product labels instead of raw slugs or provider suffixes", () => { + expect(exportPresentationLabel({ + namespaced: "anthropic/claude-fable-5-1", provider: "anthropic", id: "claude-fable-5-1", + })).toBe("Claude Fable 5.1"); + expect(exportPresentationLabel({ + namespaced: "cursor/composer-2.5", provider: "cursor", id: "composer-2.5", + })).toBe("Composer 2.5"); + expect(exportPresentationLabel({ + namespaced: "mystery/model", provider: "mystery", id: "model", displayName: "Custom Name", + })).toBe("Custom Name"); + }); + + /* + * Abilities follow the catalog row, not the vendor name. Temperature and + * reasoning_effort use opposite flags as a conservative export convention. + * This is not a complete per-model capability oracle. system_message and + * tools retain the client export convention, not verified per-model support. + */ + test("maps vision and reasoning ladders onto abilities per model", () => { + const document = buildClientConfig("raycast", context()) as RaycastGeneratedConfig; + expect(abilitiesOf(document, "anthropic/claude-opus-5")).toEqual({ + temperature: true, vision: true, system_message: true, tools: true, reasoning_effort: false, + }); + expect(abilitiesOf(document, "openai/gpt-5.6-sol")).toEqual({ + temperature: false, vision: false, system_message: true, tools: true, reasoning_effort: true, + }); + expect(abilitiesOf(document, "mystery/model")).toEqual({ + temperature: true, vision: false, system_message: true, tools: true, reasoning_effort: false, + }); + expect(abilitiesOf(document, "google/gemini-3-pro")).toEqual({ + temperature: false, vision: true, system_message: true, tools: true, reasoning_effort: true, + }); + }); + + test("native YAML round-trips, leads with our element, and never carries a credential", () => { + const sentinel = ["sk", "live", "raycast", "sentinel"].join("-"); + const withKey = { ...CONFIG, apiKeys: [{ key: sentinel }] } as OcxConfig; + const built = buildClientConfigText("raycast", { ...context(), config: withKey }); + expect(built.format).toBe("yaml"); + expect(built.text.startsWith(["providers:", " - id: opencodex"].join(String.fromCharCode(10)))).toBe(true); + expect(Bun.YAML.parse(built.text)).toEqual(built.document as never); + expect(built.text).not.toContain(sentinel); + expect(built.text).not.toContain("api_keys"); + }); + + test("the contribution owns the providers element selected by our id", () => { + const contribution = buildClientContribution("raycast", context()); + expect(contribution.clientId).toBe("raycast"); + expect(contribution.fragments.map(fragment => fragment.path)).toEqual([["providers", `[id=${OPENCODE_PROVIDER_ID}]`]]); + expect((contribution.fragments[0]!.value as { id: string }).id).toBe(OPENCODE_PROVIDER_ID); + }); + + test("resolves under the home directory and ignores XDG_CONFIG_HOME", () => { + // Raycast hardcodes ~/.config/raycast on macOS and Windows alike; honoring + // XDG here would name a file Raycast never reads. + const env = { XDG_CONFIG_HOME: join(home, "elsewhere") }; + expect(raycastAiDir(env, home)).toBe(join(home, ".config", "raycast", "ai")); + expect(raycastConfigPath(env, home)).toBe(join(home, ".config", "raycast", "ai", "providers.yaml")); + expect(INTEGRATION_CLIENTS.raycast.configPath(env, home)).toBe(raycastConfigPath(env, home)); + expect(INTEGRATION_CLIENTS.raycast.detectDir(env, home)).toBe(raycastAiDir(env, home)); + }); + + test("ships as a loopback-only integration with no env var to export", () => { + const spec = EXPORT_CLIENTS.raycast; + // `api_keys` is read literally, so a remote bind would need a plaintext + // secret on disk; the spec refuses instead. + expect(spec.loopbackOnly).toBe(true); + expect(spec.apiKeyEnv).toBe(""); + expect(spec.format).toBe("yaml"); + // Not a bare providers.yaml: a download would collide with other clients'. + expect(spec.filename).toBe("raycast-providers.yaml"); + }); + + /* + * The whole point of the `[id=opencodex]` selector: the user's own element + * survives every operation, we replace only ours, and a disable leaves the + * sequence exactly as the user wrote it. + */ + test("apply, refresh and disable touch only our element of the sequence", () => { + const configPath = installRaycast(USER_SEED); + + const applied = applyIntegration(request()); + expect(applied.ok).toBe(true); + const afterApply = readProviders(configPath); + expect(new Set(afterApply.providers.map(provider => provider.id))).toEqual(new Set(["lmstudio", OPENCODE_PROVIDER_ID])); + expect(afterApply.providers.find(provider => provider.id === "lmstudio")).toEqual(LMSTUDIO); + expect(ourProvider(afterApply).models.map(model => model.id)).toEqual(MODELS.map(model => model.namespaced).sort()); + + // A smaller catalog rewrites our element in place and nothing else. + const fewer = MODELS.filter(model => model.namespaced !== "mystery/model"); + const refreshed = refreshIntegration(request(fewer)); + expect(refreshed.ok).toBe(true); + const afterRefresh = readProviders(configPath); + expect(afterRefresh.providers.map(provider => provider.id)).toEqual(afterApply.providers.map(provider => provider.id)); + expect(afterRefresh.providers.find(provider => provider.id === "lmstudio")).toEqual(LMSTUDIO); + expect(ourProvider(afterRefresh).models.map(model => model.id)).toEqual(fewer.map(model => model.namespaced).sort()); + + const disabled = disableIntegration(request(fewer)); + expect(disabled.ok).toBe(true); + const afterDisable = readProviders(configPath); + expect(afterDisable.providers).toEqual([LMSTUDIO]); + }); + + test("the default catalog refresh updates an owned Raycast provider", async () => { + const configPath = installRaycast(USER_SEED); + expect(applyIntegration(request()).ok).toBe(true); + const fewer = MODELS.filter(model => model.namespaced !== "mystery/model"); + let loads = 0; + + const outcomes = await refreshOwnedCatalogIntegrations({ + models: async () => { + loads += 1; + return fewer; + }, + config: CONFIG, + port: 10100, + env: {}, + home, + store, + }); + + expect(outcomes).toEqual([{ client: "raycast", ok: true, changed: true }]); + expect(loads).toBe(1); + expect(readProviders(configPath).providers.find(provider => provider.id === "lmstudio")).toEqual(LMSTUDIO); + expect(ourProvider(readProviders(configPath)).models.map(model => model.id)) + .toEqual(fewer.map(model => model.namespaced).sort()); + }); + + test("implicit catalog refresh neither loads models nor connects an unowned Raycast", async () => { + const configPath = installRaycast(USER_SEED); + const outcomes = await refreshOwnedCatalogIntegrations({ + ...request(), + models: async () => { throw new Error("unowned client must not load models"); }, + }, ["raycast"]); + expect(outcomes).toEqual([]); + expect(readFileSync(configPath, "utf8")).toBe(USER_SEED); + expect(store.readRecords().raycast).toBeUndefined(); + expect(store.listOperations("raycast")).toEqual([]); + }); + + for (const hostname of ["0.0.0.0", "192.0.2.1"]) { + test(`refuses admission-authenticated bind ${hostname} without changing the file`, () => { + const configPath = installRaycast(USER_SEED); + const result = applyIntegration({ ...request(), config: { ...CONFIG, hostname } }); + expect(result).toMatchObject({ ok: false, reason: "non_loopback" }); + expect(readFileSync(configPath, "utf8")).toBe(USER_SEED); + expect(store.listOperations("raycast")).toEqual([]); + }); + } + + test("refuses a file whose providers is a map rather than a sequence", () => { + // `providers: {}` is a container we would have to REPLACE with `[]` to + // write our element, and replacing a user's container is never a success. + const configPath = installRaycast("providers: {}" + String.fromCharCode(10)); + const result = applyIntegration(request()); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.reason).toBe("unsafe"); + expect(readFileSync(configPath, "utf8")).toBe("providers: {}" + String.fromCharCode(10)); + }); + + test("refuses when the ai directory does not exist yet", () => { + // The directory appears only after "Reveal Providers Config" in Raycast's + // AI settings, which is the signal that Custom Providers is reachable. + const result = applyIntegration(request()); + expect(result.ok).toBe(false); + if (!result.ok) expect(result.reason).toBe("not_installed"); + }); +}); diff --git a/tests/clients/raycast-detect.test.ts b/tests/clients/raycast-detect.test.ts new file mode 100644 index 0000000000..4e4268b29b --- /dev/null +++ b/tests/clients/raycast-detect.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, test } from "bun:test"; +import { detectRaycast, type RaycastDetectDeps } from "../../src/integrations/raycast-detect"; + +/** + * Stubbed deps only. The real detector spawns `defaults` and reads the + * developer's subscription state, and this suite must pass identically on a + * machine with Raycast Pro, with the free tier, and with no Raycast at all. + */ +function fakeDeps( + platform: string, + existing: readonly string[], + options: { env?: Record; defaultValue?: string | null; homedir?: string } = {}, +): RaycastDetectDeps & { defaultsReads: number } { + const present = new Set(existing); + const deps = { + platform, + homedir: options.homedir ?? (platform === "win32" ? "C:\\Users\\u" : "/home/u"), + env: options.env ?? {}, + defaultsReads: 0, + exists: (path: string) => present.has(path), + readDefault: (domain: string, key: string) => { + deps.defaultsReads += 1; + expect(domain).toBe("com.raycast.macos.v1"); + expect(key).toBe("subscriptions_active"); + return options.defaultValue ?? null; + }, + }; + return deps; +} + +describe("detectRaycast", () => { + test("darwin: a Pro subscription, the app bundle and the revealed ai folder", () => { + const deps = fakeDeps("darwin", ["/Applications/Raycast.app", "/home/u/.config/raycast/ai"], { defaultValue: "1" }); + expect(detectRaycast(deps)).toEqual({ + appPath: "/Applications/Raycast.app", + aiDirPresent: true, + plan: "pro", + }); + // One process spawn per detection, not one per field. + expect(deps.defaultsReads).toBe(1); + }); + + test("darwin: the free tier is reported, not refused, and the user-local bundle is found", () => { + const deps = fakeDeps("darwin", ["/home/u/Applications/Raycast.app"], { defaultValue: "0" }); + expect(detectRaycast(deps)).toEqual({ + appPath: "/home/u/Applications/Raycast.app", + aiDirPresent: false, + plan: "free", + }); + }); + + test("darwin: a failed or unexpected defaults read is unknown, never free", () => { + expect(detectRaycast(fakeDeps("darwin", [], { defaultValue: null })).plan).toBe("unknown"); + expect(detectRaycast(fakeDeps("darwin", [], { defaultValue: "(null)" })).plan).toBe("unknown"); + expect(detectRaycast(fakeDeps("darwin", [], { defaultValue: "" })).plan).toBe("unknown"); + }); + + test("win32: LOCALAPPDATA\\Programs\\Raycast is the install path and the plan is unknown", () => { + const local = "C:\\Users\\u\\AppData\\Local"; + const deps = fakeDeps("win32", [`${local}\\Programs\\Raycast`, "C:\\Users\\u\\.config\\raycast\\ai"], { + env: { LOCALAPPDATA: local }, + defaultValue: "1", + }); + expect(detectRaycast(deps)).toEqual({ + appPath: `${local}\\Programs\\Raycast`, + aiDirPresent: true, + plan: "unknown", + }); + // `defaults` does not exist off macOS, so it is never asked. + expect(deps.defaultsReads).toBe(0); + }); + + test("win32: no LOCALAPPDATA means no app path rather than a guessed one", () => { + expect(detectRaycast(fakeDeps("win32", [])).appPath).toBeNull(); + }); + + test("linux: nothing is detected and nothing is spawned", () => { + const deps = fakeDeps("linux", [], { defaultValue: "1" }); + expect(detectRaycast(deps)).toEqual({ appPath: null, aiDirPresent: false, plan: "unknown" }); + expect(deps.defaultsReads).toBe(0); + }); +}); diff --git a/tests/clients/sync-client-integrations.test.ts b/tests/clients/sync-client-integrations.test.ts index 5661373642..65dc41a2b3 100644 --- a/tests/clients/sync-client-integrations.test.ts +++ b/tests/clients/sync-client-integrations.test.ts @@ -65,7 +65,7 @@ describe("ocx sync fans out to enabled native clients and owned file integration expect(fn).toContain("grokIntegrationEnabled(config)"); expect(fn).toContain("claudeDesktopIntegrationEnabled(config)"); - expect(fn).toContain('["mcode", "pi", "aside"]'); + expect(fn).toContain('["mcode", "pi", "aside", "raycast"]'); expect(fn).toContain("refreshOwnedCatalogIntegrations"); // Native clients keep their catches; the owned catalog helper isolates file clients. expect(fn.match(/catch \(error\)/g)?.length).toBe(2); @@ -651,17 +651,68 @@ describe("owned Pi/Aside catalogs follow filtered model selections", () => { }); }); -test("the direct ocx sync command refreshes MCode, Pi and Aside instead of relying on /api/sync", async () => { +test("the direct ocx sync command refreshes MCode, Pi, Raycast and server-owned Aside", async () => { const src = await Bun.file(new URL("../../src/cli/dispatch.ts", import.meta.url)).text(); const start = src.indexOf("sync: async deps =>"); const command = src.slice(start, src.indexOf("v2: async deps =>", start)); expect(command).toContain("refreshOwnedCatalogIntegrations"); - expect(command).toContain('["mcode", "pi"]'); + expect(command).toContain('["mcode", "pi", "raycast"]'); expect(command).toContain("refreshAsideProfilesThroughServer"); expect(command.indexOf("syncModelsToCodex")).toBeLessThan(command.indexOf("refreshOwnedCatalogIntegrations")); expect(command).toContain('synced.status !== "refused"'); }); +test("server startup owns Raycast refresh; ensure does not reuse a saved-config snapshot", async () => { + const src = await Bun.file(new URL("../../src/cli/index.ts", import.meta.url)).text(); + const start = src.slice(src.indexOf("async function handleStart"), src.indexOf("function detachedStartEnvironment")); + const ensure = src.slice(src.indexOf("async function handleEnsure"), src.indexOf("async function handleTrayProxyStart")); + expect(src).toContain("refreshOwnedCatalogIntegrations"); + expect(src).toContain('}, ["raycast"]);'); + expect(start).toContain("await refreshOwnedRaycastCatalog(config, port)"); + expect(ensure).not.toContain("await refreshOwnedRaycastCatalog("); + expect(src).not.toContain("refreshAllOwnedIntegrations"); +}); + +test("already-running ensure leaves Raycast untouched when saved host and listener policy diverge", async () => { + // Exercise the actual command body with external effects injected. Importing + // index.ts directly starts CLI dispatch, so isolate only handleEnsure here. + const src = await Bun.file(new URL("../../src/cli/index.ts", import.meta.url)).text(); + const command = src.slice(src.indexOf("async function handleEnsure"), src.indexOf("async function handleTrayProxyStart")); + const executable = new Bun.Transpiler({ loader: "ts" }).transformSync(command); + const root = mkdtempSync(join(tmpdir(), "ocx-ensure-raycast-divergence-")); + const configPath = join(root, "providers.yaml"); + const original = "providers:\n - id: opencodex\n base_url: http://127.0.0.1:10237/v1\n"; + writeFileSync(configPath, original); + const savedConfig = { + port: 10100, hostname: "192.0.2.40", providers: {}, defaultProvider: "mock", + unauthenticatedLoopbackListener: { enabled: true, port: 10999 }, + } as OcxConfig; + let refreshCalls = 0; + const deps = { + findProxyOwnerBeforeJournalRecovery: async () => ({ live: { hostname: "127.0.0.1", port: 10237 } }), + loadConfig: () => savedConfig, + codexAutoStartEnabled: () => true, + syncModelsToCodex: async () => ({ status: "skipped" }), + refreshOwnedRaycastCatalog: async () => { + refreshCalls += 1; + writeFileSync(configPath, "wrong saved destination"); + }, + injectSystemEnv: async () => ({ injected: true }), + reportShellHookFailure: () => {}, + reconcileShellHook: () => ({ state: "installed" }), + reconcileEnsureDesiredIntegrations: async () => {}, + console: { log: () => {}, error: () => {} }, + }; + try { + const ensure = new Function(...Object.keys(deps), `${executable}; return handleEnsure;`)(...Object.values(deps)) as () => Promise; + expect(await ensure()).toBe(true); + expect(refreshCalls).toBe(0); + expect(readFileSync(configPath, "utf8")).toBe(original); + } finally { + removeTreeWithRetry(root); + } +}); + test("identical explicit mutation keys join but cannot swallow a different apply or disable", async () => { let release!: () => void; const gate = new Promise(resolve => { release = resolve; }); diff --git a/tests/codex-integration/codex-catalog.test.ts b/tests/codex-integration/codex-catalog.test.ts index 5820edc6dd..bb3c8a880f 100644 --- a/tests/codex-integration/codex-catalog.test.ts +++ b/tests/codex-integration/codex-catalog.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, spyOn, test } from "bun:test"; -import { existsSync, mkdtempSync, readFileSync} from "node:fs"; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { codexAccountGatedCanonicalWireModel } from "../../src/server/responses/core"; @@ -53,9 +53,17 @@ import { import { CANONICAL_NATIVE_CATALOG_CONTENT_POLICY, mergeCatalogEntriesFromObservedState, + syncCatalogModels, type ObservedCatalogMergeInput, } from "../../src/codex/catalog/sync"; import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { saveConfig } from "../../src/config"; +import { SUBAGENT_MODELS_VERSION } from "../../src/config/subagent-models"; +import { captureCatalogAdmissionSnapshot } from "../../src/codex/catalog-admission"; +import { convergeCodexCatalog } from "../../src/codex/convergence"; +import { resetCodexRuntimeResolveCacheForTests } from "../../src/codex/runtime"; +import { resolveCodexCatalogSerializationDatabasePath, resolveEffectiveUserIdentity } from "../../src/codex/user-identity"; +import { CODEX_FORWARD_BASE_URL } from "../../src/providers/openai-tiers"; const originalFetch = globalThis.fetch; @@ -3045,7 +3053,207 @@ function mergeObservedForTest( }); } +// Exercise both production callers: removing either caller's nativeDisplayNames argument +// must fail the persisted-label assertion, even if the pure merge tests still pass. +test.each(["retained", "convergence"] as const)("%s persists and restores native labels through the catalog writer", async writer => { + const envKeys = ["CODEX_HOME", "OPENCODEX_HOME", "CODEX_CLI_PATH"] as const; + const previousEnv = envKeys.map(key => process.env[key]); + const previousFetch = globalThis.fetch; + const root = realpathSync.native(mkdtempSync(join(tmpdir(), "ocx-native-label-writer-"))); + const codexHome = join(root, "codex"); + const catalogPath = join(codexHome, "custom-catalog.json"); + let fetchCalls = 0; + try { + mkdirSync(codexHome); + mkdirSync(join(root, "ocx")); + process.env.CODEX_HOME = codexHome; + process.env.OPENCODEX_HOME = join(root, "ocx"); + writeFileSync(join(codexHome, "config.toml"), 'model_catalog_json = "custom-catalog.json"\n'); + const catalog = { models: [{ ...nativeTemplate(), slug: "gpt-5.6-sol", display_name: "Fixture Sol" }] }; + // Reuse the executable-fixture protocol from catalog-full-picker-order.test.ts so + // admission and a forced runtime refresh observe the same version and bundled rows. + const script = join(root, "fixture-codex.js"); + writeFileSync(script, [ + 'if (process.argv.includes("--version")) console.log("codex-cli 0.145.0");', + `else process.stdout.write(${JSON.stringify(JSON.stringify(catalog))});`, + ].join("\n")); + if (process.platform === "win32") { + process.env.CODEX_CLI_PATH = join(root, "fixture-codex.cmd"); + writeFileSync(process.env.CODEX_CLI_PATH, `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`); + } else { + process.env.CODEX_CLI_PATH = join(root, "fixture-codex"); + const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`; + writeFileSync(process.env.CODEX_CLI_PATH, `#!/bin/sh\nexec ${quote(process.execPath)} ${quote(script)} "$@"\n`); + chmodSync(process.env.CODEX_CLI_PATH, 0o755); + } + resetCatalogRuntimeStateForTests(); + resetCodexRuntimeResolveCacheForTests(); + resetCodexModelEntitlementCacheForTests(); + expect(loadBundledCodexCatalog()?.models?.[0]?.slug).toBe("gpt-5.6-sol"); + writeFileSync(catalogPath, JSON.stringify(catalog)); + globalThis.fetch = (async () => { + fetchCalls += 1; + throw new Error("native label writer fixture must not make a network request"); + }) as typeof fetch; + const config: OcxConfig = { + port: 10100, defaultProvider: "openai", + subagentModels: [], subagentModelsVersion: SUBAGENT_MODELS_VERSION, + providers: { + openai: { adapter: "openai-responses", baseUrl: CODEX_FORWARD_BASE_URL, authMode: "forward" }, + }, + }; + const write = async (labels?: Record) => { + if (labels) config.providers.openai!.modelDisplayNames = labels; + else delete config.providers.openai!.modelDisplayNames; + saveConfig(config); + if (writer === "convergence") { + const result = await convergeCodexCatalog(captureCatalogAdmissionSnapshot(config), { + action: "converge", scope: "catalog", reason: "management-mutation", mode: "explicit", deadlineMs: 5_000, + }); + expect(result.catalogRefresh.status).toBe("committed"); + } else { + const result = await syncCatalogModels(config); + expect(result.path).toBe(catalogPath); + expect(result.skippedReason).toBeUndefined(); + } + return (JSON.parse(readFileSync(catalogPath, "utf8")) as { models: Record[] }).models; + }; + const original = await write(); + const renamed = await write({ "gpt-5.6-sol": "Custom Sol" }); + const renamedBytes = readFileSync(catalogPath, "utf8"); + const native = renamed.find(row => row.slug === "gpt-5.6-sol")!; + expect(native.display_name).toBe("Custom Sol"); + expect(native.opencodex_native_display_name).toEqual({ + slug: "gpt-5.6-sol", original: "Fixture Sol", applied: "Custom Sol", + }); + const { opencodex_native_display_name: marker, ...withoutMarker } = native; + expect(marker).toBeDefined(); + expect({ ...withoutMarker, display_name: "Fixture Sol" }) + .toEqual(original.find(row => row.slug === "gpt-5.6-sol")!); + expect(await write({ "gpt-5.6-sol": "Custom Sol" })).toEqual(renamed); + expect(readFileSync(catalogPath, "utf8")).toBe(renamedBytes); + expect((await write({ "gpt-5.6-sol": "Changed Sol" })).find(row => row.slug === "gpt-5.6-sol")?.display_name) + .toBe("Changed Sol"); + expect(await write()).toEqual(original); + expect(fetchCalls).toBe(0); + } finally { + try { + const database = resolveCodexCatalogSerializationDatabasePath(resolveEffectiveUserIdentity(), codexHome); + for (const suffix of ["", "-journal", "-wal", "-shm"]) rmSync(`${database}${suffix}`, { force: true }); + } finally { + globalThis.fetch = previousFetch; + envKeys.forEach((key, index) => { + const value = previousEnv[index]; + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + }); + resetCatalogRuntimeStateForTests(); + resetCodexRuntimeResolveCacheForTests(); + resetCodexModelEntitlementCacheForTests(); + removeTreeWithRetry(root); + } + } +}, 30_000); + describe("Codex catalog routed normalization", () => { + test("reapplies native display names after repeated catalog merges without changing model metadata", () => { + const input = { + catalogModels: [{ ...nativeTemplate(), slug: "gpt-5.6-sol" }], + routedEntries: [], + }; + const original = mergeObservedForTest(input); + const labels = { "gpt-5.6-sol": "GPT 5.6 Sol" }; + const renamed = mergeObservedForTest({ ...input, nativeDisplayNames: labels }); + const row = renamed.find(entry => entry.slug === "gpt-5.6-sol")!; + expect(row.display_name).toBe("GPT 5.6 Sol"); + expect({ ...row, display_name: undefined, opencodex_native_display_name: undefined }).toEqual({ + ...original.find(entry => entry.slug === "gpt-5.6-sol"), display_name: undefined, + }); + const regenerated = mergeObservedForTest({ + ...input, catalogModels: renamed, nativeDisplayNames: labels, + }); + expect(regenerated.find(entry => entry.slug === "gpt-5.6-sol")?.display_name).toBe("GPT 5.6 Sol"); + const changed = mergeObservedForTest({ + ...input, catalogModels: regenerated, + nativeDisplayNames: { "gpt-5.6-sol": " Sol 5.6 " }, + }); + expect(changed.find(entry => entry.slug === "gpt-5.6-sol")?.display_name).toBe("Sol 5.6"); + expect(JSON.stringify(regenerated)).toBe(JSON.stringify(renamed)); + for (const nativeDisplayNames of [undefined, {}, { "gpt-5.6-sol": " " }]) { + const restored = mergeObservedForTest({ ...input, catalogModels: changed, nativeDisplayNames }); + expect(restored).toEqual(original); + } + }); + + test("native display names preserve external label changes when clearing the overlay", () => { + const renamed = mergeObservedForTest({ + catalogModels: [{ ...nativeTemplate(), slug: "gpt-5.6-sol" }], routedEntries: [], + nativeDisplayNames: { "gpt-5.6-sol": "Custom Sol" }, + }); + renamed.find(entry => entry.slug === "gpt-5.6-sol")!.display_name = "Updated upstream Sol"; + const restored = mergeObservedForTest({ catalogModels: renamed, routedEntries: [] }); + const row = restored.find(entry => entry.slug === "gpt-5.6-sol")!; + expect(row.display_name).toBe("Updated upstream Sol"); + expect(row.opencodex_native_display_name).toBeUndefined(); + }); + + test("native display names preserve pinned metadata upgrades and restore pinned names", () => { + for (const slug of ["gpt-5.6-sol", "gpt-6-astra"]) { + const input = { catalogModels: [{ ...nativeTemplate(), slug, display_name: slug }], routedEntries: [] }; + const original = mergeObservedForTest(input); + const renamed = mergeObservedForTest({ ...input, nativeDisplayNames: { [slug]: "Custom name" } }); + expect(renamed.find(entry => entry.slug === slug)?.display_name).toBe("Custom name"); + expect(mergeObservedForTest({ catalogModels: renamed, routedEntries: [] })).toEqual(original); + } + }); + + test("clearing a native label keeps Astra external edits subject to pinned metadata normalization", () => { + const original = mergeObservedForTest({ + catalogModels: [{ ...nativeTemplate(), slug: "gpt-6-astra", display_name: "gpt-6-astra" }], + routedEntries: [], + }); + const renamed = mergeObservedForTest({ + catalogModels: original, routedEntries: [], + nativeDisplayNames: { "gpt-6-astra": "Custom Astra" }, + }); + const external = JSON.parse(JSON.stringify(renamed)) as Record[]; + const astra = external.find(entry => entry.slug === "gpt-6-astra")!; + astra.display_name = "External Astra name"; + astra.context_window = 123; + const restored = mergeObservedForTest({ catalogModels: external, routedEntries: [] }); + const row = restored.find(entry => entry.slug === "gpt-6-astra")!; + expect(row).toEqual(original.find(entry => entry.slug === "gpt-6-astra")!); + expect(row.display_name).not.toBe("External Astra name"); + expect(row.context_window).toBe(272_000); + expect(row.opencodex_native_display_name).toBeUndefined(); + expect(astra.display_name).toBe("External Astra name"); + expect(astra.opencodex_native_display_name).toBeDefined(); + }); + + test("native display names do not leak overlay markers through catalog templates", () => { + const template = { + ...nativeTemplate(), + opencodex_native_display_name: { slug: "gpt-5.6-sol", original: "Sol", applied: "Custom" }, + }; + const entries = buildCatalogEntries(template, ["gpt-5.5"], [{ provider: "local", id: "qwen3-coder" }]); + expect(entries.length).toBeGreaterThanOrEqual(2); + for (const entry of entries) expect(entry.opencodex_native_display_name).toBeUndefined(); + expect(template.opencodex_native_display_name).toBeDefined(); + }); + + test("native display names do not relabel a routed combo occupying a native slug", () => { + const routed = { + ...nativeTemplate(), slug: "gpt-5.6-sol", display_name: "My combo", + owned_by: "combo", description: "Routed via opencodex → combo (combo).", + opencodex_catalog_kind: CODEX_NATIVE_ALIAS_CATALOG_KIND, + }; + const rows = mergeObservedForTest({ + catalogModels: [], routedEntries: [routed], + nativeDisplayNames: { "gpt-5.6-sol": "GPT 5.6 Sol" }, + }); + expect(rows.find(entry => entry.slug === "gpt-5.6-sol")?.display_name).toBe("My combo"); + }); + test("pending re-registration cannot recover ON rows from a degraded old catalog", () => { const old = { ...nativeTemplate(), slug: "vendor/model-0", owned_by: "vendor", opencodex_catalog_kind: CODEX_PROVIDER_MODEL_CATALOG_KIND }; const input = { diff --git a/tests/codex-integration/doctor.test.ts b/tests/codex-integration/doctor.test.ts index 9fdb7ee30d..acb0f1b87e 100644 --- a/tests/codex-integration/doctor.test.ts +++ b/tests/codex-integration/doctor.test.ts @@ -1,4 +1,7 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import * as proxyLiveness from "../../src/server/proxy-liveness"; +import * as cliHelp from "../../src/cli/help"; +import { getDefaultConfig } from "../../src/config"; import { spawnSync } from "node:child_process"; import { existsSync, mkdirSync, mkdtempSync, utimesSync, writeFileSync } from "node:fs"; import { join } from "node:path"; @@ -32,6 +35,7 @@ import { } from "../../src/lib/local-management-capability"; import { findDeadPid } from "../helpers/dead-pid"; import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { STORE_BUDGET_MS } from "../helpers/test-budget"; const TEST_DIR = join(import.meta.dir, ".tmp-doctor-test"); const TEST_CODEX_HOME = join(TEST_DIR, "codex"); @@ -780,6 +784,63 @@ describe("doctor abandoned response-state temps", () => { }); }); +describe("doctor version skew projection", () => { + test.each([ + ["2.42.0", "2.10.1-preview.20260805", "the running proxy is older"], + ["2.35.0", "2.36.1", "this ocx on PATH is older"], + ["2.43.0", "2.43.0", "ok ocx 2.43.0 matches the running proxy"], + ["2.43.0+a", "2.43.0+b", "neither can be identified as older"], + ["v2.43.0", "2.43.0", "neither can be identified as older"], + ["2.43.0", "unknown", null], + ["unknown", "2.43.0", null], + ["2.43.0", "0.0.0", null], + ["0.0.0", "0.0.0", null], + ["unknown", "unknown", null], + ["2.43.0", undefined, null], + ] as const)("projects CLI %s / proxy %s without false matches", async (cli, proxy, expected) => { + const home = mkdtempSync(join(tmpdir(), "ocx-doctor-skew-")); + const codexHome = join(home, "codex"); + const previousHome = process.env.OPENCODEX_HOME; + const previousCodexHome = process.env.CODEX_HOME; + const previousExitCode = process.exitCode; + const restore: Array<() => void> = []; + try { + // Runtime history diagnostics resolve and stat an explicit CODEX_HOME. + mkdirSync(codexHome, { recursive: true }); + process.env.OPENCODEX_HOME = home; + process.env.CODEX_HOME = codexHome; + writeFileSync(join(home, "config.json"), JSON.stringify({ ...getDefaultConfig(), port: 9, codexAutoStart: false })); + const logged: string[] = []; + const log = spyOn(console, "log").mockImplementation((...args: unknown[]) => { logged.push(args.map(String).join(" ")); }); + restore.push(() => log.mockRestore()); + const version = spyOn(cliHelp, "packageVersion").mockReturnValue(cli); + restore.push(() => version.mockRestore()); + // Other doctor sections probe upstream health; this diagnostic fixture must stay offline. + const fetch = spyOn(globalThis, "fetch").mockImplementation(async () => new Response(null, { status: 503 })); + restore.push(() => fetch.mockRestore()); + const proxyInfo: proxyLiveness.LiveProxy = { + pid: null, port: 9, hostname: "127.0.0.1", source: "config", ...(proxy === undefined ? {} : { version: proxy }), + }; + const live = spyOn(proxyLiveness, "findLiveProxy").mockResolvedValue(proxyInfo); + restore.push(() => live.mockRestore()); + await runDoctor([]); + const output = logged.join("\n"); + if (expected !== null) expect(output).toContain(expected); + else expect(output).not.toContain("does not match the running proxy"); + if (cli !== "2.43.0" || proxy !== "2.43.0") expect(output).not.toContain("matches the running proxy"); + if (expected === "the running proxy is older") expect(output).toContain("ocx service repair"); + } finally { + for (const cleanup of restore.reverse()) cleanup(); + process.exitCode = previousExitCode; + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousHome; + if (previousCodexHome === undefined) delete process.env.CODEX_HOME; + else process.env.CODEX_HOME = previousCodexHome; + removeTreeWithRetry(home); + } + }, STORE_BUDGET_MS); +}); + describe("doctor reclaim wiring (end to end)", () => { // The formatter tests above cannot observe deletion. This covers the call site itself: // inverting the report/reclaim ternary in runDoctor must fail a test. diff --git a/tests/config/client-config-export-new-clients.test.ts b/tests/config/client-config-export-new-clients.test.ts index 6b6b4c4e80..5a381d6237 100644 --- a/tests/config/client-config-export-new-clients.test.ts +++ b/tests/config/client-config-export-new-clients.test.ts @@ -58,12 +58,14 @@ function ctx(config: OcxConfig = LOOPBACK): ExportContext { describe("no secret reaches a client config", () => { test("the generated client support policy identifies every loopback-only integration", () => { - // Pi, Kimi, Gajae and Aside cannot emit the dedicated admission header -- - // Aside's observed provider block has four keys and none is `headers`. OMP - // and Prime can carry provider headers, but remote credential wiring is - // deliberately deferred from those initial generated integrations. + // Pi, Kimi, Gajae, Aside and Raycast cannot emit the dedicated admission + // header -- Aside's observed provider block has four keys and none is + // `headers`; Raycast's `api_keys` is read literally with no env + // interpolation. OMP and Prime can carry provider headers, but remote + // credential wiring is deliberately deferred from those initial generated + // integrations. const loopbackOnly = EXPORT_CLIENT_IDS.filter(id => EXPORT_CLIENTS[id].loopbackOnly); - expect(loopbackOnly).toEqual(["pi", "omp", "kimi", "gajae", "dsh", "mcode", "zcode", "prime", "aside"]); + expect(loopbackOnly).toEqual(["pi", "omp", "kimi", "gajae", "dsh", "mcode", "zcode", "prime", "aside", "raycast"]); }); test("every client that is not loopback-only carries the header on a remote bind", () => { diff --git a/tests/config/client-config-export.test.ts b/tests/config/client-config-export.test.ts index 707d6dd62c..6a71813e9f 100644 --- a/tests/config/client-config-export.test.ts +++ b/tests/config/client-config-export.test.ts @@ -32,6 +32,7 @@ import { normalizeExportModels as leafNormalizeExportModels } from "../../src/cl import * as omp from "../../src/clients/config-export/omp"; import * as dsh from "../../src/clients/config-export/dsh"; import * as mcode from "../../src/clients/config-export/mcode"; +import * as raycast from "../../src/clients/config-export/raycast"; import * as zcode from "../../src/clients/config-export/zcode"; /** @@ -100,6 +101,7 @@ describe("split config-export public facade", () => { ["dsh", dsh.buildDshClientConfig, dsh.summarizeDsh, dsh.buildDshContribution], ["mcode", mcode.buildMcodeClientConfig, mcode.summarizeMcode, mcode.buildMcodeContribution], ["zcode", zcode.buildZcodeClientConfig, zcode.summarizeZcode, zcode.buildZcodeContribution], + ["raycast", raycast.buildRaycastClientConfig, raycast.summarizeRaycast, raycast.buildRaycastContribution], ] as const; for (const [id, build, summarize, contribute] of leaves) { expect(EXPORT_CLIENTS[id].build).toBe(build); @@ -803,8 +805,8 @@ describe("hub-resolved Fast exports", () => { }); describe("EXPORT_CLIENTS registry", () => { - test("covers exactly the twelve file-toggle clients", () => { - expect(EXPORT_CLIENT_IDS).toEqual(["opencode", "pi", "omp", "hermes", "openclaw", "kimi", "gajae", "dsh", "mcode", "zcode", "prime", "aside"]); + test("covers exactly the thirteen file-toggle clients", () => { + expect(EXPORT_CLIENT_IDS).toEqual(["opencode", "pi", "omp", "hermes", "openclaw", "kimi", "gajae", "dsh", "mcode", "zcode", "prime", "aside", "raycast"]); for (const id of EXPORT_CLIENT_IDS) expect(isExportClientId(id)).toBe(true); // The exception clients keep their own surfaces and are not export clients. expect(isExportClientId("claude-desktop")).toBe(false); diff --git a/tests/config/client-config-new-clients.test.ts b/tests/config/client-config-new-clients.test.ts index 65b52727c9..7deb7fdb36 100644 --- a/tests/config/client-config-new-clients.test.ts +++ b/tests/config/client-config-new-clients.test.ts @@ -17,6 +17,7 @@ import { type OpenclawGeneratedConfig, } from "../../src/clients/config-export"; import { serializeDocument } from "../../src/integrations/serialize"; +import { readPath } from "../../src/integrations/state"; import type { OcxConfig } from "../../src/types"; /** @@ -159,14 +160,11 @@ describe("contributions describe what a writer would own", () => { test("every client's fragments point at real entries in its own document", () => { for (const clientId of EXPORT_CLIENT_IDS) { - const document = buildClientConfig(clientId, ctx()) as Record; + const document = buildClientConfig(clientId, ctx()); for (const fragment of EXPORT_CLIENTS[clientId].buildContribution(ctx()).fragments) { - let cursor: unknown = document; - for (const key of fragment.path) { - expect(cursor && typeof cursor === "object").toBe(true); - cursor = (cursor as Record)[key]; - } - expect(cursor).toEqual(fragment.value); + // Read through the writer's own segment grammar: Raycast's path holds + // a `[id=opencodex]` selector into a sequence, not a map key. + expect(readPath(document, fragment.path)).toEqual(fragment.value); } } }); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 6565f12821..cb554012ea 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -39,6 +39,8 @@ "anthropic-image-retry.test.ts": "adapters/anthropic", "anthropic-pool-toggle-copy.test.ts": "adapters/anthropic", "anthropic-quorum-cache.test.ts": "routing", + "anthropic-quota-dispatch.test.ts": "adapters/anthropic", + "anthropic-ratelimit-headers.test.ts": "adapters/anthropic", "anthropic-reasoning.test.ts": "adapters/anthropic", "anthropic-sidecar-account-failover.test.ts": "adapters/anthropic", "anthropic-stream-hardening.test.ts": "adapters/anthropic", @@ -72,6 +74,7 @@ "aside-profiles-routes.test.ts": "server", "aside-profiles.test.ts": "clients", "aside-profile-paths.test.ts": "clients", + "aside-profile-identity.test.ts": "clients", "aside-profile-sync-owner.test.ts": "clients", "assert-mergeable-review.test.ts": "ci-workflows", "auto-compact-budget.test.ts": "providers", @@ -125,6 +128,7 @@ "claude-authmode-migration.test.ts": "claude-integration", "claude-cli.test.ts": "claude-integration", "claude-code-thought-signature-scope.test.ts": "claude-integration", + "claude-source-envelope.test.ts": "claude-integration", "claude-compatibility.test.ts": "claude-integration", "claude-context-windows.test.ts": "claude-integration", "claude-desktop-1m.test.ts": "claude-integration", @@ -525,6 +529,7 @@ "install-scripts.test.ts": "ci-workflows", "integrations-invariants.test.ts": "gui", "integrations-journal.test.ts": "clients", + "integrations-merge.test.ts": "clients", "integrations-serialize.test.ts": "clients", "integrations-state.test.ts": "clients", "integrations-writer.test.ts": "clients", @@ -833,6 +838,8 @@ "reserve-quota-scope.test.ts": "codex-integration", "rate-limit-reset-credits.test.ts": "gui", "rate-limit-retry.test.ts": "providers", + "raycast-client.test.ts": "clients", + "raycast-detect.test.ts": "clients", "reasoning-effort.test.ts": "codex-integration", "reasoning-replay-identity.test.ts": "adapters", "reasoning-replay-robustness.test.ts": "adapters", @@ -1020,6 +1027,7 @@ "test-home-guard.test.ts": "ci-workflows", "test-runner.test.ts": "ci-workflows", "thought-signature-credential-scope.test.ts": "responses", + "reasoning-envelope.test.ts": "responses", "token-estimate.test.ts": "lib", "token-guardian.test.ts": "codex-integration", "tool-argument-integers.test.ts": "adapters", diff --git a/tests/gui/integrations-invariants.test.ts b/tests/gui/integrations-invariants.test.ts index 33e7480f86..2353104311 100644 --- a/tests/gui/integrations-invariants.test.ts +++ b/tests/gui/integrations-invariants.test.ts @@ -6,7 +6,7 @@ import { EXPORT_CLIENTS, EXPORT_CLIENT_IDS, type ExportModel } from "../../src/c import { parseConfig } from "../../src/integrations/config-io"; import { INTEGRATION_CLIENTS, INTEGRATION_CLIENT_IDS, type IntegrationClientId } from "../../src/integrations/registry"; import { createIntegrationStateStore, type IntegrationStateStore } from "../../src/integrations/store"; -import { readIntegrationState } from "../../src/integrations/state"; +import { readIntegrationState, readPath } from "../../src/integrations/state"; import { applyIntegration, disableIntegration, restoreIntegration } from "../../src/integrations/writer"; import { printSubcommandUsage, printUsage } from "../../src/cli/help"; import type { OcxConfig } from "../../src/types"; @@ -78,9 +78,9 @@ afterEach(() => { }); describe("the client registries cannot drift apart", () => { - test("every list of clients holds exactly the same twelve ids", async () => { + test("every list of clients holds exactly the same thirteen ids", async () => { /* - * Five lists name the same twelve clients, and two of them are maintained by + * Five lists name the same thirteen clients, and two of them are maintained by * hand: the GUI cannot import the backend registry, because that would * pull node:os and node:path into the browser bundle. A client added * server-side renders no row until someone remembers the tuple, and the @@ -91,7 +91,7 @@ describe("the client registries cannot drift apart", () => { const guiRouting = await import("../../gui/src/app-routing"); const expected = [...EXPORT_CLIENT_IDS].sort(); - expect(expected).toHaveLength(12); + expect(expected).toHaveLength(13); expect([...INTEGRATION_CLIENT_IDS].sort()).toEqual(expected); expect([...gui.CLIENTS].sort()).toEqual(expected); @@ -170,6 +170,13 @@ describe("every client survives a full lifecycle", () => { prime: '{\n "providers": {\n "mine": { "api": "http://keep-me" }\n }\n}\n', // Aside reads the same models.json contract as Pi and Prime. aside: '{\n "providers": {\n "mine": { "api": "http://keep-me" }\n }\n}\n', + // Raycast's `providers` is a SEQUENCE keyed by `id`, so the user's entry is + // a sibling element rather than a sibling map key. + raycast: "providers:\n - id: lmstudio\n name: LM Studio\n base_url: http://localhost:1234/v1\n models: []\n", + }; + /** Where the seed's user-owned entry lives when the seed is a sequence. */ + const USER_ELEMENT: Partial> = { + raycast: ["providers", "[id=lmstudio]"], }; for (const clientId of INTEGRATION_CLIENT_IDS) { @@ -190,18 +197,22 @@ describe("every client survives a full lifecycle", () => { const afterApply = parseConfig(readFileSync(configPath, "utf8"), format); const record = store.readRecords()[clientId]!; expect(record.fragmentPaths.length).toBeGreaterThan(0); + // Read through the writer's own segment grammar: Raycast's path holds a + // `[id=opencodex]` selector into a sequence, not a map key. for (const path of record.fragmentPaths) { - let cursor: unknown = afterApply; - for (const segment of path) { - expect(cursor && typeof cursor === "object").toBe(true); - cursor = (cursor as Record)[segment]; - } - expect(cursor).toBeDefined(); + expect(readPath(afterApply, path)).toBeDefined(); + } + // …and the user's own entry is untouched. `toMatchObject` treats an + // array as exact-length, so a sequence-shaped seed is checked by the + // same selector the writer uses to find its own element. + const userElement = USER_ELEMENT[clientId]; + if (userElement) { + expect(readPath(afterApply, userElement)).toEqual(readPath(original, userElement)); + } else { + expect((afterApply as Record)).toMatchObject( + original as Record, + ); } - // …and the user's own entry is untouched. - expect((afterApply as Record)).toMatchObject( - original as Record, - ); const disabled = disableIntegration({ clientId, models: MODELS, config: CONFIG, port: 10100, diff --git a/tests/oauth/oauth-store-multi.test.ts b/tests/oauth/oauth-store-multi.test.ts index 6cd3f21dbe..02d8f8024f 100644 --- a/tests/oauth/oauth-store-multi.test.ts +++ b/tests/oauth/oauth-store-multi.test.ts @@ -4,10 +4,14 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import * as atomicWrite from "../../src/config/atomic-write"; import * as oauthStore from "../../src/oauth/store"; +import { flushConfigDirHardeningForTests } from "../../src/config/paths"; import { resetHardenedStateForTests, + setAsyncIcaclsRunnerForTests, setIcaclsRunnerForTests, + setPlatformForTests, } from "../../src/lib/windows-secret-acl"; +import { setSyntheticWindowsPrincipalForTests } from "../../src/lib/windows-user-principal"; import { getAccountCredential, getAccountSet, @@ -35,6 +39,17 @@ import { removeTreeWithRetry } from "../helpers/remove-tree"; const TEST_DIR = join(import.meta.dir, ".tmp-oauth-store-multi-test"); let previousOpencodexHome: string | undefined; +const ICACLS_OK = { success: true, exitCode: 0, timedOut: false, stdout: "" }; + +async function cleanupOAuthStoreFixture(): Promise { + await flushConfigDirHardeningForTests(); + setIcaclsRunnerForTests(null); + setAsyncIcaclsRunnerForTests(null); + resetHardenedStateForTests(); + if (previousOpencodexHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousOpencodexHome; + if (existsSync(TEST_DIR)) removeTreeWithRetry(TEST_DIR); +} const cred = (over: Partial = {}): OAuthCredentials => ({ access: "access-1", @@ -61,21 +76,66 @@ describe("multi-account auth store", () => { mkdirSync(TEST_DIR, { recursive: true }); process.env.OPENCODEX_HOME = TEST_DIR; resetHardenedStateForTests(); - setIcaclsRunnerForTests(() => ({ - success: true, - exitCode: 0, - timedOut: false, - stdout: "", - })); + setIcaclsRunnerForTests(() => ICACLS_OK); + setAsyncIcaclsRunnerForTests(async () => ICACLS_OK); }); - afterEach(() => { - setIcaclsRunnerForTests(null); - resetHardenedStateForTests(); - if (previousOpencodexHome === undefined) delete process.env.OPENCODEX_HOME; - else process.env.OPENCODEX_HOME = previousOpencodexHome; - if (existsSync(TEST_DIR)) removeTreeWithRetry(TEST_DIR); - }); + afterEach(cleanupOAuthStoreFixture); + + test("fixture cleanup waits for a held config-directory ACL flight before restoring home or deleting files", async () => { + let release!: () => void; + const held = new Promise(resolve => { release = resolve; }); + let markStarted!: () => void; + const started = new Promise(resolve => { markStarted = resolve; }); + let deadlineTimer: ReturnType | undefined; + let cleaning: Promise | undefined; + let cleanupSettled = false; + setPlatformForTests("win32"); + // Keep SID discovery hermetic on Windows as well as on forced POSIX lanes. + setSyntheticWindowsPrincipalForTests("*S-1-5-21-1-2-3-1001"); + setAsyncIcaclsRunnerForTests(async () => { + markStarted(); + await held; + return ICACLS_OK; + }); + try { + // A real store read starts the production-tracked directory hardening flight. + expect(getAccountSet("xai")).toBeNull(); + await Promise.race([ + started, + new Promise((_, reject) => { + deadlineTimer = setTimeout(() => reject(new Error("ACL runner did not start")), INTERNAL_DEADLINE_MS); + }), + ]); + clearTimeout(deadlineTimer); + cleaning = cleanupOAuthStoreFixture().then( + () => { cleanupSettled = true; return null; }, + (error: unknown) => { cleanupSettled = true; return error; }, + ); + // An event-loop checkpoint lets an incorrectly unawaited cleanup finish; no sleep oracle. + await new Promise(resolve => setImmediate(resolve)); + expect(cleanupSettled).toBe(false); + expect(process.env.OPENCODEX_HOME).toBe(TEST_DIR); + expect(existsSync(TEST_DIR)).toBe(true); + + release(); + expect(await cleaning).toBeNull(); + expect(cleanupSettled).toBe(true); + expect(process.env.OPENCODEX_HOME).toBe(previousOpencodexHome); + expect(existsSync(TEST_DIR)).toBe(false); + } finally { + if (deadlineTimer !== undefined) clearTimeout(deadlineTimer); + // Even a broken cleanup must not release the held flight into the real runner. + setAsyncIcaclsRunnerForTests(async () => ICACLS_OK); + release(); + try { + await cleaning; + await flushConfigDirHardeningForTests(); + } finally { + setPlatformForTests(null); + } + } + }, STORE_BUDGET_MS); test("legacy single-credential auth.json normalizes and round-trips without losing login", async () => { const authPath = join(TEST_DIR, "auth.json"); diff --git a/tests/providers/provider-account-quota.test.ts b/tests/providers/provider-account-quota.test.ts index 989f55a410..1b940d71d0 100644 --- a/tests/providers/provider-account-quota.test.ts +++ b/tests/providers/provider-account-quota.test.ts @@ -33,9 +33,11 @@ async function seedTwoAccounts(): Promise { } function usageBody(fiveHour: number, sevenDay: number): string { + // These tests exercise current account measurements, not expired historical windows. + const now = Date.now(); return JSON.stringify({ - five_hour: { utilization: fiveHour, resets_at: "2026-07-05T12:00:00Z" }, - seven_day: { utilization: sevenDay, resets_at: "2026-07-08T12:00:00Z" }, + five_hour: { utilization: fiveHour, resets_at: new Date(now + 5 * 60 * 60_000).toISOString() }, + seven_day: { utilization: sevenDay, resets_at: new Date(now + 7 * 24 * 60 * 60_000).toISOString() }, }); } diff --git a/tests/providers/provider-registry-parity.test.ts b/tests/providers/provider-registry-parity.test.ts index be84701e0b..238a5808ea 100644 --- a/tests/providers/provider-registry-parity.test.ts +++ b/tests/providers/provider-registry-parity.test.ts @@ -1,16 +1,17 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, spyOn, test } from "bun:test"; import { buildCatalogEntries } from "../../src/codex/catalog"; import { CURSOR_NO_VISION_MODELS } from "../../src/adapters/cursor/discovery"; import { getModelMetadata, resolveMetadataProvider } from "../../src/generated/model-metadata"; import { buildInitProviders } from "../../src/cli/init"; import { OAUTH_PROVIDERS } from "../../src/oauth"; -import { enrichProviderFromCatalog, KEY_LOGIN_PROVIDERS } from "../../src/oauth/key-providers"; +import { enrichProviderFromCatalog, KEY_LOGIN_PROVIDERS, validateApiKey } from "../../src/oauth/key-providers"; import { deriveFeaturedProviderIds, deriveInitProviders, deriveJawcodeAliases, deriveKeyLoginMap, deriveProviderPresets, + enrichProviderFromRegistry, providerConfigSeed, } from "../../src/providers/derive"; import { PROVIDER_REGISTRY } from "../../src/providers/registry"; @@ -33,7 +34,7 @@ function nativeTemplate(): Record { const EXPECTED_KEY_PROVIDER_IDS = [ "anthropic-apikey", "openai-apikey", "meta-model", "umans", "opencode-go", "neuralwatt", "openrouter", "cline-pass", "cline", "orcarouter", "bizrouter", "groq", "google", "google-vertex", "azure-openai", "deepseek", "cerebras", "chutes", "deepinfra", "hyperbolic", "nscale", "vultr", "baseten", "commandcode", "sambanova", "nebius", "digitalocean", "scaleway", "featherless", "novita", "together", "fireworks", "firepass", "moonshot", - "huggingface", "nvidia", "venice", "zai", "zhipu-bigmodel", "zhipu-bigmodel-coding", "nanogpt", "synthetic", "siliconflow", "qwen-cloud", "tencent-coding-plan", + "huggingface", "nvidia", "venice", "zai", "zhipu-bigmodel", "zhipu-bigmodel-coding", "zhipu-bigmodel-responses", "nanogpt", "synthetic", "siliconflow", "qwen-cloud", "tencent-coding-plan", "volcengine", "volcengine-coding-plan", "volcengine-agent-plan", "qianfan", "alibaba", "alibaba-token-plan", "alibaba-token-plan-intl", "parallel", "zenmux", "litellm", "ollama-cloud", "mistral", "minimax", "minimax-cn", "kimi-code", "opencode-zen", "vercel-ai-gateway", "opencode-free", "xiaomi", "xiaomi-mimo", "kilo", "mimo-free", "mimo", "cloudflare-ai-gateway", "cloudflare-workers-ai", "gitlab-duo", @@ -440,6 +441,104 @@ describe("provider registry parity", () => { expect(glm53Entry?.default_reasoning_level).toBe("max"); }); + test("BigModel Responses exports only the officially documented static Codex models", () => { + // Independent oracle: https://docs.bigmodel.cn/cn/coding-plan/tool/codex.md, + // local models.json example checked 2026-09-07; not an authenticated /models response. + const id = "zhipu-bigmodel-responses"; + const registry = PROVIDER_REGISTRY.find(entry => entry.id === id)!; + expect(registry).toMatchObject({ + adapter: "openai-responses", + baseUrl: "https://open.bigmodel.cn/api/v1", + authKind: "key", + defaultModel: "glm-5.3", + models: ["glm-5.3", "glm-5-turbo"], + liveModels: false, + preserveCustomDestination: true, + preserveResponsesReasoningContent: true, + }); + expect(registry.modelDiscovery).toBeUndefined(); + expect(registry.preserveReasoningContentModels).toBeUndefined(); + const upstreamModalities = { "glm-5.3": ["text"], "glm-5-turbo": ["text"] }; + expect(registry.modelInputModalities).toEqual(upstreamModalities); + expect(KEY_LOGIN_PROVIDERS[id]).toMatchObject({ + models: ["glm-5.3", "glm-5-turbo"], liveModels: false, apiKeyValidation: "unknown", + }); + const provider = providerConfigSeed(registry); + enrichProviderFromRegistry(id, provider); + expect(provider.liveModels).toBe(false); + expect(provider.preserveResponsesReasoningContent).toBe(true); + const models = provider.models!.map(modelId => applyProviderConfigHints(id, provider, { + provider: id, id: modelId, + })); + // The official upstream declaration stays text-only. Catalog hints add image for the + // existing vision sidecar (vision/eligibility.ts), not native BigModel image support. + expect(provider.modelInputModalities).toEqual(upstreamModalities); + expect(models).toMatchObject([ + { id: "glm-5.3", contextWindow: 1_048_576, reasoningEfforts: ["low", "high", "max"], + defaultReasoningEffort: "max", supportsReasoningSummaries: true, inputModalities: ["text", "image"] }, + { id: "glm-5-turbo", contextWindow: 204_800, reasoningEfforts: [], + defaultReasoningEffort: "max", supportsReasoningSummaries: true, inputModalities: ["text", "image"] }, + ]); + const entries = buildCatalogEntries(nativeTemplate(), [], models); + for (const [modelId, window, efforts] of [ + ["glm-5.3", 1_048_576, ["low", "high", "max", "ultra"]], + ["glm-5-turbo", 204_800, []], + ] as const) { + const entry = entries.find(row => row.slug === `${id}/${modelId}`); + expect(entry).toMatchObject({ + context_window: window, supports_reasoning_summaries: true, + input_modalities: ["text", "image"], + }); + // Existing export policy adds a compatibility ultra tier and omits the default + // for empty ladders. The provider/CatalogModel defaults above remain official max. + expect(entry?.default_reasoning_level).toBe(modelId === "glm-5-turbo" ? undefined : "max"); + expect((entry?.supported_reasoning_levels as Array<{ effort: string }>).map(row => row.effort)) + .toEqual([...efforts]); + } + expect(entries.some(entry => String(entry.slug).includes("glm-5.3-flash"))).toBe(false); + }); + + test("BigModel Responses key login does not probe an undocumented models endpoint", async () => { + const fetchSpy = spyOn(globalThis, "fetch").mockImplementation(async () => new Response(null, { status: 403 })); + try { + const id = "zhipu-bigmodel-responses"; + expect(await validateApiKey(id, KEY_LOGIN_PROVIDERS[id], "test-bigmodel-key")).toBe("unknown"); + expect(fetchSpy).not.toHaveBeenCalled(); + } finally { + fetchSpy.mockRestore(); + } + }); + + test("BigModel Responses name collisions preserve custom transport and metadata", () => { + const id = "zhipu-bigmodel-responses"; + // Exercise both a different destination on the same wire and the canonical URL on + // another wire. Neither may acquire this preset's transport or per-model defaults. + for (const transport of [ + { adapter: "openai-responses", baseUrl: "https://custom.example.test/api/v1" }, + { adapter: "openai-chat", baseUrl: "https://open.bigmodel.cn/api/v1" }, + ]) { + const provider: OcxProviderConfig = { + ...transport, authMode: "key", apiKey: "test-custom-key", liveModels: true, + models: ["glm-5.3"], modelContextWindows: { "glm-5.3": 32_768 }, + modelReasoningEfforts: { "glm-5.3": ["medium"] }, + modelDefaultReasoningEfforts: { "glm-5.3": "medium" }, + modelSupportsReasoningSummaries: { "glm-5.3": false }, + }; + const enriched = structuredClone(provider); + enrichProviderFromRegistry(id, enriched); + expect(enriched).toEqual(provider); + const config: OcxConfig = { port: 10100, defaultProvider: id, providers: { [id]: provider } }; + const routed = routeModel(config, `${id}/glm-5.3`); + expect(routed.provider).toMatchObject(provider); + expect(routed.provider.modelContextWindows).toEqual({ "glm-5.3": 32_768 }); + expect(routed.provider.modelReasoningEfforts).toEqual({ "glm-5.3": ["medium"] }); + expect(routed.provider.modelDefaultReasoningEfforts).toEqual({ "glm-5.3": "medium" }); + expect(routed.provider.modelSupportsReasoningSummaries).toEqual({ "glm-5.3": false }); + expect(routed.provider.preserveResponsesReasoningContent).toBeUndefined(); + expect(routed.modelId).toBe("glm-5.3"); + } + }); + test("Anthropic API-key provider mirrors the OAuth entry's models on the key flow", () => { const anthropicOauth = PROVIDER_REGISTRY.find(entry => entry.id === "anthropic"); expect(KEY_LOGIN_PROVIDERS["anthropic-apikey"]).toMatchObject({ @@ -948,6 +1047,7 @@ describe("provider registry parity", () => { "minimax-cn": "minimax", "zhipu-bigmodel": "zai", "zhipu-bigmodel-coding": "zai", + "zhipu-bigmodel-responses": "zai", }); expect(resolveMetadataProvider("gemini")).toBe("google"); expect(resolveMetadataProvider("minimax-cn")).toBe("minimax"); diff --git a/tests/responses/openai-responses-passthrough.test.ts b/tests/responses/openai-responses-passthrough.test.ts index 0277da71d4..24bc8e0e02 100644 --- a/tests/responses/openai-responses-passthrough.test.ts +++ b/tests/responses/openai-responses-passthrough.test.ts @@ -569,6 +569,58 @@ describe("DeepSeek Responses endpoint contract", () => { } }); + test.each([undefined, "max", "ultra"])("BigModel Turbo omits outbound effort %s and preserves summary requests", (effort) => { + const id = "zhipu-bigmodel-responses"; + const config: OcxConfig = { + port: 10100, + defaultProvider: id, + providers: { [id]: providerConfigSeed(getProviderRegistryEntry(id)!) }, + }; + const route = routeModel(config, `${id}/glm-5-turbo`); + for (const withSummary of [false, true]) { + const raw = { + model: route.modelId, + input: "ping", + ...(effort !== undefined || withSummary ? { + reasoning: { + ...(effort !== undefined ? { effort } : {}), + ...(withSummary ? { summary: "auto" } : {}), + }, + } : {}), + }; + const before = structuredClone(raw); + const request = createResponsesPassthroughAdapter(route.provider).buildRequest(parseRequest(raw)); + const wire = JSON.parse(request.body); + expect(request.url).toBe("https://open.bigmodel.cn/api/v1/responses"); + if (withSummary) expect(wire.reasoning).toEqual({ summary: "auto" }); + else expect(wire).not.toHaveProperty("reasoning"); + expect(raw).toEqual(before); + } + }); + + test("a provider-wide empty ladder removes schema-valid raw effort", () => { + const keyed = { adapter: "openai-responses", baseUrl: "https://example.test/v1", authMode: "key" as const }; + const raw = { model: "model", input: "ping", reasoning: { effort: "high", summary: "auto" } }; + const wire = JSON.parse(createResponsesPassthroughAdapter({ ...keyed, reasoningEfforts: [] }) + .buildRequest(parseRequest(raw)).body); + expect(wire.reasoning).toEqual({ summary: "auto" }); + expect(raw.reasoning.effort).toBe("high"); + }); + + test("empty-ladder repair preserves unknown, non-rankable and native forward effort behavior", () => { + const keyed = { adapter: "openai-responses", baseUrl: "https://example.test/v1", authMode: "key" as const }; + for (const unchanged of [keyed, { ...keyed, reasoningEfforts: ["enabled"] }, { ...provider, reasoningEfforts: [] }]) { + const raw = { model: "gpt-5.6-sol", input: "ping", reasoning: { effort: "ultra" } }; + const wire = JSON.parse(createResponsesPassthroughAdapter(unchanged).buildRequest(parseRequest(raw)).body); + expect(wire.reasoning.effort).toBe("ultra"); + } + // A model-specific nonempty ladder overrides a provider-wide empty declaration. + const wire = JSON.parse(createResponsesPassthroughAdapter({ + ...keyed, reasoningEfforts: [], modelReasoningEfforts: { model: ["low", "high", "max"] }, + }).buildRequest(parseRequest({ model: "model", input: "ping", reasoning: { effort: "ultra" } })).body); + expect(wire.reasoning.effort).toBe("max"); + }); + test("a config saved before the fix is backfilled, and a hand-set path is preserved", () => { const saved = { adapter: "openai-chat", baseUrl: "https://api.deepseek.com", apiKey: "sk-test" } as Parameters[1]; enrichProviderFromRegistry("deepseek", saved); diff --git a/tests/responses/reasoning-envelope.test.ts b/tests/responses/reasoning-envelope.test.ts new file mode 100644 index 0000000000..2469b8e46b --- /dev/null +++ b/tests/responses/reasoning-envelope.test.ts @@ -0,0 +1,79 @@ +import { describe, expect, test } from "bun:test"; +import { anthropicToResponsesBody } from "../../src/claude/inbound"; +import { decodeReasoningEnvelope, encodeReasoningEnvelope } from "../../src/responses/reasoning-envelope"; +import { responsesJsonToAnthropicMessage } from "../../src/claude/outbound"; + +describe("reasoning and tool/result envelopes", () => { + test("preserves ordered thinking blocks and genuine signatures", () => { + const body = anthropicToResponsesBody({ + model: "m", messages: [{ role: "assistant", content: [ + { type: "thinking", thinking: "first", signature: "sig-first" }, + { type: "tool_use", id: "call-1", name: "Read", input: {} }, + { type: "thinking", thinking: "second", signature: "sig-second" }, + ] }], + }) as any; + expect(body.input.map((item: any) => item.type)).toEqual(["reasoning", "function_call", "reasoning"]); + expect(body.input[0].encrypted_content).toBe(encodeReasoningEnvelope({ sig: "sig-first" })); + expect(body.input[2].encrypted_content).toBe(encodeReasoningEnvelope({ sig: "sig-second" })); + }); + + test("rejects malformed or nested OpenCodex signatures", () => { + for (const signature of [ + "ocxr1:not-base64!!!", + encodeReasoningEnvelope({ sig: "nested" }), + encodeReasoningEnvelope({ sig: "", txt: "nested-empty-signature" }), + ]) { + expect(() => anthropicToResponsesBody({ + model: "m", messages: [{ role: "assistant", content: [{ type: "thinking", thinking: "x", signature }] }], + })).toThrow(); + } + }); + + test("round-trips redacted thinking without exposing it as a genuine signature", () => { + const encoded = encodeReasoningEnvelope({ sig: "sig", red: ["red-a", "red-b"] }); + const message = responsesJsonToAnthropicMessage({ + output: [{ type: "reasoning", summary: [{ type: "summary_text", text: "visible" }], encrypted_content: encoded }], + }, "m") as any; + expect(message.content[2]).toMatchObject({ type: "thinking", signature: "sig" }); + expect(message.content.slice(0, 2)).toEqual([ + { type: "redacted_thinking", data: "red-a" }, + { type: "redacted_thinking", data: "red-b" }, + ]); + }); + + test("owned fallback is bounded and decodable", () => { + const message = responsesJsonToAnthropicMessage({ + output: [{ type: "reasoning", summary: [{ type: "summary_text", text: "think" }] }], + }, "m") as any; + const signature = message.content[0].signature as string; + expect(signature.startsWith("ocxr1:")).toBe(true); + expect(decodeReasoningEnvelope(signature)).toEqual({ txt: "think" }); + }); + + test("preserves an explicitly empty fallback text", () => { + expect(decodeReasoningEnvelope(encodeReasoningEnvelope({ txt: "" }))).toEqual({ txt: "" }); + }); + + test("inbound preserves redacted-only reasoning when visible text is empty", () => { + const body = anthropicToResponsesBody({ + model: "m", messages: [{ role: "assistant", content: [{ type: "redacted_thinking", data: "opaque" }] }], + }) as any; + expect(body.input).toHaveLength(1); + expect(body.input[0].type).toBe("reasoning"); + expect(decodeReasoningEnvelope(body.input[0].encrypted_content)?.red).toEqual(["opaque"]); + }); + + test("drops an empty unsigned thinking block", () => { + const body = anthropicToResponsesBody({ + model: "m", messages: [{ role: "assistant", content: [{ type: "thinking", thinking: "", signature: "" }] }], + }) as any; + expect(body.input).toEqual([]); + }); + + test("preserves signature-only reasoning in JSON output", () => { + const message = responsesJsonToAnthropicMessage({ + output: [{ type: "reasoning", summary: [], encrypted_content: encodeReasoningEnvelope({ sig: "sig-only" }) }], + }, "m") as any; + expect(message.content).toEqual([{ type: "thinking", thinking: "", signature: "sig-only" }]); + }); +}); diff --git a/tests/responses/responses-compaction-routing.test.ts b/tests/responses/responses-compaction-routing.test.ts index 8e92f28715..a787024d95 100644 --- a/tests/responses/responses-compaction-routing.test.ts +++ b/tests/responses/responses-compaction-routing.test.ts @@ -1776,6 +1776,140 @@ describe("external task-input envelopes (#3735)", () => { } }); +describe("established-history external task input (#3807)", () => { + // Synthetic complete envelope from the #3735 contract; #3807's history rendering + // is not a captured outbound request. Keep the real tool pair distinct from delivery. + const deliveryText = " Follow up on the earlier tool result.\n"; + const acknowledged = "Delivery acknowledged."; + const continuationText = "Continue the established task."; + const summary = "Earlier tool returned 7; follow-up delivery is pending."; + const history = () => [ + { type: "message", role: "user", content: "Read the earlier value." }, + { type: "function_call", call_id: "call_history", name: "read_value", arguments: "{}" }, + { type: "function_call_output", call_id: "call_history", output: "earlier value: 7" }, + { type: "message", role: "assistant", content: "Earlier result recorded." }, + { + type: "function_call_output", id: "fco_external_followup", + name: "send_message_to_thread", namespace: "codex_app", output: deliveryText, + }, + ]; + const requestBody = () => ({ + model: "gw/model", stream: false, store: false, input: history(), + tools: [{ type: "function", name: "read_value", parameters: { type: "object", properties: {} } }], + }); + const wireHistory = [ + { role: "user", content: "Read the earlier value." }, + { role: "assistant", tool_calls: [{ id: "call_history", type: "function", function: { name: "read_value", arguments: "{}" } }] }, + { role: "tool", tool_call_id: "call_history", content: "earlier value: 7" }, + { role: "assistant", content: "Earlier result recorded." }, + { role: "user", content: deliveryText }, + ]; + + function captureChat(text: string): Array> { + const captured: Array> = []; + globalThis.fetch = (async (_url: unknown, init?: RequestInit) => { + captured.push(JSON.parse(String(init?.body))); + return jsonResponse({ + choices: [{ index: 0, message: { role: "assistant", content: text }, finish_reason: "stop" }], + usage: { prompt_tokens: 10, completion_tokens: 5 }, + }); + }) as typeof fetch; + return captured; + } + + function expectHistory( + sent: Record, + tail: Array> = [], + withToolCatalog = true, + ) { + const messages = sent.messages as Array>; + // Ordinary non-OpenAI chat turns prepend catalog guidance; compaction removes + // context.tools before translation. Require that exact prefix, not arbitrary extras. + const prefix = withToolCatalog ? [{ + role: "system", + content: expect.stringContaining("Valid tool names for this turn are exactly `read_value`."), + }] : []; + expect(messages).toHaveLength(prefix.length + wireHistory.length + tail.length); + expect(messages).toMatchObject([...prefix, ...wireHistory, ...tail]); + // Exactly one original pair: delivery must not acquire a synthesized tool identity. + expect(messages.flatMap(message => message.tool_calls ?? [])).toEqual(wireHistory[1]!.tool_calls); + expect(messages.filter(message => message.role === "tool")).toEqual([wireHistory[2]]); + expect(JSON.stringify(sent)).not.toContain("[tool output for unknown call]"); + } + + test("ordinary response preserves inter-task delivery after an established tool pair", async () => { + const captured = captureChat(acknowledged); + const res = await handleResponses(compactionRequest(requestBody()), + keyProviderConfig({ adapter: "openai-chat" }), { model: "", provider: "" }); + expect(res.status).toBe(200); + const json = await res.json() as { status?: string }; + expect(json.status).toBe("completed"); + expect(captured).toHaveLength(1); + expectHistory(captured[0]!); + }); + + test("stored-ID continuation replays the established tool pair and inter-task delivery in order", async () => { + const captured = captureChat(acknowledged); + const config = keyProviderConfig({ adapter: "openai-chat" }); + const first = await handleResponses(compactionRequest({ ...requestBody(), store: true }), + config, { model: "", provider: "" }); + expect(first.status).toBe(200); + const saved = await first.json() as { id: string; status?: string }; + expect(saved.status).toBe("completed"); + expect(typeof saved.id).toBe("string"); + expect(saved.id.length).toBeGreaterThan(0); + expect(captured).toHaveLength(1); + expectHistory(captured[0]!); + + // Send only the new user turn: the handler must retrieve the previous raw history. + const res = await handleResponses(compactionRequest({ + ...requestBody(), previous_response_id: saved.id, + input: [{ type: "message", role: "user", content: continuationText }], + }), config, { model: "", provider: "" }); + expect(res.status).toBe(200); + const json = await res.json() as { status?: string }; + expect(json.status).toBe("completed"); + expect(captured).toHaveLength(2); + expectHistory(captured[1]!, [ + { role: "assistant", content: acknowledged }, + { role: "user", content: continuationText }, + ]); + }); + + for (const version of ["v2 trigger", "v1 compact"] as const) { + test(`${version} preserves established-history delivery and pairing before summarization`, async () => { + const captured = captureChat(summary); + const config = keyProviderConfig({ adapter: "openai-chat" }); + const res = version === "v2 trigger" + ? await handleResponses(compactionRequest({ + ...requestBody(), input: [...history(), { type: "compaction_trigger" }], + }), config, { model: "", provider: "" }) + : await handleResponsesCompact(new Request("http://localhost/v1/responses/compact", { + method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(requestBody()), + }), config, { model: "", provider: "" }); + expect(res.status).toBe(200); + const json = await res.json() as { output: Array> }; + expect(captured).toHaveLength(1); + expectHistory(captured[0]!, [ + { role: "user", content: expect.stringContaining("CONTEXT CHECKPOINT COMPACTION") }, + ], false); + expect(captured[0]!.tools).toBeUndefined(); + expect(JSON.stringify(captured)).not.toContain("compaction_trigger"); + if (version === "v2 trigger") { + expect(json.output.filter(item => item.type === "compaction")).toEqual([{ + type: "compaction", id: expect.stringMatching(/^cmp_/), + encrypted_content: `ocx1:${Buffer.from(summary, "utf8").toString("base64")}`, + }]); + } else { + expect(json.output).toEqual([ + { type: "message", role: "user", content: [{ type: "input_text", text: "Read the earlier value." }] }, + { type: "message", role: "user", content: [{ type: "input_text", text: expect.stringContaining(`\n${summary}`) }] }, + ]); + } + }); + } +}); + describe("unpaired tool result boundary (#3259)", () => { function unpairedBody(item: Record): Record { return { diff --git a/tests/responses/responses-snapshot-repair-server.test.ts b/tests/responses/responses-snapshot-repair-server.test.ts index 214806b141..f6e4ac0e92 100644 --- a/tests/responses/responses-snapshot-repair-server.test.ts +++ b/tests/responses/responses-snapshot-repair-server.test.ts @@ -6,6 +6,7 @@ import { saveConfig } from "../../src/config"; import { startServer } from "../../src/server"; import { handleResponses } from "../../src/server/responses"; import { isEagerRelaySseResponse } from "../../src/server/relay"; +import { createGrokResponsesControlFrameBlockRewrite } from "../../src/server/grok-responses-control-frame"; import type { OcxConfig } from "../../src/types"; import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; import { removeTreeWithRetry } from "../helpers/remove-tree"; @@ -58,12 +59,26 @@ const CODEX_SPARSE_TERMINAL_EVENTS = [ }, ]; -function sparseSseBody(events: readonly Record[] = SPARSE_EVENTS): ReadableStream { +const GROK_CONTROL_FRAME_EVENTS = [ + { + type: "codex.rate_limits", + rate_limits: { primary: { used_percent: 12, window_minutes: 60, reset_at: 123 } }, + }, + { type: "codex.response.metadata", headers: { "x-models-etag": "fixture" } }, + { type: "response.created", response: { id: "resp_control" } }, + { type: "response.completed", response: { id: "resp_control", status: "completed", output: [] } }, +]; + +function sparseSseBody( + events: readonly Record[] = SPARSE_EVENTS, + includeEventNames = false, +): ReadableStream { return new ReadableStream({ start(controller) { const encoder = new TextEncoder(); for (const event of events) { - controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`)); + const eventLine = includeEventNames ? `event: ${event.type}\n` : ""; + controller.enqueue(encoder.encode(`${eventLine}data: ${JSON.stringify(event)}\n\n`)); } controller.enqueue(encoder.encode("data: [DONE]\n\n")); controller.close(); @@ -74,6 +89,7 @@ function sparseSseBody(events: readonly Record[] = SPARSE_EVENT function stubSparseGateway( origin: string, events: readonly Record[] = SPARSE_EVENTS, + includeEventNames = false, ): void { globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const requestUrl = typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url; @@ -82,7 +98,7 @@ function stubSparseGateway( return Response.json({ data: [] }); } if (url.origin === origin && url.pathname.endsWith("/responses")) { - return new Response(sparseSseBody(events), { + return new Response(sparseSseBody(events, includeEventNames), { status: 200, headers: { "content-type": "text/event-stream" }, }); @@ -103,6 +119,61 @@ afterEach(async () => { removeTreeWithRetry(TEST_DIR); }); +for (const controlType of ["codex.rate_limits", "codex.response.metadata"]) { + describe(`Grok control frame ${controlType}`, () => { + test.each(["{}", "not-json"])("filters an event-only discriminator with payload %s", payload => { + const rewrite = createGrokResponsesControlFrameBlockRewrite(); + expect(rewrite(`event: ${controlType}\ndata: ${payload}`)).toEqual([]); + }); + + test("filters a data-only discriminator without an event field", () => { + const rewrite = createGrokResponsesControlFrameBlockRewrite(); + expect(rewrite(`data: {"type":"${controlType}"}`)).toEqual([]); + }); + + test.each(["{}", "not-json"])("filters the last event field with payload %s", payload => { + const rewrite = createGrokResponsesControlFrameBlockRewrite(); + expect(rewrite(`event: message\nevent: ${controlType}\ndata: ${payload}`)).toEqual([]); + }); + + test("preserves completion when the last event field overrides a control type", () => { + const block = `event: ${controlType}\nevent: response.completed\ndata: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[]}}`; + expect(createGrokResponsesControlFrameBlockRewrite()(block)).toEqual([block]); + }); + + test.each(["event:", "event: ", "event"])("honors the empty reset %s", reset => { + const block = `event: ${controlType}\n${reset}\ndata: {}`; + expect(createGrokResponsesControlFrameBlockRewrite()(block)).toEqual([block]); + }); + + test("still filters the JSON type after an empty event reset", () => { + const block = `event: ${controlType}\nevent:\ndata: {"type":"${controlType}"}`; + expect(createGrokResponsesControlFrameBlockRewrite()(block)).toEqual([]); + }); + + test.each([`event: ${controlType}`, `event:\t${controlType}`, `event: ${controlType} `])( + "preserves significant event-value whitespace in %s", + eventLine => { + const block = `${eventLine}\ndata: {}`; + expect(createGrokResponsesControlFrameBlockRewrite()(block)).toEqual([block]); + }, + ); + + test("recognizes a CRLF event field without an optional space", () => { + expect(createGrokResponsesControlFrameBlockRewrite()(`event:message\r\nevent:${controlType}\r\ndata: {}`)).toEqual([]); + }); + + test("does not retain the event type across blocks or consume ordinary content", () => { + const rewrite = createGrokResponsesControlFrameBlockRewrite(); + expect(rewrite(`event: ${controlType}\ndata: {}`)).toEqual([]); + for (const block of ["data: {}", "data: not-json", ": heartbeat", "data: [DONE]", + `data: {"type":"response.output_text.delta","delta":"${controlType}"}`]) { + expect(rewrite(block)).toEqual([block]); + } + }); + }); +} + describe("responsesSnapshotRepair through /v1/responses", () => { test.skipIf(process.platform !== "darwin")( "Darwin eager-relay applies snapshot repair inline before bytes reach the client", @@ -326,6 +397,49 @@ describe("responsesSnapshotRepair through /v1/responses", () => { await server.stop(true); } }); + test.each([true, false])("the Grok marker filters Codex control frames at the client boundary (event names: %s)", async includeEventNames => { + const gateway = "https://grok-control-frame.example.test"; + stubSparseGateway(gateway, GROK_CONTROL_FRAME_EVENTS, includeEventNames); + saveConfig({ + port: 0, + defaultProvider: "sparse", + providers: { + sparse: { + adapter: "openai-responses", + baseUrl: `${gateway}/v1`, + authMode: "key", + apiKey: "test-key", + }, + }, + } as OcxConfig); + + const server = startServer(0); + try { + const request = (grokMarker: boolean) => originalFetch(new URL("/v1/responses", server.url), { + method: "POST", + headers: { + "content-type": "application/json", + ...(grokMarker ? { "x-opencodex-grok": "1" } : {}), + }, + body: JSON.stringify({ model: "sparse-model", input: "hi", stream: true }), + }); + + const grokResponse = await request(true); + expect(grokResponse.status).toBe(200); + const grokText = await grokResponse.text(); + expect(grokText).not.toContain("codex.rate_limits"); + expect(grokText).not.toContain("codex.response.metadata"); + expect(grokText).toContain('"type":"response.completed"'); + + const ordinaryResponse = await request(false); + expect(ordinaryResponse.status).toBe(200); + const ordinaryText = await ordinaryResponse.text(); + expect(ordinaryText).toContain("codex.rate_limits"); + expect(ordinaryText).toContain("codex.response.metadata"); + } finally { + await server.stop(true); + } + }); }); test("sparse JSON completion inference precedes function repair in client output and replay", async () => { diff --git a/tests/server/agent-task-recovery-cache.test.ts b/tests/server/agent-task-recovery-cache.test.ts index 2ee994f8ce..35b5ba7050 100644 --- a/tests/server/agent-task-recovery-cache.test.ts +++ b/tests/server/agent-task-recovery-cache.test.ts @@ -29,16 +29,23 @@ describe("agent task recovery cache", () => { resetAgentTaskRecoveryCache(); }); - test("shared failure gives each waiter its own result without contaminating another key", async () => { + test.each([ + { kind: "http", reason: "recovery_http_rejected" }, + { kind: "reader", reason: "recovery_transport_error" }, + { kind: "decode", reason: "recovery_invalid_output" }, + ] as const)("shared $kind failure gives each waiter its own result without contaminating another key", async ({ kind, reason }) => { let release: (() => void) | undefined; const gate = new Promise(resolve => { release = resolve; }); let fetches = 0; globalThis.fetch = (async () => { const requestNumber = ++fetches; await gate; - return requestNumber === 1 - ? new Response("raw-failure-sentinel", { status: 503 }) - : new Response(recoverySse("Independent assignment.")); + if (requestNumber !== 1) return new Response(recoverySse("Independent assignment.")); + if (kind === "decode") return new Response(new Uint8Array([0xff])); + if (kind === "reader") return new Response(new ReadableStream({ + pull(controller) { controller.error(new TypeError("private-reader-failure")); }, + })); + return new Response("raw-failure-sentinel", { status: 503 }); }) as typeof fetch; const req = new Request("http://localhost/v1/responses", { headers: codexHeaders() }); const config = routedConfig(); @@ -53,8 +60,8 @@ describe("agent task recovery cache", () => { expect(fetches).toBe(2); release?.(); const [firstResult, secondResult, otherResult] = await Promise.all([first, second, other]); - expect(firstResult).toEqual({ recovered: false, reason: "recovery_unavailable" }); - expect(secondResult).toEqual({ recovered: false, reason: "recovery_unavailable" }); + expect(firstResult).toEqual({ recovered: false, reason }); + expect(secondResult).toEqual({ recovered: false, reason }); expect(firstResult).not.toBe(secondResult); expect(otherResult).toEqual({ recovered: true }); expect(firstInput).toEqual(encryptedInput()); @@ -68,6 +75,39 @@ describe("agent task recovery cache", () => { } }); + test("shared flight reset reports abort to surviving callers and never caches late plaintext", async () => { + let release!: () => void; + const gate = new Promise(resolve => { release = resolve; }); + let fetches = 0; + globalThis.fetch = (async () => { + fetches++; + await gate; + return new Response(recoverySse("private-late-assignment")); + }) as typeof fetch; + const req = new Request("http://localhost/v1/responses", { headers: codexHeaders() }); + const firstInput = encryptedInput(); + const secondInput = encryptedInput(); + const first = recoverEncryptedAgentTaskWithResult(req, firstInput, {}, routedConfig()); + const second = recoverEncryptedAgentTaskWithResult(req, secondInput, {}, routedConfig()); + try { + expect(fetches).toBe(1); + resetAgentTaskRecoveryCache(); + release(); + const results = await Promise.all([first, second]); + expect(results).toEqual([ + { recovered: false, reason: "recovery_aborted" }, + { recovered: false, reason: "recovery_aborted" }, + ]); + expect(results[0]).not.toBe(results[1]); + expect(firstInput).toEqual(encryptedInput()); + expect(secondInput).toEqual(encryptedInput()); + expect(agentTaskRecoveryCacheSnapshotForTests()).toEqual({ entries: 0, bytes: 0 }); + } finally { + release(); + await Promise.all([first, second]); + } + }); + for (const succeeds of [true, false]) { test(`caller cancellation stays local when the remaining waiter ${succeeds ? "succeeds" : "fails"}`, async () => { let release: (() => void) | undefined; @@ -95,7 +135,7 @@ describe("agent task recovery cache", () => { release?.(); expect(await second).toEqual(succeeds ? { recovered: true } - : { recovered: false, reason: "recovery_unavailable" }); + : { recovered: false, reason: "recovery_http_rejected" }); expect(fetches).toBe(1); expect(restoreCachedEncryptedAgentTasks(req, encryptedInput(), config)).toBe(succeeds ? 1 : 0); } finally { diff --git a/tests/server/agent-task-recovery.test.ts b/tests/server/agent-task-recovery.test.ts index ceb1c5b6b5..a168f2c364 100644 --- a/tests/server/agent-task-recovery.test.ts +++ b/tests/server/agent-task-recovery.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import { createTranslatorBudget } from "../../src/lib/translator-budget"; import { warnAgentTaskRecoveryStartup } from "../../src/server"; import { @@ -7,6 +7,7 @@ import { recoverEncryptedAgentTaskWithResult, resetAgentTaskRecoveryState, restoreCachedEncryptedAgentTasks, + type AgentTaskRecoveryFailureReason, } from "../../src/server/responses/agent-task-recovery"; import { agentTaskRecoveryWaiterCountForTests } from "../../src/server/responses/agent-task-recovery-cache"; import { @@ -78,24 +79,36 @@ describe("agent task recovery (opt-in, default off)", () => { }); } - const failedRecoveries: Array<[string, () => Response]> = [ - ["HTTP 503", () => new Response("raw-error-sentinel", { status: 503 })], - ["network exception", () => { throw new Error("raw-error-sentinel"); }], - ["malformed SSE", () => new Response("data: {not-json}\n\n")], - ["missing completion", () => new Response(recoverySse("payload-sentinel").split("data: {\"type\":\"response.completed\"")[0])], - ["conflicting assignment", () => new Response(recoverySse("payload-sentinel") + recoveryCompletedSse("other-payload-sentinel"))], - ["failed terminal", () => new Response(recoverySse("payload-sentinel") + 'data: {"type":"response.failed","response":{"error":{"message":"raw-error-sentinel"}}}\n\n')], - ["incomplete terminal", () => new Response(recoverySse("payload-sentinel") + 'data: {"type":"response.incomplete"}\n\n')], - ["bare error", () => new Response(recoverySse("payload-sentinel") + 'data: {"type":"error","error":{"message":"raw-error-sentinel"}}\n\n')], + const failedRecoveries: Array<[string, () => Response, AgentTaskRecoveryFailureReason]> = [ + ["HTTP 401", () => new Response("private-error", { status: 401 }), "recovery_http_rejected"], + ["HTTP 403", () => new Response("private-error", { status: 403 }), "recovery_http_rejected"], + ["HTTP 429", () => new Response("private-error", { status: 429 }), "recovery_http_rejected"], + ["fetch TypeError", () => { throw new TypeError("private-error"); }, "recovery_transport_error"], + ["unowned TimeoutError", () => { throw new DOMException("private-error", "TimeoutError"); }, "recovery_transport_error"], + ["reader TypeError", () => new Response(new ReadableStream({ + pull(controller) { controller.error(new TypeError("private-reader-error")); }, + })), "recovery_transport_error"], + ["invalid UTF-8", () => new Response(new Uint8Array([0xff])), "recovery_invalid_output"], + ["trailing UTF-8", () => new Response(new Uint8Array([0xe2, 0x82])), "recovery_invalid_output"], + ["oversized body", () => new Response(new Uint8Array(4 * 1024 * 1024 + 1)), "recovery_invalid_output"], + ["invalid arguments", () => new Response(recoverySse("task").replace('{\\"assignment\\":\\"task\\"}', '{broken')), "recovery_invalid_output"], + ["HTTP 503", () => new Response("raw-error-sentinel", { status: 503 }), "recovery_http_rejected"], + ["network exception", () => { throw new Error("raw-error-sentinel"); }, "recovery_transport_error"], + ["malformed SSE", () => new Response("data: {not-json}\n\n"), "recovery_invalid_output"], + ["missing completion", () => new Response(recoverySse("payload-sentinel").split("data: {\"type\":\"response.completed\"")[0]), "recovery_invalid_output"], + ["conflicting assignment", () => new Response(recoverySse("payload-sentinel") + recoveryCompletedSse("other-payload-sentinel")), "recovery_invalid_output"], + ["failed terminal", () => new Response(recoverySse("payload-sentinel") + 'data: {"type":"response.failed","response":{"error":{"message":"raw-error-sentinel"}}}\n\n'), "recovery_invalid_output"], + ["incomplete terminal", () => new Response(recoverySse("payload-sentinel") + 'data: {"type":"response.incomplete"}\n\n'), "recovery_invalid_output"], + ["bare error", () => new Response(recoverySse("payload-sentinel") + 'data: {"type":"error","error":{"message":"raw-error-sentinel"}}\n\n'), "recovery_invalid_output"], // Exact-case events are also used by the pinned official Codex source. Recovery's // additional completed-status requirement remains deliberately stricter. - ["mixed-case completion", () => new Response(recoverySse("payload-sentinel").replace("response.completed", "Response.Completed"))], - ["mixed-case status", () => new Response(recoverySse("payload-sentinel").replace('"status":"completed"', '"status":"Completed"'))], - ["missing status", () => new Response(recoverySse("payload-sentinel").replace('"status":"completed",', ""))], - ["ciphertext assignment", () => new Response(recoverySse(FERNET_TASK))], + ["mixed-case completion", () => new Response(recoverySse("payload-sentinel").replace("response.completed", "Response.Completed")), "recovery_invalid_output"], + ["mixed-case status", () => new Response(recoverySse("payload-sentinel").replace('"status":"completed"', '"status":"Completed"')), "recovery_invalid_output"], + ["missing status", () => new Response(recoverySse("payload-sentinel").replace('"status":"completed",', "")), "recovery_invalid_output"], + ["ciphertext assignment", () => new Response(recoverySse(FERNET_TASK)), "recovery_invalid_output"], ]; - for (const [name, response] of failedRecoveries) { - test(`typed recovery keeps ${name} coarse and preserves false without retrying`, async () => { + for (const [name, response, reason] of failedRecoveries) { + test(`typed recovery classifies ${name} and preserves false without retrying`, async () => { const req = new Request("http://localhost/v1/responses", { headers: codexHeaders() }); const config = routedConfig(); let fetches = 0; @@ -103,7 +116,7 @@ describe("agent task recovery (opt-in, default off)", () => { const input = encryptedInput(); const original = structuredClone(input); expect(await recoverEncryptedAgentTaskWithResult(req, input, {}, config)) - .toEqual({ recovered: false, reason: "recovery_unavailable" }); + .toEqual({ recovered: false, reason }); expect(input).toEqual(original); expect(fetches).toBe(1); expect(restoreCachedEncryptedAgentTasks(req, encryptedInput(), config)).toBe(0); @@ -113,6 +126,69 @@ describe("agent task recovery (opt-in, default off)", () => { }); } + test.each(["pending", "rejecting"] as const)("HTTP refusal does not await %s body cancellation", async mode => { + let cancels = 0; + let reads = 0; + let releaseCancel: (() => void) | undefined; + const cancellation = new Promise(resolve => { releaseCancel = resolve; }); + globalThis.fetch = (async () => new Response(new ReadableStream({ + pull() { reads++; }, + cancel() { + cancels++; + return mode === "pending" ? cancellation : Promise.reject(new Error("private-cancel-error")); + }, + }, { highWaterMark: 0 }), { status: 503 })) as typeof fetch; + try { + const result = await recoverEncryptedAgentTaskWithResult( + new Request("http://localhost/v1/responses", { headers: codexHeaders() }), encryptedInput(), {}, routedConfig(), + ); + expect(result).toEqual({ recovered: false, reason: "recovery_http_rejected" }); + expect(cancels).toBe(1); + expect(reads).toBe(0); + } finally { + releaseCancel?.(); + } + }); + + test.each(["headers", "body", "caller"] as const)("owned deadline classification at %s preserves cancellation precedence", async site => { + const callbacks: Array<() => void> = []; + const timers = spyOn(globalThis, "setTimeout").mockImplementation(((callback: () => void) => { + callbacks.push(callback); + return 0 as unknown as ReturnType; + }) as typeof setTimeout); + const caller = new AbortController(); + let started!: () => void; + const ready = new Promise(resolve => { started = resolve; }); + let fetches = 0; + globalThis.fetch = ((_, init) => { + fetches++; + if (site === "body") return Promise.resolve(new Response(new ReadableStream({ + pull(controller) { + controller.enqueue(new Uint8Array([0xe2, 0x82])); + started(); + return new Promise(() => {}); + }, + }, { highWaterMark: 0 }))); + return new Promise((_resolve, reject) => { + init?.signal?.addEventListener("abort", () => reject(init.signal?.reason), { once: true }); + started(); + }); + }) as typeof fetch; + try { + const pending = recoverEncryptedAgentTaskWithResult( + new Request("http://localhost/v1/responses", { headers: codexHeaders() }), encryptedInput(), {}, routedConfig(), + { abortSignal: caller.signal }, + ); + await ready; + callbacks[0]!(); // Fire the owned deadline without wall-clock sleeps. + if (site === "caller") caller.abort(new TypeError("private-caller-error")); + expect(await pending).toEqual({ recovered: false, reason: site === "caller" ? "caller_cancelled" : "recovery_timeout" }); + expect(fetches).toBe(1); + } finally { + timers.mockRestore(); + } + }); + test("keeps the disabled fail-fast response byte-identical to the absent feature", async () => { const snapshot = async (config: ReturnType) => { let fetchCalls = 0; @@ -226,7 +302,7 @@ describe("agent task recovery (opt-in, default off)", () => { expect(response.status).toBe(400); expect(json.error?.code).toBe("unreadable_encrypted_agent_task"); - expect(json.error?.recovery_reason).toBe("recovery_unavailable"); + expect(json.error?.recovery_reason).toBe("recovery_invalid_output"); expect(fetchedUrls.length).toBeGreaterThan(0); expect(fetchedUrls[0]).toContain("chatgpt.com/backend-api/codex"); }); @@ -778,7 +854,7 @@ describe("agent task recovery (opt-in, default off)", () => { expect(fetchedUrls).toHaveLength(1); expect(fetchedUrls[0]).toContain("chatgpt.com/backend-api/codex/responses"); expect(await response.json()).toMatchObject({ - error: { code: "unreadable_encrypted_agent_task", recovery_reason: "recovery_unavailable" }, + error: { code: "unreadable_encrypted_agent_task", recovery_reason: "recovery_transport_error" }, }); }); }); diff --git a/tests/server/bounded-body.test.ts b/tests/server/bounded-body.test.ts index f5223d34a4..0bf5e0ae1b 100644 --- a/tests/server/bounded-body.test.ts +++ b/tests/server/bounded-body.test.ts @@ -1,7 +1,8 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, spyOn, test } from "bun:test"; import { BOUNDED_BODY_MAX_BYTES, boundedBodyBufferGrowthsForTests, + boundedBodyDecodeFailure, readBoundedResponseBytes, readBoundedResponseBody, } from "../../src/lib/bounded-body"; @@ -21,6 +22,65 @@ function responseFromChunks(...chunks: Uint8Array[]): Response { } describe("readBoundedResponseBody", () => { + test("only actual decoder exceptions carry the decode discriminator", async () => { + for (const bytes of [new Uint8Array([0xff]), new Uint8Array([0xe2, 0x82])]) { + let caught: unknown; + try { await readBoundedResponseBody(responseFromChunks(bytes), { fatalUtf8: true }); } + catch (error) { caught = error; } + expect(caught).toBeInstanceOf(TypeError); + expect(boundedBodyDecodeFailure(caught)).toBe("invalid_utf8"); + } + const readerError = new TypeError("private-reader-error"); + const response = new Response(new ReadableStream({ pull(controller) { controller.error(readerError); } })); + let caught: unknown; + try { await readBoundedResponseBody(response, { fatalUtf8: true }); } + catch (error) { caught = error; } + expect(caught).toBe(readerError); + expect(boundedBodyDecodeFailure(caught)).toBeUndefined(); + }); + + test("fatal UTF-8 abort retains the exact caller reason without a decode mark", async () => { + const caller = new AbortController(); + const reason = new TypeError("private-caller-error"); + const pending = readBoundedResponseBody(new Response(new ReadableStream({})), { signal: caller.signal, fatalUtf8: true }); + caller.abort(reason); + let caught: unknown; + try { await pending; } catch (error) { caught = error; } + expect(caught).toBe(reason); + expect(boundedBodyDecodeFailure(caught)).toBeUndefined(); + }); + + test.each([0, 1])("fatal timeout flush retains deadline origin %s and cancels without waiting", async deadline => { + const callbacks: Array<() => void> = []; + const timers = spyOn(globalThis, "setTimeout").mockImplementation(((callback: () => void) => { + callbacks.push(callback); + return 0 as unknown as ReturnType; + }) as typeof setTimeout); + let stalled!: () => void; + const ready = new Promise(resolve => { stalled = resolve; }); + let pulls = 0; + let cancelled = false; + const response = new Response(new ReadableStream({ + pull(controller) { + if (pulls++ === 0) controller.enqueue(new Uint8Array([0xe2, 0x82])); + else { stalled(); return new Promise(() => {}); } + }, + cancel() { cancelled = true; return new Promise(() => {}); }, + }, { highWaterMark: 0 })); + try { + const pending = readBoundedResponseBody(response, { fatalUtf8: true }); + await ready; + callbacks[deadline === 0 ? 0 : callbacks.length - 1]!(); + let caught: unknown; + try { await pending; } catch (error) { caught = error; } + expect(caught).toBeInstanceOf(TypeError); + expect(boundedBodyDecodeFailure(caught)).toBe("timeout"); + expect(cancelled).toBe(true); + } finally { + timers.mockRestore(); + } + }); + test("the bounded JSON caller allows a full total deadline for its first byte", () => { expect(UPSTREAM_JSON_BODY_READ_OPTIONS.firstByteTimeoutMs) .toBe(UPSTREAM_JSON_BODY_READ_OPTIONS.totalTimeoutMs); diff --git a/tests/server/management-client-config-route.test.ts b/tests/server/management-client-config-route.test.ts index d3d91aebdf..9fcb92e81d 100644 --- a/tests/server/management-client-config-route.test.ts +++ b/tests/server/management-client-config-route.test.ts @@ -23,6 +23,7 @@ import { type McodeGeneratedConfig, type OpencodeGeneratedConfig, type PiGeneratedConfig, + type RaycastGeneratedConfig, } from "../../src/clients/config-export"; import type { OcxConfig } from "../../src/types"; import { catalogConvergenceFactory } from "../helpers/catalog-convergence"; @@ -215,6 +216,50 @@ describe("native Anthropic effort ladder reaches the Aside document", () => { }); }); describe("GET /api/client-config", () => { + for (const hostname of ["0.0.0.0", "::", "192.0.2.40"]) { + test(`Raycast export refuses authenticated bind ${hostname} before generating a document`, async () => { + const response = await clientConfigApi(baseConfig({ hostname }), "?client=raycast"); + expect(response.status).toBe(400); + const body = await response.json() as Record; + expect(body.reason).toBe("non_loopback"); + expect(body.config).toBeUndefined(); + expect(body.text).toBeUndefined(); + }); + } + + test("Raycast export uses the declared unauthenticated listener instead of the management port", async () => { + const response = await clientConfigApi(baseConfig({ + hostname: "0.0.0.0", + unauthenticatedLoopbackListener: { enabled: true, port: 10237 }, + }), "?client=raycast"); + expect(response.status).toBe(200); + const body = await response.json() as ClientConfigEnvelope; + const document = body.config as RaycastGeneratedConfig; + expect(document.providers[0]!.base_url).toBe("http://127.0.0.1:10237/v1"); + expect(document.providers[0]!.models.length).toBeGreaterThan(0); + expect(body.text).not.toContain(REAL_LOOKING_KEY); + expect(body.text).not.toContain("api_keys"); + }); + + test("OpenCode export keeps its envelope and uses the declared unauthenticated listener", async () => { + const response = await clientConfigApi(baseConfig({ + hostname: "0.0.0.0", unauthenticatedLoopbackListener: { enabled: true, port: 10237 }, + }), "?client=opencode"); + expect(response.status).toBe(200); + const body = await response.json() as ClientConfigEnvelope; + expect(body.client).toBe("opencode"); + expect((body.config as OpencodeGeneratedConfig).provider.opencodex!.options.baseURL) + .toBe("http://127.0.0.1:10237/v1"); + }); + + test("Raycast export uses the main port for an ordinary loopback bind", async () => { + const response = await clientConfigApi(baseConfig(), "?client=raycast"); + expect(response.status).toBe(200); + const body = await response.json() as ClientConfigEnvelope; + expect((body.config as RaycastGeneratedConfig).providers[0]!.base_url) + .toBe("http://127.0.0.1:10100/v1"); + }); + test("opencode envelope carries the shared builder's exact bytes", async () => { const config = baseConfig(); const response = await clientConfigApi(config, "?client=opencode"); diff --git a/tests/server/management-integration-routes.test.ts b/tests/server/management-integration-routes.test.ts index 1f8cba92a2..e0d6563aea 100644 --- a/tests/server/management-integration-routes.test.ts +++ b/tests/server/management-integration-routes.test.ts @@ -14,6 +14,7 @@ import { handleManagementAPI } from "../../src/server/management-api"; import { setIntegrationMutationFlightTestHooks, setIntegrationPathTestHooks, + setRaycastDetectTestHook, } from "../../src/server/management/integration-routes"; import type { OcxConfig } from "../../src/types"; import { catalogConvergenceFactory } from "../helpers/catalog-convergence"; @@ -274,6 +275,31 @@ describe("GET /api/client-integrations", () => { // A read is a read: it appends nothing. expect(store.listOperations()).toHaveLength(before); }); + + test("the raycast envelope carries the plan block; every other client's does not", async () => { + // Stubbed: the real detector spawns `defaults` and would report the + // developer's own subscription. + setRaycastDetectTestHook(() => ({ appPath: "/Applications/Raycast.app", aiDirPresent: false, plan: "free" })); + try { + const raycast = await api("/api/client-integrations/raycast"); + expect(raycast.status).toBe(200); + const body = await raycast.json() as { clientId: string; raycast?: { plan: string; appPath: string | null; aiDirPresent: boolean } }; + expect(body.clientId).toBe("raycast"); + expect(body.raycast).toEqual({ appPath: "/Applications/Raycast.app", aiDirPresent: false, plan: "free" }); + + installHermes(); + const hermes = await api("/api/client-integrations/hermes"); + expect(hermes.status).toBe(200); + expect("raycast" in (await hermes.json() as Record)).toBe(false); + + // The collection read describes files, not apps: no client gets the block there. + const list = await api("/api/client-integrations"); + const { clients } = await list.json() as { clients: Array> }; + expect(clients.some(client => "raycast" in client)).toBe(false); + } finally { + setRaycastDetectTestHook(null); + } + }); }); /** The models the route itself derives, so expectations cannot drift from it. */ diff --git a/tests/service/container-bootstrap.test.ts b/tests/service/container-bootstrap.test.ts index ada807d1d0..9eec8edd6b 100644 --- a/tests/service/container-bootstrap.test.ts +++ b/tests/service/container-bootstrap.test.ts @@ -63,6 +63,7 @@ describe("container deployment contract", () => { const runtime = readFileSync(repoPath("Dockerfile"), "utf8").split(" AS runtime")[1]!; expect(runtime).toContain("OPENCODEX_HOME=/home/bun/.opencodex"); expect(runtime).toContain("CODEX_HOME=/home/bun/.codex"); + expect(runtime).toContain("OCX_SERVICE=1"); expect(runtime).toContain("install -d -m 0700 -o bun -g bun /home/bun/.opencodex /home/bun/.codex"); expect(runtime).toContain('VOLUME ["/home/bun/.opencodex", "/home/bun/.codex"]'); expect(runtime).toContain("USER bun"); diff --git a/tests/usage/quota-reset-notify.test.ts b/tests/usage/quota-reset-notify.test.ts index 6a503e69a5..519e68e869 100644 --- a/tests/usage/quota-reset-notify.test.ts +++ b/tests/usage/quota-reset-notify.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; -import { mkdtempSync, writeFileSync } from "node:fs"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { INTERNAL_DEADLINE_MS, SERVER_BUDGET_MS } from "../helpers/test-budget"; @@ -366,12 +366,8 @@ describe("config integration", () => { }); describe("webhookUrl is treated as a credential", () => { - test("ocx config show does not print it", async () => { - // For Slack and Discord the URL IS the authorization: anyone holding it can post to the - // channel. It matches none of the pre-existing secret-key patterns, so it had to be named - // explicitly — before that, `config show` printed it and `config export` wrote it to disk. + function configureWebhook(secret: string): { home: string; restore: () => void } { const home = mkdtempSync(join(tmpdir(), "ocx-redact-")); - const secret = "https://hooks.slack.com/services/T00000/B00000/zzTOKENzz"; writeFileSync(join(home, "config.json"), JSON.stringify({ port: 10100, defaultProvider: "openai", @@ -380,9 +376,23 @@ describe("webhookUrl is treated as a credential", () => { }, quotaResetNotify: { enabled: true, webhookUrl: secret }, })); - const previousHome = process.env["OPENCODEX_HOME"]; process.env["OPENCODEX_HOME"] = home; + return { + home, + restore: () => { + if (previousHome === undefined) delete process.env["OPENCODEX_HOME"]; + else process.env["OPENCODEX_HOME"] = previousHome; + }, + }; + } + + test("ocx config show does not print it", async () => { + // For Slack and Discord the URL IS the authorization: anyone holding it can post to the + // channel. It matches none of the pre-existing secret-key patterns, so it had to be named + // explicitly — before that, `config show` printed it and `config export` wrote it to disk. + const secret = "https://hooks.slack.com/services/T00000/B00000/zzTOKENzz"; + const configured = configureWebhook(secret); const written: string[] = []; const originalLog = console.log; console.log = (...args: unknown[]) => { written.push(args.map(String).join(" ")); }; @@ -395,8 +405,44 @@ describe("webhookUrl is treated as a credential", () => { expect(output).toContain("********"); } finally { console.log = originalLog; - if (previousHome === undefined) delete process.env["OPENCODEX_HOME"]; - else process.env["OPENCODEX_HOME"] = previousHome; + configured.restore(); + } + }); + + test("ocx config export omits it from stdout", async () => { + const secret = "https://hooks.slack.com/services/T00000/B00000/stdoutTOKEN"; + const configured = configureWebhook(secret); + const written: string[] = []; + const originalWrite = process.stdout.write; + process.stdout.write = ((chunk: string | Uint8Array) => { + written.push(String(chunk)); + return true; + }) as typeof process.stdout.write; + try { + expect(await handleConfigCommand(["export", "-"])).toBe(0); + const exported = JSON.parse(written.join("")) as Record; + expect(JSON.stringify(exported)).not.toContain(secret); + expect(exported["quotaResetNotify"]).toEqual({ enabled: true }); + } finally { + process.stdout.write = originalWrite; + configured.restore(); + } + }); + + test("ocx config export omits it from a file", async () => { + const secret = "https://hooks.discord.com/api/webhooks/fileTOKEN"; + const configured = configureWebhook(secret); + const outputPath = join(configured.home, "export.json"); + const originalLog = console.log; + console.log = () => {}; + try { + expect(await handleConfigCommand(["export", outputPath])).toBe(0); + const exported = JSON.parse(readFileSync(outputPath, "utf8")) as Record; + expect(JSON.stringify(exported)).not.toContain(secret); + expect(exported["quotaResetNotify"]).toEqual({ enabled: true }); + } finally { + console.log = originalLog; + configured.restore(); } }); }); diff --git a/tests/usage/request-decompress.test.ts b/tests/usage/request-decompress.test.ts index 7a536600cc..96a8f5a67a 100644 --- a/tests/usage/request-decompress.test.ts +++ b/tests/usage/request-decompress.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from "bun:test"; +import { deflateRawSync, deflateSync } from "node:zlib"; import { DecompressedBodyTooLargeError, decodeRequestBody, @@ -9,11 +10,35 @@ import { } from "../../src/server/request-decompress"; import { MANAGEMENT_JSON_BODY_MAX_BYTES } from "../../src/server/management/body"; import { handleManagementAPI } from "../../src/server/management-api"; +import { decodeRequestErrorResponse } from "../../src/server/responses/core"; import type { OcxConfig } from "../../src/types"; const PAYLOAD = { model: "gpt-5.5", input: "hello", stream: true }; const PAYLOAD_BYTES = new TextEncoder().encode(JSON.stringify(PAYLOAD)); +async function captureBodyTooLarge(run: () => unknown): Promise { + try { + await run(); + } catch (error) { + if (!(error instanceof DecompressedBodyTooLargeError)) throw error; + return error; + } + throw new Error("Expected body admission to reject"); +} + +async function expectBodyLimitResponse(error: DecompressedBodyTooLargeError, message: string): Promise { + expect(error.message).toBe(message); + expect(message.length).toBeLessThan(200); + for (const label of ["responses", "responses-compact"]) { + const response = decodeRequestErrorResponse(error, label); + expect(response.status).toBe(413); + expect(response.headers.get("retry-after")).toBeNull(); + expect(await response.json()).toEqual({ + error: { message, type: "invalid_request_error", code: "invalid_request_error" }, + }); + } +} + interface TrackedBodyStats { pulls: number; cancelled: number; @@ -48,6 +73,36 @@ function trackedBodyStream( return { body, stats }; } +describe("DecompressedBodyTooLargeError", () => { + test("preserves one- and two-argument constructors without guessing measurement provenance", async () => { + const legacy = new DecompressedBodyTooLargeError(268435457); + expect(legacy).toMatchObject({ bytes: 268435457, limit: 268435456, measurement: null }); + await expectBodyLimitResponse(legacy, "Decompressed request body exceeds 268435456 bytes"); + const custom = new DecompressedBodyTooLargeError(6, 5); + expect(custom).toMatchObject({ bytes: 6, limit: 5, measurement: null }); + await expectBodyLimitResponse(custom, "Decompressed request body exceeds 5 bytes"); + }); + + test("keeps untyped categories and non-finite numbers out of the message", async () => { + const untyped: DecompressedBodyTooLargeError = Reflect.construct(DecompressedBodyTooLargeError, [ + 6, 5, "private-header-context window".repeat(100), + ]); + expect(untyped.measurement).toBeNull(); + await expectBodyLimitResponse(untyped, "Decompressed request body exceeds 5 bytes"); + for (const bytes of [NaN, Infinity, -Infinity, -1]) { + const error = new DecompressedBodyTooLargeError(bytes, 5, "declared_wire"); + await expectBodyLimitResponse(error, "Decompressed request body exceeds 5 bytes"); + } + for (const limit of [NaN, Infinity, -Infinity]) { + const error = new DecompressedBodyTooLargeError(6, limit, "declared_wire"); + await expectBodyLimitResponse(error, "Decompressed request body exceeds unknown bytes"); + } + const huge = new DecompressedBodyTooLargeError(Number.MAX_VALUE, 5, "declared_wire"); + await expectBodyLimitResponse(huge, + "Decompressed request body exceeds 5 bytes [measurement=declared_wire; bytes=1.7976931348623157e+308]"); + }); +}); + describe("decodeRequestBody", () => { test("passes identity and absent encodings through untouched", () => { expect(decodeRequestBody(PAYLOAD_BYTES, null)).toBe(PAYLOAD_BYTES); @@ -78,10 +133,11 @@ describe("decodeRequestBody", () => { expect(new TextDecoder().decode(decodeRequestBody(compressed, "x-gzip"))).toBe(JSON.stringify(PAYLOAD)); }); - test("round-trips deflate", () => { - const compressed = Bun.deflateSync(PAYLOAD_BYTES); - expect(new TextDecoder().decode(decodeRequestBody(compressed, "deflate"))).toBe(JSON.stringify(PAYLOAD)); - }); + for (const [label, compress] of [["wrapped", deflateSync], ["raw", deflateRawSync], ["Bun raw", Bun.deflateSync]] as const) { + test(`round-trips ${label} deflate`, () => { + expect(new TextDecoder().decode(decodeRequestBody(compress(PAYLOAD_BYTES), "deflate"))).toBe(JSON.stringify(PAYLOAD)); + }); + } test("is case/whitespace tolerant on the encoding token", () => { const compressed = Bun.zstdCompressSync(PAYLOAD_BYTES); @@ -104,15 +160,39 @@ describe("decodeRequestBody", () => { expect(() => decodeRequestBody(compressed, "zstd")).toThrow(DecompressedBodyTooLargeError); }); - test("aborts DURING inflation via maxOutputLength — activation per codec (injected cap)", () => { + test("reports exact identity size at the decoder boundary", async () => { + for (const encoding of [null, "", "identity"]) { + const error = await captureBodyTooLarge(() => decodeRequestBody(Uint8Array.of(1, 2, 3, 4, 5, 6), encoding, 5)); + expect(error).toMatchObject({ bytes: 6, limit: 5, measurement: "decoded_exact" }); + await expectBodyLimitResponse(error, "Decompressed request body exceeds 5 bytes [measurement=decoded_exact; bytes=6]"); + } + }); + + test("aborts DURING inflation and reports only a decoded lower bound for every codec", async () => { // Review finding (PR #96): the cap must fire inside zlib, not after full allocation. // A small injected cap keeps the test cheap while exercising the exact // ERR_BUFFER_TOO_LARGE -> DecompressedBodyTooLargeError path. const CAP = 1024; const inflates64k = new Uint8Array(64 * 1024); - expect(() => decodeRequestBody(Bun.zstdCompressSync(inflates64k), "zstd", CAP)).toThrow(DecompressedBodyTooLargeError); - expect(() => decodeRequestBody(Bun.gzipSync(inflates64k), "gzip", CAP)).toThrow(DecompressedBodyTooLargeError); - expect(() => decodeRequestBody(Bun.deflateSync(inflates64k), "deflate", CAP)).toThrow(DecompressedBodyTooLargeError); + for (const [encoding, compressed] of [ + ["zstd", Bun.zstdCompressSync(inflates64k)], + ["gzip", Bun.gzipSync(inflates64k)], + ["x-gzip", Bun.gzipSync(inflates64k)], + ["deflate", deflateSync(inflates64k)], + ["deflate", deflateRawSync(inflates64k)], + ["deflate", Bun.deflateSync(inflates64k)], + ] as const) { + expect(compressed.byteLength).toBeLessThan(CAP); + // Exercise the streaming reader too: these invalid-JSON bytes must be + // rejected by inflation before text decoding or JSON parsing. + const req = new Request("http://localhost/v1/responses/compact", { + method: "POST", headers: { "content-encoding": encoding }, body: compressed, + }); + const error = await captureBodyTooLarge(() => readBoundedJsonRequestBody(req, CAP)); + expect(error).toMatchObject({ bytes: 1025, limit: 1024, measurement: "decoded_lower_bound" }); + await expectBodyLimitResponse(error, + "Decompressed request body exceeds 1024 bytes [measurement=decoded_lower_bound; bytes=1025]"); + } }); test("injected cap still admits bodies within the limit", () => { @@ -134,6 +214,20 @@ describe("decodeRequestBody", () => { }); describe("readJsonRequestBody", () => { + test("reports a compressed declaration without reading or echoing request metadata", async () => { + const { body, stats } = trackedBodyStream([Bun.gzipSync(PAYLOAD_BYTES)]); + const req = new Request("http://localhost/v1/responses/compact?private-query", { + method: "POST", + headers: { "content-length": "00001025", "content-encoding": "gzip", "x-private-marker": "private-header" }, + body, + }); + const error = await captureBodyTooLarge(() => readBoundedJsonRequestBody(req, 1024)); + expect(error).toMatchObject({ bytes: 1025, limit: 1024, measurement: "declared_wire" }); + await expectBodyLimitResponse(error, + "Decompressed request body exceeds 1024 bytes [measurement=declared_wire; bytes=1025]"); + expect(stats).toEqual({ pulls: 0, cancelled: 1, sentinelPulled: false }); + }); + test("rejects and cancels declared over-cap bodies before reading", async () => { const { body, stats } = trackedBodyStream([PAYLOAD_BYTES]); const req = new Request("http://localhost/v1/responses", { @@ -142,7 +236,10 @@ describe("readJsonRequestBody", () => { body, }); - await expect(readJsonRequestBody(req)).rejects.toBeInstanceOf(DecompressedBodyTooLargeError); + const error = await captureBodyTooLarge(() => readJsonRequestBody(req)); + expect(error).toMatchObject({ bytes: 268435457, limit: 268435456, measurement: "declared_wire" }); + await expectBodyLimitResponse(error, + "Decompressed request body exceeds 268435456 bytes [measurement=declared_wire; bytes=268435457]"); expect(stats.pulls).toBe(0); expect(stats.cancelled).toBe(1); }); @@ -160,8 +257,10 @@ describe("readJsonRequestBody", () => { ], { sentinel }); const req = new Request("http://localhost/api/optional", { method: "POST", headers, body }); - await expect(readBoundedJsonRequestBody(req, 5, undefined, { emptyBodyFallback: {} })) - .rejects.toBeInstanceOf(DecompressedBodyTooLargeError); + const error = await captureBodyTooLarge(() => readBoundedJsonRequestBody(req, 5, undefined, { emptyBodyFallback: {} })); + expect(error).toMatchObject({ bytes: 6, limit: 5, measurement: "observed_wire_lower_bound" }); + await expectBodyLimitResponse(error, + "Decompressed request body exceeds 5 bytes [measurement=observed_wire_lower_bound; bytes=6]"); expect(stats).toEqual({ pulls: 2, cancelled: 1, sentinelPulled: false }); }); } @@ -252,8 +351,10 @@ describe("readJsonRequestBody", () => { body: oversizedWireBody, }); expect(req.headers.get("content-length")).toBeNull(); - await expect(readBoundedJsonRequestBody(req, 1024, undefined, { emptyBodyFallback: {} })) - .rejects.toBeInstanceOf(DecompressedBodyTooLargeError); + const error = await captureBodyTooLarge(() => readBoundedJsonRequestBody(req, 1024, undefined, { emptyBodyFallback: {} })); + expect(error).toMatchObject({ bytes: oversizedWireBody.byteLength, limit: 1024, measurement: "observed_wire_lower_bound" }); + await expectBodyLimitResponse(error, + `Decompressed request body exceeds 1024 bytes [measurement=observed_wire_lower_bound; bytes=${oversizedWireBody.byteLength}]`); }); test("parses an uncompressed request without touching arrayBuffer path", async () => {