From 49554a1221310677f04f84fbe258611caf5cbab5 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 10:07:11 +0900 Subject: [PATCH 01/60] docs(devlog): proxy upstream catch-up roadmap (CLIProxyAPI, cc-switch, sub2api, magpie) (#9106) Research 001-008, gap matrix 009 (60 gaps: 34 adopted, 9 deferred, 16 rejected, 1 already present), phase docs 010-090, offline index.html, and check.mjs/check-selftest.mjs gates. Docs only. --- .../261123_proxy_upstream_catchup/000_plan.md | 111 ++++++++ .../001_cliproxyapi_wire.md | 174 ++++++++++++ .../002_cliproxyapi_ops.md | 177 ++++++++++++ .../003_ccswitch.md | 190 +++++++++++++ .../004_sub2api_gateway.md | 121 ++++++++ .../005_sub2api_platform.md | 135 +++++++++ .../006_magpie_gateway.md | 157 +++++++++++ .../007_magpie_clients.md | 265 ++++++++++++++++++ .../008_opencodex_baseline.md | 213 ++++++++++++++ .../009_gap_matrix.md | 166 +++++++++++ .../010_client_connection.md | 115 ++++++++ .../020_migration_onboarding.md | 112 ++++++++ .../030_client_coverage.md | 91 ++++++ .../040_pool_scheduling_egress.md | 107 +++++++ .../050_session_cache_continuity.md | 83 ++++++ .../060_wire_fidelity.md | 88 ++++++ .../070_shared_proxy_governance.md | 116 ++++++++ .../080_observability.md | 80 ++++++ .../090_request_policy.md | 77 +++++ .../build_index.mjs | 77 +++++ .../check-selftest.mjs | 46 +++ .../261123_proxy_upstream_catchup/check.mjs | 162 +++++++++++ .../261123_proxy_upstream_catchup/index.html | 2 + 23 files changed, 2865 insertions(+) create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/000_plan.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/001_cliproxyapi_wire.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/002_cliproxyapi_ops.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/003_ccswitch.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/004_sub2api_gateway.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/005_sub2api_platform.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/006_magpie_gateway.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/007_magpie_clients.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/008_opencodex_baseline.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/009_gap_matrix.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/010_client_connection.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/020_migration_onboarding.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/030_client_coverage.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/040_pool_scheduling_egress.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/050_session_cache_continuity.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/060_wire_fidelity.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/070_shared_proxy_governance.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/080_observability.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/090_request_policy.md create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/build_index.mjs create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/check-selftest.mjs create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/check.mjs create mode 100644 devlog/_plan/261123_proxy_upstream_catchup/index.html diff --git a/devlog/_plan/261123_proxy_upstream_catchup/000_plan.md b/devlog/_plan/261123_proxy_upstream_catchup/000_plan.md new file mode 100644 index 00000000000..347bd96ce7f --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/000_plan.md @@ -0,0 +1,111 @@ +# 000 — Proxy upstream catch-up: plan and map of content + +Unit: `devlog/_plan/261123_proxy_upstream_catchup/` · opened 2026-11-23 · class C3 (docs-only roadmap; implementation runs in later units) + +## Objective + +OpenCodex (`ocx`) is a local provider proxy for Codex and Claude Code. Four neighbouring open-source projects cover overlapping ground and move fast. This unit records what OpenCodex lacks relative to them, with source evidence on both sides, and turns the adoptable gaps into a dependency-ordered catch-up roadmap (decade docs `010`, `020`, …) plus a standalone HTML overview (`index.html`). + +The unit writes documentation only. No change lands in `src/`, `gui/`, `tests/`, `docs-site/` or `structure/` here; each phase doc is the PRD for a later implementation unit. + +## Pinned heads + +| Project | Role for OpenCodex | Head analysed | Local copy (gitignored) | +|---|---|---|---| +| OpenCodex | subject | `origin/dev` `9e0e298ef9` (2026-11-21) | `.tmp/chase/opencodex-dev/` (`git archive` export) | +| router-for-me/CLIProxyAPI (Go) | closest peer: multi-provider OAuth proxy exposing OpenAI/Claude/Gemini/Codex wire | `0d251842d2` (2026-11-23) | `.tmp/chase/CLIProxyAPI/` | +| farion1231/cc-switch (Rust/Tauri + React) | desktop config switcher for Claude Code, Codex, Gemini CLI, OpenCode; local proxy + failover | `f19a9d4f4f` (2026-11-23) | `.tmp/chase/cc-switch/` | +| Wei-Shaw/sub2api (Go + Vue) | subscription-to-API relay: shared account pools, scheduling, keys, billing, admin | `328db26f45` (2026-11-20) | `.tmp/chase/sub2api/` | +| yetone/magpie (Go/Wails + Bun plugin host) | most direct competitor: single-binary agent config switcher (60+ agents), subscription bridging, plugin ecosystem, translating gateway, deep-link import | `3377e77eb6` (2026-11-23) | `.tmp/chase/magpie/` | + +Earlier CLIProxyAPI notes live in [`devlog/_chase/20_cli-proxy-api.md`](../../_chase/20_cli-proxy-api.md), analysed at `00114be` (2026-06-29). Doc 001/002 reconcile those rows instead of repeating them. A 2026-10-17 magpie teardown is recorded in Aside memory (`~/.aside/u/0/memory/projects/opencodex.md`, "Magpie competitive teardown"); 006/007 re-verify it against the current head instead of quoting it. + +## Method + +1. Eight research lanes run in parallel on `gpt-6.2-sol` (GOAT `task.create`, codex provider, `reasoningEffort: xhigh`). Each lane owns exactly one research doc and writes nothing else. +2. Every claim cites `path:line` in the reference clone and in `.tmp/chase/opencodex-dev/`. Confirmation has two routes: parity/partial/ocx-ahead traces both implementations (entry point, implementation, gate); a gap traces the reference side and gives an OpenCodex absence receipt. Weaker rows are OBSERVED-partial or INFERRED with status `unknown`. Statuses: ocx-ahead, parity, partial, gap, unknown, n/a. Rows carry a shared `CAP-` tag; the coordinator scores each tag once in 009 against the baseline lane's OpenCodex evidence. +3. Every lane also researches recent practice on its axis through Aside (`$aside-jun`), public read-only pages only: release notes and changelogs since about 2026-09-20, issues, and community reports (GitHub discussions, Linux.do, X, blogs). Those rows carry publication date, release/commit, URL and access date, stay separate from source-read rows, and never change a confirmed status when they postdate the pinned head. +4. "OpenCodex lacks X" requires an absence receipt: pinned revision, exact command, roots, exit status, and the closest equivalent OpenCodex path inspected. +5. The coordinator merges the lane findings into `009_gap_matrix.md` (matrix, ranking, dependency graph, non-goals), then writes the decade phase docs, `index.html` and `check.mjs` (all in this unit). +6. Unpublished security weaknesses in any project stay out of every lane doc, final message, Aside query, the matrix and the HTML. Each lane may write one gitignored scratch note at `.tmp/chase/security-scratch/.md` and its doc says only that a note exists (AGENTS.md "Security working notes"). + +## Map of content + +| Doc | Content | Owner | +|---|---|---| +| `000_plan.md` | this plan, heads, method, MOC | coordinator | +| [`001_cliproxyapi_wire.md`](001_cliproxyapi_wire.md) | CLIProxyAPI translators, executors, wire protocols, model catalog, streaming/WS | Sol lane L1 | +| [`002_cliproxyapi_ops.md`](002_cliproxyapi_ops.md) | CLIProxyAPI auth/credential pool, routing, quota/cooldown, management API, config hot reload, SDK, clustering | Sol lane L2 | +| [`003_ccswitch.md`](003_ccswitch.md) | cc-switch provider switching, client config writers, MCP/skills/prompts, local proxy/failover, usage, deep links | Sol lane L3 | +| [`004_sub2api_gateway.md`](004_sub2api_gateway.md) | sub2api gateway, account scheduling, sticky sessions, rate limits, upstream protocol handling | Sol lane L4 | +| [`005_sub2api_platform.md`](005_sub2api_platform.md) | sub2api users, API keys, groups, billing, admin UI, usage stats, ops monitoring | Sol lane L5 | +| [`006_magpie_gateway.md`](006_magpie_gateway.md) | magpie gateway: translation, routing modes, cache affinity, middleware, subscription bridging, plugin host | Sol lane L6 | +| [`007_magpie_clients.md`](007_magpie_clients.md) | magpie agent config switching, migration/import, deep links, sync, LAN sharing, distribution/update, UX surfaces | Sol lane L7 | +| [`008_opencodex_baseline.md`](008_opencodex_baseline.md) | OpenCodex capability inventory at `9e0e298ef9` on the same axes | Sol lane L8 | +| [`009_gap_matrix.md`](009_gap_matrix.md) | merged gap matrix (id, source, value, effort, phase or rejection), phasing rules, dependency graph, non-goals | coordinator | +| `010` … `090` | one decade doc per catch-up phase | coordinator | +| [`index.html`](index.html) | standalone overview: matrix, phase timeline, links (generated) | coordinator | +| [`build_index.mjs`](build_index.mjs) | regenerates `index.html` from 009 and the phase docs: `node build_index.mjs` | coordinator | +| [`check.mjs`](check.mjs) | mechanical gate: file presence, gap-id coverage, declared dependencies, MODIFY anchors against the pinned export, offline HTML links: `node check.mjs` | coordinator | +| [`check-selftest.mjs`](check-selftest.mjs) | ten regression cases proving `check.mjs` fails on each defect class (incl. missing before/after sketch): `node check-selftest.mjs` | coordinator | + +## Work phases (goalplan `opencodex-upstream-proxy-catch-up-roadmap-docs-o`) + +- **wp1** research 000–009. Done when 001–008 exist with two-sided citations, dated Aside rows (or a documented Aside blocker in NOT RUN) and NOT RUN lists, and 009 synthesizes them. +- **wp2** roadmap. Done when 010…090 exist in dependency order, every adopted gap id appears in exactly one phase doc, `index.html` renders offline with resolving links, a Sol reviewer has audited the roadmap, and `check.mjs` and `check-selftest.mjs` exit 0. + +## Constraints carried into every phase doc + +- Lab boundary: `src/router.ts`, `src/server/lifecycle.ts`, `src/server/responses/core.ts` must not reach `src/lab/` (`tests/lab/core-lab-boundary.test.ts`). +- File-size ratchet: `tests/fixtures/file-size-baseline.json` caps only move down; new code goes into sibling files. +- New tests need entries in `scripts/test-layout/layout.json` (or shard) and a `tests/fixtures/test-layout-expected*.json` shard. +- Owned source areas update their `structure/` doc; `bun run structure:check` gates it. +- Actions that spend the user's identity, credits or reputation stay consent-gated (AGENTS_INSTALL.md). + +## NOT RUN + +No reference project was built or executed; comparisons are source reads plus dated web reports gathered through Aside. OpenCodex was read from an `origin/dev` export, not run. + + +## wp2 계획 — 단계 문서 형식 (2026-11-23) + +wp1 결론: gap matrix를 9개 단계(010–090)로 배치했다. 감사 뒤 60건 중 34건 채택, 보류 9, 비채택 16, 이미 있음 1 ([009](009_gap_matrix.md)). 클라이언트 트랙(010→020/030)과 런타임 트랙(040→050/070→080, 060→090)은 독립이다. + +각 단계 문서 `0X0_.md`는 아래 순서의 섹션을 모두 가진다. `check.mjs`가 섹션 이름과 `**Gaps:**` 줄을 검사한다. + +- 머리 줄: `**Gaps:**` (matrix id), `**Depends on:**`, `**Size:**` +- `## Goal` — 단계가 끝났을 때 사용자가 보는 결과 +- `## Why` — gap id별 근거 (레인 문서 링크) +- `## Changes` — OpenCodex 경로별 NEW/MODIFY, 현재 코드 위치(`path:line`, 고정 head `9e0e298ef9`)와 before/after 스케치 +- `## Dependencies` — 선행 단계와 그 이유 +- `## Acceptance` — 관찰 가능한 완료 조건 +- `## Verification` — focused `bun test` 파일, `bun run typecheck`, `bun run structure:check`, 필요 시 `ci:full` 사유 +- `## Risks` — file-size ratchet(캡 파일·2000줄 신규 한도), Lab 경계, consent, privacy +- `## Non-goals` + +각 단계를 구현하는 사람은 시작할 때 이 문서의 경로·줄 번호를 현재 `dev`에 대해 다시 확인한다. 이 단위의 줄 번호는 `9e0e298ef9` 기준이다. + +산출물: `010`–`090` 문서, `build_index.mjs`로 만든 `index.html`, 검증 스크립트 `check.mjs`. + +## 감사 기록 (wp2, 2026-11-23) + +독립 리뷰어: `gpt-6.2-sol` (reasoning high) 서브에이전트 하나가 같은 대화로 여덟 라운드를 진행했다(r1–r6 wp2, r7–r8 wp3). 매 라운드 지적은 반영하거나 근거를 들어 범위를 조정했고, 마지막 라운드에서 열린 BLOCKER·SHOULD가 없었다. + +| 라운드 | 판정 | 핵심 지적과 처리 | +|---|---|---| +| r1 (연구·matrix) | FAIL | G-002는 기존 first-party 토글과 중복 → preview·home별 상태로 축소. G-031은 이미 있음 → CLOSED. G-025 공정성 단위 미정 → 발급 키 단위, 키 간 집계는 G-057 보류. 060 → 040 의존 추가. G-040/G-058 분리, G-037/G-038 출처 정정, G-015 기존 priority 위로 축소, 응답 hook G-059 보류 | +| r2 (단계 문서) | FAIL | 020 Hub 초대와 SSH Link 흐름 혼동, 070 예산이 과거 사용량 읽기, 090 filter가 outbound body 생성 전 → 각각 분리·예약·send 지점으로 수정. MODIFY 행 근거 의무화, 010 home 선택 규칙, 030 다중 파일 복구, 050 신원 출처, 060 리소스 핸들러, 수치 정정 | +| r3 | FAIL | 090 passthrough 재생성, 070 ledger 차원, 050 신원=권한 혼동 → 재생성 지점 추가, key-window 차원 신설, JEV `callerNamespace` 사용. G-007 축소와 G-060 보류, 030 ownership·journal 복구, 060 계정 binding | +| r4 | FAIL | Codex credential replay 재생성, standalone Realtime·dictation WS 우회, 사후 보고 send → 지점 추가, `serve-options.ts` admission, retry 차단 규칙. 060 연쇄 POST, 검증기 회귀 두 건 → `check-selftest.mjs` | +| r5 | FAIL | seed 예약 경로 누락, native 리소스 조작의 범위 재확인 → 반영 | +| r6 | **PASS** | 새 지적 없음. `node check.mjs`(근거 133개 해석)와 `node check-selftest.mjs`(9개 사례) 모두 exit 0 | +| r7 (wp3: before/after 스케치) | FAIL | 목표의 "before/after 스케치" 요구를 wp3로 추가해 9개 문서에 넣고 `check.mjs`로 강제함. 070 스케치가 예약·정산 계약을 깨뜨림 → lease attach로 수정. 010 인용 누락·중복 클릭, 020 import 계약(Antigravity 리터럴·Cockpit 파싱)과 실제 저장소, 030 `EXPORT_CLIENTS`, 040 lease 키·egress 필드, 050 override 경로 → 반영 | +| r8 | NEAR-PASS | 010 preview 실패 시 잠금 해제(기존 finally 사용), 070 거절 경로·async admission·spend tracker 정산 → 반영 | + +## 결과와 다음 단계 + +- 연구: 001–008 (레인 8개, 인용 2,402개 전부 해석), 종합 009 (gap 60건: 채택 34, 보류 9, 비채택 16, 이미 있음 1). +- 로드맵: 010–090 단계 문서(각각 고정 코드를 인용한 before/after 스케치 포함), `index.html`(`node build_index.mjs`로 재생성; headless Chrome으로 오프라인 렌더 확인), 검증 `node check.mjs`와 `node check-selftest.mjs`. +- gap 상태 값: `0X0`(채택), `DEFER`, `REJECT`, `CLOSED`(고정 head의 OpenCodex에 이미 있음). +- 다음 구현은 두 트랙으로 나눠 시작할 수 있다: 클라이언트 트랙 010 → 020/030, 런타임 트랙 040 → 050/060/070 → 080/090. 각 단계는 새 구현 단위를 열 때 이 문서의 경로와 줄 번호를 현재 `dev`에서 다시 확인한다. +- 이 단위는 코드와 테스트를 바꾸지 않았다. 커밋·push·PR도 만들지 않았다. diff --git a/devlog/_plan/261123_proxy_upstream_catchup/001_cliproxyapi_wire.md b/devlog/_plan/261123_proxy_upstream_catchup/001_cliproxyapi_wire.md new file mode 100644 index 00000000000..9605fdcf1cc --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/001_cliproxyapi_wire.md @@ -0,0 +1,174 @@ +# 001 — CLIProxyAPI wire · L1 + +비교 기준은 CLIProxyAPI `0d251842d2539194ebd55ef0cdcf9c08f9c4908a`와 OpenCodex `origin/dev@9e0e298ef9`의 지정 export다. `cpa:`, `ocx:`, `mgp:` 인용은 각 고정 소스 루트에 상대적이다. 상태는 행에 적은 동작 단위에 적용한다. HTTP/WS 방향, 모델, 설정에 따라 같은 표면의 상태가 달라진다. + +## 요약 + +1. Codex와 Claude Code의 주 경로는 양쪽에 있다. 다운스트림 Responses WS ↔ 내부 스트림, Claude Messages의 native/routed SSE, compact와 모델 목록은 기반 기능으로 다시 개발할 필요가 없다. +2. Antigravity의 기존 replay 우선순위는 범위를 좁힌다. OpenCodex에 세션별 다중 서명, 재시작을 위한 snapshot, 오류 시 제거가 있다. 비교할 차이는 CPA의 이전 문맥과 part 위치 대조, native call 복원, snapshot 조건부 갱신이다. +3. xAI의 과거 forward-only 판정은 닫혔다. OpenCodex는 Grok 모델별 Responses 선택과 replay 정규화를 제공한다. CPA의 세션별 completion 보강과 xAI upstream WS는 별도 차이다. +4. 첨부 단독 턴의 손실을 전송 전에 드러내는 동작은 두 클라이언트에서 직접 체감된다. 공급자별 표현 가능성에 맞춰 기존 호환 가드를 점검할 가치가 있다. +5. Gemini API 클라이언트는 이미 OpenCodex에 연결된다. CPA와의 차이는 Gemini Interactions의 공급자 네이티브 전송이다. +6. 소규모 공유 프록시에서 replay를 확장하려면 호출자·대상·세션 소유권, 바이트 예산과 종료 상태를 함께 유지해야 한다. 양쪽의 모델 목록은 실제 대상의 모델 및 wire 능력을 투영한다. +7. Kiro 전용 wire는 OpenCodex에 있다. Claude CCH, 독립 TTS, legacy Completions의 표면 차이는 아래 후보에서 제품 채택 가치와 함께 기록했다. + +## 표면 맵 + +### CPA ingress + +| 등록 표면 | 등록 및 사용 조건 | +|---|---| +| `GET /v1/models`, `GET /v1/models/*model` | `unifiedModelsHandler`, Grok UA, Codex `client_version`, Home 여부, Claude 요청 표지에 따라 목록/상세를 투영한다. `cpa:internal/api/server_routes.go:69`, `cpa:internal/api/server_routes.go:652` | +| `POST /v1/chat/completions`, `POST /v1/completions` | OpenAI 핸들러다. legacy는 Chat으로 변환한다. `cpa:internal/api/server_routes.go:77`, `cpa:sdk/api/handlers/openai/openai_handlers.go:169` | +| `GET /v1/responses` (WS), `POST /v1/responses`, `POST /v1/responses/compact`, `POST /v1/alpha/search` | `/backend-api/codex` 아래에도 같은 네 경로가 있다. `/v1`과 direct group 모두 access middleware를 거친다. `cpa:internal/api/server_routes.go:69`, `cpa:internal/api/server_routes.go:90`, `cpa:internal/api/server_routes.go:129` | +| `POST /v1/messages`, `POST /v1/messages/count_tokens` | Claude Code ingress. query와 별개로 등록하며 body `stream`에 따라 JSON/SSE를 고른다. `cpa:internal/api/server_routes.go:88`, `cpa:sdk/api/handlers/claude/code_handlers.go:68`, `cpa:sdk/api/handlers/claude/code_handlers.go:106` | +| `GET /v1beta/models`, `GET /v1beta/models/*action`, `POST /v1beta/models/*action`, `POST /v1beta/interactions` | Gemini 목록·상세, `generateContent`·`streamGenerateContent`·`countTokens`, Interactions create. `cpa:internal/api/server_routes.go:149`, `cpa:sdk/api/handlers/gemini/gemini_handlers.go:130`, `cpa:sdk/api/handlers/gemini/interactions_handlers.go:94` | +| `POST /v1/images/generations`, `POST /v1/images/edits` | 이미지 모델 지원과 `disable-image-generation` 정책을 핸들러에서 적용한다. `cpa:internal/api/server_routes.go:79`, `cpa:sdk/api/handlers/openai/openai_images_handlers.go:318`, `cpa:sdk/api/handlers/openai/openai_images_handlers.go:774`, `cpa:sdk/api/handlers/openai/openai_images_handlers.go:881` | +| `POST /v1/videos`, `POST /v1/videos/{generations,edits,extensions}`, `GET /v1/videos/:request_id` | xAI video. 별도의 `/openai/v1/videos` POST와 `/:video_id`, `/:video_id/content` GET도 있다. `cpa:internal/api/server_routes.go:81`, `cpa:internal/api/server_routes.go:120` | +| `POST /v1/audio/speech`, `POST /v1/tts` | xAI TTS로 합류하는 OpenAI/xAI 입력 모양. `cpa:internal/api/server_routes.go:86`, `cpa:sdk/api/handlers/openai/openai_speech_handlers.go:44` | +| `POST /v1/live`, `GET /v1/live/:call_id`, `GET/POST /v1/realtime` | Codex Live 및 Realtime WS/HTTP. `/v1/realtime` 아래 POST `calls`, `client_secrets`, `sessions`, `transcription_sessions`, `translations/client_secrets`, GET/POST `translations`, GET `calls/:call_id`, POST `calls/:call_id/{hangup,accept,reject,refer}`도 등록한다. `cpa:internal/api/server_routes.go:94`, `cpa:internal/api/server_routes.go:103` | +| `GET /v1/tunnel` 및 POST/PUT/PATCH/DELETE/HEAD/TRACE/CONNECT | WebSocket tunnel 핸들러. `cpa:internal/api/server_routes.go:98` | +| `GET /muse-code/{models,config}`, `POST /muse-code/{search,browser_open}` | Muse Code client 전용 ingress. `cpa:internal/api/server_routes.go:139` | + +### CPA 내장 translator 등록 30쌍 + +방향은 **다운스트림 request → upstream wire**다. 응답 변환은 같은 등록의 역방향으로 stream/non-stream을 제공한다. `E`는 별도 request envelope 등록, `T`는 짝에 등록된 TokenCount 변환이다. binary 및 SDK builtin의 blank import가 다음 등록을 활성화한다. registry는 쌍별 transform을 찾고, 부재 시 fallback 또는 plugin hook으로 넘어간다. 아래 목록은 내장 init의 등록을 세었으며 executor 내부의 native passthrough나 plugin 런타임 등록은 별도다. `cpa:cmd/server/main.go:35`, `cpa:sdk/translator/builtin/builtin.go:7`, `cpa:internal/translator/init.go:3`, `cpa:sdk/translator/registry.go:50`, `cpa:sdk/translator/registry.go:135`, `cpa:sdk/translator/registry.go:285` + +| 타깃 | 등록된 소스 및 등록 위치 | +|---|---| +| `codex` (5) | `claude` E/T → `cpa:internal/translator/codex/claude/init.go:13`, `gemini` T → `cpa:internal/translator/codex/gemini/init.go:10`, `interactions` → `cpa:internal/translator/codex/interactions/init.go:10`, `openai` → `cpa:internal/translator/codex/openai/chat-completions/init.go:10`, `openai-response` → `cpa:internal/translator/codex/openai/responses/init.go:10` | +| `claude` (4) | `gemini` T → `cpa:internal/translator/claude/gemini/init.go:10`, `interactions` → `cpa:internal/translator/claude/interactions/init.go:10`, `openai` → `cpa:internal/translator/claude/openai/chat-completions/init.go:10`, `openai-response` E → `cpa:internal/translator/claude/openai/responses/init.go:11` | +| `gemini` (5) | `claude` T → `cpa:internal/translator/gemini/claude/init.go:10`, `gemini` T → `cpa:internal/translator/gemini/gemini/init.go:12`, `interactions` → `cpa:internal/translator/gemini/interactions/init.go:19`, `openai` → `cpa:internal/translator/gemini/openai/chat-completions/init.go:10`, `openai-response` → `cpa:internal/translator/gemini/openai/responses/init.go:10` | +| `interactions` (5) | `claude` → `cpa:internal/translator/interactions/claude/init.go:10`, `gemini` → `cpa:internal/translator/gemini/interactions/init.go:28`, `interactions` → `cpa:internal/translator/gemini/interactions/init.go:10`, `openai` → `cpa:internal/translator/openai/interactions/chat-completions/init.go:10`, `openai-response` E → `cpa:internal/translator/openai/interactions/responses/init.go:19` | +| `openai` (5) | `claude` E/T → `cpa:internal/translator/openai/claude/init.go:14`, `gemini` T → `cpa:internal/translator/openai/gemini/init.go:10`, `interactions` → `cpa:internal/translator/openai/interactions/chat-completions/init.go:19`, `openai` → `cpa:internal/translator/openai/openai/chat-completions/init.go:10`, `openai-response` E → `cpa:internal/translator/openai/openai/responses/init.go:14` | +| `openai-response` (1) | `interactions` → `cpa:internal/translator/openai/interactions/responses/init.go:28` | +| `antigravity` (5) | `claude` E/T → `cpa:internal/translator/antigravity/claude/init.go:13`, `gemini` T → `cpa:internal/translator/antigravity/gemini/init.go:10`, `interactions` → `cpa:internal/translator/antigravity/interactions/init.go:10`, `openai` E → `cpa:internal/translator/antigravity/openai/chat-completions/init.go:11`, `openai-response` E → `cpa:internal/translator/antigravity/openai/responses/init.go:11` | + +### CPA executor 및 catalog 구성 + +표의 등록은 서비스의 provider 선택에 따른다. 기존 executor 재사용, disabled 항목, plugin이 소유하는 executor, generic compat가 선택에 관여한다. credential 선택 로직은 L2 대상이다. `cpa:sdk/cliproxy/service_executors.go:339`, `cpa:sdk/cliproxy/service_executors.go:357`, `cpa:sdk/cliproxy/service_executors.go:420` + +| Provider → 등록 구현 | wire | +|---|---| +| Codex → `CodexAutoExecutor` `cpa:sdk/cliproxy/service_executors.go:344` | Responses HTTP/SSE, 다운스트림 WS와 credential 설정이 허용하면 upstream WS, compact와 count. `cpa:internal/runtime/executor/codex_websockets_executor.go:79` | +| Claude → `ClaudeExecutor` `cpa:sdk/cliproxy/service_executors.go:387` | Messages HTTP/SSE, token count, 호환 모델의 thinking replay, 조건부 CCH. `cpa:internal/runtime/executor/claude_executor_stream.go:32`, `cpa:internal/runtime/executor/claude_executor_tokens.go:22` | +| Gemini / Gemini Interactions → `GeminiExecutor`의 두 identifier `cpa:sdk/cliproxy/service_executors.go:374` | Generative Language generate/stream/count 또는 Interactions HTTP/SSE. `cpa:internal/runtime/executor/gemini_executor.go:57`, `cpa:internal/runtime/executor/gemini_executor.go:728` | +| Vertex → `GeminiVertexExecutor` `cpa:sdk/cliproxy/service_executors.go:378` | Vertex REST와 native 모델 payload. `cpa:internal/runtime/executor/gemini_vertex_executor.go:239` | +| AI Studio → `AIStudioExecutor` `cpa:sdk/cliproxy/service_executors.go:380` | `wsGateway`가 있을 때 relay를 등록한다. `cpa:internal/runtime/executor/aistudio_executor.go:228` | +| Antigravity → `AntigravityExecutor` `cpa:sdk/cliproxy/service_executors.go:385` | Google형 request envelope, 모델 계열별 Claude/Gemini 처리, replay, Interactions state. `cpa:internal/runtime/executor/antigravity_executor_stream.go:25`, `cpa:internal/runtime/executor/helps/antigravity_interactions_state.go:1` | +| Kimi 계열 4 spelling → `KimiExecutor` `cpa:sdk/cliproxy/service_executors.go:395` | ingress에 맞춰 Messages·Responses·Chat. Messages thinking cache와 Responses compact. `cpa:internal/runtime/executor/kimi_executor.go:60`, `cpa:internal/runtime/executor/kimi_executor.go:246` | +| xAI → `XAIAutoExecutor` `cpa:sdk/cliproxy/service_executors.go:397` | Responses HTTP/SSE 및 조건부 WS, compact, image/video/speech. `cpa:internal/runtime/executor/xai_websockets_executor.go:2082`, `cpa:internal/runtime/executor/xai_executor_execute.go:20` | +| Copilot / Devin / Meta → 각 전용 executor `cpa:sdk/cliproxy/service_executors.go:408` | Copilot 다중 wire/replay, Devin wire/compact, Meta request/stream 보조 처리. `cpa:internal/runtime/executor/copilot_executor.go:32`, `cpa:internal/runtime/executor/devin_executor.go:238`, `cpa:internal/runtime/executor/meta_executor.go:58` | +| OpenAI compat / plugin 후보 `cpa:sdk/cliproxy/service_executors.go:363`, `cpa:sdk/cliproxy/service_executors.go:420` | generic Chat/compat executor와 구성·plugin 등록에 따른 변형. `cpa:internal/runtime/executor/openai_compat_executor.go:103` | +| 모델 목록 재료 | `models.json`의 내장 섹션은 copilot, claude, gemini, vertex, gemini-cli, aistudio, codex-free/team/plus/pro, kimi, antigravity, xai, meta. Codex client template과 Devin은 개별 JSON 카탈로그다. 활성 provider 모델 등록과 모델 목록 투영은 `cpa:sdk/cliproxy/service_models.go:33`, `cpa:sdk/cliproxy/service_models.go:94`, `cpa:sdk/cliproxy/service_models.go:331`, `cpa:internal/registry/model_definitions.go:1`에 있다. | + +## 기능 인벤토리 + +| CAP tag | 기능 | CPA entry · 구현 · gate | OpenCodex entry · 구현 · gate 또는 부재 근거 | 상태 | 증거 | +|---|---|---|---|---|---| +| CAP-wire-responses-http | Codex Responses POST JSON/SSE | `cpa:internal/api/server_routes.go:91` → body `stream`으로 분기 `cpa:sdk/api/handlers/openai/openai_responses_handlers.go:997` → Codex Auto HTTP 및 응답 변환 `cpa:internal/runtime/executor/codex_websockets_executor.go:79`, `cpa:internal/runtime/executor/codex_executor_stream.go:351`. | `ocx:src/server/index/serve-options.ts:1411` → Responses pipeline에서 대상 adapter 및 passthrough 선택 `ocx:src/server/responses/core-pipeline.ts:93`, `ocx:src/server/responses/passthrough-dispatch.ts:1014`. surface는 fixed on `ocx:src/protocols/settings.ts:53`. | parity | OBSERVED | +| CAP-wire-responses-ws | Codex 다운스트림 WS 및 SSE bridge | `cpa:internal/api/server_routes.go:90` → `response.create/append`, synthetic prewarm, prev ID/full transcript 분기 `cpa:sdk/api/handlers/openai/openai_responses_websocket.go:453`, `cpa:sdk/api/handlers/openai/openai_responses_websocket.go:977`, `cpa:sdk/api/handlers/openai/openai_responses_websocket_requests.go:85`. 요청은 stream으로 실행하며 WS 불가 대상은 HTTP executor를 사용한다. `cpa:sdk/api/handlers/openai/openai_responses_websocket.go:1031`, `cpa:sdk/api/handlers/openai/openai_responses_websocket.go:1093`, `cpa:internal/runtime/executor/codex_websockets_executor.go:92` | `ocx:src/server/index/serve-options.ts:562` → `response.create`, `generate:false` warmup, internal Responses → SSE를 WS로 펌핑 `ocx:src/server/index/websocket-handler.ts:266`, `ocx:src/server/index/websocket-handler.ts:297`, `ocx:src/server/index/websocket-handler.ts:385`, `ocx:src/server/ws-bridge.ts:305`. 기본 Responses surface에서 upgrade 조건을 만족할 때 동작한다. 공통 최신 Codex `response.create` 범위에서 parity다. | parity | OBSERVED | +| CAP-wire-codex-upstream-ws | Codex upstream WS → SSE 및 연결 재사용 | Codex Auto 등록 `cpa:sdk/cliproxy/service_executors.go:344`. Downstream WS와 credential `websockets` 조건으로 선택, 조건 불충족 시 HTTP 또는 명시적 replay-required. `cpa:internal/runtime/executor/codex_websockets_executor.go:92`, `cpa:internal/runtime/executor/codex_websockets_executor.go:147`. WS frame을 SSE로 인코딩하고 번역한다. `cpa:internal/runtime/executor/codex_websockets_errors.go:276`, `cpa:internal/runtime/executor/codex_websockets_stream.go:559`, `cpa:internal/runtime/executor/codex_websockets_stream.go:857`. | Responses POST/WS가 공유하는 `providerFetch` → canonical Codex URL의 POST `stream:true`는 런타임 및 프록시 조건 충족 시 기본 WS, `upstreamWebsocket:false`로 해제. OpenAI public URL은 explicit true. HTTP fallback과 크기 경계가 있다. `ocx:src/server/responses/fetch-helpers.ts:446`, `ocx:src/server/responses/fetch-helpers.ts:483`, `ocx:src/server/responses/ws-upstream.ts:127`, `ocx:src/server/responses/ws-upstream.ts:263`. Cross-turn reuse와 incremental은 기본 off, incremental은 reuse를 포함. `ocx:src/config/codex-ws-incremental-setting.ts:9`, `ocx:src/config/codex-ws-incremental-setting.ts:30`. | parity | OBSERVED | +| CAP-wire-codex-http-to-ws | HTTP ingress에서 canonical Codex WS 사용 | `cpa:internal/api/server_routes.go:91`의 HTTP 경로는 downstream WS 표지가 없으므로 Codex Auto HTTP 분기 적용. `cpa:internal/runtime/executor/codex_websockets_executor.go:92`. #7088의 opt-in 요청은 아래 최신 사례에 기록했다. | HTTP POST도 `ocx:src/server/index/serve-options.ts:1411` → `ocx:src/server/responses/passthrough-dispatch.ts:1014` → `ocx:src/server/responses/ws-upstream.ts:127`의 outbound 조건을 쓴다. 이 조건은 HTTP/WS ingress보다 outbound URL·method·stream을 본다. | ocx-ahead | OBSERVED | +| CAP-wire-codex-direct-prefix | Codex direct Responses 및 compact alias | `/backend-api/codex` 그룹의 동일 Responses 핸들러, access gate. `cpa:internal/api/server_routes.go:129` | `codexCompatibleUrl`에서 `/backend-api/codex`를 `/v1`로 정규화한 후 ingress 검사와 동일 route 실행. `ocx:src/codex/context-compat.ts:83`, `ocx:src/server/index/serve-options.ts:284`, `ocx:src/server/index/serve-options.ts:1261`, `ocx:src/server/index/serve-options.ts:1411`. | parity | OBSERVED | +| CAP-wire-responses-compaction | 호환 모델의 remote compact trigger | Responses/WS ingress → Codex executor에서 `is-compat`와 trigger 검사, local summary/capsule 생성 및 후속 요청 expand. `cpa:internal/api/server_routes.go:90`, `cpa:internal/runtime/executor/codex_executor_execute.go:86`, `cpa:internal/runtime/executor/codex_executor_execute.go:396`, `cpa:internal/runtime/executor/codex_executor_execute.go:416`. | Responses ingest에서 trigger를 파싱하고, portable 또는 native trigger 미지원일 때 routed compaction으로 전환한다. `ocx:src/responses/parser.ts:274`, `ocx:src/server/responses/core-pipeline.ts:87`, `ocx:src/server/responses/core-pipeline.ts:104`, `ocx:src/responses/compaction.ts:92`. 각자의 capsule format을 사용한다. | parity | OBSERVED | +| CAP-wire-messages-sse | Claude Code native/routed Messages, JSON/SSE | `cpa:internal/api/server_routes.go:88` → `cpa:sdk/api/handlers/claude/code_handlers.go:68` → 스트림 첫 이벤트 전 HTTP 오류와 이후 SSE 실패 분기. Claude executor는 Claude 형식끼리 event forwarding, 다른 형식은 translator 호출. `cpa:sdk/api/handlers/claude/code_handlers.go:270`, `cpa:internal/runtime/executor/claude_executor_stream.go:405`, `cpa:internal/runtime/executor/claude_executor_stream.go:485`. | `ocx:src/server/index/serve-options.ts:1504` → native passthrough gate `ocx:src/server/claude-messages.ts:267`, managed branch `ocx:src/server/claude-messages.ts:1224`, routed Responses `ocx:src/server/claude-messages.ts:1316` → Anthropic event output 또는 JSON fold `ocx:src/claude/outbound.ts:650`, `ocx:src/claude/outbound.ts:1204`. 기본 surface는 `claudeCode.enabled !== false`를 따른다. `ocx:src/protocols/settings.ts:53`. | parity | OBSERVED | +| CAP-wire-count-tokens | Claude Code count endpoint | `cpa:internal/api/server_routes.go:89` → admitted model의 CountTokens 실행. 선택 executor 및 등록 TokenCount 변환에 따라 달라진다. `cpa:sdk/api/handlers/claude/code_handlers.go:106`, `cpa:sdk/api/handlers/claude/code_handlers.go:130`. | `ocx:src/server/index/serve-options.ts:1486` → native gate일 때 원래 endpoint로 전달. routed는 의도한 upstream projection을 로컬에서 추정하고 thread delta를 거절한다. `ocx:src/server/claude-messages.ts:1744`, `ocx:src/server/claude-messages.ts:1756`. 두 endpoint는 제공되며 tokenizer 정확도 계약은 다르다. | partial | OBSERVED | +| CAP-wire-claude-cch | Claude 서명과 billing header wire | Claude 등록 후 `/v1/messages?beta=true`; `claudeCCHSigningEnabled`에서 OAuth와 opt-in CLI profile API key 경로를 판단하고 최종 body에 적용. `cpa:sdk/cliproxy/service_executors.go:387`, `cpa:internal/runtime/executor/claude_executor_stream.go:35`, `cpa:internal/runtime/executor/claude_executor_execute.go:237`, `cpa:internal/runtime/executor/claude_executor_execute.go:267`, `cpa:internal/runtime/executor/claude_signing.go:299`. | Messages native와 routed adapter의 wire가 있다. Native eligibility는 모델·credential·alias 조건으로 제한하며, routed Anthropic adapter의 first-party 헤더 정책은 CCH 재서명을 제외한다. `ocx:src/server/index/serve-options.ts:1504`, `ocx:src/server/claude-messages.ts:267`, `ocx:src/adapters/anthropic.ts:649`. | partial | OBSERVED | +| CAP-wire-reasoning-budget | effort, budget, disabled/auto, summary | Codex/Claude 등록 → request translation 후 thinking 적용. 모델 메타데이터, suffix 및 source intent를 해석하고 level↔budget 변환·clamp·검증 후 provider별 wire 적용. `cpa:internal/runtime/executor/claude_executor_execute.go:88`, `cpa:internal/runtime/executor/claude_executor_execute.go:97`, `cpa:internal/thinking/apply.go:242`, `cpa:internal/thinking/validate.go:83`. | Claude/Responses ingress → inbound budget ladder와 model policy, Claude adaptive effort 또는 token budget 및 sampling 조정. `ocx:src/claude/inbound-model-options.ts:80`, `ocx:src/adapters/anthropic.ts:1126`, `ocx:src/adapters/anthropic.ts:1150`, `ocx:src/adapters/anthropic.ts:1208`. 공통 컨트롤은 제공되며 suffix, auto, 모델별 수치는 별도 동작이다. | partial | OBSERVED | +| CAP-wire-tool-schema | tool 선언·호출·결과 round trip | Responses→Claude 등록, target tool-search 지원 등 envelope 정보를 쓴다. 이름 역매핑, tool output와 cache hint, streamed tool input 및 실패를 번역한다. `cpa:internal/translator/claude/openai/responses/init.go:11`, `cpa:internal/translator/claude/openai/responses/claude_openai-responses_tool_names.go:29`, `cpa:internal/translator/claude/openai/responses/claude_openai-responses_request.go:625`, `cpa:internal/translator/claude/openai/responses/claude_openai-responses_response.go:555`. 역 client 방향에서는 Claude→Codex 등록 및 Responses output item→Claude blocks. `cpa:internal/translator/codex/claude/init.go:13`, `cpa:internal/translator/codex/claude/codex_claude_response.go:220`. | Messages/Responses 입구 → 모델의 wire와 adapter 선택, Responses function schema 및 tool output pairing, Claude adapter와 SSE blocks. xAI의 adjacency/paired 조건은 preset에서 선언. `ocx:src/server/claude-messages.ts:984`, `ocx:src/adapters/openai-responses/passthrough.ts:220`, `ocx:src/adapters/openai-responses/passthrough.ts:430`, `ocx:src/adapters/anthropic.ts:942`, `ocx:src/providers/registry/entries-core.ts:467`. 기본 function/tool-result 변환 기준. | parity | OBSERVED | +| CAP-wire-multimodal-input | 이미지/PDF 전달과 표현 불가 turn | Response→Claude envelope는 `input_image`/tool result를 변환하고 지원 불가 part 오류를 전달한다. `cpa:internal/translator/claude/openai/responses/init.go:22`, `cpa:internal/translator/claude/openai/responses/claude_openai-responses_request.go:442`, `cpa:internal/translator/claude/openai/responses/claude_openai-responses_request.go:1333`, `cpa:internal/translator/common/parts.go:26`. 변환 쌍의 구현에 따라 거절 또는 placeholder가 선택된다. `cpa:internal/translator/codex/claude/codex_claude_request.go:1412`. | Claude ingress는 file-backed image를 translated route에서 거절하고 URL/base64 이미지를 옮긴다. Base64 document는 `input_file`로 이어진다. `ocx:src/claude/inbound.ts:33`, `ocx:src/claude/inbound.ts:64`, `ocx:src/claude/inbound.ts:291`. 광범위한 representability 가드는 `protocols.unrepresentable:reject`를 쓰며 기본은 legacy다. `ocx:src/server/claude-messages.ts:798`, `ocx:src/server/claude-messages.ts:846`, `ocx:src/protocols/settings.ts:103`. | partial | OBSERVED | +| CAP-wire-images | 독립 image generation/edit ingress | 두 route → 요청 형태 및 model admission 후 Codex hosted, OpenAI-compatible 또는 xAI image dispatch. `disable-image-generation` 기본 false, all에서 route 응답 404. `cpa:internal/api/server_routes.go:79`, `cpa:sdk/api/handlers/openai/openai_images_handlers.go:318`, `cpa:sdk/api/handlers/openai/openai_images_handlers.go:774`, `cpa:sdk/api/handlers/openai/openai_images_handlers.go:881`, `cpa:config.example.yaml:1338`. | 같은 paths → image handler에서 `images.provider` 우선 적용, 미설정 시 xAI relay 및 적격 upstream 선택. `ocx:src/server/index/serve-options.ts:1299`, `ocx:src/server/index/serve-options.ts:1320`, `ocx:src/server/images.ts:708`. 개별 hosted/local tool 모드와 stream image 이벤트의 완전 일치는 미검증. | parity | OBSERVED | +| CAP-wire-stream-errors | SSE/WS 종료와 request error 투영 | Responses SSE framer가 프레임·누락 output·오류/terminal을 조정. Codex WS는 status, header, quota/context 등의 shape를 분류한다. Claude는 terminal이 부족하면 실패를 표면화한다. `cpa:sdk/api/handlers/openai/openai_responses_handlers.go:288`, `cpa:sdk/api/handlers/openai/openai_responses_handlers.go:662`, `cpa:internal/runtime/executor/codex_websockets_errors.go:61`, `cpa:internal/runtime/executor/codex_websockets_errors.go:89`, `cpa:internal/runtime/executor/claude_executor_stream.go:564`. 해당 stream 경로에서 활성. | Responses upgrade → WS bridge terminal 감지 및 envelope, Messages 브리지는 전송 시작 여부에 맞춰 오류 이벤트를 만들고 EOF 전에 terminal이 없으면 오류를 송출. `ocx:src/server/index/serve-options.ts:562`, `ocx:src/server/ws-bridge.ts:251`, `ocx:src/server/ws-bridge.ts:264`, `ocx:src/claude/outbound.ts:609`, `ocx:src/claude/outbound.ts:1053`. 클라이언트 오류 보존 기준이며 모든 vendor별 status 매핑은 비교 보류. | parity | OBSERVED | +| CAP-antigravity-replay | 세션별 thoughtSignature 및 part 복원 | Antigravity 등록과 Gemini/Flash/agent 모델 gate. stream/JSON에서 요청에 replay를 삽입, 완료를 관찰한다. canonical/body session 선택, prefix context hash·part occurrence·native call 복원, 완결 후 조건부 cache 교체 및 signature 400에서 스냅샷 조건부 무효화. Home이 활성일 때 KV를 쓴다. `cpa:internal/runtime/executor/antigravity_executor_stream.go:101`, `cpa:internal/runtime/executor/antigravity_executor_execute.go:101`, `cpa:internal/runtime/executor/antigravity_reasoning_replay.go:187`, `cpa:internal/runtime/executor/antigravity_reasoning_replay.go:898`, `cpa:internal/runtime/executor/antigravity_reasoning_replay.go:1978`, `cpa:internal/runtime/executor/antigravity_reasoning_replay.go:2232`, `cpa:internal/runtime/executor/antigravity_reasoning_replay.go:2831`, `cpa:internal/runtime/executor/antigravity_reasoning_replay.go:3643`, `cpa:internal/runtime/executor/antigravity_reasoning_replay.go:3707`, `cpa:internal/cache/antigravity_reasoning_replay_cache.go:189`. | `googleMode:cloud-code-assist`의 Antigravity 대상과 모델 gate → request-time session replay 및 응답 관찰. key는 model/session 해시와 tool name/canonical args이며 호출 occurrence별 서명을 저장한다. 캐시 TTL·상한·local snapshot 및 거절 시 session/call 제거가 있다. `ocx:src/adapters/google.ts:956`, `ocx:src/adapters/google.ts:1201`, `ocx:src/adapters/google.ts:1506`, `ocx:src/adapters/google.ts:1791`, `ocx:src/adapters/google-antigravity-replay.ts:37`, `ocx:src/adapters/google-antigravity-replay.ts:184`, `ocx:src/adapters/google-antigravity-replay.ts:344`, `ocx:src/adapters/google-antigravity-replay.ts:476`, `ocx:src/adapters/google-antigravity-replay.ts:633`, `ocx:src/adapters/google-antigravity-replay.ts:718`, `ocx:src/adapters/google-antigravity-replay.ts:822`. CPA의 문맥 prefix 및 native call 복원과는 matching 단위가 다르다. | partial | OBSERVED | +| CAP-antigravity-signature-validation | Claude 계열 opaque 서명/타입 검증 | Claude→Antigravity envelope와 executor. Claude와 Gemini signature family, carrier 인접 block 종류 조건을 함께 확인하며 cache/bypass 정책에 따라 검증한다. `cpa:internal/translator/antigravity/claude/init.go:23`, `cpa:internal/translator/antigravity/claude/signature_validation.go:67`, `cpa:internal/translator/antigravity/claude/signature_validation.go:196`, `cpa:internal/runtime/executor/antigravity_executor.go:910`. | Google adapter의 Antigravity Claude 모델 경로에서 signature sanitize, 일반 CCA call ID/opaque blob 검사와 발급처 replay scope 적용. `ocx:src/adapters/google.ts:544`, `ocx:src/adapters/google.ts:1204`, `ocx:src/adapters/google-antigravity-wire.ts:60`, `ocx:src/adapters/google-antigravity-wire.ts:218`, `ocx:src/server/responses/core-replay.ts:114`. 공통 synthetic/foreign 차단에 더해 CPA가 carrier 위치를 세분화한다. | partial | OBSERVED | +| CAP-xai-reasoning-replay | xAI Responses 및 opaque replay | xAI 등록 → Responses를 Codex format으로 변환하고 normalized tool/schema 및 reasoning을 준비한다. CPA replay는 Claude/Responses source, 유효 session/모델 범위 및 non-native continuation에 적용한다. 완료 output에서 reasoning·call을 저장하고 다음 요청에 중복 제거 후 삽입한다. `cpa:sdk/cliproxy/service_executors.go:397`, `cpa:internal/runtime/executor/xai_executor_request.go:93`, `cpa:internal/runtime/executor/xai_executor_request.go:192`, `cpa:internal/runtime/executor/xai_reasoning_replay.go:40`, `cpa:internal/runtime/executor/xai_reasoning_replay.go:67`, `cpa:internal/runtime/executor/xai_reasoning_replay.go:149`, `cpa:internal/runtime/executor/xai_reasoning_replay.go:293`, `cpa:internal/runtime/executor/xai_executor_stream.go:113`. | Responses 헤드에서 Grok 4.5/4.6/4.7 계열의 지정 OAuth/ingress에 모델별 Responses 기본값, 모델별 override를 적용. xAI는 부적합 `include`, null channel과 tool history를 정규화한다. 같은 목적지의 식별된 replay 자료는 보존하고 소유권 변화에는 strip. Chat용 plaintext reasoning도 preset으로 보존한다. `ocx:src/server/responses/request-prepare.ts:1488`, `ocx:src/server/adapter-resolve.ts:48`, `ocx:src/providers/registry/entries-core.ts:432`, `ocx:src/providers/registry/entries-core.ts:499`, `ocx:src/adapters/openai-responses/passthrough.ts:361`, `ocx:src/adapters/openai-responses/reasoning.ts:125`, `ocx:src/server/responses/core-replay.ts:114`. CPA의 xAI 전용 completion→후속 입력 보강 범위는 별도다. | partial | OBSERVED | +| CAP-wire-xai-upstream-ws | Native xAI upstream WS | GET Responses WS → handler가 다운스트림 WS context 부여 → xAI Auto의 `ExecuteStream`에서 credential `websockets` 허용 시 선택, flag가 없으면 해당 분기 off. 연결, response ID 양방향 매핑, transcript 및 compaction state 유지. `cpa:internal/api/server_routes.go:90`, `cpa:sdk/api/handlers/openai/openai_responses_websocket.go:1031`, `cpa:sdk/cliproxy/service_executors.go:407`, `cpa:internal/runtime/executor/xai_websockets_executor.go:376`, `cpa:internal/runtime/executor/xai_websockets_executor.go:488`, `cpa:internal/runtime/executor/xai_websockets_executor.go:632`, `cpa:internal/runtime/executor/xai_websockets_executor.go:2117`, `cpa:internal/runtime/executor/xai_websockets_executor.go:2172`. | A1. `ocx:src/providers/xai-transport.ts:117`은 물리 HTTP fetch를 래핑한다. `ocx:src/server/responses/ws-upstream.ts:127`은 공식 Codex와 opt-in OpenAI URL만 허용한다. downstream WS는 내부 Responses로 전달할 수 있다. | gap | OBSERVED | +| CAP-wire-gemini-ingress | Gemini SDK generate/stream/count 및 Interactions create | Gemini 등록 route의 generate/stream/count switch, Interactions의 model/agent·stream parsing과 protocol execute. `cpa:internal/api/server_routes.go:149`, `cpa:sdk/api/handlers/gemini/gemini_handlers.go:130`, `cpa:sdk/api/handlers/gemini/interactions_handlers.go:27`, `cpa:sdk/api/handlers/gemini/interactions_handlers.go:94`. | `ocx:src/server/index/serve-options.ts:677` → Gemini surface 기본 on `ocx:src/protocols/settings.ts:49` → `ocx:src/server/index/gemini-routes.ts:69`. Generate bridge는 Chat에 위임하고 Gemini JSON/SSE, count는 추정. Interactions create는 local previous ID 및 pending call을 해석하고 JSON/SSE를 합성한다. `ocx:src/server/gemini-inbound.ts:124`, `ocx:src/server/gemini-inbound.ts:159`, `ocx:src/server/gemini-interactions-inbound.ts:62`. | parity | OBSERVED | +| CAP-wire-gemini-interactions-upstream | 공급자 native Interactions JSON/SSE | Interactions/Chat/Responses/Messages/Gemini source → `interactions-api-key`에서 선택된 `gemini-interactions` executor→ native `POST /v1beta/interactions`, revision 및 continuation 처리. `cpa:internal/api/server_routes.go:153`, `cpa:internal/config/config.go:164`, `cpa:sdk/cliproxy/service_executors.go:376`, `cpa:internal/runtime/executor/gemini_executor.go:75`, `cpa:internal/runtime/executor/gemini_executor.go:728`, `cpa:internal/runtime/executor/gemini_executor.go:820`, `cpa:internal/runtime/executor/gemini_executor.go:1177`. | A2. `ocx:src/server/gemini-interactions-inbound.ts:62`은 OpenCodex가 발급한 ID로 Chat history를 이어간다. Gemini native generate의 별도 적용 범위는 `ocx:src/server/index/gemini-routes.ts:122`이며 upstream Interactions create는 해당 분기에 들어가지 않는다. | gap | OBSERVED | +| CAP-model-catalog | Client별 목록·모델 정의·동적 refresh | GET models에서 client shape 선택, provider별 active registration 및 숨김, embedded 또는 configured catalog source. Home이면 general/Devin local updater를 끈다. `cpa:internal/api/server_routes.go:652`, `cpa:sdk/cliproxy/service_models.go:33`, `cpa:internal/registry/model_registry.go:1579`, `cpa:sdk/cliproxy/service_lifecycle.go:450`, `cpa:internal/registry/catalog_sources.go:490`. | GET models의 Claude/Codex/OpenAI 투영과 managed Codex catalog refresh, 설정 및 발견된 모델 메타데이터를 사용한다. `ocx:src/server/index/serve-options.ts:930`, `ocx:src/server/index/serve-options.ts:1068`, `ocx:src/server/index/serve-options.ts:1188`, `ocx:src/codex/catalog-auto-refresh.ts:241`, `ocx:src/codex/catalog-auto-refresh.ts:263`. | parity | OBSERVED | +| CAP-model-alias | 목록 publication과 inbound alias resolve | GET 모델 목록은 등록 모델을 읽는다. 설정상 per-auth/channel alias가 있으면 exclusion 뒤 alias/Fork projection, 요청 시 역방향 upstream name resolution. `cpa:internal/api/server_routes.go:652`, `cpa:sdk/cliproxy/service_models.go:334`, `cpa:sdk/cliproxy/service_models.go:1220`, `cpa:sdk/cliproxy/service_models.go:1268`, `cpa:sdk/cliproxy/auth/oauth_model_alias.go:311`. | 목록은 configured/effective alias를 표시하고 `preferModelAliasIds`로 id를 promote. route는 configured alias 우선, qualified/bare alias와 ambiguity 검사. `ocx:src/server/index/serve-options.ts:1188`, `ocx:src/server/index/serve-options.ts:1207`, `ocx:src/router.ts:547`, `ocx:src/router.ts:593`, `ocx:src/router.ts:668`. Alias 공통 기능 parity, CPA의 per-credential Fork 정책은 별도. | parity | OBSERVED | +| CAP-wire-xai-speech | 독립 xAI TTS 및 OpenAI speech facade | 두 speech route → 지원 model allowlist/format·voice 매핑 → xAI executor의 speech POST/raw audio. 선택된 xAI model 및 credential 필요. `cpa:internal/api/server_routes.go:86`, `cpa:sdk/api/handlers/openai/openai_speech_handlers.go:52`, `cpa:sdk/api/handlers/openai/openai_speech_handlers.go:104`, `cpa:internal/runtime/executor/xai_executor_execute.go:31`, `cpa:internal/runtime/executor/xai_executor_speech.go:81`. | A3. `ocx:src/server/index/serve-options.ts:1612`는 Codex Live/realtime call, image route는 `ocx:src/server/index/serve-options.ts:1299`. Audio speech JSON 계약과 raw audio 반환의 조합은 없다. | gap | OBSERVED | +| CAP-wire-legacy-completions | `POST /v1/completions` facade | 등록은 기본. `prompt`를 Chat user message로 옮기고 JSON 또는 stream의 choices를 legacy 형태로 감싼다. `cpa:internal/api/server_routes.go:78`, `cpa:sdk/api/handlers/openai/openai_handlers.go:169`, `cpa:sdk/api/handlers/openai/openai_handlers.go:200`, `cpa:sdk/api/handlers/openai/openai_handlers.go:616`, `cpa:sdk/api/handlers/openai/openai_handlers.go:645`. | A4. `ocx:src/server/index/serve-options.ts:1544`와 `ocx:src/server/chat-completions.ts:9`는 Chat API와 messages 계약을 사용한다. | gap | OBSERVED | +| CAP-wire-kiro | 내장 Kiro request와 event stream | CPA 내장 등록 switch와 내장 모델 정의에 Kiro 전용 분기가 없다. generic compat의 native request는 OpenAI wire이며 plugin 설치 시 별도 동작 가능. `cpa:sdk/cliproxy/service_executors.go:373`, `cpa:sdk/cliproxy/service_executors.go:420`, `cpa:sdk/cliproxy/service_models.go:94`, `cpa:internal/runtime/executor/openai_compat_executor.go:103`. | Responses route에서 configured Kiro preset/adapter를 고르면 전용 request/stream 변환을 사용한다. `ocx:src/server/index/serve-options.ts:1411`, `ocx:src/providers/registry/entries-core.ts:720`, `ocx:src/adapters/registry.ts:133`, `ocx:src/adapters/kiro/adapter.ts:329`, `ocx:src/adapters/kiro/adapter.ts:349`. | ocx-ahead | OBSERVED | +| CAP-wire-kimi | Kimi 다중 wire와 thinking replay | Kimi 등록 → ingress별 Messages/Responses/Chat 선택, Messages phase의 replay 및 Responses native compact. `cpa:sdk/cliproxy/service_executors.go:395`, `cpa:internal/runtime/executor/kimi_executor.go:60`, `cpa:internal/runtime/executor/kimi_executor.go:255`, `cpa:internal/runtime/executor/kimi_executor.go:773`. | Kimi Chat preset과 별도 `kimi-responses` preset이 있으며, provider 설정에 따라 선택한다. Chat 기본과 모델별 reasoning 컨트롤 및 Responses tool adjacency가 확인된다. `ocx:src/providers/registry/entries-core.ts:677`, `ocx:src/providers/registry/entries-core.ts:680`, `ocx:src/providers/registry/entries-core.ts:693`. Messages upstream 및 동일 replay 복원 조건의 대조는 보류했다. | unknown | OBSERVED-partial | + +### 주요 wire 경로의 실행 순서 + +- **Codex Responses·WS.** CPA WS는 이전 턴의 pending tool output과 새 transcript를 먼저 분류한다. native continuation이 가능하면 `previous_response_id`와 delta를 보존하고, 그 외에는 이전 입력·출력·이번 입력을 합치거나 compaction transcript를 교체한다. OpenCodex는 다운스트림 `response.create`를 공통 Responses handler로 보내고, local replay miss이면 upstream이 omitted history를 소유하는 경우에 한해 parent ID를 넘긴다. canonical Codex나 translated route에서 그 조건이 깨지면 `previous_response_not_found`를 보내 full-context 재전송을 요구한다. `cpa:sdk/api/handlers/openai/openai_responses_websocket_requests.go:101`, `cpa:sdk/api/handlers/openai/openai_responses_websocket_requests.go:121`, `cpa:sdk/api/handlers/openai/openai_responses_websocket_requests.go:154`, `ocx:src/server/index/websocket-handler.ts:385`, `ocx:src/server/responses/request-prepare.ts:1505`, `ocx:src/server/responses/request-prepare.ts:1531`. +- **Claude Messages·SSE.** CPA의 routed Claude executor는 request envelope 변환, thinking·tool choice, cache control, 최종 wire 확정의 순서로 처리한다. Claude ingress의 선택 대상이 Codex면 Messages의 image/document/tool_result와 effort를 Codex 항목으로 옮기고 Responses event를 `message_delta/message_stop`으로 돌려준다. OpenCodex도 routed request를 공통 Responses로 보내지만 native Messages 선택은 별도 gate다. managed native와 OAuth 확장은 선택된 pool 정책을 고려하며, direct encoder는 명시적 opt-in이다. `cpa:internal/runtime/executor/claude_executor_execute.go:88`, `cpa:internal/runtime/executor/claude_executor_execute.go:158`, `cpa:internal/translator/codex/claude/codex_claude_request.go:436`, `cpa:internal/translator/codex/claude/codex_claude_request.go:594`, `cpa:internal/translator/codex/claude/codex_claude_response.go:206`, `ocx:src/protocols/settings.ts:95`, `ocx:src/server/claude-messages.ts:1224`, `ocx:src/server/claude-messages.ts:1316`. +- **Antigravity replay.** CPA는 signature 오류 및 pairing 거절에서 읽었던 snapshot을 기준으로 삭제하고, terminal 전이나 streaming call이 끝나지 않은 경우 새 ledger를 저장하지 않는다. OpenCodex Google adapter는 SSE의 part 단위로 관찰하여 다음 turn에 서명을 공급하며 session rejection과 durable call signature eviction은 별도 판정한다. CAP-antigravity-replay의 차이는 이 수명과 매칭에서 나온다. `cpa:internal/runtime/executor/antigravity_reasoning_replay.go:874`, `cpa:internal/runtime/executor/antigravity_reasoning_replay.go:898`, `cpa:internal/runtime/executor/antigravity_reasoning_replay.go:3647`, `ocx:src/adapters/google.ts:956`, `ocx:src/adapters/google.ts:1506`. +- **xAI HTTP·WS.** CPA HTTP 요청은 xAI Responses wire를 준비하고, WS는 같은 준비에 response ID 변환과 소켓 session을 더한다. replay는 이미 WS parent ID가 있는 continuation에서 건너뛴다. Assistant 문맥이 불일치하면 replay 삽입을 생략하며, 복구할 call에는 대응 output이 있어야 한다. Replay 가능한 결과가 없는 완료는 이전 항목을 지우고, 저장 backend 오류에서는 이전 상태를 유지한다. `cpa:internal/runtime/executor/xai_executor_execute.go:39`, `cpa:internal/runtime/executor/xai_websockets_executor.go:699`, `cpa:internal/runtime/executor/xai_websockets_executor.go:720`, `cpa:internal/runtime/executor/xai_reasoning_replay.go:67`, `cpa:internal/runtime/executor/xai_reasoning_replay.go:149`, `cpa:internal/runtime/executor/xai_reasoning_replay.go:313`. +- **Gemini Interactions.** CPA의 Interactions 전용 executor는 native 지원 source format과 선택 provider 조건으로 나뉜다. OpenCodex의 Gemini route는 method 검증, 사용 설정과 admission을 거쳐 Interactions create를 local state와 함께 Chat으로 실행한다. Gemini native generate gate는 `method`만 대상으로 삼는다. `cpa:internal/runtime/executor/gemini_executor.go:75`, `cpa:internal/runtime/executor/gemini_executor.go:1177`, `ocx:src/server/index/gemini-routes.ts:59`, `ocx:src/server/index/gemini-routes.ts:120`, `ocx:src/server/gemini-interactions-inbound.ts:84`. + +### 부재 검색 영수증 + +기준은 `9e0e298ef9`. 아래에서 `$O`는 `/Users/jun/Developer/new/700_projects/opencodex/.tmp/chase/opencodex-dev`다. 모든 명령은 저장소 workdir에서 그 값으로 확장한 절대 경로를 넘겼다. 검색은 각 행의 가까운 구현 및 route 분기 확인을 보조한다. + +| 영수증 | 실행 명령 | exit 및 관찰 | +|---|---|---| +| A1 | `rg -n -i -g '!**/generated/**' 'xai.?websockets\|grok.?websockets\|wss://[^" ]*(x\.ai\|grok\.com)\|buildXAIResponsesWebsocket' "$O/src" "$O/gui/src" "$O/docs-site" "$O/structure"` | 1, hit 0. 실제 dial gate가 xAI 호스트를 허용하지 않는 것도 확인했다. | +| A2 | `rg -n -i -g '!**/generated/**' 'gemini-interactions\|interactions-api-key\|generativelanguage[^" ]*/interactions\|nativeInteractionsSourceFormat' "$O/src" "$O/gui/src" "$O/docs-site" "$O/structure"` | 0, inbound handler/store/codec 및 관련 문서. Chat bridge 및 별도 Gemini generate dispatch 확인. | +| A3 | `rg -n -i -g '!**/generated/**' '/v1/audio/speech\|/v1/tts\|xai[-_ ]tts\|openai[-_ ]speech' "$O/src" "$O/gui/src" "$O/docs-site" "$O/structure"` | 1, hit 0. Realtime/Live ingress는 call/session 및 WS wire. | +| A4 | `rg -n -g '!**/generated/**' '"/v1/completions"\|legacyCompletion\|convertCompletionsRequestToChatCompletions' "$O/src" "$O/gui/src" "$O/docs-site" "$O/structure"` | 1, hit 0. Chat handler의 등록과 request contract 확인. | + +위 명령의 `\|` 표기는 Markdown 표에서 리터럴 구분자 `|`를 보이게 하기 위한 escape다. 실행된 정규식의 분기는 `|`였다. + +### 6월 chase 행 재판정 + +| 기존 항목 | 11월 고정 소스 판정 | +|---|---| +| Responses WS→SSE / Codex WS | 공통 transport 동작은 parity. CPA의 WS 진입 조건과 OpenCodex의 HTTP→upstream WS 기본 경로를 별도로 표시했다. CAP-wire-responses-ws, CAP-wire-codex-upstream-ws, CAP-wire-codex-http-to-ws. | +| Antigravity replay 667줄 대 136줄 | 양쪽에 model/session별 replay와 오류 제거가 있다. CPA가 request prefix, part occurrence 및 native call state까지 대조하고, OpenCodex는 bounded local snapshot과 call identity로 재생한다. 부분 차이는 남는다. CAP-antigravity-replay. | +| Antigravity signature validation | 두 구현 모두 family/format 유효성을 확인한다. CPA의 carrier adjacency와 OpenCodex의 replay route scope를 각각 기록했다. CAP-antigravity-signature-validation. | +| Antigravity translator 3종과 단일 Google adapter | CPA는 Gemini/Claude/Chat/Responses/Interactions의 **5개 source 등록**이다. OpenCodex 공통 adapter는 각 ingress codec과 조합하며, 적격 Antigravity direct는 현재 기본 on이다. `ocx:src/protocols/settings.ts:110`, `ocx:src/server/messages-antigravity-direct.ts:98`. | +| xAI 전용 adapter 미확인, forward-only | 모델별 native HTTP Responses와 replay guard가 있다. xAI 전용 완료 기반 replay는 부분 차이, upstream WS는 확인된 gap. CAP-xai-reasoning-replay, CAP-wire-xai-upstream-ws. | +| Claude/Kimi executor | Claude SSE 기반 기능은 유지. CCH/호환 thinking replay는 executor 세부 항목이다. `cpa:internal/runtime/executor/claude_thinking_replay.go:22`. Kimi는 내장 3 wire 확인, 대조 보류. | +| Kiro | 내장 전용 wire 기준 ocx-ahead 유지. CAP-wire-kiro. | +| Vertex | API key/OAuth/credential 및 OAuth 행은 L2. L1에서는 native Vertex 실행 등록을 확인했다. `cpa:sdk/cliproxy/service_executors.go:378`. | + +## Gap candidates + +| ID / CAP | 차이와 사용자 가치 | 노력·대상·의존성 | 위험 / 판정 | +|---|---|---|---| +| L1-1 · CAP-antigravity-replay | **high.** tool과 동일 인자가 반복되는 긴 Codex·Claude Code 턴의 signed context 복원. 문맥 일치 판정과 이전 snapshot 기준 제거를 우선 검토한다. | **L.** `src/adapters/google-antigravity-replay.ts`, Google adapter 및 `src/responses/thought-signature-replay.ts`. 공급자 wire fixture, 안정적인 session scope, terminal/partial 경계가 필요하다. | raw prompt·서명 로그 금지, 부하·재시작 보존, 기존 바이트 한도 및 core/Lab 경계. Home KV 도입은 이 후보에 포함하지 않는다. | +| L1-2 · CAP-xai-reasoning-replay | **med.** Claude/Responses client가 완료 turn의 일부 call/reasoning을 되돌려주지 않는 경우 보강. 기존 replay 상태와 겹치는 실제 보강 사례를 먼저 확인한다. | **M.** `src/responses/state/`, `src/server/responses/core-replay.ts`, `src/adapters/openai-responses/reasoning.ts`. target/credential binding, 동일 turn dedupe, compaction 무효화가 필요하다. | 불투명 replay 자료의 귀속과 보존 기간, 객체 복제량, 중복 tool execution, core 파일 크기 ratchet. | +| L1-3 · CAP-wire-xai-upstream-ws | **med.** xAI native continuation 및 소켓 재사용으로 큰 history 재전송을 줄일 수 있다. 대상 계정·모델에서의 이득은 측정 대상이다. | **L.** `src/providers/xai-transport.ts`, 새 provider-owned transport 모듈 및 `src/server/responses/fetch-helpers.ts`. Bun bounded WS gate, transcript/ID 수명, WS→SSE terminal·fallback 정책이 선행한다. | 강제 HTTP egress/pacing 준수, 암묵 재전송 방지, 프레임/queue/동시성 상한, 요청 로그 privacy, 파일 크기 ratchet. | +| L1-4 · CAP-wire-multimodal-input | **high.** 변환 경로에서 첨부만 있는 turn의 거절과 보존을 일관되게 한다. file-backed 첨부, PDF 및 다중 tool-result modality가 우선이다. | **M.** `src/protocols/guard.ts`, `src/claude/inbound.ts`, targeted adapters와 Gemini codec. target capability 및 기존 `legacy/reject` 예외의 fixture가 필요하다. | 기존 텍스트+첨부 호환성, 원문/경로·바이너리 로깅 금지, 413/400 구분 및 기존 translator budget. | +| L1-5 · CAP-wire-gemini-interactions-upstream | **med.** Gemini Interactions 전용 모델이나 공급자 상태를 사용하는 팀의 wire fidelity. 현재 local ID 경로는 계속 독립 운용할 수 있다. | **L.** `src/protocols/codecs/gemini-interactions.ts`, `src/server/gemini-interactions-inbound.ts`, Google adapter 옆의 Interactions egress. 공급자 모델 capability, revision, owner-bound upstream ID 및 실패 SSE fixture가 필요하다. | ID 소유권과 key 회전, side effect 재시도, Lab 경계, outbound 전용 설정. Background이나 agent 종류 전반 지원은 별도 검토. | +| L1-6 · CAP-wire-xai-speech | **low, reject candidate.** 범용 TTS endpoint는 Codex/Claude Code 코딩 proxy의 현재 주 경로에 대한 이득이 낮다. | **M.** 재검토 시 별도 media route·provider adapter, audio MIME 및 포맷 계약 필요. | 음성 생성 지출을 수반한다. 메모리/응답 크기 상한과 소비자 호환 검증이 필요하다. | +| L1-7 · CAP-wire-legacy-completions | **low, reject candidate.** legacy prompt 클라이언트 추가를 위한 facade다. 이번 대상 클라이언트에서 연결 가치를 확인하지 못했다. | **S.** 재검토 시 Chat route 옆 요청/응답 wrapper. | JSON/SSE usage·오류 형식, 신규 surface admission 및 파일 크기 ratchet. | +| L1-8 · CAP-wire-claude-cch | **low, reject candidate.** 기존 native passthrough와 routed Messages의 역할이 구분된다. CPA의 CCH 재서명을 동등성 요구로 놓을 근거가 부족하다. | **M.** 재검토 시 `src/adapters/anthropic.ts` 옆 wire policy와 공급자가 지원하는 계약 확인이 필요하다. | 클라이언트 provenance, 최종 body 변환 순서, billing·사용자 identity와 공급자 계약, credential privacy. | + +## OpenCodex-ahead items + +- **HTTP ingress → canonical Codex upstream WS**는 기존 Responses transport를 통해 동작한다. CPA Codex Auto에서는 downstream 표지가 gate다. CAP-wire-codex-http-to-ws. +- **내장 Kiro wire**는 provider 선택과 adapter 등록이 연결되어 있다. CAP-wire-kiro. +- **Interactions resource**는 create 외에도 owner-bound 로컬 GET/DELETE를 구현한다. cancel route는 저장된 foreground 작업의 cancel을 거절한다. CPA 고정 ingress의 비교 표면은 create다. `ocx:src/server/gemini-interactions-inbound.ts:210`, `cpa:internal/api/server_routes.go:149`. + +## 최신 사례 (Aside) + +Aside `u0` · local, CLI `1.26.1115.1556`, codemode `0.9.2`. 두 공개 페이지 batch의 외부 envelope는 `indeterminate`, `complete:false`, `truncated:false`, `partial:[no-marker]`로 반환됐다. 아래 날짜와 본문은 batch의 raw `type:final`에서 각 URL의 `ok:true`, `contentVerified:true`, 날짜 attribute를 확인한 항목만 사용했다. 페이지 탐색의 완전성이나 런타임 재현은 이 결과로 판단하지 않는다. 날짜는 UTC 게시일이다. + +| 게시일 | 릴리스 / PR / 이슈 | 출처 URL | 접근일 | 관찰 | OpenCodex 관련성 | 신뢰도 | +|---|---|---|---|---|---|---| +| 2026-11-22 | CPA v8.1.1 · `6eb8554` | https://github.com/router-for-me/CLIProxyAPI/releases/tag/v8.1.1 | 2026-11-23 | 변경 로그에서 Antigravity replay의 세션 스코프·terminal 뒤 갱신과 xAI WS ID 수명, Claude cache hint 보존이 확인된다. 고정 트리에서 `cpa:internal/runtime/executor/antigravity_reasoning_replay.go:187`, `cpa:internal/runtime/executor/antigravity_reasoning_replay.go:3653`, `cpa:internal/runtime/executor/xai_websockets_executor.go:150`, `cpa:internal/translator/claude/openai/responses/claude_openai-responses_request.go:625` 대조. | 긴 turn의 누적 상태는 종료 순서, 키 스코프, 만료와 함께 다룬다. | 높음 · release와 소스 | +| 2026-11-10 | CPA merged #7413 | https://github.com/router-for-me/CLIProxyAPI/pull/7413 | 2026-11-23 | compatible Responses의 `compaction_trigger`를 proxy summary capsule로 처리. 현 소스의 compat gate 및 stream branch를 확인. `cpa:internal/runtime/executor/codex_executor_execute.go:97`, `cpa:internal/runtime/executor/codex_executor_execute.go:416`. | OpenCodex routed compaction과 대응. native continuation·설정 상속이 경계 사례다. | 높음 · merged PR와 소스 | +| 2026-10-07 | CPA merged #6441 | https://github.com/router-for-me/CLIProxyAPI/pull/6441 | 2026-11-23 | 번역 불가 첨부로 빈 turn을 보냈던 사례를 처리했다. 현재 소스에도 request-scoped unsupported part 오류와 특정 변환 사용 지점이 있다. `cpa:internal/translator/common/parts.go:12`, `cpa:internal/translator/claude/openai/responses/claude_openai-responses_request.go:1366`. | 어떤 첨부가 보존되고 어떤 턴이 거절되는지 사용자가 확인할 수 있어야 한다. | 높음 · merged PR와 소스 | +| 2026-10-28 | CPA open #7088 | https://github.com/router-for-me/CLIProxyAPI/issues/7088 | 2026-11-23 | HTTP client에도 Codex WS 업스트림을 열어 달라는 요청. 사용자가 비교 latency를 보고했으며 원인/수치를 독립 검증하지 않았다. 선택 gate는 `cpa:internal/runtime/executor/codex_websockets_executor.go:92`에서 확인. | OpenCodex는 canonical stream의 outbound 조건으로 WS를 선택한다. 실제 속도 비교는 별도 검증이다. | 중간 · 사용자 보고, gate는 소스 확인 | +| 2026-11-23 | CPA open #7946 | https://github.com/router-for-me/CLIProxyAPI/issues/7946 | 2026-11-23 | 사용자가 v8.1.1 큰 context 동시 스트리밍 중 RSS 증가와 컨테이너 재시작을 보고했다. 게시 시각은 pin 커밋보다 앞선다. | replay/stream 이식의 바이트 예산과 병렬 load 확인 항목이다. 원인과 적용 범위 미확정. | 중간 · 단일 사용자 보고 | +| 2026-11-23 | Magpie v0.1.4719 · `3ae5d0a` | https://github.com/yetone/magpie/releases/tag/v0.1.4719 | 2026-11-23 | Magpie 고정 커밋보다 뒤에 게시된 사례(post-head)다. Coding Plan별 catalog와 GLM-5.4 이미지 입력이 릴리스에 기재됐다. pin 소스의 plan catalog 선택과 fixture를 확인했다. `mgp:internal/provider/presets.go:274`, `mgp:internal/provider/testdata/zhipu_plan_catalog.json:131`, `mgp:internal/provider/zhipu_plan_catalog_test.go:48`. | 모델 문자열이 같아도 판매 채널별 modality를 catalog에 따로 노출하는 사례다. | 높음 · release와 소스, fixture 미실행 | + +## Deferred checks + +- 등록 30쌍의 모든 코너 케이스. Codex↔Responses/Claude, Responses→Claude, Gemini ingress/Interactions 및 Antigravity·xAI replay에 집중했다. 나머지 Chat↔Gemini, Interactions의 전체 cross-provider matrix, Vertex schema dialect는 등록과 대표 호출 위치까지 확인했다. +- Kimi thinking 복원, Claude compatible replay의 정확한 OpenCodex 대체 경로, Copilot/Devin/Meta의 native response/compact, generic gateway별 변환, AI Studio relay 및 plugin format 등록의 세부 동작. +- Codex duplex control·`response.append`와 OpenCodex steer/inject의 이벤트별 동등성, WS fallback handshake 범위, 실제 transport별 시간 및 메모리 측정. +- Codex Live/Realtime/SIP/translation, tunnel, Muse Code, Codex alpha search, video 및 image generation의 provider별 stream 이벤트와 제한은 ingress map 범위. +- per-credential alias collision/Fork, 카탈로그 각 공급자 템플릿/refresh 실패, 모델별 thinking 범위의 전수 비교. +- credential, OAuth, cooldown, Home 배치 구조와 관리/플러그인 운영은 L2 범위다. + +## NOT RUN + +- 빌드, 테스트, 서버 실행, upstream 인증 호출, Codex/Claude Code/Gemini 클라이언트 재현 및 성능 측정. +- Linux.do 검색은 `/Users/jun/.local/bin/codemode --account u0 --host local --cwd /Users/jun/Developer/new/700_projects/opencodex --code -`의 `browse.exec`로 `https://linux.do/search?q=CLIProxyAPI%20WebSocket`에 접근했다. raw item은 `EBLOCKED / login-wall`, 최종 URL은 `https://linux.do/login`이었다. 공개 접근 범위에서 종료했다. diff --git a/devlog/_plan/261123_proxy_upstream_catchup/002_cliproxyapi_ops.md b/devlog/_plan/261123_proxy_upstream_catchup/002_cliproxyapi_ops.md new file mode 100644 index 00000000000..dfac4b8f0b4 --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/002_cliproxyapi_ops.md @@ -0,0 +1,177 @@ +# 002 — CLIProxyAPI 운영 계층 대조 + +## 1. 요약 + +- **Vertex 서비스 계정 gap은 닫혔다.** OpenCodex는 Vertex용 JSON 등록, OS credential store, OAuth JWT 교환 및 bearer 전송을 구현한다. 기존의 “key/ADC만” 분류는 ADC가 제공하는 OAuth 경로도 놓쳤다. +- **xAI OAuth는 양쪽에 있다.** CPA는 device flow, OpenCodex는 callback PKCE·device flow·기존 Grok CLI 세션 가져오기를 제공한다. xAI wire/WS/replay 판정은 L1 소관이다. +- **개인용 로컬 프록시에서 가장 구체적인 차이는 credential별 egress다.** CPA는 로그인 때 지정한 경로를 해당 credential에 보존한다. OpenCodex egress는 provider 단위다. +- **pool의 기본 전략과 quota failover는 이미 겹친다.** 같은 이름의 fill-first라도 CPA는 우선순위 후보 중 첫 credential을 사용하고, OpenCodex에는 소진 임계치와 quota window 방향을 반영하는 전략이 있다. +- **재시작이 잦거나 여러 명이 쓰는 프록시에는 cooldown 보존과 credential 진단이 유용하다.** CPA는 선택적으로 cooldown을 복원하며 management에서 auth별 모델·검증·refresh를 다룬다. +- **로컬 사용량 분석과 소규모 공유의 요구를 구분한다.** OpenCodex는 자체 usage ledger와 하위 client key 관리가 있고, CPA는 단기 소비형 usage queue와 plugin sink를 제공한다. +- **Home control plane, native plugin 배포, 외부 credential storage는 별도 운영 범위다.** 단일 로컬 설치의 추격 우선순위에는 넣지 않는다. + +기준은 CPA `0d251842d2539194ebd55ef0cdcf9c08f9c4908a`, OpenCodex `9e0e298ef9720cfeaa1209f090a68e4d1965d2a1`이다. `cpa:`는 gitignored clone, `ocx:`는 `origin/dev` archive를 가리킨다. 비교 결과는 실행 검증을 포함하지 않는다. `OBSERVED-partial`은 양쪽 계약의 일부 또는 한쪽 구현만 읽은 행이다. 이 경우 상태는 `unknown`으로 유지했다. + +## 2. 표면 맵 + +### 실행·관리 등록 + +표에서 `G/Pu/Pa/D/Po/H`는 각각 GET, PUT, PATCH, DELETE, POST, HEAD다. v0/v8 행의 경로는 각각 `/v0/management`와 `/v8/management` 뒤에 붙는다. + +| CAP tag | 등록 표면 및 gate | 소스 | +| --- | --- | --- | +| CAP-client-key-auth | 공통 access middleware 아래 `/v1`의 `G /models, /models/*model`, `Po /chat/completions, /completions, /images/{generations,edits}, /videos{,/generations,/edits,/extensions}, /audio/speech, /tts, /messages{,/count_tokens}, /responses{,/compact}, /alpha/search, /live`, `G /videos/:request_id, /responses, /live/:call_id`. WS Responses는 `G /responses`. | cpa:internal/api/server_routes.go:68–95 | +| CAP-client-key-auth | `/backend-api/codex` 아래 `G/Po /responses`, `Po /responses/compact, /alpha/search`. `/openai/v1` 아래 영상 생성·조회·content. `/v1beta` 아래 `G /models`, `G/Po /models/*action`, `Po /interactions`. `/muse-code` 아래 `G /models, /config`와 `Po /search, /browser_open`. 각 그룹에 access middleware가 있다. | cpa:internal/api/server_routes.go:120–155 | +| CAP-client-key-auth | `/v1/realtime`의 WS/HTTP, `/calls` 생성·조회·hangup/accept/reject/refer, `/client_secrets`, `/sessions`, `/transcription_sessions`, `/translations`와 그 client secrets. Realtime client secret 경로와 일반 access 경로를 나눈다. `/v1/tunnel`은 GET의 별도 handler와 POST/PUT/PATCH/DELETE/HEAD/TRACE/CONNECT도 등록한다. SDK 동적 WS attachment는 변경 가능한 WS auth를 적용한다. SDK 옵션의 `G /keep-alive`도 별도 등록할 수 있다. | cpa:internal/api/server_routes.go:98–118,587–626, cpa:internal/api/server_keepalive.go:24 | +| CAP-management-api | 관리 secret 설정 시 v0/v8 등록. Home에서는 management availability가 404를 반환한다. OAuth callback은 availability와 pending session/state 계약을 적용한다. 다른 관리 route에는 관리 secret middleware를 추가한다. `G/H /healthz` 및 `G /`가 별도 등록된다. | cpa:internal/api/server.go:281–289, cpa:internal/api/server_management.go:14–29,204–225, cpa:internal/api/server_management_v8.go:12–20, cpa:internal/api/server_routes.go:55–58,159 | +| CAP-management-api | **v0 config/routing**. `G /config, /latest-version`, `G/Pu /config.yaml`. `G/Pu/Pa`의 `/debug, /logging-to-file, /logs-max-total-size-mb, /error-logs-max-files, /usage-statistics-enabled, /request-log, /ws-auth, /request-retry, /max-retry-credentials, /max-retry-interval, /force-model-prefix, /routing/strategy, /quota-exceeded/{switch-project,switch-preview-model}`. `G/Pu/Pa/D /proxy-url`. `Po /api-call, /reset-quota, /quota/{fetch,reset}` 및 `G /quota/providers, /model-definitions/:channel`. | cpa:internal/api/server_management.go:31–34,48–86,110–133,182 | +| CAP-management-api | **v0 lists/credentials**. `G/Pu/Pa/D`의 `/api-keys, /{gemini,interactions,claude,codex,xai,meta,vertex}-api-key, /openai-compatibility, /oauth-excluded-models, /oauth-model-alias, /oauth-request-scoped-errors`. `G/Po/D /auth-files`, `G /auth-files/{models,download}`, `Pa /auth-files/{status,fields}`, `Po /auth-files/refresh, /vertex/import`. | cpa:internal/api/server_management.go:88–103,135–189 | +| CAP-management-api | **v0 observability/plugins**. `G/D /logs`, `G /request-error-logs{,/:name}, /request-log-by-id/:id, /api-key-usage, /usage-queue`. `G /plugins, /plugin-store`, `Po /plugin-store/:id/install`, `D /plugins/:id`, `Pa /plugins/:id/enabled`, `G/Pu/Pa /plugins/:id/config`, `G/Po/D /plugins/:id/quota`, `Po /plugins/:id/quota/reset`. | cpa:internal/api/server_management.go:35–46,92–93,105–112 | +| CAP-management-api | **v8 config/operations**. `G/Pu/Pa /config`, `G/Pu /config.yaml`, `G/Pu/Pa/D /config/*path`. `G /server/{server-id,latest-version}`, `Po /requests/api-call, /routing/cooldown/reset, /routing/model-definitions/refresh, /models/refresh`, `G /routing/model-definitions/:channel`. `G/D /observability/logs`와 `G /observability/{logs/errors,logs/errors/:name,logs/requests/:id,usage/api-keys,usage/queue,requests/in-flight}`. | cpa:internal/api/server_management_v8.go:21–45 | +| CAP-management-api | **v8 credentials/plugins**. `G/Po/D /credentials`, `G /credentials/{models,download,siwc/status}`, `Pa /credentials/{status,fields}`, `Po /credentials/{refresh,verify}`. `G /plugins, /plugins/store`, `D /plugins/:id`, `Po /plugins/store/:id/install`, `G/Po/D /plugins/:id/quota`. 활성 plugin은 별도 management 경로도 등록한다. | cpa:internal/api/server_management_v8.go:47–71, cpa:internal/api/server_management.go:234 | +| CAP-oauth-login | **v0 OAuth**. `G /{anthropic,codex,antigravity,kimi,kimi-ai,xai,devin,meta}-auth-url, /get-auth-status`, `D /oauth-session`, `G/Po /oauth-callback`. **v8 OAuth**. `G/Po /oauth/auth-url, /oauth/callback`, `Po /oauth/import, /oauth/siwc/bind`, `G /oauth/{status,siwc/status}`, `D /oauth/session`. v8 provider dispatcher는 Copilot 및 plugin을 추가한다. 직접 callback은 `G /anthropic/callback, /codex/callback, /antigravity/callback, /callback, /devin/callback`. | cpa:internal/api/server_management.go:25–26,189–200, cpa:internal/api/server_management_v8.go:14–15,56–63, cpa:internal/api/handlers/management/auth_files_v8.go:403–427, cpa:internal/api/server_routes.go:173–250 | +| CAP-management-ui | `G /management.html`, local/remote `-tui`, `-standalone` embedded TUI. `-management-base-url` → config base URL → localhost 순으로 기존 instance에 연결한다. | cpa:internal/api/server_routes.go:58, cpa:internal/api/server_management.go:312–339, cpa:cmd/server/main.go:178–180,752–845 | +| CAP-control-plane | `-home-jwt` 또는 `HOME_JWT`, opt-out `-home-disable-cluster-discovery`. `-discover`, `-discover-json`, `-discover-service-type` 및 서버 DNS-SD 광고 설정. `-local-model`은 embedded catalog 선택 입력이다. RESP listener는 같은 대외 listener의 protocol mux를 사용한다. | cpa:cmd/server/main.go:165–181,290–294,359–379, cpa:internal/config/parse.go:79–83, cpa:internal/api/protocol_multiplexer.go:125,182, cpa:internal/api/redis_queue_protocol.go:42 | +| CAP-plugin-host | CLI flag 등록·실행, OAuth, frontend access, auth-file parse, executors, model 등록·routing, translation, interceptors, scheduler, quota, usage, management. Home sync 및 local management store에서 설치. 런타임·플랫폼 gate는 `plugins.enabled`와 지원 loader다. | cpa:cmd/server/main.go:208–213,654–675, cpa:sdk/pluginapi/types.go:79–172, cpa:sdk/cliproxy/service_plugins.go:89–147, cpa:internal/pluginhost/host.go:223–286, cpa:internal/pluginhost/loader_unix.go:179–232 | +| CAP-sdk-embedding | 공개 `sdk/config`, `sdk/auth`, `sdk/access`, `sdk/api`(+handlers), `sdk/cliproxy`(+auth/executor/session/usage/pipeline 등), `sdk/translator`, `sdk/pluginapi`·`pluginabi`·`pluginhost`·`pluginstore` 및 `proxyutil`·`httptransport`·`logging`. 대표 주입 경로는 builder와 usage plugin 등록이다. | cpa:sdk/cliproxy/builder.go:109–245, cpa:sdk/cliproxy/service_plugins.go:62–68, cpa:sdk/api/options.go:20–35, cpa:sdk/api/management.go:34–70 | +| CAP-amp-integration | 현재 tree의 Amp 관련 소스는 legacy config 키를 제거하는 경로다. 이 기능을 현행 등록으로 세지 않았다. Muse Code와 tunnel은 각각 위 등록 행에 해당한다. | cpa:internal/config/config_yaml.go:1018–1020, cpa:internal/api/server_routes.go:98–101,139–146 | + +### CLI·SDK 인증 등록 + +`-no-browser`, callback port 설정 및 `-login-proxy`는 해당 로그인 동작의 옵션이다. Provider authenticator 등록과 실행은 별개다. `sdk/auth.Manager.Login`은 지정 authenticator를 호출하고 store가 있으면 결과를 저장한다. 런타임 refresh는 별도 `sdk/cliproxy/auth.Manager`와 executor가 수행한다. 기본 파일 store는 `auth-dir`의 credential을 사용한다. [cpa:cmd/server/main.go:152–174,642–649,684–711; cpa:internal/cmd/auth_manager.go:13–25; cpa:sdk/auth/manager.go:54–85; cpa:internal/config/config_defaults.go:6] + +| CAP tag | CLI·SDK provider · 흐름 | 주요 구현 | +| --- | --- | --- | +| CAP-oauth-codex | `-codex-login`, `-codex-device-login`. PKCE/loopback callback 또는 device code. 관리 v8 `provider=codex`. `-siwc-bind` 및 v8 bind는 기존 Codex credential의 추가 OAuth binding이다. | cpa:sdk/auth/codex.go:38–58,113,192, cpa:sdk/auth/codex_device.go:26–39, cpa:internal/api/handlers/management/auth_files_provider_oauth.go:258, cpa:internal/cmd/siwc_bind.go:138 | +| CAP-oauth-claude | `-claude-login`, v0 anthropic/v8 claude. PKCE authorization code와 callback, provider 실행 refresh. | cpa:sdk/auth/claude.go:38, cpa:internal/api/handlers/management/auth_files_provider_oauth.go:99, cpa:internal/runtime/executor/claude_executor_auth.go:149 | +| CAP-oauth-antigravity | `-antigravity-login` 및 관리 로그인. Google authorization-code exchange 후 프로젝트 discovery와 credential 저장. | cpa:sdk/auth/antigravity.go:35,156,345–378, cpa:internal/api/handlers/management/auth_files_provider_oauth.go:730, cpa:internal/runtime/executor/antigravity_executor_auth.go:33 | +| CAP-oauth-kimi | `-kimi-login`, `-kimi-ai-login`, SDK `kimi`/`kimi-ai`/`kimi.ai`, 관리 domain 선택. Device authorization과 refresh. | cpa:sdk/auth/kimi.go:26–58,85,133, cpa:internal/api/handlers/management/auth_files_provider_oauth.go:1148–1160, cpa:internal/runtime/executor/kimi_executor.go:1133 | +| CAP-oauth-xai | `-xai-login` 및 관리 로그인. Discovery, device authorization/poll, provider token refresh. | cpa:sdk/auth/xai.go:35–50,82–126, cpa:internal/auth/xai/xai.go:68,343, cpa:internal/api/handlers/management/auth_files_provider_oauth.go:898 | +| CAP-oauth-copilot | `-copilot-login` 및 v8 auth-url. GitHub device authorization 후 Copilot credential exchange. | cpa:sdk/auth/copilot.go:26–70, cpa:internal/api/handlers/management/auth_files_v8.go:420–421, cpa:internal/runtime/executor/copilot_executor.go:79 | +| CAP-oauth-devin | `-devin-login` 및 관리 로그인. Authorization code/PKCE, loopback 또는 수동 callback 복귀. | cpa:sdk/auth/devin.go:44–57,103,151,254, cpa:internal/api/handlers/management/auth_files_devin_oauth.go:46 | +| CAP-oauth-meta | `-meta-login` 및 관리 로그인. Device authorization. SDK는 API key 만료 정보가 없으므로 일반 만료 스케줄과 구분한다. | cpa:sdk/auth/meta.go:27–51,105, cpa:internal/api/handlers/management/auth_files_provider_oauth.go:1008, cpa:internal/runtime/executor/meta_executor.go:109 | +| CAP-oauth-vertex | `-vertex-import`/`-vertex-import-prefix`, v0 Vertex import 및 v8 OAuth import. 서비스 계정 JSON → auth record → Google OAuth access token. API key 경로도 있다. | cpa:internal/cmd/vertex_import.go:23,83–109, cpa:internal/api/handlers/management/auth_files_v8.go:533–537, cpa:internal/runtime/executor/gemini_vertex_executor.go:196–217,1846–1860 | +| CAP-credential-files | config synthesis에는 Gemini/Interactions, Codex, Claude, xAI, Meta, OpenAI compatibility, Vertex 등 API keys가 있다. file synthesis에는 provider auth JSON 및 plugin auth parse가 있다. AI Studio executor는 catalog에 존재하며 별도 CLI 로그인 flag 근거는 없다. | cpa:internal/config/config.go:160–208, cpa:internal/watcher/synthesizer/config.go:77–177, cpa:internal/watcher/synthesizer/file.go:108–143,214–215, cpa:sdk/cliproxy/service_models.go:113–128 | + +## 3. 기능 인벤토리 + +### 요청에서 credential 선택까지 읽은 경로 + +- **Codex Responses.** CPA의 POST Responses는 non-stream에서 `ExecuteWithAuthManager`, SSE에서 `ExecuteStreamWithPreFTKeepAlive`로 들어간다. WS도 `ExecuteStreamWithAuthManager`를 호출하고 성공 상태의 auth를 연결에서 기억한다. 로컬 manager는 후보 credential을 선택하고 시도 결과를 `MarkResult`에 전달한다. OpenCodex의 POST와 별도 gate가 있는 WS는 모두 Responses 처리 경로에 들어가며, `resolveResponsesCodexAuth`가 route의 `codexAccountMode`를 account 선택에 전달한다. pre-output 거절은 Codex pool health에 반영된다. [cpa:sdk/api/handlers/openai/openai_responses_handlers.go:997,1087,1159; cpa:sdk/api/handlers/openai/openai_responses_websocket.go:456,652,1093–1095,1211; cpa:sdk/cliproxy/auth/conductor_execution.go:1230–1275,1452–1496; ocx:src/server/index/serve-options.ts:562–579,1411–1419; ocx:src/server/index/websocket-handler.ts:359; ocx:src/server/responses/core-auth.ts:234,309; ocx:src/server/responses/core-codex-account.ts:146–156] +- **Claude Code Messages/SSE.** CPA의 `ClaudeMessages`와 count_tokens는 같은 manager에 연결되며 stream은 pre-first-token 경로를 쓴다. OpenCodex는 `/v1/messages` ingress에서 API key/Origin을 확인하고, native passthrough 또는 Responses bridge에서 선택한다. 번역 경로에는 session/model 기준 Anthropic 선택과 upstream refusal rotation이 있다. native와 번역 경로가 모든 quota/affinity 상황에서 같은 결과를 낸다는 판정은 보류한다. [cpa:sdk/api/handlers/claude/code_handlers.go:74,130,184,270; ocx:src/server/index/serve-options.ts:1485–1537; ocx:src/server/claude-messages.ts:352,820,1294; ocx:src/server/responses/request-transport.ts:1398; ocx:src/server/responses/adapter-dispatch.ts:1387] +- **별도 프로토콜인 Gemini.** CPA의 `/v1beta/models/*action`과 `/v1beta/interactions`는 access middleware를 거치며 Vertex auth의 API key/서비스 계정 분기가 실행 단계에서 결정된다. OpenCodex는 native Gemini generation에서 설정된 Antigravity OAuth row를 고르고, 모델 허용 여부를 판단한 뒤 그 account의 access snapshot을 요청한다. Vertex의 OAuth bearer는 별도로 Google adapter의 Vertex 분기에서 확인했다. [cpa:internal/api/server_routes.go:149–155; cpa:internal/runtime/executor/gemini_vertex_executor.go:239–290; ocx:src/server/index/gemini-routes.ts:59,135–143; ocx:src/server/gemini-native.ts:50–83; ocx:src/adapters/google.ts:1290–1303] + +| CAP tag | 기능 | CLIProxyAPI 등록 → 구현 → gate | OpenCodex 근거 또는 부재 receipt | 상태 | 근거 등급 | +| --- | --- | --- | --- | --- | --- | +| CAP-oauth-vertex | Vertex 서비스 계정 OAuth | CLI import/v0 `POST /vertex/import`/v8 `POST /oauth/import` → `service_account` record 저장 → `vertex` executor → key가 없고 등록된 SA가 있을 때 `CredentialsFromJSON`과 `TokenSource.Token`을 사용하고 bearer 전송. cpa:cmd/server/main.go:172–173,684, cpa:internal/api/server_management.go:189, cpa:internal/api/handlers/management/auth_files_v8.go:533–537, cpa:internal/cmd/vertex_import.go:83–109, cpa:sdk/cliproxy/service_executors.go:379, cpa:internal/runtime/executor/gemini_vertex_executor.go:196–217,1846–1860 | `POST /api/providers/keys`는 등록 provider와 credential을 요구하고, JSON을 OS credential store에 보존한 뒤 `gcp-sa:` 참조를 저장한다. Google Vertex 설정에서 API key/marker/ADC를 구분하고, marker 또는 ambient ADC의 서비스 계정으로 JWT bearer 교환을 수행한다. `authorized_user` refresh와 metadata 경로도 있다. ocx:src/server/management-api.ts:406, ocx:src/server/management/oauth-account-routes.ts:1280–1297, ocx:src/providers/api-keys.ts:163–187,249–273, ocx:src/lib/gcp-adc.ts:82–105,378–423,433, ocx:src/adapters/google.ts:1290–1303 | parity | OBSERVED | +| CAP-oauth-xai | xAI 로그인 선택지·refresh | `-xai-login`/관리 auth-url → discovery/device Start/Poll → credential → xAI executor refresh가 refresh token을 사용한다. cpa:cmd/server/main.go:161,705–706, cpa:internal/api/handlers/management/auth_files_v8.go:416, cpa:sdk/auth/xai.go:47–126, cpa:internal/auth/xai/xai.go:68,343, cpa:internal/runtime/executor/xai_executor_auth.go:16–30 | `ocx login xai`/`POST /api/oauth/login`에서 registry를 거쳐 기본 callback PKCE, 명시적 device flow, local Grok import fallback 및 force-login opt-out을 선택한다. 계정 refresh는 lock과 저장 generation을 사용한다. ocx:src/oauth/login-cli.ts:152,237, ocx:src/server/management/oauth-account-routes.ts:278,364, ocx:src/oauth/index.ts:310–314,832,1151, ocx:src/oauth/xai.ts:362,461,572–604 | ocx-ahead | OBSERVED | +| CAP-oauth-codex | Codex/ChatGPT 사용자 OAuth | `-codex-login`/`-codex-device-login`와 v8 codex opt-in → `Login`의 callback PKCE 또는 device branch → Codex refresh. cpa:cmd/server/main.go:152–153,692–696, cpa:sdk/auth/codex.go:38–58,192, cpa:internal/runtime/executor/codex_executor_auth.go:154 | `ocx login chatgpt`/관리 로그인 → registry의 `chatgpt` 및 login flow → 저장된 account token snapshot. Device와 callback 선택 계약의 end-to-end 동등성은 따로 확인한다. ocx:src/oauth/login-cli.ts:152,237, ocx:src/oauth/index.ts:397,599,1635,1889, ocx:src/oauth/chatgpt-device.ts:235–242 | parity | OBSERVED | +| CAP-oauth-claude | Claude 사용자 OAuth | CLI/v0/v8 login → PKCE authenticator → credential 및 executor refresh. cpa:cmd/server/main.go:154,698–699, cpa:internal/api/server_management.go:191, cpa:sdk/auth/claude.go:38, cpa:internal/runtime/executor/claude_executor_auth.go:149 | 일반 login route/CLI → `anthropicOAuthDefinition` → 계정별 refresh lock과 저장. 사용자가 provider OAuth 등록 후 선택하는 범위의 비교다. ocx:src/server/management/oauth-account-routes.ts:278,364, ocx:src/oauth/login-cli.ts:237, ocx:src/oauth/index.ts:318,876,1152 | parity | OBSERVED | +| CAP-oauth-antigravity | Antigravity 사용자 OAuth | CLI/v8 → code exchange 및 project discovery → refresh executor. cpa:cmd/server/main.go:158,690–691, cpa:internal/api/handlers/management/auth_files_v8.go:410–411, cpa:sdk/auth/antigravity.go:156,345–378, cpa:internal/runtime/executor/antigravity_executor_auth.go:33 | 일반 login route/CLI의 `google-antigravity` → account snapshot. Native Gemini는 provider 활성·OAuth/Cloud Code Assist 조건을 검사하고 account+project를 사용한다. ocx:src/oauth/index.ts:360,599, ocx:src/server/management/oauth-account-routes.ts:278,364, ocx:src/server/gemini-native.ts:50–83 | parity | OBSERVED | +| CAP-oauth-kimi | Kimi 사용자 OAuth 및 domain 범위 | 명시적 Kimi/Kimi AI flags 또는 v8 두 provider 분기 → device 흐름, 도메인별 authenticator → refresh. cpa:cmd/server/main.go:159–160,700–704, cpa:sdk/auth/kimi.go:26–58,85,133, cpa:internal/runtime/executor/kimi_executor.go:1133 | 등록된 `kimi`로 명시적 OAuth login/refresh 가능. 호스트 환경변수 override는 있지만 공개 registry는 기본 `.com`을 사용하는 단일 `kimi` definition이다. CPA의 두 명시적 로그인과 범위가 다르다. ocx:src/oauth/index.ts:320,1635, ocx:src/oauth/login-cli.ts:237, ocx:src/oauth/kimi.ts:12,83,212–226 | partial | OBSERVED | +| CAP-oauth-kiro | Kiro 내장 등록 | CPA `cmd/server/main.go:152–174`, `internal/cmd/auth_manager.go:13–25` 및 `sdk/auth/refresh_registry.go:9–19`의 내장 roster에 없다. `rg -il '\bkiro\b'`를 CPA `sdk/auth`, `internal/auth`, `sdk/cliproxy/service_executors.go`, `cmd/server/main.go`에 실행해 출력이 없었다. | 명시적 login → `kiro` OAuth registry → `kiro` adapter 등록. ocx:src/oauth/login-cli.ts:237, ocx:src/oauth/index.ts:354, ocx:src/providers/registry/entries-core.ts:718–726 | ocx-ahead | OBSERVED | +| CAP-oauth-secondary | Copilot, Devin, Meta | CLI와 v8에 등록. GitHub device → Copilot exchange, Devin PKCE code, Meta device. cpa:cmd/server/main.go:162–164,707–711, cpa:internal/api/handlers/management/auth_files_v8.go:418–423, cpa:sdk/auth/copilot.go:26–70, cpa:sdk/auth/devin.go:44–57, cpa:sdk/auth/meta.go:37–51 | ocx:src/oauth/index.ts:265–411에 별도 provider 정의가 있다. Copilot 및 Meta domain/권한·토큰 계약의 정확한 교집합은 미확인. | unknown | OBSERVED-partial | +| CAP-token-refresh | 요청 시 refresh 및 선행 refresh | `Service.Run`은 일반 mode에서 manager를 load하고 auto-refresh를 시작한다. `shouldRefresh`는 expiry·refresh lead·backoff·SIWC/outer 상태를 따로 보며, management 수동 refresh도 있다. cpa:sdk/cliproxy/service_lifecycle.go:89–106, cpa:sdk/auth/refresh_registry.go:9–19, cpa:sdk/cliproxy/auth/conductor_refresh.go:137–179, cpa:sdk/cliproxy/auth/auto_refresh_loop.go:265–289, cpa:internal/api/server_management_v8.go:54 | 요청 snapshot에서 account별 만료·refresh 및 generation 보호. CLI가 Guardian을 시작하고 sweep은 명시적 활성 때만 실행한다. cpa와 선행 refresh의 기본 활성 범위가 다르다. ocx:src/oauth/index.ts:599,708–747,832,1019, ocx:src/cli/index.ts:635, ocx:src/oauth/token-guardian.ts:133–138,318 | partial | OBSERVED | +| CAP-credential-files | credential 수명주기·진단 | 로컬 기본 `FileTokenStore` + config/file synthesis. 관리 `/credentials`는 list/upload/download/models/status/fields/refresh/verify/delete를 제공한다. 등록된 관리 secret 및 non-Home gate. cpa:cmd/server/main.go:642–649, cpa:sdk/auth/filestore.go:75,178,210,236, cpa:internal/api/server_management_v8.go:47–55, cpa:internal/api/handlers/management/auth_files_refresh.go:15, cpa:internal/api/handlers/management/auth_files_v8.go:546,612, cpa:internal/api/server_management.go:213–225 | 인증된 `/api/oauth/accounts`에 list, pause, probe, import, alias, delete가 있고 provider-key store 관리가 있다. probe는 store write 없는 조회이며 generic import는 adapter 레지스트리를 거친다. 공통 provider-independent credential JSON transport·검증 UI 계약과는 다르다. ocx:src/server/index/serve-options.ts:681–695, ocx:src/server/management/oauth-account-routes.ts:556,698,1105–1198,1280–1323, ocx:src/oauth/account-import/registry.ts:14 | partial | OBSERVED | +| CAP-credential-pool | round-robin와 fill-first | Responses/Claude/SDK manager → strategy normalize → priority bucket 및 model eligibility → RR 기본, FF 명시 선택. cpa:sdk/cliproxy/service_config.go:66–126, cpa:sdk/cliproxy/auth/selector.go:1074,1234, cpa:sdk/cliproxy/auth/scheduler.go:463–524,1328,1463–1472 | Responses account 선택 및 관리 `/api/pool/settings` → Codex/Anthropic/generic·API key pool별 전략. generic proactive는 유효 roster와 opt-in을 요구하고, API key proactive 전략은 명시 설정 또는 active key 비활성 시 적용된다. 같은 전략명에서 소진 임계치/선호 순서 의미가 다르다. ocx:src/server/responses/core-auth.ts:234,309, ocx:src/server/management/oauth-account-routes.ts:796, ocx:src/oauth/generic-account-failover.ts:245–255,596,890–908, ocx:src/codex/routing/selection.ts:722–731, ocx:src/providers/key-failover.ts:491–522 | partial | OBSERVED | +| CAP-credential-pool-weighted | operator가 정한 credential weight | `routing.strategy=weighted-round-robin`에서 selector는 eligible priority bucket의 양수 weight를 선택·예약한다. 파일/설정 입력의 weight도 검사한다. cpa:sdk/cliproxy/service_config.go:78,113–122, cpa:sdk/cliproxy/auth/scheduler_weighted.go:7–30, cpa:internal/config/parse.go:60–62,103–104 | 같은 pool 경로의 reset-near weighted Codex/Anthropic과 Cursor 쪽 weight가 있어 가중 선택 전체를 gap으로 보지 않는다. 공통 운영자가 각 credential에 정적 비율을 주는 계약과는 다르다. API key schema는 RR/FF/quota다. R-A. ocx:src/codex/routing/selection.ts:529–539,722–725, ocx:src/oauth/anthropic-routing.ts:886–888, ocx:src/config/schema/leaf-validators.ts:352,371 | partial | OBSERVED | +| CAP-cache-affinity | session-to-credential affinity | `routing.session-affinity` 기본 false, selector wrap 후 ID 바인딩과 rebind 규칙 적용. Responses WS는 별도 pin 유지. cpa:config.example.yaml:212, cpa:sdk/cliproxy/service_config.go:94–126, cpa:sdk/cliproxy/auth/selector.go:1625,1737–1765, cpa:sdk/api/handlers/openai/openai_responses_websocket.go:619–664 | Responses에서 route mode와 session 증거로 선택하고, Anthropic/generic 어댑터에 별도 affinity 및 관리 reset이 있다. 지원 provider·scope 게이트가 달라 공통 toggle 동등성은 없다. ocx:src/server/responses/core-auth.ts:309, ocx:src/server/responses/request-transport.ts:1398–1428, ocx:src/oauth/generic-session-affinity.ts:35–59,82–116, ocx:src/server/management/oauth-account-routes.ts:643 | partial | OBSERVED | +| CAP-model-credential-routing | 모델별 credential eligibility와 aliases | 등록 모델 목록에 file/provider/API key별 제외·prefix·alias 반영 → registry/scheduler model match → 해당 auth의 실행 alias/후보 결정. credential과 model route가 있어야 적용된다. cpa:sdk/cliproxy/service_models.go:33,75–126,334–342, cpa:sdk/cliproxy/auth/scheduler.go:1244,1328, cpa:sdk/cliproxy/auth/conductor_models.go:236–307,495–510, cpa:internal/config/config.go:210–219 | Responses/Anthropic 선택에 model ID를 넘기고, Gemini native는 Antigravity account/model route의 allow/reroute/deny를 사용한다. 범용 per-credential alias와 engine taxonomy는 다르다. ocx:src/server/responses/request-transport.ts:1398–1428, ocx:src/server/index/gemini-routes.ts:135, ocx:src/server/gemini-native.ts:50–57,74–83 | partial | OBSERVED | +| CAP-failover | bounded retry와 quota cooldown | `Execute/ExecuteStream` → `pickNextMixed` → 결과를 credential/model scope에 반영. 429는 Retry-After와 fallback backoff, 또 다른 retry round는 오류·budget·max wait를 확인한다. `disable-cooling` 기본 false. CPA 예제는 retry 3/interval 30초/credential cap 0이며 loader의 생략값과 동일하다고 단정하지 않는다. cpa:sdk/cliproxy/auth/conductor_execution.go:339,460,596,773,1275,1914, cpa:sdk/cliproxy/auth/conductor_selection.go:1882–1957, cpa:sdk/cliproxy/auth/conductor_cooldown.go:1636,1904–1955, cpa:sdk/cliproxy/service_auth.go:667–673, cpa:internal/config/parse.go:64–76, cpa:config.example.yaml:250–266 | Codex pre-output refusal, Anthropic response rotation, generic/key failover 및 cooldown이 있다. 선택 모드, 사용 가능한 대체 credential과 pre-output 단계가 제약이다. 전 provider 공통 retry round/max-wait 상한과 같은 계약은 확인되지 않았다. ocx:src/server/responses/core-codex-account.ts:146,284,803–816, ocx:src/codex/routing/cooldown-math.ts:153–223, ocx:src/server/responses/adapter-dispatch.ts:1387,1487, ocx:src/oauth/generic-account-failover.ts:675–725, ocx:src/providers/key-failover.ts:392 | partial | OBSERVED | +| CAP-cooldown-persistence | API key cooldown의 재시작 복원 | non-Home `SaveCooldownStatus`가 있을 때 파일 또는 주입 store 구성 → manager startup restore → auth/model deadline을 복원한다. 기본 off. cpa:internal/config/parse.go:73, cpa:sdk/cliproxy/service_auth.go:680–708, cpa:sdk/cliproxy/service_lifecycle.go:86–99, cpa:sdk/cliproxy/auth/conductor_cooldown.go:232,320,1246 | R-H/R-H2. `src/providers/api-key-cooldowns.ts:1–26`는 process-local map, `src/providers/key-failover.ts:491–522,839–843,937–940`은 선택·갱신 경로다. `src/lib/state-store-registrations.ts:129–135`에는 이 상태의 만료 sweep이 등록된다. quota/event history 또는 이 receipt의 범위는 API key pool의 deadline이다. | gap | OBSERVED | +| CAP-quota-exceeded-policy | switch-project/preview 및 credits fallback | `switch-project`와 `switch-preview-model`은 v0/TUI와 설정·diff에서 읽고 쓴다. 비테스트 tree의 exact field 사용처에서 executor/selector 소비는 찾지 못했다. 별도 `antigravity-credits`는 opt-in last-resort branch가 있다. cpa:internal/api/server_management.go:75–82, cpa:internal/api/handlers/management/quota.go:13–24, cpa:internal/config/config_types.go:564–573, cpa:sdk/cliproxy/auth/conductor_execution.go:488–489,814–815 | OpenCodex는 Antigravity model/account reroute를 갖는다. CPA의 요청 중 switch-project/preview 기능을 근거로 채점하지 않았으며 credits의 spend policy 동등성은 미확인. ocx:src/server/gemini-native.ts:50–57 | unknown | OBSERVED-partial | +| CAP-quota-management | probe와 cooldown reset | v0 `/quota/{providers,fetch,reset}` 및 v8 `/routing/cooldown/reset` → handler → manager 또는 plugin quota provider. 관리 secret 및 non-Home 조건. cpa:internal/api/server_management.go:82–86, cpa:internal/api/server_management_v8.go:33,69–71, cpa:internal/api/handlers/management/quota.go:28, cpa:sdk/cliproxy/auth/conductor_cooldown.go:1138 | 관리 `/api/provider-quotas`와 `/api/oauth/accounts/clear-cooldown`, `/probe`. OpenCodex의 `GET /api/quota-resets`는 reset 이벤트 조회이며 credit 소비 동작과도 구분된다. ocx:src/server/management/provider-routes.ts:879, ocx:src/server/management/oauth-account-routes.ts:1092–1129, ocx:src/server/management/quota-reset-routes.ts:20–51 | partial | OBSERVED | +| CAP-client-key-auth | 다운스트림 인증 및 관리 키 분리 | 그룹 access middleware → config access provider → key set. 키 목록이 비어 있으면 provider 미등록. Bearer와 provider별 header/query 형태를 받아들이며 management에는 별도 secret이 필요하다. cpa:internal/api/server_routes.go:69–70,129–150, cpa:internal/access/config_access/provider.go:13–20,55–105, cpa:internal/api/server_middleware.go:506–530, cpa:internal/api/server_management.go:29 | loopback 기본 허용, 외부 bind는 data credential 필요. Responses/WS와 Messages는 ingress별 입력을 사용한다. `/api/*` admin/GUI session 별도 gate. ocx:src/server/auth-cors.ts:400,446–451,698–700,755–783, ocx:src/server/index/serve-options.ts:562–569,681–695,1504–1515 | parity | OBSERVED | +| CAP-management-api | admin config/credential 운영 API | secret이 활성화되면 v0/v8 등록. v8의 YAML/JSON tree와 field-path mutation은 `ConfigV8`이 처리한다. cpa:internal/api/server.go:281–289, cpa:internal/api/server_management_v8.go:17–55, cpa:internal/api/handlers/management/config_v8.go:29, cpa:internal/api/handlers/management/handler.go:351,427–491 | `/api/*` 관리 gate → config/provider/OAuth handler. `/api/config`와 `/api/settings` 및 provider updates의 typed JSON 계약이 있다. CPA API 호환을 뜻하지 않는다. ocx:src/server/index/serve-options.ts:681–740, ocx:src/server/management-api.ts:372–406, ocx:src/server/management/config-routes.ts:394–407,553 | parity | OBSERVED | +| CAP-management-ui | dashboard 등록 및 asset 공급 | `/management.html` → local asset → 없으면 release asset bootstrap. non-Home 및 `disable-control-panel` gate, 자동 갱신은 별도 off 설정. cpa:internal/api/server_routes.go:58, cpa:internal/api/server_management.go:312–339, cpa:internal/managementasset/updater.go:62–118,192 | 기본 패키징 `gui/dist`를 찾아 Bun이 serve, 관리 요청은 session/secret gate. 배포된 관리 asset의 별도 GitHub updater와 제품 구조가 다르다. ocx:package.json:18–22, ocx:src/server/gui-static.ts:53–70,181–195, ocx:src/server/index/serve-options.ts:690,1910 | parity | OBSERVED | +| CAP-config-hot-reload | config와 credential 파일 변경 반영 | 일반 mode에서 fsnotify watch 생성 → YAML/auth-dir 이벤트 구분 → config debounce/hash/load → service runtime update, auth synthesis 및 client refresh. Home은 config subscriber 경로. cpa:sdk/cliproxy/service_lifecycle.go:204–231, cpa:internal/watcher/events.go:29–44,109–117, cpa:internal/watcher/config_reload.go:29–98, cpa:sdk/cliproxy/service_config.go:45–49,194,272–330 | startup JSON config 및 관리 mutation/live provider reload와 topology baseline. CLI OAuth login은 실행 중 proxy에 reload 요청을 보낸다. 임의 YAML·auth-dir drop-in의 fsnotify 동등성을 의미하지 않는다. ocx:src/server/index.ts:219–227, ocx:src/server/management/provider-routes.ts:942–1011, ocx:src/oauth/login-cli.ts:90–105, ocx:src/config/live-topology.ts:15–20 | partial | OBSERVED | +| CAP-config-schema | v8 YAML 구조와 v0 flat 호환 | `-config` → YAML decode/validation → `flattenV8` 및 load/save normalization. 설정에는 access, credential behavior, routing, request policy, OAuth, plugins, observability가 포함되고 `Home`은 로컬 YAML 입력에서 제외한다. cpa:cmd/server/main.go:171, cpa:internal/config/parse.go:55–105, cpa:internal/config/config_v8.go:77–120,278–310,536,709, cpa:internal/config/config.go:49,62–68 | `startServer`가 config를 load. JSON provider Zod schema, settings API, 이전 상태에 대한 load degradation 경로가 있다. YAML 표현 자체는 이식 대상이 아니다. ocx:src/server/index.ts:219–227, ocx:src/config/schema/leaf-validators.ts:346–371,434–435, ocx:src/server/management/config-routes.ts:379–407 | partial | OBSERVED | +| CAP-usage-per-key | key 단위 카운트의 대상 | v0 `/api-key-usage`/v8 `/observability/usage/api-keys` → manager의 **업스트림 API key auth** success/fail/recent bucket. 집계 조회는 관리 gate. usage event에는 별도 ingress access identity 문맥이 있다. cpa:internal/api/server_management.go:92, cpa:internal/api/server_management_v8.go:43, cpa:internal/api/handlers/management/api_key_usage.go:56–116, cpa:internal/redisqueue/plugin.go:63–70 | `GET /api/keys`는 설정한 **다운스트림 client key ID**에 대해 persisted ledger rollup을 제공한다. 같은 이름으로 두 통계를 합산할 수 없다. ocx:src/server/management/oauth-account-routes.ts:1392–1404, ocx:src/server/management/api-key-usage.ts:64–80,209 | partial | OBSERVED | +| CAP-usage-event-export | RESP 소비형 queue와 plugin sink | management enabled 또는 Home이 transport를 열고 usage collection은 기본 off, Home은 강제 on. usage plugin → short-retention queue → 관리 GET pop 또는 RESP LPOP/RPOP·SUBSCRIBE. cpa:internal/api/server.go:283–285, cpa:internal/config/parse.go:70–71, cpa:sdk/cliproxy/service_lifecycle.go:59–68, cpa:internal/redisqueue/plugin.go:16–31,216, cpa:internal/redisqueue/queue.go:39–98, cpa:internal/api/handlers/management/usage.go:24–36, cpa:internal/api/redis_queue_protocol.go:42,158–186 | R-G. `/api/usage`, request-history와 per-key rollup은 로컬 지속 ledger 조회다. 이 동작은 consumptive pop/pubsub wire를 제공하지 않는다. ocx:src/server/management/logs-usage-routes.ts:247, ocx:src/server/management/request-history-routes.ts:45, ocx:src/usage/log.ts:1205,1807 | gap | OBSERVED | +| CAP-request-log | 요청 로그와 기록 조회 | server에 middleware 설치 → request/error 기록 및 관리 logs 조회. 상세 request log는 `RequestLog`, commercial mode는 middleware 설치 gate. cpa:internal/api/server.go:205–220, cpa:internal/api/server_options.go:36–39, cpa:internal/api/middleware/request_logging.go:36–76, cpa:internal/api/server_management_v8.go:38–45 | ingress request log와 usage ledger, request history 및 설정 가능한 debug 조회. 응답 경로에 request log 기록이 있고 `/api/logs`·`/api/debug`·`/api/usage`는 관리 gate를 거친다. body capture/retention 계약이 차이 난다. ocx:src/server/index/serve-options.ts:1504–1537, ocx:src/server/request-log.ts:738, ocx:src/server/management/logs-usage-routes.ts:128–175,247 | partial | OBSERVED | +| CAP-credential-proxy | credential egress와 OAuth login proxy | `-login-proxy`/v8 auth session proxy → credential에 `proxy_url` 저장 → file/API key synthesis → HTTP helper가 request override, auth, global 순으로 결정한다. 명시 설정이 없으면 기존 transport·환경 경로를 사용한다. cpa:cmd/server/main.go:157, cpa:sdk/auth/manager.go:54–71,142–144, cpa:internal/api/handlers/management/auth_files_v8.go:119–128, cpa:internal/watcher/synthesizer/file.go:214–215, cpa:internal/watcher/synthesizer/config.go:141–177, cpa:internal/runtime/executor/helps/proxy_helpers.go:36–69 | R-E. `providers..proxy/noProxy`의 관리 설정은 provider 단위로 읽힌다. pool row는 key ID와 상태를 담고, egress resolver에 전달되는 설정 단위는 provider다. 분리 provider row가 우회 구성이 될 수 있다. ocx:src/server/management/provider-routes.ts:1401, ocx:src/config/schema/leaf-validators.ts:352,434–435, ocx:src/server/responses/fetch-helpers.ts:362, ocx:src/lib/provider-egress.ts:160–178 | gap | OBSERVED | +| CAP-payload-overrides | 선언적 JSON payload rules | `requests.payload` → Claude/Codex/Gemini 등 executor에서 변환 후 적용. rule이 있을 때 default/default-raw, override/override-raw, replace, filter를 model·protocol·path·header 조건에 적용한다. cpa:internal/config/config_v8.go:90, cpa:internal/config/config_types.go:686–700, cpa:internal/runtime/executor/claude_executor_execute.go:254, cpa:internal/runtime/executor/claude_executor_stream.go:248, cpa:internal/runtime/executor/gemini_executor.go:846, cpa:internal/runtime/executor/helps/payload_helpers.go:109–148,300–391 | R-F/R-K. `providerConfigSchema` 및 response effort policy에는 typed 지정값/cap이 있다. request의 임의 JSON 경로를 protocol별 조건으로 조작하는 운영자 규칙 엔진과는 범위가 다르다. ocx:src/config/schema/leaf-validators.ts:346–371, ocx:src/server/effort-policy.ts:170,207,249 | gap | OBSERVED | +| CAP-control-plane | Home worker/cluster mode | compose는 한 worker에 `HOME_JWT`를 요구한다. `-home-jwt` → mTLS bootstrap 및 remote config → subscriber, membership discovery 및 Home credential dispatch. local watcher·일반 management 대신 Home gate가 적용된다. cpa:docker-compose.cluster.yml:1–29, cpa:cmd/server/main.go:176–177,290–294,359–379, cpa:internal/home/certificate.go:59, cpa:internal/home/client.go:813–847, cpa:sdk/cliproxy/service_home.go:391–398,547, cpa:sdk/cliproxy/auth/conductor_home_execution.go:156–268 | R-C. OpenCodex `/api/link`에서 standalone/client/hub enrolment·relay 제어가 있지만 요청별 CPA Home credential dispatch나 `CLUSTER NODES` 계약은 없다. ocx:src/server/management/link-routes.ts:720–824, ocx:src/server/index/serve-options.ts:696–707, ocx:src/config/schema/leaf-validators.ts:967 | gap | OBSERVED | +| CAP-credential-store-backends | 외부 credential/config persistence | `cmd/server/main.go`의 opt-in env로 Postgres/Object/Git 선택, startup config mirror 및 token store 등록. 로컬 기본은 파일이며 Home은 세 store를 끈다. cpa:cmd/server/main.go:296–346,459–569,642–649 | R-C. credential 저장 `src/oauth/store.ts`, provider key의 opt-in OS keychain, Link enrollment 별도 경로. 세 외부 credential store 및 config mirror 계약을 구현하는 근거는 없다. ocx:src/server/management/oauth-account-routes.ts:1299–1323, ocx:src/server/management/link-routes.ts:804–824 | gap | OBSERVED | +| CAP-plugin-host | native plugin loading·capability dispatch | `plugins.enabled`와 개별 item 설정 → `Host.ApplyConfig` → 지원 platform loader의 ABI 검사 → auth/exec/model/translation/scheduler/sink/management 등록. v0/v8 store install 및 plugin management route도 등록된다. cpa:internal/pluginhost/config.go:38–64, cpa:internal/pluginhost/host.go:223–286, cpa:internal/pluginhost/loader_unix.go:179–232, cpa:sdk/cliproxy/service_plugins.go:89–147, cpa:internal/api/server_management_v8.go:65–71, cpa:internal/api/handlers/management/plugin_store.go:231 | R-B. Bun의 공개 adapter/programmatic API와 소스 제공 provider registry가 근접하다. 실행 중 native capability plugin lifecycle와 ABI 로더 계약은 없다. ocx:src/index.ts:1–21, ocx:src/providers/registry/entries-core.ts:718–726 | gap | OBSERVED | +| CAP-plugin-distribution | Home plugin distribution | `Home.Enabled && Plugins.Enabled` → installed-version/platform 요청 → `GetPluginSync` resolved manifests 또는 server 미지원 시 legacy sync → 플랫폼별 설치와 load/status 처리. cpa:sdk/cliproxy/home_plugins.go:48–106, cpa:internal/home/client.go:1629, cpa:internal/homeplugins/sync.go:126,199,319–350,677, cpa:sdk/cliproxy/service_home.go:164–210 | R-B/R-C. Link의 managed child 제어와 OpenCodex 패키지 업데이트는 있다. Home이 별도 plugin 아티팩트를 해석해 동기화·로드 상태를 보고받는 계약은 없다. ocx:src/server/management/link-routes.ts:819–824, ocx:src/server/management/config-routes.ts:998–1053 | gap | OBSERVED | +| CAP-sdk-embedding | proxy in-process embedding | CLI도 `NewBuilder`에서 build/run. explicit config/path, SDK hooks, access/auth manager 및 watcher/executor 주입, `RegisterUsagePlugin`. cpa:internal/cmd/run.go:34–59, cpa:sdk/cliproxy/builder.go:109–245,271–282, cpa:sdk/cliproxy/service_lifecycle.go:34,176–201, cpa:sdk/cliproxy/service_plugins.go:62–68 | 패키지 Bun export에서 `startServer`, config, adapter, bridge를 노출하고 `Bun.serve`로 실행한다. 언어 차이만으로 gap을 만들지 않는다. CPA builder의 주입 표면은 더 넓다. ocx:package.json:5–13, ocx:bin/package-main.mjs:4–9, ocx:src/index.ts:1–21, ocx:src/server/index.ts:213–227,684 | partial | OBSERVED | +| CAP-oauth-siwc | 기존 Codex credential에 보조 SIWC bind | `-siwc-bind` 또는 v8 `POST /oauth/siwc/bind` → 기존 credential에 대해서만 명시적 bind 시작과 상태 조회 → outer grant와 독립 refresh due. cpa:cmd/server/main.go:174,687, cpa:internal/api/server_management_v8.go:59–61, cpa:internal/api/handlers/management/oauth_siwc.go:54,165,219–222, cpa:sdk/cliproxy/auth/types.go:1332–1376 | R-I. OpenCodex의 `chatgpt` 로그인과 account refresh는 outer credential 경로다. 기존 Codex credential에 별도 SIWC OAuth grant를 binding하고 갱신하는 계약을 찾지 못했다. ocx:src/oauth/index.ts:397,599,1635, ocx:src/server/management/oauth-account-routes.ts:278–364 | gap | OBSERVED | +| CAP-amp-integration | Amp legacy와 대체 표면 | 해당 키는 legacy cleanup에서 제거된다. source 검색에도 활성 Amp route/module은 없었고, OAuth/management·Muse Code·Codex direct route는 각자의 entry다. cpa:internal/config/config_yaml.go:1018–1020, cpa:internal/api/server_routes.go:129–146 | R-D의 hits는 `stampCodex…`/locale 문자열이다. OpenCodex client export는 별도 표면이다. 동작하는 CPA Amp capability 증거가 없어 추격 대상으로 세지 않는다. ocx:src/clients/config-export.ts:1504,1845 | n/a | OBSERVED | + +### OpenCodex 부재 검색 영수증 + +전부 `9e0e298ef9` 고정 export다. 아래 `O`는 `/Users/jun/Developer/new/700_projects/opencodex/.tmp/chase/opencodex-dev`다. 각 행의 정확한 실행 형식은 `rg -il '' "$O/src" "$O/gui/src" "$O/docs-site" "$O/structure"`이며 `O`에 위 경로의 절대값을 전달했다. 표의 `\|`는 검색 패턴의 `|`다. 표의 가장 가까운 구현을 확인한 뒤 위 인벤토리에서 겹치지 않는 계약을 기술했다. + +| Receipt | `` | exit / hit 파일 수 | 확인한 가장 가까운 결과 | +| --- | --- | --- | --- | +| R-A | `smooth.weighted\|weighted.round.robin\|credential.*weight\|weight.*credential` | 0 / 10 | Cursor 및 Anthropic/Codex 가중·quota 정책, `src/config/schema/leaf-validators.ts:371`의 API key 전략. | +| R-B | `home.plugin.sync\|plugin.abi\|plugin.host\|dlopen\|LoadLibrary\|plugin.store\|RegisterUsagePlugin` | 0 / 21 | native OS 호출과 process 유틸 관련 hits. `src/index.ts:1–21`의 Bun programmatic exports 및 `src/server/management/link-routes.ts:819–824`의 배포 제어. | +| R-C | `PGSTORE_DSN\|GITSTORE_GIT_URL\|OBJECTSTORE_ENDPOINT\|CLUSTER NODES\|COPROXY\|docker-compose.cluster\|credential.store.backend\|home-jwt` | 1 / 0 | `src/server/management/link-routes.ts:720–824`, `src/server/management/oauth-account-routes.ts:1299–1323`. | +| R-D | `ampcode\|amp-module\|amp cli\|amp-upstream` | 0 / 3 | Codex quota 관측 함수 이름과 locale 문자열. `src/clients/config-export.ts:1504`가 가까운 확장 표면이다. | +| R-E | `proxyUrl\|proxy-url\|proxy_url\|credential.*proxy` | 0 / 85 | `src/lib/provider-egress.ts:160–178`, `src/config/schema/leaf-validators.ts:352,434–435`, `src/server/responses/fetch-helpers.ts:362`. | +| R-F | `payload.*override\|override.*payload\|json.path.*(filter\|override)\|default-raw\|override-raw` | 0 / 6 | compaction 설정/ledger/UI 및 request override 주변 코드. `src/server/effort-policy.ts:170,207,249`의 typed 처리도 확인. | +| R-G | `redis.*usage\|usage.*redis\|usage.queue\|RESP2\|BRPOP\|LPOP` | 0 / 5 | 대시보드 문자열과 `src/server/management/logs-usage-routes.ts:247`의 ledger 조회, `src/usage/log.ts:1205,1807`. | +| R-H | `credential.*cooldown.*(store\|persist)\|save.cooldown.status` | 0 / 4 | 구조 문서 hits. 실제 API key 상태는 `src/providers/api-key-cooldowns.ts:1–26`의 process-local map, `src/providers/key-failover.ts:491–522`에서 소비. | +| R-H2 | `setKeyCooldown\|sweepExpiredApiKeyCooldowns\|clearKeyCooldowns` | 0 / 6 | 등록된 동작은 write/clear와 TTL sweep이다. `src/lib/state-store-registrations.ts:129–135`, `src/providers/key-failover.ts:839–843,937–940`. | +| R-I | `oauth.*siwc\|siwc.*oauth\|siwc.bind` | 1 / 0 | `src/oauth/index.ts:397,599,1635`의 기본 ChatGPT grant. | +| R-K | `payload.rule\|ApplyPayloadConfig\|payload.*(override\|filter)\|default-raw\|override-raw\|json.path.*(filter\|override)` | 0 / 13 | native Messages의 wire override 등 좁은 policy와 SSE rewrite 관련 hits. `src/server/messages-native.ts:1452`의 override는 전송 format 선택이다. | + +### 6월 chase 대사 + +| CAP tag | 이전 행 | 판정 | +| --- | --- | --- | +| CAP-oauth-vertex | `20_cli-proxy-api.md:25,48,65–66` 및 `02_gap_inventory.md:12,25` | **닫힘.** `CAP-oauth-vertex`의 등록 → keychain marker → OAuth bearer 증거. CPA 선례의 grant도 서비스 계정 token exchange다. | +| CAP-oauth-xai | `20_cli-proxy-api.md:26,40,49,67` 및 `02_gap_inventory.md:12,26` | **인증 gap 없음.** 이전 행도 xAI OAuth 존재를 기록했다. 현재 OpenCodex에서 callback/device/import/refresh를 보았다. `reasoning replay/WS` 문구는 인증과 분리해 L1로 보낸다. | +| CAP-oauth-codex / CAP-oauth-claude / CAP-oauth-antigravity / CAP-oauth-kimi | `20_cli-proxy-api.md:39–47` | 양쪽 OAuth 등록 유지. Kimi domain과 Codex SIWC 추가 grant는 별도 행에서 판단한다. Wire parity는 L1 범위다. | +| CAP-oauth-kiro | `20_cli-proxy-api.md:27,50` 및 `02_gap_inventory.md:12` | 내장 Kiro OAuth/adapter 등록 기준으로 OpenCodex 선행 유지. | +| CAP-oauth-antigravity | `02_gap_inventory.md:22`의 Google Gemini CLI OAuth | legacy Gemini CLI provider와 Antigravity OAuth는 다른 로그인·프로젝트 identity다. 현행 CPA 내장 CLI/auth manager 및 OpenCodex Gemini native gate에서 이전 migration 제외 결정을 바꿀 근거가 없다. cpa:internal/cmd/auth_manager.go:13–25, ocx:src/server/gemini-native.ts:74–83 | + +## 4. Gap candidates + +공통 구현 제약은 core→Lab import 금지, 소유 `structure/` 문서 갱신, capped 파일의 sibling 분리, 관리 DTO 및 로그에서 credential·proxy 비밀 보호다. quota를 읽는 동작과 유상 credit 소비는 별도이며 opt-in/consent를 유지한다. 표의 후보에는 확인된 gap의 단계적 축소판과 `partial` 행의 보강도 포함된다. + +| ID | CAP tag | 빠진 동작과 가치 | 노력 및 likely OpenCodex target | 의존성·위험 | +| --- | --- | --- | --- | --- | +| L2-1 | CAP-credential-proxy | **high** · 같은 provider pool에서 credential별 `proxy/noProxy`, 로그인·refresh·execution 일관성. 여러 계정 때문에 provider를 분리하는 비용을 낮춘다. | **L** · `src/providers/api-key-resolve.ts`, `src/lib/provider-egress.ts`, `src/oauth/types.ts`, `src/server/responses/fetch-helpers.ts`, 관리/UI. HTTP까지만 먼저 범위를 고정할 수 있다. | account selection snapshot, generation 및 connection isolation 선행. WebSocket/SDK와 OAuth transport의 명시 정책, proxy secret redaction, mode 변경 시 stale send 방지. | +| L2-2 | CAP-cooldown-persistence | **high** · API key pool의 이미 확인된 quota cooldown을 정상 재시작과 live recycle에 복원. | **M** · `src/providers/api-key-cooldowns.ts`, `src/providers/key-failover.ts`, `src/server/lifecycle.ts`의 sibling store/lifecycle. | credential ID·generation으로 삭제/교체를 구별하고 쿨다운 재적용/만료/clock drift를 다룬다. raw key나 upstream body 저장은 피한다. 이후 OAuth scope는 독립 단계다. | +| L2-3 | CAP-credential-files | **med** · 기존 account 관리에 provider-independent 모델 eligibility/refresh 결과를 읽는 진단 DTO와 명시적 검증 UI 보강. | **M** · `src/server/management/oauth-account-routes.ts` sibling, `src/oauth/account-import/`, `src/providers/quota/`. | probe/refresh/유상 completion을 구별, per-account refresh mutex·generation 사용, token JSON 다운로드를 기본화하지 않는다. 읽기 위주 UI가 선행 가능. | +| L2-4 | CAP-payload-overrides | **med** · 호환 endpoint별 모델/protocol에서 반복되는 소수 default/drop을 운영자가 지정. | **L** · 별도 `src/config/schema/` leaf 및 `src/adapters/` post-translation hook, 검증된 allowlist부터. | canonical validation, tool safety, fallback/WS 일관성, body/header redaction. Lab 정책 의존을 core에 추가하지 않는다. 자유로운 body rewrite는 별도 검토. | +| L2-5 | CAP-credential-pool-weighted | **med** · 소규모 팀에서 남은 quota와 독립적인 operator 지정 배분. | **M** · `src/oauth/pool-kernel.ts`, `src/oauth/pool-settings-capability.ts`, `src/providers/key-failover.ts`, 관리/UI. | priority/deny/affinity/cooldown가 weight보다 우선하는 계약 필요. 후보 peek는 cursor를 전진시키지 않고 실제 admission에서만 반영. | +| L2-6 | CAP-usage-event-export | **med** · 외부 집계기가 cursor 기반으로 읽는 관리 전용 usage events. | **M** · `src/usage/log.ts`, `src/server/management/request-history-routes.ts` sibling에서 cursor/retention 계약 추가. | ledger와 idempotency, audit 권한 및 redaction. CPA 호환 RESP server는 **reject candidate**. 작은 팀에 필요한 것은 안정적 export다. | +| L2-7 | CAP-oauth-siwc | **low** · 기존 Codex credential에 secondary SIWC bind/renew. | **L** · 도입한다면 `src/codex/`의 전용 grant와 명시적 관리 session. | **reject candidate** · 필요로 하는 기본 Codex/Claude Code proxy 사용자군을 확인하지 못했다. 별도 user consent·token 저장·회전 수명주기 및 provider 허용 계약이 필요하다. | +| L2-8 | CAP-control-plane / CAP-credential-store-backends | **low** · Home scheduling 및 multi-backend credential/config mirror. | **XL** · 새로운 control plane, worker protocol 및 저장 adapter. | **reject candidate** · 현재 목표는 로컬 프록시/소규모 공유. Link/hub 운영과 다른 HA/저장·키 소유권 제품이며 전용 threat model과 운영 주체가 필요. | +| L2-9 | CAP-plugin-host / CAP-plugin-distribution | **low** · native ABI host와 remote artifact 수명주기. | **XL** · host isolation, SDK/ABI, provenance/rollbacks, plugin management 표면. | **reject candidate** · Bun 기본 경로에 배포·심사 부담을 추가한다. community scheduler 사례에서 필요한 정책만 built-in 후보로 평가할 수 있다. | + +## 5. OpenCodex 선행 + +- 내장 Kiro 로그인·adapter와 xAI OAuth flow 선택지가 `CAP-oauth-kiro`/`CAP-oauth-xai`의 관찰된 우위다. +- OpenCodex는 요청 이력과 관련된 downstream key ID rollup을 지속 ledger에서 제공한다. CPA의 관리 API key usage는 upstream auth bucket이다. 이 차이를 “CPA usage 없음”으로 표현하면 CPA의 plugin sink/queue를 누락하게 된다. +- reset-near weighted Codex/Anthropic 및 quota-based fill-first는 `CAP-credential-pool-weighted`의 operator 지정 static weight와 다른 기능이다. 로컬 계정 소진·재사용에 이미 쓰는 정책을 유지한 채 소규모 팀의 고정 배분을 검토할 수 있다. + +## 6. 최신 사례 (Aside) + +공개 GitHub 페이지를 Aside `u0/local`에서 읽었다. 기준일은 2026-11-23 KST다. Release·PR의 진술과 pinned source를 함께 확인한 경우에도 태그 ancestry나 runtime 결과를 추정하지 않았다. 확인한 사례 중 날짜가 CPA 고정 head 이후인 사례는 없다. + +| 발행일 | release/commit/PR | 출처 | 접근일 | 관찰 | OpenCodex 관련성 | 확신 | +| --- | --- | --- | --- | --- | --- | --- | +| 2026-11-22 UTC | CPA v8.1.1 · `6eb8554` | [릴리스](https://github.com/router-for-me/CLIProxyAPI/releases/tag/v8.1.1) | 2026-11-23 | v8 management에 Copilot OAuth 추가, Linux 기본과 no-plugin 빌드 구분. Copilot 분기를 cpa:internal/api/handlers/management/auth_files_v8.go:420–421, ABI 검사 경로를 cpa:internal/pluginhost/loader_unix.go:179–232에서 확인. | 일반적인 로그인 UI는 provider별 pending/device 상태를 표현해야 한다. native plugin은 배포 품목을 늘린다. | 높음 · 공식 release+source | +| 2026-11-09 UTC (merge) | CPA PR #7370 | [로그인 프록시 PR](https://github.com/router-for-me/CLIProxyAPI/pull/7370) | 2026-11-23 | CLI OAuth flow에 지정한 proxy를 credential의 다음 요청에도 연결하는 변화. cpa:cmd/server/main.go:157 및 cpa:sdk/auth/manager.go:54–71,142–144에서 저장까지를 확인. | L2-1은 요청 transport만 바꾸면 로그인/refresh egress와 불일치할 수 있다. | 높음 · merged PR+source | +| 2026-11-07 UTC (merge) | CPA PR #7311 | [SIWC 갱신 PR](https://github.com/router-for-me/CLIProxyAPI/pull/7311) | 2026-11-23 | SIWC의 독립 renewal window와 macOS maintenance wake deferral 변경. pinned source의 window 계산과 outer/inner 분리 확인. cpa:sdk/cliproxy/auth/types.go:1332–1376, cpa:sdk/cliproxy/auth/conductor_refresh.go:160–167 | grant 추가는 저장할 필드와 background renew 조건을 늘린다. L2-7 effort 근거. | 높음 · merged PR+일부 source | +| 2026-10-15 | CPA issue #6646, open | [긴 cooldown 보고](https://github.com/router-for-me/CLIProxyAPI/issues/6646) | 2026-11-23 | 보고자는 모든 credential이 cooled일 때 긴 `Retry-After`를 transient 429로 소비하는 클라이언트를 보고했다. 현재 source에 model cooldown header와 bounded server wait는 있다. issue의 전체 재현 및 linked fix 상태는 확인하지 않았다. cpa:sdk/cliproxy/auth/selector.go:403, cpa:sdk/cliproxy/auth/conductor_selection.go:1948–1956 | pool의 다음 가능 시점과 같은 요청을 재시도해도 되는지의 정보를 구분할 필요가 있다. | 중간 · 사용자 보고+관련 source | +| 2026-11-16 | Weekly Quota Router v0.1.2, community | [Discussion #7604](https://github.com/router-for-me/CLIProxyAPI/discussions/7604) | 2026-11-23 | 작성자는 주간 reset 우선, 5h quota fallback, 확인된 quota 회복 후 복귀 및 shadow 기본값을 게시했다. CPA의 scheduler 호출 표면은 cpa:internal/pluginhost/scheduler.go:11–65에서 확인. plugin의 실제 동작은 작성자 보고다. | L2-5와 별개로 reset 시점·fresh evidence를 우선하는 로컬 정책 수요가 있다. | 중간 · community 보고+host source | +| 2026-11-20 | Sub2API v0.2.24 · `5c2982a` | [릴리스](https://github.com/Wei-Shaw/sub2api/releases/tag/v0.2.24) | 2026-11-23 | UI가 수동 token refresh 반복과 background refresh 충돌 가능성을 안내한다. pinned Sub2API `328db26f45`의 action tooltip과 번역 키에서 같은 안내를 확인. s2a:frontend/src/components/admin/account/AccountActionMenu.vue:36, s2a:frontend/src/i18n/locales/en/admin/accounts.ts:507 | L2-3의 refresh action은 현재 진행 중인 refresh 상태를 보여주고 중복을 합칠 수 있다. | 높음 · 공식 release+source | + +## 7. Deferred checks + +- OAuth별 실제 브라우저 callback, device code timeout/cancel/re-login, Kimi 도메인, Copilot catalog와 Devin/Meta scope, per-provider refresh journal의 crash recovery를 실행하지 않았다. +- CPA `disable-cooling`의 per-auth override, request-scoped errors, mixed provider priority 및 weighted reservation의 모든 transport edge, preview/project switch 설정의 git history는 별도 심화 대상이다. 명칭이 비슷한 quota mode 사이의 wire 결과는 추정하지 않았다. +- Dashboard 외부 asset의 UI 메뉴·TUI 전체 화면, standalone SQL/Object/Git store의 충돌·failover와 Home server-side scheduler의 내부 구현은 읽지 않았다. 비교는 pinned CPA worker의 호출과 gate까지다. +- Native plugin callback ABI 전체, Windows/no-CGO 배포, 설치 checksum과 store authentication, Home plugin retry/delete/status의 모든 분기는 표면과 일부만 읽었다. 릴리스·직접 artifact 설치의 checksum entry는 확인했다. cpa:internal/pluginstore/install.go:116–133,146–169 +- OAuth/login 외 xAI replay/WS, Codex WS frame fidelity, Claude event 변환은 L1로 넘긴다. 이 문서의 WS/SSE 읽기는 auth/admission/credential selection에 집중했다. +- 외부 라이브 사용량 수집기와 community plugin의 코드 또는 아티팩트를 실행하지 않았다. + +## 8. NOT RUN + +- **NOT RUN:** 빌드, 테스트, 서버 기동, 릴리스 검증, OAuth 및 데이터·관리 API 실제 호출, plugin 설치/로드, cluster 접속. +- **NOT RUN:** Aside codemode의 rendered batch는 `/Users/jun/.local/bin/codemode --cwd /Users/jun/Developer/new/700_projects/opencodex --account u0 --host local --code -`에서 `status=indeterminate`, `complete=false`, `partial=["no-marker"]`를 반환했다. 같은 공개 페이지는 native `/Users/jun/.local/bin/aside repl --account u0 --host local --file -`로 열어 위 표의 직접 소스를 확인했다. diff --git a/devlog/_plan/261123_proxy_upstream_catchup/003_ccswitch.md b/devlog/_plan/261123_proxy_upstream_catchup/003_ccswitch.md new file mode 100644 index 00000000000..64e5122b559 --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/003_ccswitch.md @@ -0,0 +1,190 @@ +# 003 — CC Switch 클라이언트 전환과 로컬 라우팅 (L3) + +## 1. 요약 + +- 비교 기준은 CC Switch `f19a9d4f4f08bda03106a7be87c77cbcdf55b019`과 OpenCodex `origin/dev` `9e0e298ef9720cfeaa1209f090a68e4d1965d2a1` export다. 아래 `ccs:`와 `ocx:`는 각각의 고정 트리를 가리킨다. +- Codex·Claude Code 사용자에게 우선순위가 높은 차이는 앱별 현재 목적지와 전환 결과를 한곳에서 보는 경험이다. CC Switch는 직접 연결과 로컬 라우팅의 선택을 별도로 유지한다. OpenCodex에는 이미 `sync`, 네이티브 토글, Claude 실행기와 설정 복구 경로가 있다. +- 직접 전환은 Codex의 TOML·인증·카탈로그, Claude의 JSON 키, Gemini의 dotenv·JSON처럼 클라이언트의 파일 계약을 따른다. 같은 파일을 여러 기능이 쓸 경우 공용 쓰기 조정과 중단 복구가 중요하다. +- 소규모 팀에는 키를 따로 넣는 공급자 가져오기와 설치 직후의 연결 진단이 유용하다. OpenCodex는 CC Switch 파일을 읽는 키 없는 미리보기를 이미 제공한다. URL 열기로 시작하는 공급자 가져오기는 별도 기능이다. +- CC Switch의 세션 기반 비용 집계는 프록시를 거치지 않는 실행까지 포함한다. OpenCodex의 프록시 사용량에는 이미 기기·요청 출처가 있으므로 두 데이터의 중복과 추정치를 표현하는 것이 선행 과제다. +- CC Switch의 WebDAV/S3는 관리 DB와 Skills 스냅샷을 복원한다. OpenCodex Remote Link는 Home과 Child의 라우팅·카탈로그를 맞춘다. 클라우드 백업과 팀용 라이브 라우팅의 필요를 각각 평가할 수 있다. +- Codex Responses WebSocket은 OpenCodex가 구현한다. CC Switch의 같은 경로에서 GET 업그레이드는 426을 반환하고 POST는 HTTP/SSE로 처리한다. + +## 2. 표면 맵 + +### CC Switch IPC와 UI + +| 등록된 표면 | 등록 및 구현 경로 | +|---|---| +| 공급자·설정 | 조회/읽기 실패 행/현재 값/추가/편집/삭제/라이브 추가·제거/전환/기본 가져오기, Claude Desktop·Grok 공식 카드, 설정 경로·오류·마이그레이션·Codex 이력/압축, 로그·프라이버시·최적화 설정. `ccs:src-tauri/src/lib.rs:1553–1597`. 폼의 앱별 프리셋 선택은 `ccs:src/components/providers/forms/ProviderForm.tsx:1004–1045`, `:2229`, 카드 이벤트는 `ccs:src/App.tsx:1678–1681`, `ccs:src/hooks/useProviderActions.ts:226` → `ccs:src/lib/query/mutations.ts:343` → `ccs:src/lib/api/providers.ts:182–187`. | +| 업데이트·플러그인·공식/제3자 잔액 | 설치·재시작, portable 경로와 상태/다운로드/확인, 클라이언트 플러그인 설치·목록·토글·삭제·업데이트·마켓, Claude 플러그인/온보딩, 공급자 사용량 스크립트·구독/플랜/잔액. `ccs:src-tauri/src/lib.rs:1598–1630`. | +| MCP·프롬프트·프로필 | MCP 목록/검사·취소/CRUD/앱 토글/가져오기/재동기화, 프롬프트 CRUD/활성화/파일 가져오기·위치·본문, Pi 템플릿/네이티브 공급자·세션, OMP 네이티브 상태, 프로젝트 프로필 CRUD/적용/해제. `ccs:src-tauri/src/lib.rs:1632–1668`. | +| 연결 진단·이동·백업 | 모델 조회, 엔드포인트 속도·사용자 지정 후보 관리, 앱 경로/정렬, SQL 입출력, WebDAV/S3 연결·업로드·다운로드·설정·메타데이터, 파일 대화상자, DB/기타 백업 목록·복원·이름·삭제·폴더 열기, 라이브 재투영, Deep Link 대기열/전처리/import, 환경 변수 충돌·삭제. `ccs:src-tauri/src/lib.rs:1669–1720`. | +| Skills | 설치/삭제/백업/복원/앱별 플래그, 리포지터리·토큰, 발견/검색/갱신, 로컬 가져오기·ZIP·재투영·저장 위치 이동. `ccs:src-tauri/src/lib.rs:1721–1749`. | +| 로컬 프록시/트레이 | 자동 실행, 서버 시작·정지·복원, 앱 모드·라우트·Stack·Codex 카탈로그 갱신, 트레이 페이지·패널·작업, 프록시 전역 및 앱별 설정, failover 큐/상태/자동 전환. `ccs:src-tauri/src/lib.rs:1750–1791`. | +| 통계·세션·도구 | 요약/시계열·공급자/모델/요청별 조회, 가격 편집·models.dev·환율, 세션 기반 집계/재구축, 스트림 프로브, 세션 목록·인덱스·검색/취소·메시지·이미지·내보내기·삭제·터미널, 설치 탐지·도구 수명주기. `ccs:src-tauri/src/lib.rs:1792–1838`. | +| 공유 카드·클라이언트별 보조 작업 | Universal provider CRUD/투영, 아이콘, OpenCode의 라이브 가져오기·기본 모델·OMO/Slim, OpenClaw의 카탈로그·환경·도구·워크스페이스, Hermes 모델/메모리/대시보드, 전역 업스트림 프록시·테마, managed auth와 Agy/WorkBuddy/Claude/Kimi/DSH/Copilot 계정·쿼터. `ccs:src-tauri/src/lib.rs:1839–1942`. | +| OS 진입점 | 단일 인스턴스 콜백·Tauri `on_open_url`·플랫폼별 등록, 시작 시 복구, 트레이 콜백과 종료. `ccs:src-tauri/src/lib.rs:499`, `:534`, `:1179–1217`, `:1246`, `:1406`, `:1949–1994`. | + +### CC Switch 클라이언트 16종 + +`AppType::ALL`과 `AppSpec`이 등록/분기 기준이다. `stack`은 Claude Code, Claude Desktop, Codex에서만 true다. MCP와 Skills의 앱 플래그는 14종으로 Claude Desktop과 OpenClaw를 제외한다. 개별 투영 방법과 설치 가능 여부는 서비스에서 다시 결정한다. `ccs:src-tauri/src/app_config.rs:48–103`, `:353–498`, `ccs:src-tauri/src/services/mcp.rs:365–401`, `:491`, `ccs:src-tauri/src/services/skill/sync.rs:480–489`. + +| CAP tag | 클라이언트·모드 | 관리 대상 및 gate | +|---|---|---| +| CAP-client-config-claude | Claude Code · 직접/라우팅/Stack | `settings.json`의 `env`와 전환 키. MCP는 별도 `~/.claude.json`. `ccs:src-tauri/src/config.rs:286–310`, `ccs:src-tauri/src/services/provider/mod.rs:7740–7759`. | +| CAP-client-config-claude-desktop | Claude Desktop · 직접/라우팅/Stack | 3P config library, 공식/직접 가능 카드 또는 라우팅 필요 카드. `ccs:src-tauri/src/claude_desktop_config.rs:306`, `ccs:src-tauri/src/services/provider/mod.rs:7720–7733`. | +| CAP-client-config-codex | Codex · 직접/라우팅/Stack | `config.toml`, `auth.json`, 모델 카탈로그, managed OAuth 소유 기록. `ccs:src-tauri/src/codex_config.rs:293`, `:844–846`, `ccs:src-tauri/src/services/provider/mod.rs:7769–7804`. | +| CAP-client-config-gemini | Gemini CLI · 직접/라우팅 | `.gemini/.env`와 `settings.json`의 인증 종류·기본 모델. `ccs:src-tauri/src/gemini_config.rs:9–19`, `:258–262`, `ccs:src-tauri/src/services/provider/gemini_direct.rs:38–62`, `:83–113`. | +| CAP-client-config-grok | Grok Build · 직접/라우팅 | `config.toml`의 모델/공급자 선택. 직접 변경은 전용 엔진, proxy는 독립 Responses 네임스페이스. `ccs:src-tauri/src/grok_config.rs:31–32`, `ccs:src-tauri/src/services/provider/mod.rs:7809`, `ccs:src-tauri/src/proxy/server.rs:363–365`. | +| CAP-client-config-opencode | OpenCode · 추가형 | JSONC 우선, JSON 대체. `provider`(V1), `providers`(V2) 조각 추가/제거, 기본 모델 명령, OMO/Slim 상호 배타 경로. `ccs:src-tauri/src/opencode_config.rs:59–72`, `:456`, `:513–566`, `ccs:src-tauri/src/services/provider/mod.rs:7627–7636`, `ccs:src-tauri/src/lib.rs:1850–1853`, `:1926–1932`. | +| CAP-client-config-openclaw | OpenClaw · 추가형 | `openclaw.json`과 별도 백업, 기본 모델/카탈로그/agents/env/tools와 워크스페이스 파일 명령. `ccs:src-tauri/src/openclaw_config.rs:46–47`, `:376`, `ccs:src-tauri/src/lib.rs:1855–1868`, `:1933–1942`. | +| CAP-client-config-hermes | Hermes · 추가형 | `config.yaml`, 모델/메모리 설정, 런처. `ccs:src-tauri/src/hermes_config.rs:101–102`, `ccs:src-tauri/src/lib.rs:1870–1878`. | +| CAP-client-config-pi | Pi · 추가형 | `models.json`의 명시적 공급자, 자체 enable과 프롬프트 파일/템플릿 경로. `ccs:src-tauri/src/pi_config/mod.rs:75–76`, `:243–246`, `ccs:src-tauri/src/services/provider/mod.rs:7462–7465`, `ccs:src-tauri/src/lib.rs:1650–1659`. | +| CAP-client-config-mcode | MiniMax Code · 추가형 | `config.yaml` 커스텀 모델과 클라이언트 플러그인. `ccs:src-tauri/src/mcode_config.rs:99–100`, `ccs:src-tauri/src/services/plugin_manager/mcode.rs:1–3`. | +| CAP-client-config-kimi | Kimi Code · 추가형 | `config.toml`과 프로필 인증 조건. 추가와 현재 선택이 별도이며 전환이 `switch_and_commit`으로 이어진다. `ccs:src-tauri/src/kimi_config.rs:97`, `ccs:src/App.tsx:460`, `ccs:src-tauri/src/services/provider/mod.rs:7514–7526`. | +| CAP-client-config-dsh | DeepSeek Harness · 추가형 | YAML 프로필 계열, `save_and_commit`으로 라이브 상태와 DB를 묶는다. `ccs:src-tauri/src/services/provider/mod.rs:7503–7512`, `ccs:src-tauri/src/dsh_config.rs:129`, `:997`. | +| CAP-client-config-agy | Antigravity CLI · 카드별 실행 | `.gemini/antigravity-cli/settings.json`과 공유 customizations. 카드 전환은 거절하고 카드에서 터미널로 실행한다. `ccs:src-tauri/src/agy_config.rs:32–41`, `:224–239`, `ccs:src-tauri/src/services/provider/mod.rs:7466–7472`. | +| CAP-client-config-omp | Oh My Pi · 추가형 | 프로필별 `models.yml`·`config.yml`, 고유 enable. `ccs:src-tauri/src/omp_config.rs:182–202`, `ccs:src-tauri/src/services/provider/mod.rs:7481–7483`. | +| CAP-client-config-copilot | GitHub Copilot CLI · 추가형 | BYOK `providers.json`과 설정의 override, 공식 카드는 터미널용. 추가는 Copilot 자체 기본 모델 선택을 유지한다. `ccs:src-tauri/src/copilot_config.rs:109–131`, `ccs:src-tauri/src/services/provider/mod.rs:7474–7478`. | +| CAP-client-config-workbuddy | WorkBuddy · 추가형 | `models.json`에 BYOK 후보 추가. 공식 카드의 추가 동작은 계정 선택 경로를 사용한다. `ccs:src-tauri/src/workbuddy_config.rs:55`, `ccs:src-tauri/src/services/provider/mod.rs:7492–7500`. | + +### 로컬 HTTP와 OpenCodex 비교 진입점 + +| 표면 | 등록된 진입점 | +|---|---| +| CC Switch 상태·Claude | GET `/health`, `/status`. POST `/v1/messages`, `/claude/v1/messages`. Claude Desktop 3P GET `/claude-desktop/v1/models`, POST `/claude-desktop/v1/messages`. `ccs:src-tauri/src/proxy/server.rs:309–325`. | +| CC Switch OpenAI | GET `/models`, `/v1/models`. Chat POST에 무접두/`/v1`/`/v1/v1`/`/codex/v1` 별칭. Responses와 compact도 같은 접두 조합이며 Responses GET은 426 핸들러. Grok Build는 `/grokbuild/v1/responses`와 `/compact` POST. `ccs:src-tauri/src/proxy/server.rs:327–386`. | +| CC Switch 나머지 | Alpha Search와 images generations/edits POST에 위 네 접두 조합. Gemini any-method `/v1beta/*path`, `/gemini/v1beta/*path`, `/gemini/v1/*path`. `ccs:src-tauri/src/proxy/server.rs:388–431`. | +| OpenCodex CLI | `start`, `sync`/`sync-cache`, `connect`/`link`/`disconnect`, `restore`, `codex-shim`, `claude`/`claude desktop`, `opencode`, `integration `, `provider`/`alias`/`fallback`/`usage`, `config`/`export`/`tray`/`update`. `ocx:src/cli/dispatch.ts:418–482`, `:596–680`, `:762–906`, `:921–946`. | +| OpenCodex 파일·실행기·GUI | Native와 managed file integrations는 별도 API. Preview/apply/disable/history/restore와 클라이언트별 registry 및 format exporters. Gateway connectors는 `agy`와 `antigravity`. `ocx:src/server/management-api.ts:396–398`, `ocx:src/server/management/integration-routes.ts:748`, `ocx:src/clients/client-ids.ts:1–7`, `ocx:src/integrations/registry.ts:283–535`, `ocx:src/integrations/gateway-clients/index.ts:14–19`, `ocx:src/server/management/gateway-client-routes.ts:12–38`. | +| OpenCodex Remote Link·데스크톱 | 연결 모드에서 `syncConnectedClient`로 원격 카탈로그/선택 설정을 적용한다. `link`의 SSH 전송·터널은 별도 수명주기가 있다. Tauri가 sidecar·tray menu·업데이트 IPC를 제공한다. `ocx:src/cli/sync-command.ts:52–123`, `ocx:src/cli/link.ts:495`, `ocx:src/link/supervisor.ts:272–299`, `ocx:desktop/src-tauri/src/lib.rs:330–367`, `:427–434`. | + +## 3. 기능 인벤토리 + +### 세 클라이언트의 종단 경로 + +**Codex.** CC Switch 앱 폼은 Codex 프리셋에서 config/auth를 구성하고 전환 시 `switch_provider` → `ProviderService::switch` → 장치의 direct/proxy 모드를 읽는다. Direct는 등록된 공급자와 이전 소유자에 따라 TOML 관리 키·공급자 표를 투영한다. `codex_direct`가 판정한 인증 동작, 카탈로그, 소유 기록을 파일 계획에 넣고 같은 작업에서 현재 포인터를 확정한다. `preserve_codex_official_auth_on_switch` 기본은 false이고, 보존을 켠 경우 기존 공식 로그인과 공급자 인증 위치를 분리한다. 이 구현의 실패 복구는 `mode/operation.rs`의 pending을 따라간다. `write_codex_live_atomic`에 있는 auth→TOML 실패 보상은 별도 helper다. `ccs:src/config/codexProviderPresets.ts:209`, `ccs:src-tauri/src/commands/provider.rs:198–240`, `ccs:src-tauri/src/services/provider/mod.rs:7544–7579`, `:7769–7804`, `ccs:src-tauri/src/services/provider/codex_direct.rs:393`, `:591`, `:1329–1396`, `ccs:src-tauri/src/settings.rs:775`, `ccs:src-tauri/src/codex_config.rs:853–902`. + +OpenCodex `ocx sync`는 로컬에서 `syncModelsToCodex` → owned catalog refresh → `injectCodexConfig`로 간다. 외부 공급자나 사용자 소유 `openai_base_url`을 감지하고 보호하며, 표준 경로에서는 `openai`의 목적지와 catalogue 포인터를 관리한다. native 토글 기본값은 ON이고 역할 gate가 별도로 있다. 명시적 sync의 OFF 경로는 카탈로그만 갱신할 수 있다. `codex-shim install|status|uninstall` 및 기존 shim의 update 후 자동 복구도 별도 표면이다. 연결 모드의 `sync`는 Home catalog/설정 적용 경로를 택한다. `ocx:src/cli/dispatch.ts:418`, `:612–652`, `ocx:src/cli/sync-command.ts:52–123`, `:145–165`, `ocx:src/codex/desired-state.ts:63–85`, `ocx:src/codex/sync.ts:167–175`, `:231–236`, `:308`, `ocx:src/codex/inject.ts:194–273`, `:817–866`, `ocx:src/cli/codex-shim-autorestore.ts:52–64`. + +**Claude Code.** CC Switch는 앱 프리셋을 선택한 뒤 같은 전환 IPC로 들어온다. Direct는 이전/새 카드의 관리 키만 교체하고 다음 공급자 포인터를 함께 반영한다. `settings.json`을 기본으로 선택하며 기존 legacy 경로를 고려한다. MCP는 `~/.claude.json`에 따로 투영한다. Proxy 모드에서는 필요한 클라이언트 계약만 갱신하고 라우트 포인터를 바꾼다. OpenCodex `ocx claude`는 기본으로 로컬 runtime을 준비하고 `ANTHROPIC_BASE_URL`, 인증 및 모델 슬롯을 자식 환경에 구성한다. 로컬 설정 또는 실행 중인 서비스의 Claude 토글이 꺼져 있으면 네이티브 실행으로 분기한다. 지속 파일 쓰기는 UI의 모델 기본값 preview→fingerprint apply 또는 별도로 활성화한 intercept의 소유 `env` 쓰기에 있다. `ccs:src/config/claudeProviderPresets.ts:77`, `ccs:src-tauri/src/config.rs:286–310`, `ccs:src-tauri/src/services/provider/mod.rs:7544–7579`, `:7740–7759`, `ccs:src-tauri/src/services/provider/claude_direct.rs:51`, `ccs:src-tauri/src/live/project/claude.rs:128–148`, `:250–258`, `ocx:src/cli/dispatch.ts:921–938`, `ocx:src/cli/claude.ts:247–297`, `:332–381`, `:849–879`, `ocx:src/server/management/agent-settings-routes.ts:1518–1538`, `ocx:src/claude/intercept/settings.ts:224–269`, `ocx:src/claude/intercept/runtime.ts:118`. + +**Gemini CLI.** CC Switch Gemini 프리셋 → 선택된 카드 → `switch_normal`의 Gemini 분기 → `gemini_direct::switch_to`다. 제3자 카드는 설정과 API-key 요구를 먼저 검증하고 공식 카드는 Google OAuth 종류를 사용한다. `.env`의 Gemini 목적지/인증/모델 키와 `settings.json`의 `security.auth.selectedType`, `model.name`을 따로 계획한다. dotenv와 JSON의 주변 값을 보존하면서 두 파일과 현재 포인터를 같은 pending 작업으로 반영한다. Gemini 모드를 라우팅으로 전환하면 `/gemini/v1beta/*path` 등 로컬 HTTP로 들어온다. OpenCodex에서는 Gemini wire와 업스트림 OAuth 및 Agy connector가 각각 등록돼 있다. Gemini CLI의 이 두 파일을 프로젝션하는 진입점에는 아래 `GEM` 영수증을 적용했다. `ccs:src/config/geminiProviderPresets.ts:36`, `ccs:src-tauri/src/services/provider/mod.rs:7616–7619`, `ccs:src-tauri/src/services/provider/gemini_direct.rs:38–113`, `ccs:src-tauri/src/live/project/gemini.rs:19–45`, `:131–135`, `ccs:src-tauri/src/proxy/server.rs:428–431`, `ocx:src/server/index/gemini-routes.ts:59–94`, `ocx:src/integrations/gateway-clients/index.ts:14–19`. + +### 비교 행 + +| CAP tag | 기능 | CC Switch 진입 → 구현 → gate | OpenCodex 진입 → 구현 → gate 또는 부재 근거 | status | 근거 | +|---|---|---|---|---|---| +| CAP-provider-presets | 공급자 프리셋과 추가 | 앱 폼에서 preset 선택 및 제출 → `add_provider`. 앱별 배열과 Universal 별도. `ccs:src/components/providers/forms/ProviderForm.tsx:1004–1045`, `:2229`, `ccs:src-tauri/src/commands/provider.rs:70`, `ccs:src/config/universalProviderPresets.ts:61–96`. | `ocx provider` 및 `/api/providers` → registry/custom provider 설정. 게이트는 사용자 설정과 계정 가용성이고 프리셋은 프록시 공급자 단위. `ocx:src/cli/dispatch.ts:762–765`, `ocx:src/providers/registry.ts:1`, `ocx:src/server/management/provider-routes.ts:896`, `:1133`. | partial | OBSERVED | +| CAP-client-config-codex | Codex 라우팅/직접 전환 | 위 종단 추적. 카드별 direct 목적지와 proxy route를 저장한다. | 위 종단 추적. owned proxy 설정·카탈로그·native 복귀가 있다. 임의로 저장한 외부 카드의 현재 값까지 전환하는 모델과 범위가 다르다. | partial | OBSERVED | +| CAP-client-config-claude | Claude Code 직접/프록시 전환 | 위 종단 추적. 직접 카드와 routed 카드 모두 UI에서 전환한다. | 위 종단 추적. 런처, tier-default 파일 적용, intercept와 native 토글의 역할이 나뉜다. | partial | OBSERVED | +| CAP-client-config-gemini | Gemini CLI `.env`/JSON 연결 | 위 종단 추적. 공식 OAuth/제3자 키 분기와 직접/라우팅 gate. | `GEM`. Gemini data plane과 Agy connector는 Gemini CLI 파일 연결을 제공하지 않는다. | gap | OBSERVED | +| CAP-client-config-opencode | OpenCode 연결과 지속 공급자 추가 | `switch_provider` 또는 live add → `write_live_snapshot` → `set_provider_with_format`, additive와 포맷 검사. `ccs:src-tauri/src/lib.rs:1561–1563`, `ccs:src-tauri/src/services/provider/live.rs:635–704`, `ccs:src-tauri/src/opencode_config.rs:513–566`. | `ocx opencode` → `/api/models` 기반 V1/V2 block과 `OPENCODE_CONFIG_CONTENT` → 실행할 프로세스에만 주입. 이 런처는 기존 글로벌/프로젝트 설정을 충돌 진단에 쓴다. 지속 연결은 별도로 `integration client enable --client opencode` → 글로벌 경로와 관리 `opencodex` 조각 → 승인된 writer apply/restore로 제공한다. CC Switch는 여러 개별 공급자 카드를 저장하고 임의의 카드를 라이브에 추가한다. `ocx:src/cli/dispatch.ts:944–946`, `ocx:src/cli/opencode.ts:149–152`, `:655–676`, `ocx:src/cli/integrations.ts:248–354`, `ocx:src/integrations/registry.ts:298–305`, `ocx:src/clients/config-export.ts:1528–1547`, `ocx:src/server/management/integration-routes.ts:1249–1298`. | partial | OBSERVED | +| CAP-client-config-claude-desktop | Claude Desktop 연결 | 3P 카드 `switch_provider` → `switch_desktop_direct`; `needs_routing` 카드가 라우팅 UI 경로 사용. `ccs:src-tauri/src/services/provider/mod.rs:7720–7733`. | `ocx claude desktop` → profile apply 또는 first-party binding. 사용자 명령과 경로별 설정 gate. `ocx:src/cli/dispatch.ts:921–930`, `ocx:src/cli/claude-desktop.ts:325–341`, `ocx:src/claude/desktop-first-party.ts:279–290`. 세부 picker 슬롯 비교는 유보. | partial | OBSERVED | +| CAP-client-config-agy | Antigravity CLI 연결 | 카드의 terminal 액션 → 카드별 `--gemini_dir`과 공유 customization. direct switch 거절. `ccs:src-tauri/src/lib.rs:1838`, `ccs:src-tauri/src/services/provider/mod.rs:7466–7472`, `ccs:src-tauri/src/agy_config.rs:224–239`. | GUI/`connect agy` → `connectGatewayClient`와 connector, 대상 모델·입장 정책 먼저 검증. `ocx:src/server/management/gateway-client-routes.ts:12–38`, `ocx:src/integrations/gateway-clients/index.ts:30–41`, `:68–83`. | partial | OBSERVED | +| CAP-client-config-extensions | 기타 파일·추가형 앱군 | 표면 맵의 10종(Grok, OpenClaw, Hermes, Pi, MCode, Kimi, DSH, OMP, Copilot, WorkBuddy). | `ocx:src/clients/client-ids.ts:1–7`, `ocx:src/integrations/registry.ts:283–535`, `ocx:src/cli/export-command.ts:1–15`. 앱별 ownership, 승격/전환 gate 및 native store 비교는 유보. | unknown | OBSERVED-partial | +| CAP-client-config-atomic-rollback | 관리 파일의 원자 쓰기·복구 | Codex/Claude/Gemini 명시적 전환 → `AppWrite` → 파일별 stage와 첫 쓰기 백업, 해시 검증 및 pending 저장. publish 전 실패는 폐기 가능, publish 이후 다음 작업/시작에서 전진 복구 후 포인터 확정. `ccs:src-tauri/src/live/engine.rs:129–185`, `ccs:src-tauri/src/mode/operation.rs:65–203`, `:208–279`, `ccs:src-tauri/src/mode/controller.rs:1767–1783`. | `integration client enable/restore` → file writer의 snapshot/journal/atomic replace와 restore, 충돌 덮어쓰기는 명시 옵션. Codex 고유 writer는 lock과 destination 재검증, preimage 보상. `ocx:src/cli/integrations.ts:248–354`, `ocx:src/integrations/writer.ts:338–345`, `:659–775`, `ocx:src/integrations/config-io.ts:326–338`, `ocx:src/codex/config-write-lock.ts:133–163`, `ocx:src/codex/inject-coordination.ts:384`. 복구 모델이 같다는 판정은 유보. | partial | OBSERVED | +| CAP-mcp-client-sync | 공급자와 독립적인 MCP 정의 저장/가져오기/투영 | `upsert_mcp_server`·`toggle_mcp_app`·import/resync → `McpService` DB + 앱 enable. Claude `mcpServers`, Codex `[mcp_servers.*]`, Gemini `settings.json`, OpenCode 포맷 변환. `ccs:src-tauri/src/lib.rs:1633–1641`, `ccs:src-tauri/src/services/mcp.rs:51`, `:276–287`, `:365–401`, `:461–522`, `:589–669`, `ccs:src-tauri/src/mcp/claude.rs:93–105`, `ccs:src-tauri/src/mcp/codex.rs:347`, `ccs:src-tauri/src/mcp/gemini.rs:89–100`, `ccs:src-tauri/src/mcp/opencode.rs:185`. | `MCP`. Remote Workspace의 세션별 도구 구성과 MCP 메시징 서비스가 있다. 사용자 전역 앱 설정에서 범용 server 정의를 수집하고 재투영하는 표면이 없다. | gap | OBSERVED | +| CAP-skills-client-sync | Skills 검색·설치/삭제·선택 앱 투영 | 명시적 설치/앱 toggle → DB의 app flag와 SSOT, sync method에 따라 복사/링크, 삭제 전 백업과 restore. `ccs:src-tauri/src/lib.rs:1722–1749`, `ccs:src-tauri/src/commands/skill.rs:74–147`, `ccs:src-tauri/src/services/skill/sync.rs:73–89`, `:213–303`, `ccs:src-tauri/src/services/skill/backup.rs:59`, `:246`. | `SKILL`. Codex prompt-layer 분석은 홈의 기존 manifest를 읽는다. 여러 앱에 걸친 설치·동기화/복구를 수행하지 않는다. | gap | OBSERVED | +| CAP-prompt-profiles | 앱별 지침 프로필과 `CLAUDE.md` 전환 | `enable_prompt`·`import_prompt_from_file` → DB 선택·기존 편집 내용 보관 및 원자 쓰기. `CLAUDE.md`, `AGENTS.md`, `GEMINI.md` 등은 앱별 경로. Pi 템플릿 별도. `ccs:src-tauri/src/lib.rs:1643–1655`, `ccs:src-tauri/src/services/prompt.rs:146–227`, `ccs:src-tauri/src/prompt_files.rs:21–73`. | `PROMPT`. Codex prompt 관리 API와 UI가 한 클라이언트의 prompt layer를 관리한다. 여러 클라이언트의 활성 지침 프로필을 지정하는 등록점과 projector가 없다. | gap | OBSERVED | +| CAP-client-project-profiles | 프로젝트 단위 공급자 구성 | `apply_profile` → `ProfileService::apply`, 선택 프로필·지원 앱 gate. `ccs:src-tauri/src/lib.rs:1663–1668`, `ccs:src-tauri/src/commands/profile.rs:194`, `ccs:src-tauri/src/services/profile.rs:346`. | `ocx:src/integrations/route-intent.ts:1`, `ocx:src/integrations/aside-profiles.ts:1` map까지만 확인. 프로젝트 path와 per-app 전환 의미 비교 유보. | unknown | OBSERVED-partial | +| CAP-local-proxy | 로컬 프록시·앱별 접속 전환 | Tauri start/takeover/stop-restore → proxy service와 mode controller; 기본 bind `127.0.0.1:15721`. 사용자 start/모드, 시작 시 저장 모드 복구. `ccs:src-tauri/src/commands/proxy.rs:34–88`, `ccs:src-tauri/src/proxy/types.rs:14–20`, `ccs:src-tauri/src/lib.rs:1406`. | `ocx start`/desktop sidecar → Bun listeners와 data-plane admission. 동일한 로컬 중계 목적. CLI 서비스, listener, Remote Link 수명주기는 별도 확장. `ocx:src/cli/dispatch.ts:107–115`, `ocx:src/server/index.ts:684–728`, `ocx:src/server/index/serve-options.ts:560–600`, `ocx:desktop/src-tauri/src/lib.rs:357–434`. | parity | OBSERVED | +| CAP-wire-responses-http | Codex Responses HTTP/SSE | Responses POST → `handle_responses` → provider forwarder → Anthropic/Chat 변환 또는 Responses 처리. 앱 모드의 선택 공급자와 wire 설정에 따름. `ccs:src-tauri/src/proxy/server.rs:345–359`, `ccs:src-tauri/src/proxy/handlers.rs:1142–1237`, `:1260–1286`, `:1394–1404`. | `POST /v1/responses` → request dispatch와 Responses core, 시작된 listener·입장·대상 route gate. `ocx:src/server/index/serve-options.ts:1411–1483`, `ocx:src/server/responses/core.ts:30–66`. 기본 입출력 중계 기준이며 변환별 동등성은 유보. | parity | OBSERVED | +| CAP-wire-responses-ws | Codex Responses WebSocket | GET Responses → `handle_responses_websocket`, 426 반환으로 HTTP 전환 유도. `ccs:src-tauri/src/proxy/server.rs:343–359`, `ccs:src-tauri/src/proxy/handlers.rs:1125–1139`. | 동일 URL에서 `websockets: true`(기본 false) 및 입장을 확인한 뒤 Bun WS로 승격한다. WS 메시지 처리와 Responses dispatch를 연결한다. `ocx:src/config/feature-flags.ts:3–5`, `ocx:src/config/proxy-env.ts:68`. `ocx:src/server/index/serve-options.ts:560–600`, `:1924`, `ocx:src/server/index/websocket-handler.ts:106`, `:359`. | ocx-ahead | OBSERVED | +| CAP-wire-messages-sse | Claude Messages HTTP/SSE | 등록된 `/v1/messages` → `handle_messages` → 선택 provider와 `apiFormat`으로 전송/변환·stream parser. `ccs:src-tauri/src/proxy/server.rs:315–324`, `ccs:src-tauri/src/proxy/handlers.rs:290–408`, `:791–817`. | `POST /v1/messages` → Anthropic 경로, 요청·auth·Claude 활성 정책. 별도 count_tokens도 등록. `ocx:src/server/index/serve-options.ts:1485–1536`, `ocx:src/server/claude-messages.ts:606`, `ocx:src/server/messages-shared.ts:105`. 기본 SSE 중계 기준. | parity | OBSERVED | +| CAP-failover | 공급자 큐·circuit breaker | UI queue/auto failover IPC → per-app ordered candidates와 provider별 Closed/Open/HalfOpen. 기본 auto failover false, enable에서 P1 선택 뒤 저장. `ccs:src-tauri/src/lib.rs:1784–1791`, `ccs:src-tauri/src/commands/failover.rs:148–250`, `ccs:src-tauri/src/proxy/provider_router.rs:73–188`, `ccs:src-tauri/src/proxy/circuit_breaker.rs:194–273`, `ccs:src-tauri/src/database/dao/proxy.rs:240`. | `ocx fallback`과 `/api/fallback` → 모델/공급자/기기 정책, cooldown·이미 시도한 대상 제외 기록, ambiguous reset은 별도 허용 판단. 전역 model/provider 기본 ON. 앱별 명시 큐와 같은 상태 머신이라는 근거는 유보. `ocx:src/cli/dispatch.ts:823–826`, `ocx:src/cli/fallback.ts:40–43`, `:80–111`, `ocx:src/server/management/fallback-routes.ts:33–34`, `ocx:src/routing/fallback-policy.ts:211–239`, `ocx:src/router.ts:405–411`, `ocx:src/server/responses/reset-replay.ts:168–178`, `:215–230`. | partial | OBSERVED | +| CAP-model-mapping | 요청 모델 별칭/매핑 | 선택된 provider route의 요청 forwarder가 Claude 계열 매핑을 적용. 카드 env/model 값에 따라 원래/전송 모델을 결정. `ccs:src-tauri/src/proxy/forwarder.rs:1523`, `ccs:src-tauri/src/proxy/model_mapper.rs:129`. | `ocx alias` → router가 configured provider 및 모델 ID로 별칭 해석. `ocx:src/cli/dispatch.ts:786–788`, `ocx:src/router.ts:560–610`, `:671`. 앱별 tier/Stack 이름의 동등성은 유보. | partial | OBSERVED | +| CAP-usage-cost | 프록시 요청 비용/토큰 | 프록시 로깅 기본 ON → logger의 모델 가격, 캐시/입출력 토큰, multiplier 계산 → Usage IPC. `ccs:src-tauri/src/proxy/types.rs:19`, `ccs:src-tauri/src/proxy/usage/logger.rs:78–115`, `:344`, `ccs:src-tauri/src/proxy/usage/calculator.rs:36`, `ccs:src-tauri/src/commands/usage.rs:23–171`. | `/api/logs`, `/api/usage` → 관리 API가 proxy 요청·집계와 비용 계산을 제공. 사용자 가격, 캐시 단가와 미가격 상태를 처리한다. `ocx:src/server/management/logs-usage-routes.ts:73`, `:128`, `:200–247`, `ocx:src/usage/cost.ts:203–210`, `:303–331`. 공통 프록시 요약 기준. | parity | OBSERVED | +| CAP-usage-native-sessions | 프록시 외 네이티브 세션 비용 집계 | `sync_session_usage`, `rebuild_codex_usage` 및 주기적 수집 → per-source 파서·파일 cursor/중복 판단 → `get_session_usage_summary`. `ccs:src-tauri/src/lib.rs:1454–1466`, `:1810–1814`, `ccs:src-tauri/src/commands/usage.rs:45–58`, `:329–366`, `ccs:src-tauri/src/services/session_usage.rs:69–91`, `:146–236`. | `SESS`. Usage의 기기·출처 facet과 storage scanner에서 확인된 등록/구현의 경계는 프록시 요청과 파일 용량이다. Codex rollout을 읽는 별도 모듈은 세션 이력 작업용이며 Usage 집계의 소스가 아니다. 증분 세션 토큰 수집→비용 집계 연결을 찾지 못했다. | gap | OBSERVED | +| CAP-session-manager | 로컬 에이전트 이력 통합 조회 | session 화면의 명시적 list/index/search → 15개 소스 scan과 내용 조회, markdown export/terminal action. 일부 client 삭제는 자체 CLI에서 요구한다. `ccs:src-tauri/src/lib.rs:1817–1831`, `ccs:src-tauri/src/commands/session_manager.rs:17–74`, `:219–290`, `ccs:src-tauri/src/session_manager/mod.rs:97–117`, `:235–244`. | `SESS`. 프록시 요청 history는 conversation ID 필터를 제공하고 storage는 세션 경로를 검색한다. 이 표면들은 여러 CLI의 로컬 transcript·본문 인덱스를 제공하지 않는다. | gap | OBSERVED | +| CAP-endpoint-speed-test | 후보 HTTP 응답 시간 비교 | `test_api_endpoints` → URL별 warm-up GET 후 timed GET을 병렬 실행하며 latency/status/error를 내보냄. 명시적 호출/유효 URL과 bounded timeout. 모델 스트림 health check는 별도 IPC. `ccs:src/components/providers/forms/EndpointSpeedTest.tsx:340`, `ccs:src/lib/api/vscode.ts:17–21`, `ccs:src-tauri/src/commands/provider.rs:927`, `ccs:src-tauri/src/services/speedtest.rs:26–122`, `ccs:src-tauri/src/commands/stream_check.rs:15`. | `PROBE`. `/api/providers/test`와 `/test-completion`은 공급자 연결/실제 model probe다. 후보 URL 배열의 동일 조건 warm-up GET 비교를 제공하지 않는다. | gap | OBSERVED | +| CAP-deeplink-import | 공급자·MCP·프롬프트·Skill import 링크 | `deplink.html` 생성기 → OS Tauri callback → parse/pending → 확인 dialog → 리소스별 import. 공개 링크 실행은 검증 범위에서 제외했다. `ccs:deplink.html:1468`, `:1717`, `:1810–1914`, `ccs:src-tauri/src/lib.rs:310–347`, `:1179–1217`, `ccs:src-tauri/src/deeplink/parser.rs:15–74`, `ccs:src/components/DeepLinkImportDialog.tsx:206`, `:230–249`, `:1012`, `ccs:src-tauri/src/commands/deeplink.rs:40–75`. | `DEEP`. Dashboard hash navigation, OAuth redirect, 명시적 CC Switch 파일 import는 동작한다. OS custom URI로 리소스 미리보기→적용을 시작하는 등록점이 없다. | gap | OBSERVED | +| CAP-provider-import-ccswitch | 외부 도구 공급자 가져오기 | 앱 config를 현재/기본 행으로 import하는 명령, OpenCode/Hermes/OpenClaw 전용 import와 파일 기반 관리 DB 복원. `ccs:src-tauri/src/lib.rs:1564`, `:1850–1873`, `ccs:src-tauri/src/commands/provider.rs:285–299`, `:314`. | `provider import-cc-switch` → 로컬 `cc-switch.db`/legacy JSON에서 허용된 공급자 메타데이터만, 기본 preview, 정지 상태에서 명시 apply/restore, private origin opt-in과 Child gate. `ocx:src/cli/provider.ts:659–660`, `ocx:src/cli/provider-cc-switch-import.ts:4`, `:86–106`, `:168–172`, `ocx:src/providers/cc-switch-import-source.ts:42`. 가져오기 방향과 데이터 범위가 다르다. | partial | OBSERVED | +| CAP-config-import-export | 관리 설정의 이동 | 명시적 파일 대화상자/SQL export/import → DB dump/load 및 선택적으로 라이브 재투영. `ccs:src-tauri/src/lib.rs:1685–1701`, `ccs:src-tauri/src/commands/import_export.rs:30–88`. | `config export/import` → raw config round-trip, import `--yes` 및 기존 client connection gate. `export `는 다른 계약의 생성 출력. `ocx:src/cli/dispatch.ts:871–873`, `:905–907`, `ocx:src/cli/config-command.ts:22–54`, `:361–396`, `ocx:src/cli/export-command.ts:1–15`. | partial | OBSERVED | +| CAP-backup-local | 관리 상태 DB 정기 백업·복원 | 수동 create/list/restore/rename/delete와 periodic maintenance → 일관 SQLite image를 임시 경로에 작성·검증하고 publish, 크기 제한 선택 가능(기본 없음). `ccs:src-tauri/src/commands/import_export.rs:142–211`, `ccs:src-tauri/src/database/backup.rs:581–619`, `:645–671`, `:1239`, `ccs:src-tauri/src/settings.rs:821`. | OpenCodex의 파일 복원과 storage 정책은 확인. 여러 runtime DB에 대한 지원 백업 범위와 외부 도구 복원 경로 비교를 유보. `ocx:src/integrations/writer.ts:659`, `ocx:src/server/management/route-registry.ts:295–297`, `ocx:src/cli/config-command.ts:22–54`. | unknown | OBSERVED-partial | +| CAP-sync-webdav | WebDAV 스냅샷 push/pull | IPC → WebDAV adapter → SQL/ZIP 업로드 뒤 manifest, 다운로드에서 schema/size/hash 확인 후 복원. manual `enabled`, auto `enabled && auto_sync`. `ccs:src-tauri/src/commands/webdav_sync.rs:65–99`, `ccs:src-tauri/src/services/webdav_sync.rs:48–146`, `ccs:src-tauri/src/commands/sync_support.rs:61–65`, `ccs:src-tauri/src/services/webdav_auto_sync.rs:28–29`. | `CLOUD`. Remote Link의 Home/Child sync는 클라이언트 설정 투영·원격 연결 용도이며 WebDAV 스냅샷을 발행하거나 복원하지 않는다. | gap | OBSERVED | +| CAP-sync-s3 | S3 호환 스냅샷 push/pull | 별도 S3 IPC → SigV4 transport로 같은 형식 저장·검증. manual enable과 auto enable 분리. `ccs:src-tauri/src/commands/s3_sync.rs:64–95`, `ccs:src-tauri/src/services/s3.rs:4`, `ccs:src-tauri/src/services/s3_sync.rs:30–117`, `ccs:src-tauri/src/services/s3_auto_sync.rs:28–29`. | `CLOUD`. 명시적 파일 `config export/import`와 Link transport에 S3 object sync/복원 계약이 없다. | gap | OBSERVED | +| CAP-client-plugin-management | 클라이언트 플러그인과 마켓 관리 | Tauri plugin IPC → app별 설치/권한과 명령 선택, 공식 CLI와 Codex 토글 처리. `ccs:src-tauri/src/lib.rs:1606–1616`, `ccs:src-tauri/src/commands/plugin_manager.rs:21–36`, `ccs:src-tauri/src/services/plugin_manager/mod.rs:910–938`, `:1024–1049`. | `PLUG`. Codex plugins doctor가 진단을 제공하고 `ocx start`의 loader는 로컬 프록시 코드 hook을 실행한다. 클라이언트 마켓/플러그인 수명주기 관리 범위가 없다. | gap | OBSERVED | +| CAP-desktop-tray | 백그라운드 트레이 | Tauri builder → native menu/panel callback, 사용자 표시/동작 선택. 공급자/라우팅과 사용량 뷰 진입. `ccs:src-tauri/src/lib.rs:1246`, `:1761–1767`, `ccs:src-tauri/src/tray.rs:2780`, `:3506`. | Tauri setup에서 tray 설치/가용성 gate → icon/menu와 platform popup. 상태·계정·사용량·업데이트 동작이 있다. `ocx:desktop/src-tauri/src/lib.rs:367–434`, `ocx:desktop/src-tauri/src/tray.rs:75`, `:164–206`, `ocx:desktop/src-tauri/src/native_tray.rs:44–81`. 공통 트레이 제공 기준. | parity | OBSERVED | +| CAP-desktop-update | 데스크톱 업데이트 | Updater plugin과 check/download/install IPC, 자동 설정 기본 false와 지원 플랫폼 gate, portable 수동 경로. `ccs:src-tauri/src/lib.rs:642`, `:1597–1604`, `ccs:src-tauri/src/commands/settings.rs:348`, `:457–472`, `ccs:src-tauri/src/app_update.rs:66–83`, `:225–243`, `ccs:src/contexts/UpdateContext.tsx:179–198`, `ccs:src-tauri/src/settings.rs:773`. | Tauri updater + 배포 빌드 background check, 다운로드와 pending install. `ocx:desktop/src-tauri/src/lib.rs:274–296`, `:330–341`, `:434`, `ocx:desktop/src-tauri/src/updater.rs:354–391`, `:458`, `:513`. 자동 설치의 조건 비교는 유보. | partial | OBSERVED | +| CAP-ui-i18n | 다국어 React UI | 앱 부팅 `i18n` → 저장/OS locale 선택, 영어 fallback과 settings 동기화. `ccs:src/i18n/index.ts:35–74`, `ccs:src/i18n/languages.ts:7–45`. | root `LanguageProvider` → 로케일 감지와 카탈로그, 영어 fallback 및 선택 UI. `ocx:gui/src/main.tsx:11–20`, `ocx:gui/src/i18n/shared.ts:6–30`, `ocx:gui/src/i18n/provider.tsx:6–25`, `ocx:gui/src/App.tsx:587`. | parity | OBSERVED | +| CAP-fleet-link | Home/Child 라이브 동기화 | WebDAV/S3와 추적한 설정 경로는 저장 스냅샷 전송. 앱 등록의 remote fleet 제어 여부는 이 비교에서 낮은 우선순위로 뒀다. | `ocx link` 및 connected `sync` → SSH supervisor/버전과 원격 카탈로그·선택적 apply/restart. `ocx:src/cli/link.ts:495`, `ocx:src/cli/sync-command.ts:60–123`, `ocx:src/link/supervisor.ts:272–299`. | unknown | OBSERVED-partial | + +### 스냅샷 복원 경계 + +공통 snapshot manifest에는 `db.sql`과 `skills.zip`의 크기/해시가 있다. WebDAV와 S3 모두 artifact 이후 manifest를 발행한다. 러닝 사용량과 요청 로그, provider health, 라이브 백업, 세션 cursor는 동기화 export에서 빠지고 일부 테이블은 다운로드 시 로컬 값을 보존한다. Restore는 Skill 상태 쓰기 lock 안에서 기존 Skill을 백업하고, ZIP을 복원한 뒤 SQL을 반영하며 SQL 실패 시 Skill을 복원한다. 전송 잠금 아래 provider/MCP/Skills 및 prompt 라이브 재투영을 시도하고, 이후 투영 실패는 복원 상태의 warning으로 전달한다. 자동 worker는 DB 변경을 debounce하고 enable 조건에 따라 업로드한다. 다운로드는 명시적 명령이다. `ccs:src-tauri/src/services/sync_protocol.rs:108`, `:193–246`, `:380–425`, `ccs:src-tauri/src/services/webdav_sync.rs:67–78`, `ccs:src-tauri/src/services/s3_sync.rs:44–56`, `ccs:src-tauri/src/database/backup.rs:145–164`, `ccs:src-tauri/src/commands/sync_support.rs:140–167`, `:203–233`, `ccs:src-tauri/src/services/provider/live.rs:984–1029`, `ccs:src-tauri/src/services/auto_sync.rs:136–183`, `:199–224`. + +### OpenCodex 부재 영수증 + +아래 명령 실행 기준은 `9e0e298ef9` export의 루트 `/Users/jun/Developer/new/700_projects/opencodex/.tmp/chase/opencodex-dev`다. 모든 검색 root는 `src gui/src desktop docs-site structure`이고, 파일 경로만 반환하는 `-l`로 확인했다. 각 행은 검색 결과와 가장 가까운 진입점 및 구현을 함께 검토한 결과다. + +| ID | 정확한 명령 | 종료·매치 파일 수 | 확인한 근접 경로와 범위 | +|---|---|---|---| +| GEM | `rg -n -i -l 'GEMINI_API_KEY\|Gemini CLI\|GOOGLE_GEMINI_BASE_URL\|\.gemini/\|GEMINI_CLI_HOME' src gui/src desktop docs-site structure` | 0 · 9 | `ocx:src/server/index/gemini-routes.ts:59–94`의 요청 어댑터와 `ocx:src/integrations/gateway-clients/index.ts:14–19`의 Agy/Antigravity를 확인했다. `ocx:src/clients/client-ids.ts:1–7`와 CLI dispatch에 Gemini CLI write/apply 진입점이 없다. | +| MCP | `rg -n -i -l 'mcpServers\|mcp_servers\|mcp.{0,22}(sync\|import\|export)\|(sync\|import\|export).{0,22}mcp' src gui/src desktop docs-site structure` | 0 · 72 | `ocx:src/remote-control/workspace-codex-runtime.ts:367`, `:508`, `ocx:src/remote-control/workspace-claude-runtime.ts:117`은 원격 세션 도구 표면이고 `ocx:src/cli/message-mcp-command.ts:1`은 메시징 도구다. `ocx:src/server/management/integration-routes.ts:748`의 관리 대상과 `ocx:src/integrations/registry.ts:283–535`를 확인했다. | +| SKILL | `rg -n -i -l 'SKILL\.md\|skills.{0,16}(sync\|install)\|(sync\|install).{0,16}skills' src gui/src desktop docs-site structure` | 0 · 11 | `ocx:src/codex/prompt-layers.ts:605–630`의 기존 manifest 열람 및 `ocx:src/integrations/writer.ts:2–5`의 관리 provider 블록 writer. 카탈로그·설치와 per-app Skill 투영이 없다. | +| PROMPT | `rg -n -i -l 'CLAUDE\.md\|GEMINI\.md\|prompt.{0,18}(profile\|sync\|import)' src gui/src desktop docs-site structure` | 0 · 18 | `ocx:src/server/management/codex-prompt-routes.ts:1`, `ocx:gui/src/pages/codex-set-prompt.tsx:1`의 Codex 전용 prompt UI/API와 `ocx:src/claude/agents-inject.ts:264`의 generated agents. 앱별 지침 프로필 라이브 파일 선택은 포함되지 않는다. | +| DEEP | `rg -n -i -l 'ccswitch://\|opencodex://\|deep[_ -]?link\|on_open_url\|register_uri_scheme_protocol' src gui/src desktop docs-site structure` | 0 · 28 | `ocx:gui/src/protocol-deep-links.ts:43–98`은 dashboard hash, `ocx:src/cli/provider-cc-switch-import.ts:86–106`은 CLI file import다. `ocx:desktop/src-tauri/src/lib.rs:330–367`의 plugin/handler 등록에 대한 URI import 연결이 없다. | +| CLOUD | `rg -n -i -l 'webdav\|s3 sync\|s3.sync\|aws4-hmac-sha256\|S3Client\|skills\.zip' src gui/src desktop docs-site structure` | 1 · 0 | `ocx:src/cli/sync-command.ts:52–87`, `ocx:src/link/supervisor.ts:272–299`는 Home·Child catalog/SSH 운영 경로. `ocx:src/cli/config-command.ts:22–54`는 로컬 설정 파일 이동이며 remote object 저장/복원이 없다. | +| SESS | `rg -n -i -l 'archived_sessions\|session_index\|session.{0,15}(usage\|search)\|export_session_markdown\|\.claude/projects' src gui/src desktop docs-site structure` | 0 · 47 | `ocx:src/storage/scanner.ts:63–75`, `:250–251`은 용량 범주, `ocx:src/server/management/request-history-routes.ts:90–104`은 프록시 요청 필터, `ocx:src/server/management/logs-usage-routes.ts:200–247`은 요청 기반 사용량. `ocx:src/codex/history-rollout-read.ts:1`은 이력 검사 경로. 해당 UI/API는 native 세션 콘텐츠 인덱스나 native 토큰 ingest를 제공하지 않는다. | +| PLUG | `rg -n -i -l 'plugin marketplace\|marketplace.{0,12}(refresh\|add)\|plugin (install\|marketplace)\|plugins\.json' src gui/src desktop docs-site structure` | 0 · 3 | `ocx:src/codex/plugins-doctor.ts:1`은 진단. `ocx:src/cli/index.ts:559`, `ocx:src/plugins/loader.ts:270–276`, `ocx:src/plugins/upstream-hooks.ts:1–10`은 프록시 로컬 hook이며 앱 CLI의 마켓 관리 경로가 없다. | +| PROBE | `rg -n -i -l 'speedtest\|test_api_endpoints\|endpoint.{0,12}(latency\|ping\|speed)\|stream.check\|latency_ms' src gui/src desktop docs-site structure` | 0 · 1 | 별도로 `ocx:src/server/management/route-registry.ts:407–408`, `ocx:src/server/management/provider-routes.ts:1613–1619`, `ocx:src/server/management/provider-completion-test.ts:266`을 확인했다. 공급자 모델 probe와 후보 HTTP GET 속도 비교의 호출 계약이 다르다. | + +표 안의 `\|`는 Markdown 셀 이스케이프이며 실행 시 정규식의 `|`다. 백슬래시가 붙은 리터럴 점(`\.`)은 실행한 패턴 그대로다. + +## 4. Gap candidates + +후보는 12개이며 `reject candidate` 3개를 포함한다. 인벤토리의 `gap` 여부와 개선 후보 우선순위는 독립적이다. 대상 경로는 제안이다. 공통 제약은 Lab을 코어 import graph에 추가하지 않는 것, cap에 걸린 파일 대신 sibling module을 선택하는 것, 실제 계정/설치/외부 전송은 명시적 사용자 동작에 묶는 것이다. + +| ID | 빠진 경험과 가치 | 노력 및 가능 경로 | 선행 조건·리스크 | +|---|---|---|---| +| L3-1 | **high** · `CAP-client-config-codex` + `CAP-client-config-claude` 앱별 라우팅 상태·전환·복구 결과를 같은 desktop 화면에서 확인. | M · `gui/src/pages/integrations/`, `src/server/management/native-integration-routes.ts`, 기존 shim/Claude 동작 재사용. | proxy/native/remote owner 판단, 동시 쓰기와 drift 표시. 기존 비밀이나 개인 로그인 이전은 범위에서 제외. | +| L3-2 | **high** · `CAP-deeplink-import` 팀원이 공유 공급자나 Home 연결을 열어 미리보기와 명시적 적용으로 이어가는 진입점. | M · `desktop/src-tauri/`, `gui/src/pages/integrations/`, `src/providers/cc-switch-import*`의 투영·미리보기 계약 참고. | 리소스 schema와 trusted destination, 사용자 확인, 링크/로그에서 credential 제외. MCP/Skill 실행 동작 제외. | +| L3-3 | **high** · `CAP-endpoint-speed-test` 여러 후보 URL의 응답시간, 상태 및 실패를 선택 전 같은 화면에서 비교. | M · `src/server/management/`의 기존 provider probe 옆 sibling route + `gui/src/pages/Providers.tsx` 인접 UI. | 로컬/원격 admission, bounded concurrency·timeout, 사용량이 발생하는 stream probe와 버튼 및 집계 분리. | +| L3-4 | **med** · `CAP-client-config-gemini` 명시적 enable/disable 및 복구로 Gemini CLI를 로컬 또는 Home proxy에 연결. | M · `src/integrations/gateway-clients/`, `src/clients/`, `gui/src/pages/integrations/`. | 기존 Gemini inbound 계약, dotenv 레이아웃과 JSON 두 파일의 분할 복구, 인증 재사용을 명시. Agy 네임스페이스와 구분. | +| L3-5 | **med** · `CAP-usage-native-sessions` Codex/Claude 네이티브 실행의 비용·토큰을 데이터 출처와 함께 연결. | L · `src/usage/`, `src/server/management/logs-usage-routes.ts` 인접 모듈, `gui/src/pages/Usage.tsx`. | 명시적 파일 읽기, metadata-only 수집, cursor·부분 쓰기·중복 식별, provider별 가격 근거. 요청 처리 경로 밖에서 실행. | +| L3-6 | **med** · `CAP-config-import-export` + `CAP-backup-local` 복원 미리보기와 내보낼 관리 항목을 보여주는 로컬 백업 흐름. | M · `src/cli/config-command.ts`, `src/integrations/state.ts`, GUI 설정. | credential 제외 기본값을 새 번들 형식에 명시, 현재 standalone/Child 상태와 journal 충돌 처리. 기존 raw export 계약 유지. | +| L3-7 | **med** · `CAP-sync-webdav` + `CAP-sync-s3` 관리 설정을 저장소에 보내고 다른 기기에서 복원하는 선택적 백업 수단. | L · L3-6의 format/restore 계약 선행. `src/config/` 인접 백업 모듈과 GUI 설정. | 백업 신뢰 범위, secret 기본 제외·암호화 여부, version/검증/부분 복원·동시 발행 충돌. Remote Link 전송 계약과 독립. | +| L3-8 | **med** · `CAP-mcp-client-sync` Codex/Claude Code의 선택된 MCP 항목에 대해 읽기, 변경 미리보기와 명시적 적용. | L · `src/integrations/` writer/journal·GUI preview, TOML/JSON projection. | 적용 전 설치 여부·명령/원격 URL 확인, credential redaction, 프로젝트 범위/전역 범위 구분과 소유권 보존. 자동 실행 제외. | +| L3-9 | **med** · `CAP-failover` 소형 팀을 위한 앱별 fallback 경로의 순서와 현재/제외 사유 가시성. | M · `src/routing/`, `src/cli/fallback.ts`, GUI routing. 기존 정책이 표현 가능한 부분부터 구성. | in-flight stream 중복, 암묵적 POST replay, 비용·계정 선택 정책, `src/router.ts` 크기 ratchet. | +| L3-10 | **low · reject candidate** · `CAP-session-manager` 범용 세션 index·본문 검색·삭제·재실행 복제. | XL · 각 앱의 세션 저장소와 installer/terminal 수명주기 필요. | 프록시의 기본 임무 밖이며 원문·이미지의 추가 보관과 파기 권한이 필요하다. L3-5의 메타데이터 집계로 좁힌다. | +| L3-11 | **low · reject candidate** · `CAP-skills-client-sync` + `CAP-prompt-profiles` 범용 Skills marketplace 및 전역 지침 전환 복제. | XL · 파일 sync, 설치/삭제, 전용 앱별 instruction semantics. | 원격 패키지 실행·기존 지침 덮어쓰기·프로젝트 정책 영향이 크고 로컬 프록시 연결의 선행 조건이 아니다. | +| L3-12 | **low · reject candidate** · `CAP-client-plugin-management` 모든 클라이언트의 플러그인/마켓과 업데이트 관리. | XL · 지속적인 CLI 버전별 어댑터와 설치 권한·업데이트 검증. | 프록시 hook 및 연결 진단과 제품 범위가 다르다. 외부 marketplace 접근·새로운 실행 권한을 도입한다. | + +## 5. OpenCodex-ahead 항목 + +- **확정 `CAP-wire-responses-ws`.** OpenCodex는 native WebSocket upgrade와 메시지 처리를 제공한다. CC Switch의 등록 handler는 426 응답으로 HTTP/SSE fallback을 유도한다. `ocx:src/server/index/serve-options.ts:560–600`, `:1924`, `ocx:src/server/index/websocket-handler.ts:359`, `ccs:src-tauri/src/proxy/handlers.rs:1125–1139`. +- **OpenCodex에서 관찰한 확장.** SSH Home/Child lifecycle, 실행 중인 서비스의 route intent 및 카탈로그/설정 sync는 cloud snapshot과 별도 용도를 해결한다. `CAP-fleet-link`는 CC Switch 등록 범위의 대응 기능 유무를 전수 검증하기 전까지 `unknown`이다. `ocx:src/cli/sync-command.ts:60–123`, `ocx:src/link/supervisor.ts:272–299`. + +## 6. 최신 사례 (Aside) + +공개 릴리스·PR·이슈·Discussions만 읽었다. 날짜는 발행일 또는 merge일(UTC), 접근일은 KST다. `f19a9d4f4f`의 committer time은 `2026-11-23T12:13:51Z`다. 그 이후 발행된 릴리스 공지는 post-head로 표시했다. 로컬 대조는 같은 동작이 고정 트리에 있는지를 확인하는 데 사용했다. + +| 발행·merge 날짜 | 릴리스·커밋·PR | 출처 URL | 접근일 | 관찰 | OpenCodex 관련성 | 신뢰도 | +|---|---|---|---|---|---|---| +| 2026-11-23 | v4.0.40, **post-head 공지** | [CC Switch release](https://github.com/farion1231/cc-switch/releases/tag/v4.0.40) | 2026-11-23 | Grok 공식 카드 계정 선택, Antigravity 플러그인, 캐시 적중률. Agy 플러그인 adapter는 고정 트리에도 있다. `ccs:src-tauri/src/services/plugin_manager/agy.rs:181`, `:325`. | 전환 UI가 계정과 공급자 및 비용 출처를 구분해 표시할 필요. | 높음 · 공식 릴리스와 어댑터 소스 | +| 2026-11-22 | v4.0.39 / #9011 `f346fb64` | [Backup limit PR](https://github.com/farion1231/cc-switch/pull/9011), [release](https://github.com/farion1231/cc-switch/releases/tag/v4.0.39) | 2026-11-23 | 백업 총 크기 제한을 선택적으로 추가했다. 설정 default는 `None`, periodic maintenance에서도 retention을 호출한다. `ccs:src-tauri/src/settings.rs:821`, `ccs:src-tauri/src/database/backup.rs:581–588`. | 관리 백업을 도입할 경우 보관 비용과 복구 여유를 함께 설정 가능. | 높음 · merge 및 고정 트리 | +| 2026-11-22 | #9795 `ea420cc0` | [Codex TOML refactor](https://github.com/farion1231/cc-switch/pull/9795) | 2026-11-23 | Codex TOML 편집 로직과 다른 폼 공통 필드 로직을 분리했다. `ccs:src/utils/codexConfigUtils.ts:1`, `ccs:src/utils/providerConfigUtils.ts:1`. | OpenCodex의 config writer와 프리셋 입력을 따로 검증하는 사례. | 높음 · merge 및 파일 확인 | +| 2026-11-21 | v4.0.38 / #9768 `63798b89` | [WorkBuddy import PR](https://github.com/farion1231/cc-switch/pull/9768), [release](https://github.com/farion1231/cc-switch/releases/tag/v4.0.38) | 2026-11-23 | 팀이 멤버에게 공급자 링크를 전달하는 실제 사용 동기를 PR에 기록했다. WorkBuddy가 allowlist와 app-specific builder에 추가됐다. `ccs:src-tauri/src/deeplink/parser.rs:109`, `ccs:src-tauri/src/deeplink/provider.rs:1191`. | L3-2의 앱별 지원 범위와 사용자 확인 우선순위. | 높음 · merge/코드, 팀 사례는 작성자 보고 | +| 2026-11-21 | Discussions Q&A | [CC Switch community discussion list](https://github.com/farion1231/cc-switch/discussions?discussions_q=sort%3Adate_created) | 2026-11-23 | Codex Desktop `26.1117.4957.0`의 aggregation 동작이 달라졌다는 미응답 사용자 글. | 파일 apply receipt와 실행 중 데스크톱의 카탈로그 상태를 각각 관찰할 필요. | 낮음 · 제목과 게시일 확인, 재현 안 함 | +| 2026-11-19 | v4.0.36 / #9220 `81b84221` | [Plugins page PR](https://github.com/farion1231/cc-switch/pull/9220), [release](https://github.com/farion1231/cc-switch/releases/tag/v4.0.36) | 2026-11-23 | 당시 여섯 클라이언트 플러그인을 공식 CLI 중심으로 관리. Codex 파일 토글 예외 및 current IPC 확인. `ccs:src-tauri/src/commands/plugin_manager.rs:21–36`. | `src/plugins`의 프록시 hook과 클라이언트 플러그인 지원을 UX에서 구별. | 높음 · merge/코드 | +| 2026-11-15 | open #9534 | [ZIP file modes report](https://github.com/farion1231/cc-switch/issues/9534) | 2026-11-23 | Skills ZIP 복원 후 실행 비트가 빠진다는 사용자 보고. 기본 ZIP 옵션이 고정 트리에서도 보인다. `ccs:src-tauri/src/services/webdav_sync/archive.rs:31–58`. | 관리 파일 백업을 추가할 때 이식 가능한 메타데이터 계약의 필요. | 중간 · 이슈 및 pack 경로, 실제 복원 미검증 | +| 2026-11-15 | open #9559 | [WebDAV upload report](https://github.com/farion1231/cc-switch/issues/9559) | 2026-11-23 | Windows/NAS에서 Unicode 경로의 PUT이 실패하고 연결 확인은 통과했다는 사용자 보고. | L3-7에서 연결 확인 결과와 실제 발행 가능성을 구분하는 근거. | 낮음 · 작성자 환경 보고 | +| 2026-11-12 | #9400 `4376e5df` | [Codex rollout parser PR](https://github.com/farion1231/cc-switch/pull/9400) | 2026-11-23 | 누적 세션의 token parsing에서 할당과 중복 스캔을 줄였다. `ccs:src-tauri/src/services/session_usage_codex.rs:1`, `ccs:src-tauri/src/services/session_usage.rs:82–91`. | L3-5에서 파일 증분 cursor와 사용자 홈 I/O 예산을 정할 근거. | 높음 · merge, 성능 수치는 재측정 안 함 | +| 2026-10-11 | open #8146 | [Per-device usage request](https://github.com/farion1231/cc-switch/issues/8146) | 2026-11-23 | 사용자에게는 설정 동기화와 별도로 기기별 사용량이 필요했다. 요청 log/rollup은 실제 snapshot 제외 목록에 있다. `ccs:src-tauri/src/database/backup.rs:145–164`. | 기존 OpenCodex usage device/source facet을 재사용하는 근거. `ocx:src/server/management/logs-usage-routes.ts:200–247`. | 높음 · 요구와 소스 범위 확인 | +| 2026-10-02 | Magpie #531 `93a1e3e7`, #574 `bb42b476` | [Snapshot short write](https://github.com/yetone/magpie/pull/531), [usage upload short write](https://github.com/yetone/magpie/pull/574) | 2026-11-23 | Magpie는 WebDAV 성공 응답과 저장된 길이를 추가로 대조하고 short write를 재시도한다. `mgp:internal/davsync/dav.go:364`, `:423–439`. | L3-7의 운영 진단 및 발행 후 확인 사례. | 높음 · merge 및 고정 트리의 snapshot 경로 | +| 2026-09-24 | Magpie #45 `00b17368` | [Codex provider import](https://github.com/yetone/magpie/pull/45) | 2026-11-23 | 기존 Codex TOML에서 공급자를 발견하고 사용자가 고른 항목을 가져온다. `mgp:internal/provider/import_codex.go:17`, `:79`. | OpenCodex의 keyless CC Switch importer와 함께 선택형 온보딩 비교 사례. | 높음 · merge 및 parser 확인 | + +## 7. Deferred checks + +- 나머지 13종 클라이언트의 전환 전후 원문 비교, vendor별 최초 입력/설정 경로 override, Windows/WSL/portable 권한·파일 잠금, tray와 CLI의 동일 상태 전이. OpenCode는 V1/V2 추가와 OMO 입구까지 비교했다. +- 각 앱의 MCP transport 형식·유효성 검사와 부분 오류 전파, Skills ZIP 복원·링크/복사 플랫폼별 의미, 프로젝트 프로필과 Pi 템플릿의 복구 조건. +- Codex Stack 자체 카탈로그, compaction·image·search 변환, Claude/Claude Desktop streaming별 event fidelity, Gemini 네이티브 모델 API와 auth 종류별 스트림 대조. 등록을 확인했으며 응답 의미의 1:1 parity는 평가하지 않았다. +- WebDAV 구형 layout fallback과 S3 호환 제품별 요청 서명, worker 간 충돌, 실제 스냅샷 복원 및 device-only 상태 적용, updater 설치/재시작 정책의 플랫폼 차이. +- 세션 소스별 토큰 파서·중복 제거, 자동 수집 시간, CLI plugin 설치·갱신, 원격 fleet과 내보내기 대상별 갱신·복구까지의 전수 비교. + +## 8. NOT RUN + +- 양쪽 빌드·테스트·서버 실행, GUI/트레이/installer 동작 검증, 실제 홈과 자격증명 읽기·쓰기, 링크 실행, 네트워크 프록시 요청, WebDAV/S3 연결·전송·복원 모두 미실행. 이 문서의 상태는 고정 트리 소스 읽기 기준이다. +- Aside `codemode --account u0 --host local --cwd … --code -`의 `browse.exec` 렌더 배치는 `indeterminate` / `partial: ["no-marker"]`를 반환했다. 같은 Aside에서 `browse.readText({url,fresh:true})`로 공개 GitHub/API 발행물의 본문과 날짜를 읽었다. `linux.do/search`는 HTTP 403, Reddit 검색은 브라우저가 빈 본문을 반환했다. 외부 커뮤니티 확인 범위는 공개 GitHub Discussions와 이슈까지다. diff --git a/devlog/_plan/261123_proxy_upstream_catchup/004_sub2api_gateway.md b/devlog/_plan/261123_proxy_upstream_catchup/004_sub2api_gateway.md new file mode 100644 index 00000000000..cf1c4a11c26 --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/004_sub2api_gateway.md @@ -0,0 +1,121 @@ +# 004 — sub2api gateway core (L4) + +기준은 sub2api `328db26f450edbdf9f8d4344a3ea903ac6396842` (2026-11-20), OpenCodex `origin/dev` `9e0e298ef9720cfeaa1209f090a68e4d1965d2a1` (2026-11-21)이다. `s2a:`는 `.tmp/chase/sub2api/`, `ocx:`는 `.tmp/chase/opencodex-dev/`에서 읽은 소스다. 표의 판정은 해당 행의 동작 범위에 한정한다. + +## 1. 요약 + +1. Codex와 Claude Code를 동시에 쓸 때 가장 직접적인 차이는 sub2api가 실제 동시 사용량과 대기열을 보고 계정을 고른다는 점이다. OpenCodex의 Codex·Claude pool 선택은 세션과 quota 정책을 우선하고, Kiro 경로에 계정별 lease가 있다. +2. sub2api의 일반 스케줄러는 가용 계정에서 priority, load, LRU를 차례로 적용한다. OpenAI의 queue·실패율·TTFT 가중 점수는 별도 설정을 켰을 때 쓰인다. +3. 두 프로젝트 모두 Codex와 Claude의 세션 affinity를 유지한다. Gemini에서 sub2api는 첫 사용자 입력을 포함하는 안정적인 prefix로 일반 요청을 묶고, 명시적 cache 리소스에는 생성 계정을 고정한다. +4. sub2api의 user slot은 같은 사용자의 여러 API key가 공유한다. 여러 사람이 proxy를 쓸 때 한 사용자의 fan-out이 다른 사람의 처리 용량을 잠식하는 문제에 대응한다. +5. HTTP SSE와 Responses WS 모두 계정을 바꾸기 전에 출력과 replay 상태를 확인한다. OpenCodex는 전송 결과가 불명확한 reset에서 명시적 허용과 self-contained 입력을 요구한다. +6. sub2api는 계정마다 upstream proxy를 선택한다. OpenCodex는 provider 단위 proxy를 제공하므로 같은 provider의 여러 계정에 각기 다른 네트워크 경로가 필요한 경우가 비교 대상이다. +7. 429의 적용 범위는 provider마다 다르다. Antigravity는 근거가 부족한 429로 한 요청이 계정 여럿에 냉각을 걸지 않도록 제한한다. + +## 2. 표면 맵 + +서버가 `RegisterGatewayRoutes`를 호출한다. 아래 표에서 `G`는 `GatewayHandler`, `O`는 `OpenAIGatewayHandler`다. 기본 텍스트 ingress에는 API key 인증, 모델 allowlist, 분기 middleware 및 그룹 검사가 연결된다. Gemini는 Google 형식 API key middleware를 사용한다. 인증·과금 정책은 L5 범위다. `s2a:backend/internal/server/router.go:133`, `s2a:backend/internal/server/routes/gateway.go:198`, `:358`, `:391`. + +| ingress | 메서드와 경로 | 핸들러·분기 | 등록 근거 | +|---|---|---|---| +| `/v1` | POST `/messages`, `/messages/count_tokens`, `/systemone` | Messages는 group platform에 따라 G/O. CountTokens는 G/O와 Grok 전용 분기. SystemOne은 G | `s2a:backend/internal/server/routes/gateway.go:68`, `:212` | +| `/v1` | GET `/models`, `/models/:model`, `/usage`, `/sub2api/billing` | 모델/사용량/과금 조회는 G. 목록에 `client_version`이 있으면 Codex manifest이며 OpenAI 그룹만 O | `s2a:backend/internal/server/routes/gateway.go:82`, `:205`, `:224`, `:550` | +| `/v1` | POST `/responses`, `/responses/*subpath`, `/chat/completions`, `/alpha/search`, `/embeddings`; GET `/responses` | Responses/Chat은 G/O, subpath guard 후 input token 요청은 O, AlphaSearch 및 WS는 O, Embeddings는 OpenAI 그룹 | `s2a:backend/internal/server/routes/gateway.go:178`, `:234`, `:248`, `:260` | +| `/v1` | POST `/live`; GET `/live/:call_id` | O Live, LiveSideband | `s2a:backend/internal/server/routes/gateway.go:231` | +| `/v1` | POST `/images/{generations,edits}` 및 두 경로의 `/async`; GET `/images/tasks/:task_id` | 동기는 OpenAI/Grok, 비동기는 AsyncImage | `s2a:backend/internal/server/routes/gateway.go:95`, `:273` | +| `/v1/images/batches` | POST·GET 목록, GET `/models`, `/:id`, `/:id/items`, `/:id/items/:custom_id/content`, `/:id/download`; POST `/:id/cancel`; DELETE `/:id`, `/:id/outputs` | BatchImage | `s2a:backend/internal/server/routes/gateway.go:278` | +| `/v1` | POST `/videos`, `/videos/{generations,edits,extensions}`; GET `/videos/:request_id` 및 `/videos/{generations,edits,extensions}/:request_id`, 각 GET의 `/content` | Grok. 생성·조회는 Composite 그룹도 허용 | `s2a:backend/internal/server/routes/gateway.go:111`, `:155`, `:290` | +| `/v1` | POST `/tts`, `/stt`, `/custom-voices`, `/web_search`, `/x_search`; GET `/custom-voices`, `/custom-voices/:voice_id`, `/custom-voices/:voice_id/audio`, `/realtime`; PATCH·DELETE `/custom-voices/:voice_id` | Grok voice/Realtime WS는 O, 검색은 G | `s2a:backend/internal/server/routes/gateway.go:305`, `:326`, `:339` | +| root 별칭 | POST `/responses`, `/responses/*subpath`, `/alpha/search`, `/messages/count_tokens`, `/chat/completions`, `/embeddings`; GET `/responses`, `/models`, `/models/:model` | 위 텍스트, discovery, WS 핸들러 재사용 | `s2a:backend/internal/server/routes/gateway.go:381`, `:399`, `:422` | +| root 별칭 | `/v1`을 뺀 동기·비동기 images 및 task 조회, videos, voice, realtime, web/x_search 경로 | 위 media·검색 핸들러 재사용 | `s2a:backend/internal/server/routes/gateway.go:442`, `:460`, `:494` | +| `/backend-api/codex` | POST `/realtime/calls`, `/responses`, `/responses/*subpath`, `/alpha/search`; GET `/:call_id`, `/responses`, `/models` | Codex direct alias, Live/Sideband, Responses HTTP/WS, manifest | `s2a:backend/internal/server/routes/gateway.go:408` | +| `/v1beta` | GET `/models`, `/models/:model`; POST `/models/*modelAction` | G native Gemini. 실행 action은 `generateContent`, `streamGenerateContent`, `countTokens` | `s2a:backend/internal/server/routes/gateway.go:358`, `s2a:backend/internal/service/gemini_messages_compat_service.go:1117` | +| `/v1beta` | POST·GET `/cachedContents`; GET·PATCH·DELETE `/cachedContents/:cacheID` | G 명시적 컨텍스트 cache 리소스 | `s2a:backend/internal/server/routes/gateway.go:374` | +| `/antigravity` | GET `/models`; `/v1` 아래 POST `/messages`, `/messages/count_tokens`, GET `/models`, `/usage`; `/v1beta` 아래 GET `/models`, `/models/:model`, POST `/models/*modelAction` | 전용 `/v1`, `/v1beta` 그룹은 Antigravity platform 고정 | `s2a:backend/internal/server/routes/gateway.go:511`, `:520`, `:537` | +| `/api/v3`, `/v3`, `/v1`, root | POST `/contents/generations/tasks`; GET·DELETE `/contents/generations/tasks/:task_id` | O SeedanceTasks. 범위 인접 media ingress | `s2a:backend/internal/server/routes/gateway.go:394` | + +Composite POST는 client model을 기반으로 대상 platform을 정한다. Gemini 경로는 route parameter로 platform을 결정한다. API key·그룹 관리나 별도로 등록되는 MCP·결제·패널 route는 gateway map 밖이다. `s2a:backend/internal/server/routes/gateway.go:572`, `:596`, `:629`, `s2a:backend/internal/server/router.go:127`. + +## 3. 기능 인벤토리 + +| CAP tag | 기능 | sub2api entry · 구현 · gate | OpenCodex entry · 구현 · gate / absence | 상태 | 증거 | +|---|---|---|---|---|---| +| CAP-account-load-balancing | 계정 priority·실시간 load·LRU | Messages의 `SelectAccountWithLoadAwareness`. 모델 및 계정 상태를 걸러 Redis batch load를 조회하고 priority → 선택적 조기 reset → load → LRU를 적용한 뒤 실제 slot을 잡는다. OpenAI legacy에도 batch load가 있다. `load_batch_enabled=true`, `prefer_soonest_reset=false`. `s2a:backend/internal/handler/gateway_handler.go:683`, `s2a:backend/internal/service/gateway_scheduling.go:652`, `:708`, `:738`, `s2a:backend/internal/service/openai_gateway_scheduling.go:1326`, `:1417`, `s2a:backend/internal/config/config.go:2661` | Responses의 account-mode 경로는 Codex auth context를 만든다. Codex pool에는 quota·round-robin·fill-first 및 reset-near 가중 배치가 있고 Kiro 동시부하 선택은 provider gate가 있다. `quota-pool/assemble.ts`의 plan weight는 quota 집계에도 쓰인다. `ocx:src/server/index/serve-options.ts:1442`, `ocx:src/server/responses/core-auth.ts:306`, `ocx:src/codex/auth-context.ts:1443`, `ocx:src/codex/routing/selection.ts:514`, `:556`, `ocx:src/oauth/generic-account-failover.ts:745`, `ocx:src/server/responses/request-transport.ts:214`, `ocx:src/quota-pool/assemble.ts:252` | partial | OBSERVED | +| CAP-account-scheduler-weights | priority·queue·error rate·TTFT 복합 점수 | Responses HTTP/WS → `SelectAccountWithSchedulerForCapability`. advanced DB setting은 기본 false. 활성화 시 priority·load·wait·실패율·TTFT 점수와 top K, 선택적 sticky 가산점·quota/reset/cost 가중치를 적용한다. off면 legacy previous-response/일반 load 경로. `s2a:backend/internal/handler/openai_gateway_handler.go:697`, `:2897`, `s2a:backend/internal/service/openai_account_scheduler.go:28`, `:994`, `:1057`, `:1917`, `:2078`, `:2374`, `s2a:backend/internal/config/config.go:2579` | 같은 Responses auth 경로의 Codex `reset-near-weighted`는 reset 기반 가중 선택을 한다. 실패 상태의 입력은 별도 health 판정으로 들어간다. 조사한 경로에서 이들을 queue·TTFT 점수와 결합하는 selector는 확인되지 않았다. `ocx:src/server/responses/core-auth.ts:306`, `ocx:src/codex/routing/selection.ts:524`, `:538`, `ocx:src/codex/routing.ts:1272` | partial | OBSERVED | +| CAP-account-concurrency | 계정별 동시 실행 상한·대기열 | Messages·Responses는 선택 결과의 lease 또는 WaitPlan으로 실제 `account.Concurrency`를 집행한다. Redis script가 만료 정리와 count/acquire를 수행한다. sticky 대기 기본 3/120초, fallback 기본 100/30초. 부하 분모 `EffectiveLoadFactor()`와 실제 slot 수는 구분된다. `s2a:backend/internal/handler/gateway_handler.go:427`, `:448`, `s2a:backend/internal/handler/openai_gateway_handler.go:796`, `:2436`, `s2a:backend/internal/service/gateway_scheduling.go:708`, `:754`, `s2a:backend/internal/repository/concurrency_cache.go:93`, `:631`, `s2a:backend/internal/config/config.go:2656` | Responses의 Kiro OAuth 경로는 `oauthAccountFailover.maxConcurrentPerAccount` 아래에서 계정별 lease 및 제한된 대기를 적용한다. 글로벌 active-turn cap은 전 provider의 총량을 제한한다. `ocx:src/server/responses/request-transport.ts:214`, `:1508`, `ocx:src/oauth/kiro-account-load.ts:70`, `:84`, `ocx:src/server/lifecycle.ts:34` | partial | OBSERVED | +| CAP-user-concurrency | 인증 사용자 기준 공정성 | 인증 middleware가 API key 소유자 `UserID`와 `Concurrency`를 주입한다. Messages/Responses HTTP와 WS turn에서 user slot 집행. Redis key는 user 기준이며 신규 사용자 기본 설정은 5다. `s2a:backend/internal/server/middleware/api_key_auth.go:285`, `s2a:backend/internal/handler/gateway_handler.go:253`, `s2a:backend/internal/handler/openai_gateway_handler.go:2165`, `:3170`, `s2a:backend/internal/repository/concurrency_cache.go:708`, `s2a:backend/internal/config/config.go:2432` | A1. `runAdmittedHttpTurn`은 active-turn lease 및 workflow admission을 적용한다. `MAX_ACTIVE_TURNS=256`은 총량이고 session lane은 API key 소유자별 하드 캡을 집행하지 않는다. `ocx:src/server/index/serve-options.ts:1442`, `:1535`, `ocx:src/server/admitted-http-turn.ts:29`, `ocx:src/server/lifecycle.ts:34`, `:177` | gap | OBSERVED | +| CAP-cache-affinity | Codex/Claude 세션 affinity | Responses에서 session signal·prompt cache key·안정적인 내용 유래 seed로 hash를 얻고 group 단위 sticky binding을 사용한다. 이전 response ID lookup이 별도이며 session TTL 기본 3600초. Claude는 기존 세션 metadata, ephemeral cache content, 메시지 digest 순으로 hash를 얻어 cache binding을 조회한다. `s2a:backend/internal/handler/openai_gateway_handler.go:648`, `s2a:backend/internal/service/openai_gateway_scheduling.go:164`, `:235`, `s2a:backend/internal/service/openai_account_scheduler.go:2374`, `s2a:backend/internal/handler/gateway_handler.go:298`, `s2a:backend/internal/service/gateway_service.go:977`, `s2a:backend/internal/service/gateway_scheduling.go:131`, `s2a:backend/internal/config/config.go:2580` | Codex account-mode admission은 thread binding과 quota scope를 풀고 cache affinity 기본값은 true다. 이전 응답이 특정 계정에 종속되는 경우를 별도 취급한다. Claude native OAuth는 계정 선택 후 pool-enabled일 때 세션 affinity를 쓴다. `ocx:src/server/responses/core-auth.ts:306`, `ocx:src/codex/auth-context.ts:1264`, `:1443`, `ocx:src/codex/routing/selection.ts:370`, `ocx:src/codex/routing/cache-affinity.ts:36`, `ocx:src/server/messages-native-oauth.ts:152`, `ocx:src/oauth/anthropic-routing.ts:390`, `:1117` | parity | OBSERVED | +| CAP-gemini-cache-affinity | Gemini native의 암묵적 cache affinity | `/v1beta/models/*modelAction`에서 명시적 cache가 없을 때 Gemini CLI 세션을 우선한다. 없으면 API key·model·tools·system·첫 user parts를 포함하는 안정 prefix를 쓰며, 미결속 시 digest fallback이 있다. 선택 후 Gemini native 또는 Antigravity로 송신한다. `s2a:backend/internal/server/routes/gateway.go:372`, `s2a:backend/internal/handler/gemini_v1beta_handler.go:466`, `:498`, `:587`, `:747`, `s2a:backend/internal/service/gemini_session.go:25` | native Google ingress와 direct/delivery selection을 확인했다. 일반 OAuth affinity의 해당 Google 경로 적용 및 key scope까지 추적하지 않았다. `ocx:src/server/index/serve-options.ts:677`, `ocx:src/server/index/gemini-routes.ts:117`, `:134` | unknown | OBSERVED-partial | +| CAP-gemini-cached-contents | Gemini 명시적 컨텍스트 cache 및 생성 계정 고정 | `/v1beta/cachedContents` CRUD. 서비스 연결, Gemini 그룹, 지원 계정 유형 및 생성 가격 조건 필요. upstream cache와 공개 리소스의 binding을 저장하고, 호출 시 저장 계정 외 후보를 제외한다. `s2a:backend/internal/server/routes/gateway.go:374`, `s2a:backend/internal/handler/gemini_cached_contents_handler.go:32`, `:181`, `:221`, `:238`, `:584`, `s2a:backend/internal/service/gemini_cached_content.go:150`, `:725`, `s2a:backend/internal/handler/gemini_v1beta_handler.go:563` | A2. Gemini ingress는 model 및 interaction 요청을 분기하고 native method parser는 generation/count/embed를 등록한다. cache 이름을 소유하거나 생성 계정에 고정하는 리소스 계약과 다르다. `ocx:src/server/index/gemini-routes.ts:59`, `:86`, `:134`, `ocx:src/server/gemini-native-paths.ts:8`, `:18`, `:44` | gap | OBSERVED | +| CAP-account-cooldown | 429·과부하에 따른 일시 배제 | gateway forward error → `HandleUpstreamError`. 429는 provider별 reset/Retry-After/설정 fallback, 529는 overload, 조건부 규칙은 계정 또는 model scope 임시 배제. selector의 `IsSchedulable`은 reset·overload·temp 시간을 본다. `s2a:backend/internal/service/gateway_upstream_response.go:544`, `s2a:backend/internal/service/ratelimit_service.go:333`, `:584`, `:1247`, `:1399`, `:2064`, `:2836`, `s2a:backend/internal/service/account.go:194` | Codex pool dispatch는 결과를 account health로 기록하고 실패창·쿨다운을 구분한다. Claude OAuth pool은 분류된 거부와 429 reset 정책에 따라 계정 전환을 검토한다. 계정이 속한 pool 및 모델 경로별로 동작한다. `ocx:src/server/responses/passthrough-dispatch.ts:970`, `ocx:src/codex/routing.ts:1272`, `ocx:src/codex/routing/failure-window.ts:180`, `ocx:src/oauth/anthropic-routing.ts:390`, `:1177`, `ocx:src/oauth/anthropic-rate-limit-policy.ts:16` | partial | OBSERVED | +| CAP-antigravity-429-scope | reset 근거가 빈약한 429의 냉각 범위 | Gemini/Claude 및 compat forward의 retry loop와 반환 처리 양쪽에서 요청 단위로 bare 429의 첫 계정만 냉각할 수 있게 한다. 구조화된 quota/reset 증거가 있는 응답은 별도. `s2a:backend/internal/handler/gemini_v1beta_handler.go:747`, `s2a:backend/internal/service/antigravity_gateway_retry.go:646`, `s2a:backend/internal/service/antigravity_bare429_scope.go:38`, `:56`, `s2a:backend/internal/service/antigravity_gateway_compat.go:502` | Google HTTP 계층에 Antigravity retry가 있고 generic OAuth의 429 account rotation 제외 조건이 있다. 동일 요청의 모든 transport에서 passive cooldown writer까지 조사하지 않았다. `ocx:src/server/index/gemini-routes.ts:134`, `ocx:src/adapters/google-http.ts:282`, `ocx:src/oauth/generic-account-failover.ts:675` | unknown | OBSERVED-partial | +| CAP-token-refresh | 요청 시 갱신과 선제 갱신 | Claude/Gemini/OpenAI/Antigravity/Grok token provider와 background cycle을 구성한다. 공통 API가 account lock과 저장 순서를 관리한다. 선제 갱신 기본 on, 확인 5분, 만료 전 30분. `s2a:backend/internal/service/gateway_service.go:1334`, `s2a:backend/internal/service/openai_gateway_service.go:1224`, `s2a:backend/internal/service/wire.go:142`, `:161`, `:175`, `:349`, `:364`, `:380`, `s2a:backend/internal/service/oauth_refresh_api.go:176`, `:203`, `:429`, `s2a:backend/internal/config/config.go:2708` | OAuth credential 요청 시 유효한 토큰을 조회하고, 갱신이 필요하면 계정 스코프 refresh를 실행한다. xAI·Anthropic 전용 갱신과 일반 lock, 저장 세대 확인이 있다. start CLI는 guardian을 연결하고 선제 sweep은 기본 off다. `ocx:src/oauth/index.ts:708`, `:747`, `:832`, `:1048`, `:1140`, `ocx:src/cli/index.ts:635`, `ocx:src/oauth/token-guardian.ts:137` | parity | OBSERVED | +| CAP-client-upstream-headers | Claude Code·Codex upstream 인식과 호환 헤더 | Claude forward는 OAuth와 client 분류에 따라 요청 헤더 정규화. OpenAI forward는 Codex client 분류, OAuth 헤더 및 설정된 account identity mode 처리. `force_codex_cli=false`. `s2a:backend/internal/service/gateway_forward.go:232`, `:244`, `s2a:backend/internal/service/gateway_upstream_request.go:212`, `s2a:backend/internal/service/openai_gateway_forward.go:226`, `:575`, `:1399`, `s2a:backend/internal/config/config.go:2532` | Claude native/adapter 경로는 정규화된 Anthropic protocol version과 SDK 헤더를 쓰며 credential 유형에 따라 송신한다. Codex branch는 canonical-forward account-mode 및 auth ownership을 구분한다. account identity mode 전반의 대응은 미확인이다. `ocx:src/server/claude-messages.ts:809`, `ocx:src/adapters/anthropic.ts:600`, `:617`, `ocx:src/server/responses/core-auth.ts:296` | partial | OBSERVED | +| CAP-client-tls-profile | 선택 가능한 Claude upstream TLS profile | Messages → `GatewayService.Forward` → 계정 설정 기반 `ResolveTLSProfile` → HTTP upstream transport. `s2a:backend/internal/handler/gateway_handler.go:923`, `s2a:backend/internal/service/gateway_forward.go:377`, `:434`, `s2a:backend/internal/service/tls_fingerprint_profile_service.go:177`, `s2a:backend/internal/repository/http_upstream.go:245` | OpenCodex provider-scoped egress와 헤더 경로만 확인했다. TLS profile 대응 비교는 보류한다. `ocx:src/lib/provider-egress.ts:160`, `ocx:src/adapters/anthropic.ts:607` | unknown | OBSERVED-partial | +| CAP-upstream-proxy | 같은 provider 안의 계정별 egress | Messages/Responses/Gemini native는 선택된 계정의 ProxyID와 실제 proxy가 있을 때 그 경로로 요청, 없으면 빈 proxy 경로 사용. Grok OAuth 갱신은 선택 시점의 proxy binding과 일치 여부를 확인한다. `s2a:backend/internal/service/gateway_forward.go:369`, `:434`, `s2a:backend/internal/service/openai_gateway_forward.go:1085`, `s2a:backend/internal/service/gemini_messages_compat_service.go:1136`, `s2a:backend/internal/service/grok_token_provider.go:69`, `:117` | Responses HTTP 소켓 선택은 `providers..proxy`와 전역 상속을 해석한다. provider outbound가 같은 계약을 쓰며 WS는 transport 정책을 따로 적용한다. OAuth credential record와 Codex auth context에 대한 확인은 A3. `ocx:src/types/provider.ts:558`, `ocx:src/lib/provider-egress.ts:160`, `ocx:src/lib/provider-outbound.ts:301`, `ocx:src/server/responses/fetch-helpers.ts:357`, `:459` | partial | OBSERVED | +| CAP-failover | 제한된 same-account retry와 후보 전환 | Messages와 Responses는 선택 실패 목록과 switch 예산을 쓴다. Claude는 forward 중 writer가 진행하면 replay를 중단한다. OpenAI는 의미 출력이 없는 것으로 판정한 일부 write/keepalive 뒤에만 예외 허용. 기본 switch 예산 10, Gemini 3. API-key pool mode에 별도 동일 계정 retry 설정. `s2a:backend/internal/handler/gateway_handler.go:1062`, `s2a:backend/internal/handler/failover_loop.go:193`, `s2a:backend/internal/handler/openai_gateway_handler.go:917`, `:970`, `:4022`, `s2a:backend/internal/service/account.go:1247`, `s2a:backend/internal/config/config.go:2529` | native Claude·Codex account dispatch와 quota/refusal별 sibling 선택을 지원한다. Claude account pool은 enabled gate, Codex는 account-mode 및 request ownership gate 아래 작동한다. `ocx:src/server/index/serve-options.ts:1442`, `:1535`, `ocx:src/server/messages-native-oauth.ts:152`, `ocx:src/oauth/anthropic-routing.ts:390`, `:1177`, `ocx:src/server/responses/core-codex-account.ts:803`, `ocx:src/server/responses/core-auth.ts:306` | parity | OBSERVED | +| CAP-reset-replay | 결과 불명확한 Responses 전송의 재실행 | HTTP Responses failover는 client 연결과 응답 write 상태를 확인한다. WS 후속 turn은 재구성할 수 있는 bridge payload만 교체 계정에 전달하고, native에서 전체 history가 없으면 연결을 닫는다. `s2a:backend/internal/handler/openai_gateway_handler.go:917`, `:3333`, `:4022`, `s2a:backend/internal/service/openai_ws_forwarder_ingress.go:715`, `:1356` | HTTP/WS Responses의 reset 정책은 전송 결과 불명확 시 fail-closed로 시작하고, provider `retryOnReset` opt-in 및 self-contained 재송신 조건을 평가한다. 전송 실패 이후의 명시적 replay 권한에 한정해 앞선다. `ocx:src/server/index/serve-options.ts:562`, `:1442`, `ocx:src/server/responses/reset-replay.ts:139`, `:230`, `ocx:src/server/responses/codex-ws-wire.ts:483`, `ocx:src/server/responses/codex-ws-exchange.ts:369`, `ocx:src/providers/key-failover.ts:778` | ocx-ahead | OBSERVED | +| CAP-wire-responses-ws | Codex Responses HTTP/WS의 upstream 모드 | GET Responses WS는 upgrade → account capability 선택 → relay/bridge. HTTP POST는 provider별 forward, SSE 또는 WS upstream을 선택한다. WS 전역·OAuth·API key gate 기본 true, mode router v2 기본 false. account gate/force HTTP도 적용. `s2a:backend/internal/server/routes/gateway.go:234`, `:249`, `s2a:backend/internal/handler/openai_gateway_handler.go:2494`, `:2897`, `:3323`, `s2a:backend/internal/service/openai_ws_protocol_resolver.go:38`, `:102`, `s2a:backend/internal/config/config.go:2540` | POST Responses handler와 GET upgrade가 분리되어 있다. WebSockets는 config가 true인 경우만 열리며 ingress lease를 사용한다. Codex upstream exchange의 SSE delivery·WS bridge도 확인했다. `ocx:src/server/index/serve-options.ts:562`, `:578`, `:1445`, `ocx:src/config/feature-flags.ts:3`, `ocx:src/server/responses/codex-ws-exchange.ts:274` | parity | OBSERVED | +| CAP-streaming | Claude SSE와 Responses 스트림 종료 처리 | Claude `reqStream` → SSE forward에서 idle timeout과 keepalive 처리, OpenAI는 semantic output·terminal event 및 usage 추적. stream idle 180초/keepalive 10초 기본, OpenAI first-output timeout은 0에서 off. `s2a:backend/internal/service/gateway_forward.go:864`, `s2a:backend/internal/service/gateway_upstream_response.go:753`, `:1216`, `s2a:backend/internal/service/openai_gateway_forward.go:1252`, `s2a:backend/internal/service/openai_gateway_response_handling.go:51`, `:1040`, `s2a:backend/internal/config/config.go:2523`, `:2647` | Claude native passthrough는 대상 조건을 먼저 검사하며 Responses는 upstream event stream detection과 terminal 처리 경계를 갖는다. 양쪽의 타이머·usage·disconnect 정책이 동일하다는 의미는 아니다. `ocx:src/server/index/serve-options.ts:1411`, `:1504`, `ocx:src/server/claude-messages.ts:809`, `:1379`, `ocx:src/server/responses/passthrough-delivery.ts:533`, `:1371` | parity | OBSERVED | +| CAP-model-mapping | 요청 모델·upstream 모델의 선택과 변환 | 그룹별 channel mapping을 핸들러에서 해석한다. Composite는 일치한 요청에 모델을 다시 쓰고, 선택된 계정의 `GetMappedModel`은 exact/wildcard 매핑을 적용한다. `s2a:backend/internal/server/routes/gateway.go:596`, `:615`, `s2a:backend/internal/handler/openai_gateway_handler.go:587`, `s2a:backend/internal/service/openai_gateway_forward.go:274`, `s2a:backend/internal/service/gateway_forward.go:322`, `s2a:backend/internal/service/account.go:1010` | route resolver가 provider 설정과 discovery/known model에 따라 alias를 풀고 Codex account-mode 경로에서 model entitlement를 따로 검사한다. 그룹 channel과 계정마다 별도의 임의 wildcard table을 둔 s2a와 정책 단위가 다르다. `ocx:src/server/index/serve-options.ts:1445`, `ocx:src/router.ts:599`, `:671`, `ocx:src/server/responses/core-auth.ts:306`, `:317` | partial | OBSERVED | +| CAP-grok-subscription-routing | Grok OAuth 요청 경로 | group platform이 Grok일 때 OpenAI gateway에 연결한다. Responses는 별도 Grok forward를 호출하고 OAuth 유형이면 Grok token provider를 사용한다. session affinity는 model scope를 갖는다. `s2a:backend/internal/server/routes/gateway.go:68`, `:234`, `s2a:backend/internal/domain/platforms.go:128`, `s2a:backend/internal/service/openai_gateway_forward.go:160`, `s2a:backend/internal/service/openai_gateway_grok.go:34`, `s2a:backend/internal/service/openai_gateway_service.go:1239`, `s2a:backend/internal/service/openai_gateway_scheduling.go:177` | Responses request transport의 xAI 분기와 xAI OAuth refresh 경로를 확인했다. 각 Grok media 및 session scope 동작은 별도 검증이 필요하다. `ocx:src/server/index/serve-options.ts:1445`, `ocx:src/server/responses/request-transport.ts:229`, `ocx:src/oauth/index.ts:1151` | partial | OBSERVED | + +### OpenCodex absence receipts + +모두 `9e0e298ef9720cfeaa1209f090a68e4d1965d2a1` export에서 수행했다. 아래 명령의 `$PIN`은 `/Users/jun/Developer/new/700_projects/opencodex/.tmp/chase/opencodex-dev`다. 검색과 인벤토리의 가장 가까운 실행 경로를 함께 읽었다. + +| ID | 명령 · 검색 루트 · 종료 코드 | 판정 범위 | +|---|---|---| +| A1 | `rg -n -i 'user.{0,8}concurrency\|concurrency.{0,8}per.?user\|user.?slot' "$PIN/src" "$PIN/gui/src" "$PIN/docs-site/src" "$PIN/structure"` · exit 1 | HTTP admission의 turn/workflow lease와 WS connection cap을 확인했다. 사용자 ID로 공유되는 slot 및 대기열은 확인되지 않았다. `ocx:src/server/admitted-http-turn.ts:29`, `ocx:src/server/lifecycle.ts:34`, `ocx:src/server/index/serve-options.ts:581` | +| A2 | `rg -n -i 'cached.?contents' "$PIN/src" "$PIN/gui/src" "$PIN/docs-site/src" "$PIN/structure"` · exit 1 | Gemini route parser/dispatcher는 model·method·interaction 계약을 구현한다. Gemini cache 리소스 등록 및 계정 binding은 확인되지 않았다. `ocx:src/server/gemini-native-paths.ts:18`, `:44`, `ocx:src/server/index/gemini-routes.ts:59` | +| A3 | `rg -n 'accountProxy\|proxyByAccount\|perAccountProxy\|\bproxy_id\b\|\bproxyId\b' "$PIN/src" "$PIN/gui/src" "$PIN/docs-site/src" "$PIN/structure"` · exit 1 | `OcxProviderConfig`의 proxy 필드와 transport의 provider egress binding을 확인했다. 같은 provider의 계정들에 proxy를 따로 붙이는 옵션은 조사한 계약에서 확인되지 않았다. `ocx:src/oauth/types.ts:76`, `:106`, `ocx:src/types/provider.ts:558`, `ocx:src/server/responses/fetch-helpers.ts:357` | + +## 4. Gap candidates + +값은 코딩 에이전트를 로컬에서 쓰는 개인과 작은 공유 팀을 기준으로 순서를 매겼다. 후보 5건 중 2건은 인벤토리의 `gap`, 3건은 `partial` 행의 보완이다. + +| ID | 빠진 동작 | 가치 | 공수 | OpenCodex 대상 및 선행 조건 | 위험과 검증 경계 | +|---|---|---|---|---|---| +| L4-01 | Codex 및 Claude OAuth pool에서 upstream 계정별 lease와 bounded wait. 계정 포화 시 세션 affinity와 대기 한도를 함께 고려 | high | L · HTTP/SSE와 WS turn의 release 소유권 및 취소 경합 | `src/oauth/kiro-account-load.ts`의 기존 lease 원리, `src/server/responses/request-transport.ts`, `src/server/messages-native-oauth.ts`, `src/codex/`. 물리 전송 단위 계정 선택 시점 확정 | SSE 종료·WS idle·failover 때 lease 중복 또는 누락. replay 허용 확대는 별도 결정. Lab 참조 금지, sibling 파일로 ratchet 준수 | +| L4-02 | 계정 가용성과 quota 후보를 먼저 걸러 낸 뒤 priority와 실제 부하를 반영하는 선택. TTFT·실패율은 관측 품질이 확보된 뒤 반영 | high | L · 선택/preview 일치, 소량 표본에서 점수 안정화 | L4-01, `src/codex/routing/selection.ts`, `src/oauth/anthropic-routing.ts`, `src/routing/`. 기존 manual pin·thread affinity·quota gate 보존 | 짧은 peak로 account churn과 cache miss 증가 가능. 자동 quota 소비 확대 금지, 계정 식별자와 원문 비로그 | +| L4-03 | 공유 proxy에서 사용자 또는 인증된 호출자 기준으로 동시 turn을 제한 | med | L · ingress별 주체 통합, 여러 key의 동일 주체 귀속 및 응답 코드 | `src/server/auth-cors.ts`, `src/server/admitted-http-turn.ts`, WS turn admission. L5와 신뢰 가능한 owner 식별 계약 선행 | 인증 없는 loopback 요청이나 익명 키를 사용자로 잘못 묶을 수 있음. 개인 기본값을 건드리지 않는 opt-in과 privacy 경계 | +| L4-04 | provider 기본 egress를 상속하면서 선택된 계정에 명시적 override 적용 | med | L · HTTP·WS·refresh·quota 조회의 일관된 egress, 세션 partition | `src/lib/provider-egress.ts`, `src/lib/provider-outbound.ts`, `src/oauth/store.ts`, `src/codex/auth-context.ts`. 먼저 HTTP/WS·refresh transport 계약을 확인 | proxy URL과 인증 비밀 노출, 잘못된 proxy로 fallback 및 재사용된 socket의 route 혼선. 신뢰 경계 검증과 명시적 설정 필요 | +| L4-05 | Gemini 명시적 cache API와 생성 계정/프로젝트에 귀속된 요청 처리 | low | XL · resource lifecycle, TTL, cache 생성의 비용 및 복구 | `src/server/index/gemini-routes.ts`, `src/server/gemini-native.ts`, Google adapter. 실제 Gemini SDK 사용자 수요와 운영 범위 선결 | cache 리소스의 소유권/만료 및 유료 side effect. 개인 도구에서 storage/billing 복제 비용이 큼 | +| L4-R1 | reject candidate · TLS fingerprint 및 client identity 위장 profile 포팅 | low | L · 외부 client 버전·transport 결합 | 프로토콜 호환성은 기존 헤더·버전 분기에서 다룬다 | 외부 서비스가 관찰하는 client identity를 합성하는 기능은 OpenCodex 호환성 목표의 우선순위 밖이다 | + +## 5. OpenCodex-ahead items + +- Responses에서 실패한 물리 전송을 재실행할 권한을 별도로 판정한다. HTTP/WS에서 중단된 입력이 실제로 upstream에 도착했을 수 있고, self-contained 여부와 provider의 `retryOnReset` 허용은 그 경우에도 필요하다. sub2api의 HTTP gate는 client·downstream write를 중심으로 평가하며 native WS 후속 turn은 full payload가 없을 경우 자체적으로 종료한다. `ocx:src/server/responses/reset-replay.ts:139`, `:230`, `ocx:src/server/responses/codex-ws-wire.ts:483`, `s2a:backend/internal/handler/openai_gateway_handler.go:4022`, `s2a:backend/internal/service/openai_ws_forwarder_ingress.go:1356`. + +## 6. 최신 사례 (Aside) + +게시 시각은 UTC 날짜로, 열람 날짜는 세션 현지 시간(KST)으로 적었다. PR 본문의 운영 측정치는 제보자의 표본이다. 공개 소스를 확인할 수 있는 항목은 pinned 코드와 대조했다. + +| 게시일 | 릴리스·commit·PR | source URL | 열람일 | 관측 | OpenCodex 관련성 | 신뢰 | +|---|---|---|---|---|---|---| +| 2026-11-20 | sub2api v0.2.24 · `5c2982a` | [release](https://github.com/Wei-Shaw/sub2api/releases/tag/v0.2.24) | 2026-11-23 | Antigravity 429 냉각 범위, OpenAI timeout 후 account switch, OAuth refresh 저장 순서 수정. 로컬 snapshot의 bare 429 처리와 durable refresh 저장 경로 확인. `s2a:backend/internal/service/antigravity_bare429_scope.go:56`, `s2a:backend/internal/service/oauth_refresh_api.go:429` | upstream 오류와 token rotation의 경계 회귀를 분리해서 다룰 근거 | 높음 · release 및 소스 | +| 2026-11-20 | #8973 · merge `242556f` | [merged PR](https://github.com/Wei-Shaw/sub2api/pull/8973) | 2026-11-23 | 증거가 빈약한 bare 429의 account cooldown을 요청당 한 계정으로 제한. reporter는 작은 pool에서 관련 없는 요청도 503을 겪었다고 기록. loop/후처리 확인. `s2a:backend/internal/service/antigravity_gateway_retry.go:646`, `s2a:backend/internal/service/antigravity_bare429_scope.go:38`, `:56` | request fault와 account quota를 구분할 때 여러 계정에 걸친 부작용을 측정할 사례 | 높음 · 코드, 중간 · 운영 제보 | +| 2026-11-16 | #8822 · merge `04503e0` | [merged PR](https://github.com/Wei-Shaw/sub2api/pull/8822) | 2026-11-23 | Gemini native 안정 prefix. PR 운영 표본은 cache-read token 비율 5.1%→20.8%를 보고한다. maintainer가 failover cache billing 보상을 유지했고 pinned handler에서 안정 hash를 확인했다. `s2a:backend/internal/handler/gemini_v1beta_handler.go:466`, `s2a:backend/internal/service/gemini_session.go:25` | session affinity 도입 효과는 계정 유지율과 실제 cache-read를 함께 봐야 한다 | 높음 · 코드, 중간 · 단일 운영 표본 | +| 2026-11-20 | 공개 제안 #8984 · PR #8961 | [feature issue](https://github.com/Wei-Shaw/sub2api/issues/8984) | 2026-11-23 | 다음 새 세션에서도 동일 사용자에게 먼저 기존 affinity를 고려하는 opt-in 제안. pin 시점 기준 구현으로 집계하지 않았다 | cross-session cache reuse와 사용자 간 load 균형을 함께 평가할 사례 | 중간 · 공개 제안 | +| 2026-11-21 | 공개 issue #9002 · linked PR #9004 · **post-head** | [sticky rebind report](https://github.com/Wei-Shaw/sub2api/issues/9002) | 2026-11-23 | 긴 Claude SSE가 먼저 바뀐 sticky binding을 다시 기록한다는 경쟁 조건 제보. pin의 forward 성공 후 bind와 저장 경로를 확인했다. `s2a:backend/internal/handler/gateway_handler.go:1133`, `s2a:backend/internal/repository/gateway_cache.go:51` | affinity write 소유권을 검증할 동시성 사례 | 중간 · 소스 연결, 실행 미검증 | +| 2026-11-06 | 사용자 issue #8552 · v0.2.19 | [TTFT report](https://github.com/Wei-Shaw/sub2api/issues/8552) | 2026-11-23 | 같은 OAuth 계정의 동시 실행 수와 TTFT가 함께 상승했다고 보고했다. pin의 first-output timeout 기본값은 0이다. `s2a:backend/internal/config/config.go:2523` | L4-01의 포화 관측과 L4-02의 TTFT 가중치를 따로 검증할 근거. 관측 상관관계의 원인은 미확정 | 중간 · 사용자 표본 | +| 2026-11-04 | 사용자 issue #8513 · v0.2.19 | [later-turn WS report](https://github.com/Wei-Shaw/sub2api/issues/8513) | 2026-11-23 | v0.2.19에서 후속 turn 429 뒤 context 유실을 보고했다. pin의 native 경로는 후속 turn에 안전한 payload가 없으면 종료하도록 연결되어 있다. `s2a:backend/internal/service/openai_ws_forwarder_ingress.go:1356`, `s2a:backend/internal/handler/openai_gateway_handler.go:3333` | 과거 버전 제보를 현재 결함으로 옮기지 않고 turn별 replay 회귀 사례로 사용 | 높음 · pin의 종료 분기, 중간 · 과거 운영 제보 | +| 2026-11-22 | CLIProxyAPI v8.1.1 · `6eb8554`, changelog `94b164b` | [peer release](https://github.com/router-for-me/CLIProxyAPI/releases/tag/v8.1.1) | 2026-11-23 | Antigravity CountTokens에서 짧은 cooldown 및 429 상태 기록. CPA pin `0d251842d2`에서 공통 request preparation과 429 상태 처리 호출을 확인했다. `cpa:internal/runtime/executor/antigravity_executor_tokens.go:25`, `:162`, `cpa:internal/runtime/executor/antigravity_executor_request.go:118` | generation과 token-count가 상태 범위를 공유할 때 각각의 오류 기록 계약 확인 | 높음 · 릴리스 및 소스 | +| 2026-11-17 | Linux.do 사용자 게시물 | [remote ingress report](https://linux.do/t/topic/3192610) | 2026-11-23 | 동일 설치에서 loopback 및 계정 테스트는 성공했으나 다른 컴퓨터에서 간헐적 request-body 400을 겪었다는 제보. 원인과 버전은 미확정 | upstream 가용성과 공유 ingress의 body 읽기 실패를 구분하는 진단 사례 | 낮음 · 단일 제보 | +| 2026-10-08 | Linux.do 도구 비교 | [CPA and sub2api discussion](https://linux.do/t/topic/2995845) | 2026-11-23 | 개인 사용과 다인 사용에서 선택 기준이 달라진다는 의견과 pool 구성의 중요성을 확인했다 | L4-03의 수요 근거는 공유 사용에 한정 | 낮음 · 커뮤니티 의견 | + +Aside `u0/local`, CLI `1.26.1115.1556`, codemode `0.9.2`. GitHub 페이지 본문은 `browse.exec`의 raw `type=final` 항목에서 읽고 직접 페이지 방문 결과의 `relative-time`으로 게시일을 확인했다. codemode 외부 결과는 marker 인식 실패를 보고했다. 따라서 raw 항목에서 성공과 URL이 확인된 페이지의 양성 증거만 사용했다. + +## 7. Deferred checks + +- `/backend-api/codex` manifest의 upstream merge와 catalog 세부 필드, `/responses/compact`·`input_tokens`의 세부 의미, Codex WS forwarded transport별 warm pool 및 reconnect 조합. +- Claude CountTokens의 브리지·Grok 로컬 추정 정확성, Claude OAuth 정상화의 헤더별 비교, TLS profile 동작과 TLS·WS egress 조합. +- Gemini direct/Vertex/Antigravity의 모든 credential type, OpenCodex 쪽의 native Gemini cache affinity 전 경로 및 Antigravity 429 cooldown writer의 전체 비교, 명시적 cache mutation recovery의 운영 조건. +- Grok Live/Realtime 및 video/voice/search, Seedance task, SystemOne, embeddings, async/batch image의 upstream payload와 quota 계정 선택. 등록은 §2에 기록했다. +- 스케줄러 DB fallback, Redis snapshot/outbox/rebuild와 multi-replica lease failure, 사용자/계정 limit의 실측 공정성, provider별 선제 갱신 속도 및 cache warm 효과. + +## 8. NOT RUN + +- 빌드, 테스트, lint, 서버 실행, OAuth refresh, upstream inference, SSE/WS 전송 및 계정·Redis·DB 실측. 코드 검토와 공개 페이지 읽기만 수행했다. +- Aside의 `/Users/jun/.local/bin/codemode --account u0 --host local --cwd /Users/jun/Developer/new/700_projects/opencodex --timeout-ms 55000 --code -`에서 GitHub `browse.exec`의 외부 응답이 `ENOMARKER`, `partial: ["no-marker"]`를 반환했다. `api.github.com` 날짜 조회도 사용 가능한 내용을 반환하지 않았다. §6 본문 증거는 raw final에서 복구했고 날짜는 `/Users/jun/.local/bin/aside repl --account u0 --host local`의 public DOM 읽기로 확인했다. +- 외부 사용자의 운영 현상 재현, 공개 이슈 전수 조사, release tag 전체 ancestry 비교. sub2api checkout은 `git log`에서 pin 한 커밋만 보였다. diff --git a/devlog/_plan/261123_proxy_upstream_catchup/005_sub2api_platform.md b/devlog/_plan/261123_proxy_upstream_catchup/005_sub2api_platform.md new file mode 100644 index 00000000000..733228982f0 --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/005_sub2api_platform.md @@ -0,0 +1,135 @@ +# 005 — sub2api 플랫폼과 OpenCodex의 팀 공유 기능 + +L5 · 2026-11-23 · sub2api `328db26f450edbdf9f8d4344a3ea903ac6396842` (2026-11-20, shallow) · OpenCodex `9e0e298ef9` (2026-11-21, origin/dev export). `s2a:`, `ocx:`는 각 스냅샷 루트 기준이다. 상태는 행에 정의한 기능의 범위에 적용한다. + +## 1. 요약 + +- 소규모 팀의 공용 proxy에 가장 가치 있는 차이는 **발급 키별 소비 한도**다. sub2api는 누적 비용 및 5h/1d/7d 비용 window를 검사한다. OpenCodex의 기존 spend ledger는 workflow root와 upstream identity/pool을 기준으로 한다. +- **OpenCodex에 이미 키별 사용량과 모델 제한이 있다.** 관리자 `GET /api/usage?apiKeyId=…`, 키 목록의 요청 수, Hub 역할의 키 자체 집계, 최종 provider/model 기준 제한이 출발점이다. +- 단기 팀원·자동화에는 발급 키 만료가 유용하다. 회전 후보 secret의 만료와 발급 키 자체의 만료는 다른 수명주기다. +- 개인 사용자에게도 유용한 관측성은 실패·지연·429와 거절 이유다. OpenCodex에는 liveness/readiness와 인증된 metrics export가 있고 sub2api에는 내장 규칙·이벤트·silence가 더 있다. +- Codex Responses HTTP/WS와 Claude Code Messages/SSE에서 인증된 키 귀속과 종료 사용량 기록을 확인했다. 한도 설계에서는 타임아웃·재시도·종료에 따른 사용량 증거의 품질도 중요하다. +- 팀 관리 이력은 키 발급·폐기·스코프 변경의 구조화된 이벤트부터, 관리 MCP는 진단 읽기부터 고려할 수 있다. +- 사용자 계정 플랫폼, 상품·구독, 잔액 차감·결제·환불, 리딤, 공지, DB 설치 wizard와 Postgres/Redis 의무화는 단일 사용자 로컬 proxy 범위 밖이다. + +## 2. 표면 맵 + +경로는 상위 prefix를 상속한다. 등록 단위별로 CRUD 및 변형을 묶었다. 전체 조립은 `s2a:backend/internal/server/router.go:117`–136, 별도 setup mode는 `s2a:backend/cmd/server/main.go:78`–104다. + +| 등록 단위 | 표면 및 gate | +| --- | --- | +| 기본·설치 | GET `/health`, GET `/setup/status`, POST `/api/event_logging/batch` (sink). 설치 모드 `/setup/{status,test-db,test-redis,install}`, 변경·연결 테스트는 `NeedsSetup` guard. CLI `-setup`, `AUTO_SETUP`, Vue `/setup`. `s2a:backend/internal/server/routes/common.go:10`, `s2a:backend/internal/setup/handler.go:23`, `s2a:backend/cmd/server/main.go:70`. | +| 로그인·설정 | `/api/v1/auth` register/login/2fa/passkey login/verify-code/refresh/logout/promo·invitation 검증/password reset. LinuxDo, GitHub, Google, WeChat (payment 포함), OIDC, DingTalk OAuth start/callback과 해당 bind/create/complete/pending 변형. `/settings/{public,email-unsubscribe}` 및 인증된 `/auth/{me,revoke-all-sessions,oauth/bind-token}`. Redis limits 및 backend-mode guard. `s2a:backend/internal/server/routes/auth.go:29`–260. | +| 사용자·키·집계 | `/api/v1/user` profile/password/affiliate transfer/identity binding/notify-email/TOTP·step-up/passkeys/platform-quotas/key daily usage/MCP config·consent·grants. `/keys` CRUD, `/groups/{available,rates}`, `/channels/available`, `/usage` list/detail/errors/stats + dashboard stats/trend/models/snapshot-v2/batch key usage. JWT, backend-mode, panel limiter, audit, usage heavy limiter. `s2a:backend/internal/server/routes/user.go:20`–119. | +| 사용자·콘텐츠 | `/announcements` list/read, `/redeem` use/history, `/subscriptions` list/active/progress/summary, `/channel-monitors` list/status, `/channel-monitor-v2` dimensions/snapshot/models/matrix/errors/users (feature + mode 조건). optional-JWT `/model-plaza`, `/pages` slug·이미지·admin 목록. `s2a:backend/internal/server/routes/user.go:122`, `s2a:backend/internal/server/routes/model_plaza.go:16`, `s2a:backend/internal/handler/page_handler.go:261`. | +| Gateway의 플랫폼 접점 | `/v1` Responses POST 및 GET WS, Messages POST, models, usage, `/v1/sub2api/billing` 배율 조회. root aliases 및 Codex direct `/backend-api/codex`, `/antigravity/v1`의 별도 usage, Gemini native `/v1beta` 및 `/antigravity/v1beta`의 URL 모델에 group allowlist 적용. `s2a:backend/internal/server/routes/gateway.go:194`–249, :355–419, :515–543, `s2a:backend/internal/server/middleware/api_key_auth.go:176`. 스케줄링·wire는 L4. | +| 관리자 코어 | `/api/v1/admin`: compliance, dashboard(snapshot/stats/realtime/trends/models/groups/key·user usage/ranking/backfill), users(CRUD/identity/balance/history/keys/limits/RPM/platform quotas/attributes), user-attributes, groups(CRUD/model allowlist/composite/capacity/rates/RPM/keys), api-keys(group 재지정), subscriptions(assign/bulk/extend/reset/revoke/restore/delete/progress), usage(logs/stats/search/cleanup tasks). admin auth + panel limiter + audit + compliance. `s2a:backend/internal/server/routes/admin.go:26`, :164–192, :283–361, :689–736. | +| 관리자 공급자·채널 | accounts(CRUD/test/state/credentials/imports/bulk/privacy/usage/quota/schedule/models), openai/gemini/antigravity/grok OAuth, cn-providers quota/balance, proxies CRUD/test/quality/bulk, channels pricing/CRUD, scheduled-test-plans, error-passthrough-rules, tls-fingerprint-profiles, plugins CRUD·upload·enable·config·test·UI session 및 `/api/v1/plugin-ui/:token/*path`. `s2a:backend/internal/server/routes/admin.go:24`, :362–445, :458–543, :737–800. | +| 관리자 설정·운영 | settings, SMTP·메일 템플릿, admin/scoped admin keys, panel limits, cooldown/timeout/rectifier/beta/web-search. data-management agent health/source/S3/jobs; backups S3/image storage/schedule/create/list/download/restore/delete; system version/update/rollback/restart. ops concurrency/account availability/QPS WS/realtime/alerts/silence/email/runtime/request·upstream·ingress errors/system logs/dashboard. channel-monitors probes/history/templates 및 V2 config/reads. `s2a:backend/internal/server/routes/admin.go:193`–281, :572–688, :801–884, `s2a:backend/internal/server/routes/custom_admin_keys.go:10`. | +| 관리자 사용자 운영 | announcements + read status, redeem-codes generate/export/create-and-redeem/expire/batch, promo-codes CRUD/usages, affiliates invites/rebates/transfers/users, audit-logs list/detail/clear, risk-control, prompt-audit config/runtime/probe/events. `s2a:backend/internal/server/routes/admin.go:138`–184, :446–457, :544–571, :830–849. | +| 결제 | `/api/v1/payment` config/checkout/plans/limits/orders 생성·확인·조회·취소·환불 요청. public verify/resolve, webhook EasyPay/Alipay/WxPay/Stripe/Airwallex. `/admin/payment` dashboard/config/orders 처리·재시도·환불, plans 및 providers CRUD. 사용자 JWT 및 admin auth 계층, checkout 서비스 enable. `s2a:backend/internal/server/routes/payment.go:40`–135, `s2a:backend/internal/service/payment_order.go:25`. | +| 관리 MCP | `/api/v1/mcp` POST/GET/DELETE 등록, stateless handler는 POST만 허용. protected resource/authorization discovery, `/mcp/oauth/{register,token,revoke}`, 별도 JWT 사용자 consent와 grants. 사용자 profile/quotas/groups/channels/keys/usage/dashboard/subscriptions 및 admin dashboard/users/balance/groups/accounts/usage/subscriptions/ops의 allowlisted tool. `s2a:backend/internal/server/routes/mcp.go:21`, `s2a:backend/internal/managementmcp/server.go:31`–67, `s2a:backend/internal/managementmcp/catalog.go:86`–150. | +| Vue 공개·사용자 UI | setup/home/login/register/email-verify/auth callbacks/forgot·reset/key-usage/legal/model-plaza, 공개 payment result/Stripe/Airwallex/popup, root redirect 및 catch-all. 사용자 dashboard/keys/batch-image/usage/redeem/affiliate/available-channels/settings-mcp/oauth-mcp-authorize/profile/subscriptions/purchase/orders/payment-qrcode/custom/monitor. session 및 feature guard. `s2a:frontend/src/router/index.ts:23`–421, :517, :743, :827–970. | +| Vue 관리자 UI | dashboard/ops/audit-logs/users/groups/channels-pricing·monitor/subscriptions/accounts/plugins/announcements/proxies/redeem/promo-codes/settings/risk-control/prompt-audit/usage/affiliates/orders 대시보드·목록·플랜. 관리자 및 해당 feature gate. `s2a:frontend/src/router/index.ts:425`–737, :910–970. | +| 저장소·배포·도구 | Ent/Postgres+migrations, Redis, Compose named/local bind/external DB standalone/dev, root/deploy Dockerfile, Caddy/systemd/installers/Apple Container/data management 서비스. Vue en/zh locale, OpenSpec 변경 작업 및 `skills/sub2api-admin` CLI/REST 운영 가이드. `s2a:backend/cmd/server/wire_gen.go:40`, `s2a:deploy/docker-compose.yml:14`, `s2a:deploy/docker-compose.local.yml:22`, `s2a:deploy/docker-compose.standalone.yml:13`, `s2a:frontend/src/i18n/index.ts:10`, `s2a:openspec/config.yaml:1`, `s2a:skills/sub2api-admin/SKILL.md:20`. | + +## 3. 기능 인벤토리 + +| CAP tag | 기능 | sub2api 등록 → 구현 → gate | OpenCodex 등록 → 구현 → gate 또는 부재 근거 | 상태 | 근거 | +| --- | --- | --- | --- | --- | --- | +| CAP-client-api-keys | 발급·조회·폐기 | `s2a:backend/internal/server/routes/user.go:20`, :83 → `s2a:backend/internal/handler/api_key_handler.go:106`, :182, :298 → `s2a:backend/internal/service/api_key_service.go:495`, :795. JWT와 소유자 확인, 그룹 선택 시 가입 조건. | `ocx:src/server/management/route-registry.ts:352`, :357, :369 → `ocx:src/server/management/oauth-account-routes.ts:197`, :1392, :1499–1567. admin/session gate `ocx:src/server/index/serve-options.ts:690`; 착신 키 인가 정책 `ocx:src/server/auth-cors.ts:400`, :782. 사용자 셀프서비스는 CAP-tenant-auth 참조. | parity | OBSERVED | +| CAP-api-key-model-scope | 모델 호출 제한 | `s2a:backend/internal/server/routes/gateway.go:206`, :364 → `s2a:backend/internal/server/middleware/group_model_allowlist.go:31`, :52; enabled group의 요청 모델 기준 `s2a:backend/internal/service/group_model_allowlist.go:84`–93. | `ocx:src/server/management/oauth-account-routes.ts:1509`, `ocx:src/server/index/serve-options.ts:1152`, :1411, :1504 → `ocx:src/server/admission-model-scope.ts:69`, :129, `ocx:src/server/responses/request-prepare.ts:765`, `ocx:src/server/responses/core-combo.ts:1192`, `ocx:src/server/claude-messages.ts:993`, `ocx:src/server/index/websocket-handler.ts:385`. 구성 키의 provider/model 리스트가 있을 때 최종 목적지에 적용. | ocx-ahead | OBSERVED | +| CAP-api-key-expiry | 발급 키 만료 | `s2a:backend/internal/server/routes/user.go:87` → `s2a:backend/internal/service/api_key_service.go:590`, :879 → `s2a:backend/internal/server/middleware/api_key_auth.go:224`–239. standard에서 만료 검사, simple 조기 반환 및 read-only 예외 :176–196. | A6. `ocx:src/types/config.ts:336`–370 및 `ocx:src/server/management/api-key-rotation.ts:22`, :33, :51는 pending rotation 대상이며 `ocx:src/server/auth-cors.ts:532`의 기존 secret에는 별도 발급 기한이 없다. | gap | OBSERVED | +| CAP-api-key-ip-scope | 발급 키의 IP 규칙 | `s2a:backend/internal/server/routes/user.go:87`–89 → `s2a:backend/internal/service/api_key_service.go:495`, :795 → `s2a:backend/internal/server/middleware/api_key_auth.go:145`에서 키 IP 정책이 있을 때 검사. | A6. `ocx:src/types/config.ts:336`–363, `ocx:src/server/auth-cors.ts:396`, :782는 키 provider/model 범위 및 listener 단위 인증이다. 발급 키에 붙는 IP 정책은 없다. | gap | OBSERVED | +| CAP-api-key-budget | 키별 비용 ceiling 및 5h/1d/7d 비용 window | `s2a:backend/internal/server/routes/user.go:87`–89 및 `s2a:backend/internal/server/routes/gateway.go:212`, :234, :249 → `s2a:backend/internal/server/middleware/api_key_auth.go:224`, `s2a:backend/internal/handler/gateway_handler.go:266`, `s2a:backend/internal/handler/openai_gateway_handler.go:624`, :2794 → `s2a:backend/internal/service/billing_cache_service.go:744`–788 및 `s2a:backend/internal/repository/usage_billing_repo.go:434`, :448. standard 기본, 0 unlimited, simple은 명시 설정 시 세 비용 window만 적용 (`s2a:backend/internal/config/config.go:2132`–2135). user/group RPM은 별개다. | A1. `ocx:src/types/config.ts:336`, 키 인가 `ocx:src/server/auth-cors.ts:782`, token spend `ocx:src/server/responses/request-spend.ts:174`, `ocx:src/lib/spend-reservation-ledger.ts:86`, :144는 root/upstream identity/pool 기준. `ocx:src/server/hub-usage-windows.ts:77`는 upstream quota를 보여 준다. 발급 키 누적·window 차단과는 집계 대상이 다르다. | gap | OBSERVED | +| CAP-usage-per-key | 관리 키별 사용량 조회 | `s2a:backend/internal/server/routes/admin.go:292`, :296 → `s2a:backend/internal/handler/admin/dashboard_handler.go:467`. 사용자 일별 조회 `s2a:backend/internal/server/routes/user.go:47` → `s2a:backend/internal/handler/usage_handler.go:679`–715의 JWT 소유자 검사. | `ocx:src/server/index/serve-options.ts:690`, `ocx:src/server/management/logs-usage-routes.ts:247`, :318 → `ocx:src/server/management/usage-aggregate-cache.ts:331`. 키 목록 `ocx:src/server/management/oauth-account-routes.ts:1392` → `ocx:src/server/management/api-key-usage.ts:102`, :209 및 `ocx:gui/src/pages/ApiKeys.tsx:176`. 구성 키만 `apiKeyId`로 귀속. | parity | OBSERVED | +| CAP-usage-self-service | 키가 자기 사용량·한도를 조회 | `s2a:backend/internal/server/routes/gateway.go:230` → `s2a:backend/internal/handler/gateway_handler.go:1616`–1659. 인증된 key ID로 일별/모델별 통계, 키 제한 상태. 읽기 예외 `s2a:backend/internal/server/middleware/api_key_auth.go:176`–180. | `ocx:src/server/index/serve-options.ts:843` → `ocx:src/server/hub-usage.ts:10`–26, :55–72. dedicated header + configured key + Hub 역할, 동일 ID 필터 및 읽기 후 재인가. 별개 `/v1/usage/windows`는 단일 upstream provider scope의 quota를 반환 (`ocx:src/server/hub-usage-windows.ts:77`–92). | partial | OBSERVED | +| CAP-usage-request-accounting | Codex HTTP/WS와 Claude SSE 귀속·저장 | `s2a:backend/internal/server/routes/gateway.go:212`, :234, :249 → `s2a:backend/internal/handler/openai_gateway_handler.go:863`, :3274 및 `s2a:backend/internal/handler/gateway_handler.go:972` → `s2a:backend/internal/service/openai_gateway_usage.go:176`, :507–540, `s2a:backend/internal/service/gateway_usage_billing.go:660`, :863–900. API key auth 후 standard billing 또는 simple usage 분기. | HTTP `ocx:src/server/index/serve-options.ts:1411`, :1504 및 WS :562 → `ocx:src/server/index/websocket-handler.ts:332`, :385 → `ocx:src/server/auth-cors.ts:661`, `ocx:src/server/request-log.ts:738`, `ocx:src/usage/log.ts:1205`. 요청/turn 종료, 보고·추정 구분, WS 별도 gate, loopback 익명 usage에는 key ID 없음. | parity | OBSERVED | +| CAP-cost-accounting | 요청 비용 산정·집계 | usage routes `s2a:backend/internal/server/routes/user.go:106`, `s2a:backend/internal/server/routes/admin.go:712`; `s2a:backend/internal/service/openai_gateway_usage.go:341`, :589 및 `s2a:backend/internal/service/gateway_usage_billing.go:1029`, :1326에서 usage·tier·가격·rate를 비용 row에 반영. standard에서 집행, simple 분기는 위 행. | 관리 usage `ocx:src/server/management/logs-usage-routes.ts:247`, :318 → `ocx:src/server/management/shared.ts:249`, `ocx:src/usage/cost.ts:882`, :917. 관리자 인가 및 가격·usage 증거가 있을 때 요청/시도별 estimate. 금전 정산은 별개. | parity | OBSERVED | +| CAP-billing-balance | 잔액 차감·구독 사용량 반영 | gateway `s2a:backend/internal/server/routes/gateway.go:212`, :234, :249 → `s2a:backend/internal/service/billing_cache_service.go:744` → `s2a:backend/internal/service/gateway_usage_billing.go:357` → `s2a:backend/internal/repository/usage_billing_repo.go:22`, :69, :174–245. standard에서 request + key dedup과 차감 트랜잭션. 사용량 row 기록은 별도 경로. | A4. `ocx:src/server/management/shared.ts:249`, `ocx:src/usage/cost.ts:882`는 estimate. `ocx:src/lib/spend-reservation-ledger.ts:86` 예약은 upstream 전송 보호다. 수신 사용자 잔액이나 구독을 차감하지 않는다. | gap | OBSERVED | +| CAP-tenant-auth | 입주 사용자·JWT·셀프서비스 | `s2a:backend/internal/server/routes/auth.go:29`, :251, `s2a:backend/internal/server/routes/user.go:20`, `s2a:backend/internal/server/routes/admin.go:302` → `s2a:backend/internal/service/auth_service.go:173`, :545. 등록 설정, 로그인, 인증 후 권한과 상태 조건. | A4. `ocx:src/server/index/serve-options.ts:690` → `ocx:src/server/management-auth.ts:625`, :634의 session/admin principal은 설치 운영 권한이다. 별도 고객 등록 및 가입한 사용자의 셀프서비스 계정이 없다. | gap | OBSERVED | +| CAP-tenant-plans | 그룹·구독 기간·할당량 | `s2a:backend/internal/server/routes/admin.go:331`, :689 및 `s2a:backend/internal/server/routes/user.go:93`, :137 → `s2a:backend/internal/service/api_key_service.go:483`, `s2a:backend/internal/service/subscription_service.go:203`, :1005. standard에서 subscription group admission `s2a:backend/internal/server/middleware/api_key_auth.go:202`, :245. | A4. `ocx:src/server/admission-model-scope.ts:69`와 `ocx:src/server/hub-usage-windows.ts:77`는 키 제한과 upstream quota 조회. 사용자 entitlement, 그룹 유효기간, 플랜을 집행하지 않는다. ClinePass는 upstream plan 조회다. | gap | OBSERVED | +| CAP-payments | 구매·입금·환불·상품 플랜 | `s2a:backend/internal/server/routes/payment.go:40`, :71, :80, :92 → `s2a:backend/internal/handler/payment_handler.go:253` → `s2a:backend/internal/service/payment_order.go:25`, :36, :162, :411. checkout 활성 및 provider 선택 조건. | A4. `ocx:src/server/management/shared.ts:249`, `ocx:src/usage/credit-billing.ts`는 사용량/credit 산정 표현이며 checkout/webhook을 제공하지 않는다. | gap | OBSERVED | +| CAP-dashboards-usage | 운영자·사용자 dashboard | Vue auth/admin `s2a:frontend/src/router/index.ts:195`, :429, :910, API `s2a:backend/internal/server/routes/admin.go:283`, `s2a:backend/internal/server/routes/user.go:106` → `s2a:backend/internal/handler/admin/dashboard_handler.go:81`, `s2a:backend/internal/handler/usage_handler.go:522`, `s2a:frontend/src/views/user/UsageView.vue:514`. | `ocx:gui/src/App.tsx:691`–702 → `ocx:gui/src/pages/use-dashboard-data.ts:315`, `ocx:gui/src/pages/Usage.tsx:161`, `ocx:gui/src/components/v2-usage/use-usage-report.ts:23` → 인증된 `ocx:src/server/management/logs-usage-routes.ts:247`. 로컬/Hub 운영 UI 제공, 고객 계정 포털의 범위는 다르다. | partial | OBSERVED | +| CAP-admin-operations | 운영자의 upstream·설정 운영 | `s2a:backend/internal/server/routes/admin.go:26`, :362, :572, :677에서 admin guard 뒤 account create/update/test `s2a:backend/internal/handler/admin/account_handler.go:1020`, :1155, :1295와 settings/system을 제공한다. 세부 위임 키는 매핑만 수행. | `ocx:src/server/index/serve-options.ts:690`, `ocx:src/server/management-api.ts:376`, :394, :406, :409 → `ocx:src/server/management/provider-routes.ts:1392`, `ocx:src/server/management/oauth-account-routes.ts:1240`–1383, `ocx:src/server/management/system-routes.ts:174`–211의 provider key 및 서비스 관리. | partial | OBSERVED | +| CAP-ops-health | HTTP liveness/readiness | `s2a:backend/internal/server/router.go:117` → `s2a:backend/internal/server/routes/common.go:12` public status. Compose의 app 및 의존 서비스 healthchecks `s2a:deploy/docker-compose.yml:214`, :266, :309. | `ocx:src/server/index/serve-options.ts:608`, :634–646의 public exact GET liveness와 drain-aware readiness. `ocx:Dockerfile:104`는 liveness. 비교 범위는 proxy 프로세스 HTTP probe. | ocx-ahead | OBSERVED | +| CAP-ops-monitoring | 오류 분류·운영 지표 | `s2a:backend/internal/server/routes/admin.go:193`–279 → `s2a:backend/internal/handler/admin/ops_dashboard_handler.go:18`, `s2a:backend/internal/handler/admin/ops_handler.go:216`, :557. ops 기본 켜짐 `s2a:backend/internal/config/config.go:2403`. | 인증 후 `ocx:src/server/management-api.ts:391` → `ocx:src/server/management/metrics-routes.ts:4`, recorder는 `ocx:src/config/feature-flags.ts:25`에서 `metricsExport.enabled === true`일 때 `ocx:src/server/index/serve-options.ts:263`으로 붙인다, terminal 집계 `ocx:src/server/request-log.ts:1581`, UI `ocx:gui/src/App.tsx:700`–701. Prometheus scrape와 로컬 진단을 제공하며 운영 분석 범위에 차이가 있다. | partial | OBSERVED | +| CAP-ops-alerting | 규칙·이벤트·silence | `s2a:backend/internal/server/routes/admin.go:193`–231 → `s2a:backend/internal/service/ops_alert_evaluator_service.go:156`, :215, :295, :678. ops 및 runtime monitoring enabled, rule enabled, 메일은 별도 alert 설정. | A5. `ocx:src/server/management/metrics-routes.ts:4`는 scrape, `ocx:src/server/management/low-quota-routes.ts`는 upstream quota 진단, `ocx:src/telemetry/consent.ts:58`은 제품 telemetry 정책이다. alert rules/events/silence 관리가 없다. | gap | OBSERVED | +| CAP-admin-audit | 관리 변경 감사 원장 | `s2a:backend/internal/server/routes/admin.go:27`–32, :154 → `s2a:backend/internal/server/middleware/audit_log.go:168`, :301 → `s2a:backend/internal/service/audit_log_service.go:71`, :130. admin route middleware에서 변경/지정된 민감 읽기/MCP 읽기 기록, admin 감사 조회. | A3. `ocx:src/server/management/route-registry.ts:352`–374의 mutates는 metadata, `ocx:src/server/management-auth.ts:625`는 principal, `ocx:src/server/request-log.ts:738`은 inference history다. 통합 운영 변경 이벤트 원장이 없다. | gap | OBSERVED | +| CAP-management-mcp | 관리용 OAuth MCP 서버 | `s2a:backend/internal/server/routes/mcp.go:21`–55 → `s2a:backend/internal/managementmcp/auth.go:32`, :75, :99, `s2a:backend/internal/managementmcp/server.go:31`, :112. read-only/user/admin scope 및 기존 HTTP handler 재사용. `mcp.public_url` 기본 빈 값, ResourceURL에서 off (`s2a:backend/internal/config/config.go:130`, :2177, `s2a:backend/internal/handler/mcp_oauth_handler.go:38`). | A2. `ocx:src/server/management-api.ts:370`–411 및 `ocx:src/server/management/route-registry.ts`는 관리 HTTP, `ocx:skills/ocx/SKILL.md:174`는 CLI. `ocx:src/cli/message-mcp-command.ts`는 메시징이며 관리 API OAuth tool transport가 없다. | gap | OBSERVED | +| CAP-storage-platform | 플랫폼 상태 저장·지속성 | `s2a:backend/cmd/server/wire_gen.go:40`, :50 → `s2a:backend/internal/repository/ent.go:104`, :139, `s2a:backend/internal/repository/redis.go:23`; DB/Redis 구성 및 Compose volumes. | `ocx:src/server/request-log.ts:738` → `ocx:src/usage/log.ts:548`, :1205 로컬 JSONL. 관리 storage `ocx:src/server/management/route-registry.ts:294`–316 → `ocx:src/server/management/logs-usage-routes.ts:645`, `ocx:src/storage/policy.ts:527`. `ocx:src/storage/cleanup/db.ts:3`, :23은 Codex 파일용 SQLite다. DB 엔진 일치는 제품 목표 밖. | n/a | OBSERVED | +| CAP-deploy-docker | 컨테이너 기동 | `s2a:Dockerfile:156`–161 및 `s2a:deploy/Dockerfile:121`–126 → `s2a:deploy/docker-compose.yml:44`, :207의 AUTO_SETUP과 dependency health. local/dev/standalone 변형 별도. | `ocx:Dockerfile:82`–107 → 단일 Bun process, `ocx:docker/config.json:4` 비-loopback bind, `ocx:src/server/auth-cors.ts:400`의 인가 정책. 컨테이너 제공 범위에서 parity. | parity | OBSERVED | +| CAP-redeem-platform | 자체 리딤·프로모션 | `s2a:backend/internal/server/routes/user.go:129`, `s2a:backend/internal/server/routes/admin.go:544`, :560 → `s2a:backend/internal/handler/redeem_handler.go:43`, `s2a:backend/internal/service/redeem_service.go:394`, :491–517. JWT 소유자와 코드 상태·종류별 balance/concurrency/subscription 변경. | A4. `ocx:src/server/management-api.ts:389`–390의 Grok coupon/Anthropic reset grant는 upstream 계정 혜택 처리다. proxy 자체 사용자 코드 발급·교환이 없다. | gap | OBSERVED | +| CAP-announcements | 공지·대상·읽음 | `s2a:backend/internal/server/routes/admin.go:446`, `s2a:backend/internal/server/routes/user.go:123` → `s2a:backend/internal/handler/announcement_handler.go:29`, :53 → `s2a:backend/internal/service/announcement_service.go:227`, :301. 사용자 권한 및 대상·기간 조건. | A4. `ocx:src/server/management/system-routes.ts:72`, `ocx:gui/src/App.tsx:693`은 설치 상태를 읽으며 공지 발행·사용자별 읽음 원장이 없다. | gap | OBSERVED | +| CAP-setup-onboarding | 설치·접속 안내 | `s2a:backend/cmd/server/main.go:78`–104 → `s2a:backend/internal/setup/handler.go:23`, :55, :251 → `s2a:frontend/src/router/index.ts:23`. 초기 setup이 필요할 때 CLI/env/wizard로 DB/Redis/admin 설정. | `ocx:gui/src/App.tsx:691`에서 Setup 페이지 선택 → `ocx:gui/src/pages/SetupHub.tsx:56`, :92, :123에서 연결·선택적 설정 안내. DB wizard는 S2A 의존성에서 비롯된다. | partial | OBSERVED | +| CAP-i18n-dashboard | UI 언어 선택 | `s2a:frontend/src/main.ts:53` → `s2a:frontend/src/i18n/index.ts:10`, :33, :45, :62. en/zh lazy load, 선택 저장. | `ocx:gui/src/main.tsx:18` → `ocx:gui/src/i18n/provider.tsx:6`, :21, `ocx:gui/src/i18n/shared.ts:6`, :24, `ocx:gui/src/App.tsx:142`. 저장 선택과 더 넓은 locale 집합. | ocx-ahead | OBSERVED | +| CAP-operator-skill | 운영 스킬·CLI | `s2a:skills/sub2api-admin/SKILL.md:20`, :28, :43 및 `s2a:skills/sub2api-admin/references/admin-cli.md:200`, :210. 환경 변수·CLI/REST recipe. | `ocx:skills/ocx/SKILL.md:34`, :174 및 `ocx:src/cli/capabilities.ts:41`–48. 전체 명령 단위 대응과 entry gate는 검증 보류. | unknown | OBSERVED-partial | +| CAP-architecture-specs | OpenSpec과 개발 계약 | `s2a:openspec/config.yaml:1`, `s2a:openspec/changes/codex-manifest-pinned-accounts/proposal.md:15`, `s2a:openspec/changes/add-openai-compatible-prompt-audit/proposal.md:22`는 요구사항 묶음. | `ocx:structure/INDEX.md`의 ownership map과 현재 catch-up plan이 인접하다. 개발 도구와 제안은 런타임 비교 범위 밖. | n/a | OBSERVED | +| CAP-managed-backups | 예약 backup·복구·원격 대상 | `s2a:backend/internal/server/routes/admin.go:621`, :645의 agent/S3/backup/restore 및 역할·step-up 등록 확인. 내부 워커는 보류. | `ocx:src/server/management/route-registry.ts:294`–316 → `ocx:src/storage/policy.ts:549`; cleanup/restore는 로컬 유지보수. 다른 snapshot/복원 경로들과의 정확한 범위 비교 보류. | unknown | OBSERVED-partial | + +Codex와 Claude Code 연결 안내도 소스로 대조했다. sub2api는 키 사용 모달이 Claude Base URL·token 및 Codex Responses TOML을 만든다. OpenCodex는 Codex 대상이 admission token을 요구할 때 `env_key`를 쓰며 Claude Code는 연결/구독 모드에 따라 자식 환경을 정한다. Gemini native는 sub2api의 전용 API-key middleware 후 URL 모델 제한을 거친다. OpenCodex도 native branch에서 admission scope를 적용한다. `s2a:frontend/src/components/keys/UseKeyModal.vue:882`, :1280, `ocx:src/codex/inject/config-toml.ts:158`–177, `ocx:src/cli/claude.ts:324`–352, `s2a:backend/internal/server/routes/gateway.go:358`–369, `ocx:src/server/index/gemini-routes.ts:127`. + +OpenCodex의 제품 telemetry 경로는 별도다. `ocx:src/server/management/telemetry-routes.ts:13`의 설정·상태, `ocx:src/server/background-lifecycle.ts:148`의 scheduler, `ocx:src/telemetry/consent.ts:70`–122의 opt-out/notice/결정 gate가 적용된다. sub2api의 Claude SDK 이벤트 수신 경로는 200 sink이고, 운영 알림은 별도 ops 경로다. 이 차이는 scrape나 팀 알림을 제품 telemetry에 결합할 근거가 되지 않는다. `s2a:backend/internal/server/routes/common.go:16`, `s2a:backend/internal/server/routes/admin.go:193`. + +### 부재 조사 명령과 결과 + +모두 `9e0e298ef9`의 OpenCodex export를 검색했다. `O`는 `/Users/jun/Developer/new/700_projects/opencodex/.tmp/chase/opencodex-dev`다. 실제 명령은 각 root를 절대 경로로 넘겼다. roots는 `src gui/src docs-site structure`. 유사 기능의 등록·구현은 표의 해당 행에 있다. + +- **A1** (exit 0). upstream key pool·telemetry·entitlement 일치. inbound 키 형식과 spend scope를 대조. + `rg -n -i 'apiKey(Quota|RateLimit|Budget|Spend|Concurrency|Rpm)|per[- ]key.{0,32}(rate limit|concurrency|budget|quota|ceiling)|rate_limit_(5h|1d|7d)|quota_used' "$O/src" "$O/gui/src" "$O/docs-site" "$O/structure"` +- **A2** (exit 1). 일치 없음. 관리 등록표와 messaging MCP 대조. + `rg -n -i '(/mcp/oauth|/api/(v[0-9]+/)?mcp|oauth-protected-resource|management.?mcp|mcp.?management)' "$O/src" "$O/gui/src" "$O/docs-site" "$O/structure"` +- **A3** (exit 1). 일치 없음. 관리 principal과 inference ledger 대조. + `rg -n -i '(/api/(v1/)?(admin/)?audit-logs|AuditLogService|ADMIN_AUDIT|audit-log\.jsonl|adminMutationAudit|managementAudit)' "$O/src" "$O/gui/src" "$O/docs-site" "$O/structure"` +- **A4** (exit 0). ClinePass upstream plan probe 2행만 일치. 인접 관리 handlers와 등록표 대조. + `rg -n -i '(/api/(v1/)?(admin/)?(payment|subscriptions|announcements|redeem-codes|promo-codes|users)(/|["\x27])|PaymentOrder|UserSubscription|balanceHistory)' "$O/src" "$O/gui/src" "$O/docs-site" "$O/structure"` +- **A5** (exit 1). 일치 없음. metrics, quota 진단, telemetry 대조. + `rg -n -i '(/api/(v1/)?(admin/)?ops/(alert|ws/qps)|alert[-_]rules|OpsAlertEvaluator|AlertSilences)' "$O/src" "$O/gui/src" "$O/docs-site" "$O/structure"` +- **A6** (exit 1). 일치 없음. key schema, admission, pending rotation 대조. + `rg -n -i '(apiKeyExpiresAt|clientKeyExpiresAt|IPWhitelist|IPBlacklist|ip_whitelist|ip_blacklist|keyExpiry|keyExpiration|dataPlane.*(CIDR|AllowIP))' "$O/src" "$O/gui/src" "$O/docs-site" "$O/structure"` + +## 4. Gap candidates + +| ID | 권고 범위 | 가치 / 노력 | 예상 위치·의존성·위험 | +| --- | --- | --- | --- | +| L5-1 | 선택형 inbound key 소비 한도와 거절 이유. 팀용 request/token 예산부터 검토하고 USD ceiling은 가격 증거 및 정산 규칙을 확정한 뒤 평가한다. sub2api의 RPM은 user/group 범위다. | high / L — HTTP·WS turn·SSE, 동시 예약/종료, 재시작과 카운터 수명. | `src/server/index/`, `src/server/auth-cors.ts`, `src/server/responses/request-spend.ts` 인접 모듈, `src/lib/spend-reservation-ledger.ts`, `src/usage/`, key GUI. 기존 root/upstream 의미, retry/fallback/cancel, usage 품질, 단일 사용자 기본 경로 부담. | +| L5-2 | 발급 키 만료 시각 및 상태. 신규 turn과 진행 중인 WS/rotation의 경계를 명시. | high / M — 기존 key ID·CRUD 재사용, 세션 및 시간 규칙. | `src/types/config.ts`, `src/server/auth-cors.ts`, key management, WS 및 Remote Link ingress, `gui/src/pages/ApiKeys.tsx`. 기존 키 호환과 secret 미기록. | +| L5-3 | 팀 운영 알림. 기존 metrics의 failure/latency/limited 신호로 임계치와 최근 상태를 제공. | med / M — window, 소음 억제, 회복 상태. | `src/server/request-metrics.ts`, `src/server/management/metrics-routes.ts`, 운영 GUI. label cardinality, 소량 데이터, 알림 기본 off, 외부 전송은 명시적 설정. | +| L5-4 | 관리 변경 감사. 키 발급/스코프/폐기, 설정 변경의 시간·결과·대상 종류·권한 유형. | med / M — 이벤트 스키마·retention·조회. | `src/server/management-api.ts`, `src/server/management/route-registry.ts`, `src/server/management-auth.ts`, `src/storage/`. 필드 allowlist, 요청 원문·credential·계정 식별자 미기록, 기존 consent 유지. | +| L5-5 | 읽기 전용 관리 MCP. usage/health/key metadata만 existing management 계약 위에서 평가. | low / L — client interop, transport, 신원과 원격 권한. | `src/server/management/route-registry.ts`, `src/cli/capabilities.ts`, `skills/ocx/`. 기존 CLI 사용 경로 고려, L5-4 이후 actor 확인, inference key와 관리 권한 분리, response 최소화. | +| L5-6 | **reject candidate** — IP 제한 복제. 고정망엔 가치가 있으나 소규모 팀의 첫 단계에서는 키 스코프와 수명을 우선. | low / M — 프록시 경유 IP, IPv4/IPv6 정책. | `src/server/index/`, `src/server/auth-cors.ts`. reverse proxy/tunnel별 주소 신뢰와 호환성. | +| L5-7 | **reject candidate** — 셀프 가입/RBAC, 그룹 상품·구독, 잔액·결제·환불·리딤·promo/affiliate. 단일 사용자 제품 범위 밖. 팀 비용 통제는 L5-1과 기존 키별 사용량부터. | low / XL — 테넌트 및 상거래 운영에 걸침. | 관리·저장·GUI 전반. 금전·계정 consent, 청구 및 보존 책임. | +| L5-8 | **reject candidate** — 공지 포털, 플랫폼 운영 UI 전면 복제, 프롬프트 원문 감사, Postgres/Redis 의무화, DB setup wizard, OpenSpec 강제 이관. 팀은 기존 UI/metrics/Docker와 배포 안내에서 시작한다. i18n과 운영 스킬은 기존 OpenCodex 기능을 활용한다. | low / XL — 인프라·마이그레이션·운영 부담. | `src/storage/`, `src/telemetry/`, `gui/src/`의 기존 계약 활용. 팀용 usage UI는 기존 결과의 coverage·freshness 표시부터 평가. | + +공통 제약은 Lab import boundary, 파일 크기 ratchet, structure ownership, locale 문구 동기화 및 기존 consent gate다. + +## 5. OpenCodex-ahead + +- 키의 **최종 목적지** provider/model 범위. sub2api group의 클라이언트 모델 allowlist와 비교한 해상도다. `ocx:src/types/config.ts:342`–362, `ocx:src/server/admission-model-scope.ts:129`, `s2a:backend/internal/service/group_model_allowlist.go:84`–93. +- drain-aware **HTTP readiness**와 liveness를 별도로 노출한다. sub2api의 고정 `/health` 응답 및 Compose 의존성 health와 비교했다. `ocx:src/server/index/serve-options.ts:608`, :634, `s2a:backend/internal/server/routes/common.go:12`. +- **GUI locale** 집합이 더 넓다. 번역 완성도와 서버 응답·메일 locale 범위는 미비교. `ocx:gui/src/i18n/shared.ts:6`, `s2a:frontend/src/i18n/index.ts:10`. + +## 6. 최신 사례 (Aside) + +| 공개·병합일 | release/PR/issue | 공개 URL | 접속일 | 확인한 내용 | OpenCodex 관련성 | 신뢰도 | +| --- | --- | --- | --- | --- | --- | --- | +| 2026-11-20 | v0.2.24 · release 화면 commit `5c2982a` | [sub2api v0.2.24](https://github.com/Wei-Shaw/sub2api/releases/tag/v0.2.24) | 2026-11-23 | 사용량·비용 귀속 및 평균 처리 속도 집계가 릴리스 항목. pinned commit은 버전 동기화, shallow에서 태그 ancestry 미확인. | 실제 요청에 정책·비용·성능 관측의 단위를 함께 묶는다. | 높음, 공식 릴리스 문구 | +| 2026-11-17 | v0.2.22 · `b0fa9f3` | [sub2api v0.2.22](https://github.com/Wei-Shaw/sub2api/releases/tag/v0.2.22) | 2026-11-23 | 고동시성 사용자별 차감 묶음과 usage 집계/retention 개선을 공개. pinned usage 모드 분기는 `s2a:backend/internal/service/gateway_usage_billing.go:838`–900, 배치 성능은 미검증. | 키 한도는 동시성·retention이 겹칠 때 admission과 집계 지연을 살필 필요가 있다. | 높음, 성능은 릴리스 측 보고 | +| 2026-11-16 | merged #8659 · `0c641e5` | [sub2api #8659](https://github.com/Wei-Shaw/sub2api/pull/8659) | 2026-11-23 | 그룹 가격 multiplier/RPM 동기화의 트랜잭션. `s2a:backend/internal/repository/user_group_rate_repo.go:291`, :358에서 각각 확인. | 설정을 부분 적용하지 않는 정책 데이터 모델 참고. | 높음, 병합과 소스 확인 | +| 2026-11-09 | merged #8606 | [sub2api #8606](https://github.com/Wei-Shaw/sub2api/pull/8606) | 2026-11-23 | OpenAI Responses cache-write TTL 관측을 사용량·비용 계층에 전달. `s2a:backend/migrations/250_openai_cache_write_ttl.sql:4`, :7 및 `s2a:backend/internal/service/openai_gateway_usage.go:414`에서 필드 확인. | cache 비용 provenance와 추정치 표시 참고. | 높음, 병합과 로컬 필드 확인 | +| 2026-09-28 | open #7655 | [sub2api #7655](https://github.com/Wei-Shaw/sub2api/issues/7655) | 2026-11-23 | 사용자가 로컬 스크립트·청구 도구에 user usage만 위임하는 read-only credential 요청. pinned JWT usage 및 key self-usage 등록은 `s2a:backend/internal/server/routes/user.go:20`, :106, `s2a:backend/internal/server/routes/gateway.go:230`. | 팀 usage와 MCP의 읽기 위임에 범위가 중요하다. | 중간, 사용자 요청 및 경로 확인 | +| 2026-11-21 | open #9000 · post-head | [sub2api #9000](https://github.com/Wei-Shaw/sub2api/issues/9000) | 2026-11-23 | Anthropic 서버 압축 usage 관측과 비용 집계가 어긋난다는 사용자 보고. pinned 자료형 및 스트림 처리 입구는 `s2a:backend/internal/service/gateway_service.go:658`, `s2a:backend/internal/service/gateway_upstream_response.go:1320`. 해당 사례 재현 및 보고 후 변경은 미검증. | 네이티브 usage와 추정치를 구분하는 운영 요구. pinned 상태에는 영향 없음. | 중간, 사용자 보고 | +| 2026-11-21 | LiteLLM v1.112.0-dev.2 · #52859/#52860/#52955 · post-head | [LiteLLM v1.112.0-dev.2](https://github.com/BerriAI/litellm/releases/tag/v1.112.0-dev.2) | 2026-11-23 | 팀 예산 비율 메일 알림과 설정 UI, app customer scope 알림을 dev release에 명시. | 운영 경고를 정책의 집계 대상에 묶는 사례. | 중간, 경쟁 프로젝트 공식 dev release, 소스 미대조 | + +## 7. Deferred checks + +- Responses HTTP/WS와 Messages SSE의 키 귀속·정산 접점, Gemini native 모델 제한 진입을 우선 읽었다. 실 Codex/Claude Code header 선택, Gemini 상세 비용 기록과 root/direct/Antigravity의 전체 endpoint × 정책 교차표는 보류. +- 각 OAuth/브라우저 세션 lifecycle, TOTP/passkey와 reset 설정별 분기, custom admin key 위임 정책, provider lifecycle 및 scheduled probes 구현은 등록 근거 중심. +- 결제 주문 entry/gate는 확인했다. 제공자별 webhook 정산·환불, promo/affiliate, data-management agent 및 S3 작업, risk-control·prompt-audit 데이터 흐름은 전수 검증하지 않았다. +- 대시보드 화면 세부 계약, locale별 번역 completeness, OpenSpec 작업 완료 여부, 운영 스킬의 전체 명령 및 MCP client별 OAuth·revocation·감사 보존 범위를 보류했다. + +## 8. NOT RUN + +- NOT RUN — 빌드, 테스트, typecheck, lint, 서버 기동, Docker·DB·Redis·GUI·MCP·실클라이언트 실행, 결제/리딤/upstream 호출. 출처는 pinned 소스와 공개 Aside 페이지다. +- NOT RUN — `/Users/jun/.local/bin/codemode --cwd /Users/jun/Developer/new/700_projects/opencodex --account u0 --host local --code -`의 `browse.exec` 배치는 `status=indeterminate, complete=false, partial=["no-marker"]`를 반환했다. native Aside REPL로 GitHub 공개 페이지를 읽었다. +- NOT RUN — 비로그인 Linux.do 사례 확인. `/Users/jun/.local/bin/aside repl --account u0 --host local`로 연 공개 검색 URL이 `https://linux.do/login`으로 이동했고 snapshot은 `Error: Element matching selector 'main' not found.`를 반환했다. 커뮤니티 근거는 공개 GitHub 이슈의 사용자 보고를 사용했다. diff --git a/devlog/_plan/261123_proxy_upstream_catchup/006_magpie_gateway.md b/devlog/_plan/261123_proxy_upstream_catchup/006_magpie_gateway.md new file mode 100644 index 00000000000..25dca69aba6 --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/006_magpie_gateway.md @@ -0,0 +1,157 @@ +# 006 — Magpie gateway와 runtime + +기준은 Magpie `3377e77eb697609727c675efe1fbcc9c5b33e54a`와 OpenCodex `origin/dev` `9e0e298ef9720cfeaa1209f090a68e4d1965d2a1`이다. `mgp:`와 `ocx:`는 각각 `.tmp/chase/magpie/`와 `.tmp/chase/opencodex-dev/`를 뜻한다. 비교 상태는 소스에서 따라간 범위에 적용한다. + +## 요약 + +- 개인 사용자에게 가장 직접적인 차이는 장시간 대화의 캐시 비용이다. Magpie는 대화별로 특정 그룹 대상과 계정을 유지하고 cache read/write 및 TTL을 사용한다. OpenCodex도 Codex 계정과 provider 키에 캐시 affinity가 있고 JEV에 선택형 세션 pin이 있다. 일반 combo가 따뜻한 대상을 유지하는 범위를 우선 비교할 가치가 있다. +- Codex Responses, Claude Messages, Chat Completions, Gemini 생성은 양쪽에 있다. Magpie의 Responses WS는 `response.create`와 `response.interrupt`를 처리한다. OpenCodex는 활성화된 네이티브 전송에서 `response.steer`와 `response.inject`까지 처리한다. +- Magpie는 전송 오류로 만든 502도 아직 보류 중이면 후보를 바꿀 수 있다. OpenCodex는 처리 여부가 불명확한 재전송을 기본 거절하며 자족적 body에 대한 운영자 허용과 시도 예산을 따로 둔다. 두 동작 차이만으로 503 발생 빈도나 중복 과금 빈도를 판단할 수 없다. +- OpenCodex도 실제 Claude Code CLI를 실행한다. 남은 차이는 Magpie의 계정별 장기 프로세스와 resume, 대기 중인 도구 결과의 연결이다. OpenCodex의 `claude-cli`는 매 턴 stateless이고 클라이언트가 도구 실행을 소유한다. +- 소규모 팀은 gateway key 범위에 맞춘 Claude Code statusline과 quota/cache 표시를 통해 세션의 실제 대상을 바로 볼 수 있다. OpenCodex에는 이에 사용할 quota, usage, key admission이 이미 있다. +- Magpie의 확장점은 `moejs` 인프로세스 body/event 미들웨어, Bun subprocess의 provider/auth 호스트, 설정된 요청 masking으로 나뉜다. OpenCodex의 로컬 플러그인 계약은 outbound URL/headers에 집중한다. +- 10월 17일 Aside 조사에서 언급된 6개 라우팅과 direct-HTTP 전용 Claude 비교는 이 기준점에서 갱신했다. 현재 Magpie 소스에는 기본 Smart와 11개 등록형 전략이 있고 OpenCodex에 CLI adapter가 있다. 이전 기록은 Aside의 projects/opencodex.md 「Magpie competitive teardown」을 참조했다. + +## 표면 맵 + +Magpie `serve`는 `gateway.New` 및 `ListenAndServe`로 이어진다. 기본 주소는 `127.0.0.1:3425`이고 `MAGPIE_ADDR`, 저장된 포트, LAN/TLS 설정이 주소를 결정한다. 핸들러 공통 경로는 caller, 읽기 전용 키, 키 한도, 동시성, Origin을 검사한다. `plugins/gateway`는 Gateway 관리 화면의 built-in 등록이다. `mgp:internal/cli/main.go:674`, `mgp:internal/cli/providers_cli.go:1737`, `mgp:internal/cli/providers_cli.go:1805`, `mgp:internal/settings/settings.go:2288`, `mgp:internal/gateway/lan.go:36`, `mgp:internal/gateway/gateway.go:857`, `mgp:internal/gateway/gateway.go:1094`, `mgp:plugins/gateway/gateway.go:22`. + +| 표면 | 등록과 연결 | +| --- | --- | +| 탐색·카탈로그 | GET `/`, `/v1`, `/v1/`, `/models`, `/v1/models`, `/v1/models/{id...}`, `/muse-code/models`, `/api/hello`, `/v1beta/models`, `CodexCatalogPath`. `mgp:internal/gateway/gateway.go:1108`, `mgp:internal/gateway/gateway.go:1260` | +| 주 추론 | POST `/v1/chat/completions`, `/v1/responses`, `/v1/responses/compact`, `/v1/messages` 및 각 비버전 별칭. GET `/v1/responses`와 `/responses`의 WS upgrade. POST `/v1/messages/count_tokens`. POST `/v1beta/models/{model}:{method}`의 `generateContent`, `streamGenerateContent`, `countTokens`. `mgp:internal/gateway/gateway.go:1199`, `mgp:internal/gateway/gateway.go:1213`, `mgp:internal/gateway/gateway.go:1262`, `mgp:internal/gateway/gateway.go:2611` | +| 클라이언트 전용 입구 | `/backend-api/codex/…`는 `codexBackend`가 Responses/compact/catalog 및 backend relay를 분기한다. Codex 연결 설정은 이 base URL을 쓴다. Claude Code는 `ANTHROPIC_BASE_URL` 설정에서 Messages로 진입한다. 두 클라이언트 모두 계정별 bridge 대상 또는 다른 provider/model을 선택할 수 있다. `mgp:internal/gateway/codex_backend.go:42`, `mgp:internal/gateway/codex_backend.go:69`, `mgp:internal/gateway/codex_backend.go:340`, `mgp:internal/gateway/codex_backend.go:987`, `mgp:internal/agent/codex.go:1986`, `mgp:internal/agent/codex.go:2962`, `mgp:internal/agent/claude.go:2025`, `mgp:internal/agent/claude.go:2546` | +| Ollama 호환 | GET `/api/version`, `/api/tags`, POST `/api/show`, `/api/chat`, `/api/generate`. `mgp:internal/gateway/gateway.go:1124`, `mgp:internal/gateway/ollama.go:29`, `mgp:internal/gateway/ollama_chat.go:66` | +| 추론 외 요청 | POST `/v1/systemone`, `AlphaSearchPath`와 `/v1` 별칭, images generations/edits, embeddings, rerank, decisions, audio transcriptions/translations/speech, videos 생성, videos 및 content 조회, Realtime GET WS. `systemone` 외 나열된 일반 경로는 비버전 별칭도 등록된다. `mgp:internal/gateway/gateway.go:1209`, `mgp:internal/gateway/gateway.go:1214`, `mgp:internal/gateway/gateway.go:1228` | +| Vendor native | GET/POST/PUT/PATCH/DELETE `/v1/magpie/native/{provider}/{path...}`. 활성 provider와 key scope를 확인하고 등록된 provider 목적지로 전달한다. `mgp:internal/gateway/gateway.go:1240`, `mgp:internal/gateway/native.go:60`, `mgp:internal/gateway/native.go:90` | +| Usage·진단 | `/v1/magpie/quotas`, `AccountsPath`, usage summary와 requests GET/POST, quota history와 remote cards/library/agent-models/refresh/reset, session route/statusline/trace/snapshot/events/concurrency/key limit. 프로세스 진단은 `ClaudeRunsPath`, heap, CPU, goroutines, restart, remote update 및 Omarchy GET/OPTIONS. `mgp:internal/gateway/gateway.go:1131`, `mgp:internal/gateway/gateway.go:1142`, `mgp:internal/gateway/gateway.go:1182` | +| 공유·내장 채팅 | `AdminPath`, OwnMCP 목록, 키 발급/조회/폐기, OIDC 교환, remote prove, 키/CA/join 페이지 및 데이터, `ChatPagePath`의 assets/models/Messages/files/ASR/TTS. 배포와 클라이언트 설정은 L7 범위다. `mgp:internal/gateway/gateway.go:1151`, `mgp:internal/gateway/gateway.go:1167`, `mgp:internal/gateway/gateway.go:1175` | +| MCP·확장점 | Claude bridge의 session token handler, `/mcp/{name}`, `/mcp/run/{name}`, Search/Vision/Memory/Sessions/Image/Browser/Tools/Hub MCP, browser extension/status 및 이미지 파일. Go built-ins는 gateway, groups, rotation, routing, middleware, masking, budget, usage, tools, search, sessions, library, warmups, otel. `mgp:internal/gateway/gateway.go:1244`, `mgp:plugins/all/all.go:5` | +| Plugin 관리·런타임 | GUI GET `/api/plugins`, `updates/listings/agents/github/git/npm/market/search/page/counts/builtin`, POST `choose/check/mirror/registry/like/builtin/{op}` 계열. 등록 계약은 built-in manifest, OpenCode providers/auth, pi provider extension, 비동기 gateway hooks, moejs request/account/provider/event/response 및 routing/usage, tool/budget/page와 agent 확장이다. `mgp:internal/gui/providers.go:1755`, `mgp:internal/gui/plugins.go:607`, `mgp:internal/gui/plugins.go:760`, `mgp:internal/gui/plugins_counts.go:85`, `mgp:internal/gui/builtins.go:146`, `mgp:internal/plugin/host.js:1476`, `mgp:internal/middleware/points.go:70`, `mgp:docs/subsystems/plugin-runtime.md:181`, `mgp:docs/subsystems/plugin-runtime.md:271` | +| 계정 등록·경로 | 기본 `StartSignInWith`는 Claude, Codex, Copilot, Gemini, Antigravity 및 별도 CLI 분기를 다룬다. Plugin 계정의 authorize/finish/API key/import와 목록은 Bun host RPC다. 계정 선택 후 Claude는 subprocess, Codex 및 여러 OAuth 계정은 계정별 signer/transport, plugin은 host fetch를 탄다. `mgp:internal/gui/providers.go:3658`, `mgp:internal/provider/signin.go:247`, `mgp:internal/provider/signin.go:332`, `mgp:internal/provider/account.go:217`, `mgp:internal/gateway/gateway.go:6224`, `mgp:internal/provider/plugins.go:751`, `mgp:internal/plugin/providers.go:1035` | + +### 등록된 번역 쌍 + +네 입구는 공통 `Request`와 `Event`를 통해 서로 변환된다. 아래 `native/IR`은 대상이 해당 wire를 지원하면 relay하고, 변환이나 수집이 필요하면 IR로 갈 수 있다는 뜻이다. 실제 후보는 provider가 가진 `Speaks` 및 모델별 API, relay 가능 여부, compaction/봉인 상태, 모달리티에 의해 제한된다. translated non-stream도 upstream에는 stream으로 요청한 뒤 모아 client JSON으로 렌더링한다. `mgp:internal/provider/provider.go:2259`, `mgp:internal/gateway/gateway.go:6253`, `mgp:internal/gateway/gateway.go:6380`, `mgp:internal/gateway/gateway.go:9962`, `mgp:internal/gateway/gateway.go:10034`, `mgp:internal/gateway/gateway.go:10194`. + +| 입력 → 출력 wire | Chat | Responses | Anthropic | Gemini | +| --- | --- | --- | --- | --- | +| Chat | native/IR | IR | IR | IR | +| Responses | IR | native/IR | IR | IR | +| Anthropic | IR | IR | native/IR | IR | +| Gemini | IR | IR | IR | native/IR | + +공통 등록은 `parseRequest`, `buildFor/build`, `decoder/makeEncoder`다. Vertex 빌더와 Code Assist 응답 decoder가 Gemini 계열의 추가 upstream 변형을 다룬다. 같은 프로토콜의 모든 기능이 보존된다는 판정에는 이 맵을 사용하지 않았다. `mgp:internal/gateway/gateway.go:10347`, `mgp:internal/gateway/gateway.go:10404`, `mgp:internal/gateway/gateway.go:10432`, `mgp:internal/gateway/gateway.go:10492`, `mgp:internal/gateway/gateway.go:10648`. + +## 기능 인벤토리 + +| CAP tag | 기능 | Magpie 진입점·구현·게이트 | OpenCodex 대응 또는 부재 근거 | 상태 | 근거 | +| --- | --- | --- | --- | --- | --- | +| CAP-wire-responses-http | Codex Responses HTTP/SSE 및 번역 | POST 등록 → `serveAgent` → 후보별 native relay 또는 번역. 전송은 대상 API 선택과 request 형태에 의존한다. `mgp:internal/gateway/gateway.go:1201`, `mgp:internal/gateway/gateway.go:6380`, `mgp:internal/gateway/gateway.go:9962` | POST에서 caller admission, `handleResponses`와 `handleResponsesInner`의 adapter/passthrough 분기. 범위는 생성 요청 및 SSE/JSON이다. `ocx:src/server/index/serve-options.ts:1411`, `ocx:src/server/index/serve-options.ts:1445`, `ocx:src/server/responses/core-pipeline.ts:35`, `ocx:src/adapters/registry.ts:229` | parity | OBSERVED | +| CAP-wire-responses-ws | Responses WS, continuation 및 중간 제어 | GET upgrade로 `serveResponsesSocket`. `response.create`를 내부 POST로 전달하고 같은 소켓의 이전 항목을 합친다. `response.interrupt`는 진행 중인 일치 turn을 취소한다. 그 외 frame type은 거절한다. `mgp:internal/gateway/gateway.go:1270`, `mgp:internal/gateway/codex_backend.go:69`, `mgp:internal/gateway/responses_ws.go:192`, `mgp:internal/gateway/responses_ws.go:283`, `mgp:internal/gateway/responses_ws.go:461`, `mgp:internal/gateway/responses_ws.go:500` | GET auth/Origin, `websockets === true`. `response.create`의 SSE-to-WS와 연결 상태에 더해 지원되는 네이티브 전송에서 `response.steer` 및 `response.inject`를 처리한다. `codexNativeSteering`과 `codexNativeInjection`, 대상 게이트가 적용된다. `ocx:src/server/index/serve-options.ts:562`, `ocx:src/config/feature-flags.ts:3`, `ocx:src/server/index/websocket-handler.ts:227`, `ocx:src/server/responses/native-response-control.ts:37`, `ocx:src/server/responses/native-response-control.ts:45` | ocx-ahead | OBSERVED | +| CAP-wire-responses-compact | Codex compaction 처리 | POST compact → `unaryCompact` → compaction 호환 Responses 대상. 호환 계정은 `compaction_trigger`를 사용한다. native/sealed 요구가 있으면 일반 번역을 거절한다. `mgp:internal/gateway/gateway.go:1203`, `mgp:internal/gateway/responses_compact.go:48`, `mgp:internal/gateway/responses_compact.go:79`, `mgp:internal/gateway/gateway.go:6405` | POST 분기와 model routing 후 `supportsNativeResponsesCompactEndpoint`/account 조건을 검사하고 native 경로 또는 routed compaction을 사용한다. native compaction 표면에 대해 일치한다. `ocx:src/server/index/serve-options.ts:1261`, `ocx:src/server/responses/compact.ts:744`, `ocx:src/server/responses/compact.ts:872`, `ocx:src/server/responses/compact.ts:1863` | parity | OBSERVED | +| CAP-wire-responses-replay | HTTP `previous_response_id` | Responses handler에서 이전 입력·출력을 caller key와 묶어 제한된 메모리에 보관한다. 같은 native 보관 경로는 upstream ID로 이어갈 수 있다. `store:false`는 일반 HTTP 보관에 들어가지 않는다. `mgp:internal/gateway/gateway.go:1201`, `mgp:internal/gateway/prev_response.go:24`, `mgp:internal/gateway/prev_response.go:428`, `mgp:internal/gateway/prev_response.go:634`, `mgp:internal/gateway/gateway.go:6431` | Responses prepare에서 thread와 replay owner를 사용해 확장한다. state는 `store:false` 정책 및 spill/shutdown 경로가 있다. 저장 매체와 ownership 처리가 다르다. `ocx:src/server/index/serve-options.ts:1445`, `ocx:src/server/responses/request-prepare.ts:458`, `ocx:src/responses/state.ts:858`, `ocx:src/responses/state.ts:1259` | partial | OBSERVED | +| CAP-wire-claude-messages | Claude Messages SSE, count_tokens | `keepsSignIn` 등록에서 request handler로 진입한다. 같은 wire relay 또는 변환으로 `message_start`, tool block, thinking/signature delta를 내보낸다. `mgp:internal/gateway/gateway.go:1207`, `mgp:internal/gateway/gateway.go:1213`, `mgp:internal/gateway/gateway.go:6380`, `mgp:internal/gateway/anthropic.go:1779`, `mgp:internal/gateway/anthropic.go:1884` | Messages/count_tokens 입구에 surface 설정과 auth가 적용된다. route에 따라 native projection 또는 Responses bridge와 client encoder를 거친다. `ocx:src/server/index/serve-options.ts:1486`, `ocx:src/server/index/serve-options.ts:1536`, `ocx:src/protocols/settings.ts:53`, `ocx:src/server/claude-messages.ts:814`, `ocx:src/server/claude-messages.ts:1316`, `ocx:src/server/claude-messages.ts:1390`, `ocx:src/server/claude-messages.ts:1745` | parity | OBSERVED | +| CAP-wire-chat-completions | OpenAI Chat JSON/SSE | POST route는 Chat parser/encoder를 쓰고 지원 wire에 대해 relay를 먼저 검토한다. `mgp:internal/gateway/gateway.go:1199`, `mgp:internal/gateway/gateway.go:6253`, `mgp:internal/gateway/gateway.go:10351`, `mgp:internal/gateway/gateway.go:10648` | POST route가 gateway admission을 거쳐 Chat→Responses body 또는 native path를 고르고 번역 응답은 Chat SSE로 되돌린다. `ocx:src/server/index/serve-options.ts:1544`, `ocx:src/server/index/serve-options.ts:1576`, `ocx:src/server/chat-completions.ts:431`, `ocx:src/server/chat-completions.ts:578`, `ocx:src/server/chat-completions.ts:780` | parity | OBSERVED | +| CAP-wire-gemini | Gemini 생성, stream, count와 Interactions | `/v1beta/models` 및 모델 action. `generateContent`, `streamGenerateContent`, `countTokens`를 허용한다. Gemini native 또는 IR이며 Gemini encoder는 client stream을 낸다. `mgp:internal/gateway/gateway.go:1262`, `mgp:internal/gateway/gateway.go:2636`, `mgp:internal/gateway/gemini.go:734` | 기본 활성인 Gemini surface와 caller/model scope. native 또는 `handleGeminiGeneration`을 사용한다. `/v1` 별칭과 Interactions 분기가 있다. parser의 embed 두 메서드는 dispatch에서 501이다. `ocx:src/server/index/serve-options.ts:676`, `ocx:src/protocols/settings.ts:49`, `ocx:src/server/index/gemini-routes.ts:59`, `ocx:src/server/index/gemini-routes.ts:81`, `ocx:src/server/index/gemini-routes.ts:122`, `ocx:src/server/gemini-native-paths.ts:8`, `ocx:src/server/gemini-inbound.ts:259` | ocx-ahead | OBSERVED | +| CAP-wire-ollama | Ollama 호환 client | 5개 route 등록. chat/generate는 `ollamaChat`에서 body와 모델을 읽어 gateway로 전달한다. `mgp:internal/gateway/gateway.go:1124`, `mgp:internal/gateway/ollama_chat.go:66` | 정확한 요청 경로 다섯 개를 등록하고 method, 키 및 Origin admission 뒤 처리한다. `ocx:src/server/index/serve-options.ts:672`, `ocx:src/server/ollama-native-paths.ts:6`, `ocx:src/server/index/ollama-routes.ts:41` | parity | OBSERVED | +| CAP-wire-realtime | 음성용 Realtime WS | `/v1/realtime` upgrade, model 및 key/account scope 확인, 단일 대상. 그룹 이름을 거절하고 연결 시도 후보는 해당 대상의 keys/accounts에서 고른다. `mgp:internal/gateway/gateway.go:1228`, `mgp:internal/gateway/realtime.go:146`, `mgp:internal/gateway/realtime.go:183`, `mgp:internal/gateway/realtime.go:219` | `/v1/realtime` 또는 `/v1/live` upgrade와 call create/sideband. provider live relay resolver로 연결한다. standalone WS는 겹치고 call-create 및 vendor별 wire 범위가 다르다. `ocx:src/server/index/serve-options.ts:1612`, `ocx:src/server/index/serve-options.ts:1649`, `ocx:src/server/live.ts:685`, `ocx:src/server/live.ts:818`, `ocx:src/server/live.ts:945` | partial | OBSERVED | +| CAP-wire-retrieval | OpenAI-shaped embeddings/rerank | POST route → body admission/model 확인 → `serveRetrieval`로 provider/group 처리. `mgp:internal/gateway/gateway.go:1218`, `mgp:internal/gateway/embeddings.go:30`, `mgp:internal/gateway/embeddings.go:100` | A6. 가장 가까운 Gemini native parser는 `embedContent`/`batchEmbedContents`를 인식하지만 dispatch는 501을 반환한다. OpenAI URL은 등록되지 않았다. `ocx:src/server/gemini-native-paths.ts:8`, `ocx:src/server/index/gemini-routes.ts:81`, `ocx:src/server/index/serve-options.ts:676`, `ocx:src/server/index/serve-options.ts:1922` | gap | OBSERVED | +| CAP-wire-native-provider-path | Vendor native 경로 relay | `NativePath`와 5개 method → `nativeAny`/Ark 처리. 활성 provider가 필요하고 범위가 제한된 key의 요청은 거절한다. `mgp:internal/gateway/gateway.go:1240`, `mgp:internal/gateway/native.go:60`, `mgp:internal/gateway/native.go:90`, `mgp:internal/gateway/native.go:359` | A6. OCX native Responses나 Gemini는 고정된 프로토콜 endpoint 및 route resolver를 거친다. provider id와 임의 경로를 받는 입구가 아니다. `ocx:src/server/index/serve-options.ts:676`, `ocx:src/server/index/serve-options.ts:1411`, `ocx:src/server/index/serve-options.ts:1922` | gap | OBSERVED | +| CAP-routing-strategies | 그룹, 키, 계정 선택 모드 | `serve` → `plan/planGroup` → registered strategy. 빈 routing은 Smart/Quota first. `rotation`이 Ordered, Rotate, LeastUsed, Pace, Weighted, FreeFirst, Fastest, Cheapest, Drain, FreeExpiring, SmallFirst를 등록한다. 미등록 명시 모드는 목록 순서다. `Manual`은 별도 group 제어 상태다. `mgp:internal/gateway/gateway.go:3342`, `mgp:internal/gateway/fallback.go:542`, `mgp:internal/gateway/fallback.go:701`, `mgp:internal/gateway/routing.go:2798`, `mgp:internal/gateway/routing.go:2878`, `mgp:internal/routes/routes.go:184`, `mgp:internal/routes/strategies.go:685`, `mgp:plugins/rotation/rotation.go:20` | Responses combo는 대상이 설정된 경우 ladder로 실행된다. 지원 전략은 failover, round-robin, random, least-used, reset-window, JEV이며 combo 기본은 failover. `routing`에도 효율·quota profile 평가가 있어 이름만으로 비교할 수 없다. `ocx:src/server/responses/core.ts:79`, `ocx:src/combos/types.ts:213`, `ocx:src/combos/types.ts:583`, `ocx:src/combos/resolve.ts:482`, `ocx:src/routing/evaluator.ts:1` | partial | OBSERVED | +| CAP-cache-affinity | 그룹 대상 및 provider 키/계정 cache stickiness | 선택 후 provider/model 또는 group과 대화/subagent 키로 `affine`. session/turn/strict/off 및 기본 cache 경로. 명시 캐시 사용량이 0이면 input token으로 추정하는 경로가 있다. 성공 후 read/write와 1h cache를 기록하고 `affinity.json`에 write-behind 한다. `mgp:internal/gateway/gateway.go:3347`, `mgp:internal/gateway/gateway.go:3594`, `mgp:internal/gateway/gateway.go:6033`, `mgp:internal/gateway/affinity.go:243`, `mgp:internal/gateway/affinity.go:303`, `mgp:internal/gateway/affinity.go:688`, `mgp:internal/gateway/affinity.go:845`, `mgp:internal/gateway/affinity.go:1272` | Responses Codex auth → account/thread selection이며 pool affinity는 `false`에서만 꺼진다. provider API-key 선택은 별도 `consultProviderCacheAffinity`가 있다. JEV session pin은 opt-in이다. 일반 combo의 교차 provider cache-hit 순서화와 일부 계정 고정은 다른 범위다. `ocx:src/server/responses/core-auth.ts:309`, `ocx:src/codex/auth-context.ts:1443`, `ocx:src/codex/routing/selection.ts:357`, `ocx:src/providers/key-failover.ts:607`, `ocx:src/providers/cache-affinity.ts:83`, `ocx:src/combos/jev-session-pin-config.ts:2` | partial | OBSERVED | +| CAP-failover | 전송 불명확성의 자동 재시도 제한 | 후보 시도에 `holdWriter`를 두고 아직 전달하지 않은 오류를 분류한다. 401/402/403/404/408/429/5xx 및 일부 body 조건을 고려하며 일반 context overflow는 제외한다. non-stream 번역의 transport 오류는 502로 들어가고, `failed`이면 rest 후 다음 후보를 시도한다. warm affinity의 일정 오류는 잠깐 뒤 동일 후보도 한 번 더 확인한다. `mgp:internal/gateway/gateway.go:4170`, `mgp:internal/gateway/gateway.go:5703`, `mgp:internal/gateway/gateway.go:5727`, `mgp:internal/gateway/gateway.go:10039`, `mgp:internal/gateway/fallback.go:2161`, `mgp:internal/gateway/fallback.go:3789` | Responses passthrough/WS에서 commitment 및 처리 증거를 함께 판단한다. 이미 관측된 응답은 `refused-committed`, upstream 처리 여부 unknown/processed는 `refused-ambiguous`다. `retryOnReset`이 없으면 allowance도 없다. opt-in 시 `store:false`, no continuation/background, client-executed tools, allowance count를 검사한다. 상태와 본문이 확인된 별도 fallback은 여전히 가능하다. `ocx:src/lib/request-failure-model.ts:153`, `ocx:src/server/responses/passthrough-dispatch.ts:775`, `ocx:src/server/responses/codex-ws-wire.ts:483`, `ocx:src/server/responses/reset-replay.ts:112`, `ocx:src/server/responses/reset-replay.ts:229` | ocx-ahead | OBSERVED | +| CAP-bridge-claude-cli | 실제 Claude Code CLI와 계속되는 세션 | 선택된 `Account.Agent == "claude"`에서 CLI bridge. `owner`와 대화 조건에 맞는 run의 재사용 또는 saved session의 resume을 선택하고, 새 run의 MCP 도구 결과는 gateway handler로 받는다. `claudePrintMode`와 실행 환경이 모드를 가른다. `mgp:internal/gateway/gateway.go:6224`, `mgp:internal/gateway/gateway.go:1244`, `mgp:internal/gateway/claude_subscription.go:1025`, `mgp:internal/gateway/claude_subscription.go:2070`, `mgp:internal/gateway/claude_subscription.go:4091`, `mgp:internal/gateway/claude_subscription.go:6663`, `mgp:internal/gateway/claude_subscription.go:7392`, `mgp:internal/settings/settings.go:536` | 활성 `claude-cli` provider → adapter `runTurn` → 실제 Claude CLI, quota preflight, stateless stream-json, client-owned tools. 선택한 tool catalog는 capture MCP를 쓰며 도구 실행은 client 소유다. `ocx:src/providers/registry/entries-extended.ts:1798`, `ocx:src/adapters/registry.ts:173`, `ocx:src/server/responses/core-pipeline.ts:128`, `ocx:src/adapters/claude-cli/adapter.ts:122`, `ocx:src/adapters/claude-cli/adapter.ts:196`, `ocx:src/adapters/claude-cli/adapter.ts:223`, `ocx:src/adapters/claude-cli/adapter.ts:265` | partial | OBSERVED | +| CAP-bridge-codex-oauth | Codex/ChatGPT subscription native relay | Codex backend와 일반 Responses로 들어간다. 선택한 `codex` 계정의 signer, turn state, streaming socket 경로가 있으며 이 대상이 있어야 relay할 수 있다. `mgp:internal/gateway/gateway.go:1260`, `mgp:internal/gateway/codex_backend.go:69`, `mgp:internal/gateway/codex_backend.go:993`, `mgp:internal/gateway/gateway.go:6881`, `mgp:internal/gateway/gateway.go:6915`, `mgp:internal/gateway/codex_socket.go:532` | Codex URL 정규화와 Responses entry → 선택한 `codexAccountMode`로 auth context 해석 → native passthrough. `ocx:src/codex/context-compat.ts:83`, `ocx:src/server/index/serve-options.ts:1411`, `ocx:src/server/responses/core-auth.ts:309`, `ocx:src/codex/auth-context.ts:1062`, `ocx:src/server/responses/passthrough-dispatch.ts:775` | parity | OBSERVED | +| CAP-bridge-oauth | Codex 외 OAuth 및 vendor별 transport | GUI sign-in과 관리 → built-in sign-in dispatch → 사용 가능한 계정의 signer. Copilot Auto와 Google 계열은 고유 경로다. plugin sign-in 계약은 다음 별도 행에 있다. `mgp:internal/gui/providers.go:3658`, `mgp:internal/provider/signin.go:332`, `mgp:internal/provider/account.go:217`, `mgp:internal/gateway/gateway.go:6236` | POST `/api/oauth/login` 및 계정 관리 등록, provider adapter 및 auth pipeline을 사용한다. Claude OAuth와 CLI, Gemini/Code Assist 계열 등은 개별 path를 가진다. provider별 로그인·refresh·quota 동등성은 따로 검증해야 한다. `ocx:src/server/management/route-registry.ts:354`, `ocx:src/server/management/route-registry.ts:378`, `ocx:src/server/management/oauth-account-routes.ts:256`, `ocx:src/adapters/registry.ts:173`, `ocx:src/server/responses/core-auth.ts:309` | partial | OBSERVED | +| CAP-gateway-middleware | 설정형 ingress body, provider/account 및 reply event/JSON hooks | builtin `middleware`가 `gwmw.Use`를 등록한다. 활성 middleware 패키지가 있을 때 `serveAgent`에서 체인을 시작하고 `onRequest`/`onAccount`/`onProvider`와 `onEvent`/`onResponse`를 수행한다. plugin별 enable/config와 hook budget이 적용된다. `mgp:plugins/middleware/middleware.go:23`, `mgp:internal/gateway/middleware.go:24`, `mgp:internal/gateway/middleware.go:102`, `mgp:internal/middleware/middleware.go:133`, `mgp:internal/middleware/middleware.go:197`, `mgp:internal/middleware/run.go:143`, `mgp:internal/middleware/run.go:253` | A3. `ocx start`의 plugin context는 URL+headers를 내보내는 `registerUpstreamRewriter`와 shutdown만 준다. body, reply 이벤트 및 account filter는 계약에 없다. `ocx:src/cli/index.ts:559`, `ocx:src/plugins/loader.ts:32`, `ocx:src/plugins/loader.ts:270`, `ocx:src/plugins/upstream-hooks.ts:15`, `ocx:src/plugins/upstream-hooks.ts:64` | gap | OBSERVED | +| CAP-gateway-middleware-packages | Param Override, Model Map, Word Guard, Think Tags, Codex History | pinned host에서 설치·활성 middleware의 선언을 읽고 hooks를 등록한다. 기본 market에는 param-override/model-map/word-guard/think-tags가 있다. Codex History의 별도 공개 패키지와 기본 빈 provider/alias 설정은 Aside로 확인했다. 각 패키지 코드의 개정은 Magpie head와 독립이다. `mgp:internal/plugin/market.json:28`, `mgp:internal/plugin/middleware.go:15`, `mgp:internal/middleware/middleware.go:133`, `mgp:docs/subsystems/gateway-middleware.md:17` | adapter/model resolver 안에 고정된 변환이 있고 로컬 플러그인 계약은 URL+headers다. 패키지별 wire 동작의 기능 단위 대조는 보류했다. `ocx:src/router.ts:723`, `ocx:src/plugins/upstream-hooks.ts:15` | unknown | OBSERVED-partial | +| CAP-plugin-host | OpenCode auth plugin과 pi provider 호스트 | `/api/plugins/{op}`에서 설치/활성화. Bun subprocess가 OpenCode hooks 또는 pi provider를 로드한다. authorize/finish/provider list, 모델 요청은 account scope로 RPC/Fetch에 이어진다. `mgp:internal/gui/plugins.go:760`, `mgp:internal/plugin/host.go:1091`, `mgp:internal/plugin/host.go:2120`, `mgp:internal/plugin/host.js:1476`, `mgp:internal/plugin/host.js:1527`, `mgp:internal/plugin/pi.js:498`, `mgp:internal/plugin/pi.js:641`, `mgp:internal/plugin/providers.go:1035`, `mgp:internal/provider/plugins.go:751` | A2a. 로컬 `setup(ctx)` import는 같은 Bun process에서 실행되며 auth/provider를 등록하는 API는 없다. provider 생성은 내장 adapter registry가 한다. `ocx:src/plugins/loader.ts:32`, `ocx:src/plugins/loader.ts:270`, `ocx:src/adapters/registry.ts:198`, `ocx:src/adapters/registry.ts:229` | gap | OBSERVED | +| CAP-plugin-distribution | 커뮤니티 plugin의 검색, 설치, 업데이트 | discovery와 add/upgrade를 등록한다. `dist` index/tarball 설치 경로가 있고 serving 시작 30초 뒤 및 매시간 확인한다. 설치된 활성 `@magpie-community/` namespace와 unpinned일 때 자동 업그레이드하며, git/일반 npm/pinned에는 별도 확인 또는 수동 적용이 있다. `mgp:internal/gui/plugins.go:687`, `mgp:internal/gui/plugins.go:760`, `mgp:internal/plugin/dist.go:170`, `mgp:internal/plugin/dist.go:310`, `mgp:internal/plugin/updates.go:68`, `mgp:internal/plugin/updates.go:77`, `mgp:internal/plugin/updates.go:211`, `mgp:internal/plugin/updates.go:317`, `mgp:internal/gateway/gateway.go:999` | A2b. 로컬 디렉터리 최근접이며 시작 시 신뢰 검사 후 파일을 로드한다. `plugins-doctor`는 Codex 클라이언트 자체의 bundled marketplace 진단이다. `ocx:src/plugins/loader.ts:158`, `ocx:src/plugins/loader.ts:270`, `ocx:src/codex/plugins-doctor.ts:146` | gap | OBSERVED | +| CAP-request-masking | 프롬프트의 secret/PII/사용자 단어 masking 및 응답 복원 | 활성 privacy 규칙 또는 강제 key 경로에서 masking built-in을 사용한다. 선택한 대상과 정책에 대해 upstream 전 body를 처리한다. `masking.go`에서 규칙/placeholder와 선택형 로컬 detector, 복원 writer를 만든다. 필수 masking 미가용/차단 오류는 요청을 보내기 전에 처리한다. `mgp:plugins/redact/redact.go:23`, `mgp:plugins/redact/redact.go:46`, `mgp:internal/gateway/gateway.go:3067`, `mgp:internal/gateway/redact.go:32`, `mgp:internal/gateway/redact.go:65`, `mgp:internal/gwmw/gwmw.go:285`, `mgp:internal/masking/masking.go:29`, `mgp:internal/masking/masking.go:57`, `mgp:internal/masking/masking.go:381`, `mgp:internal/masking/masking.go:431` | A1의 hit는 이미 알려진 outbound credential을 terminal upstream error·diagnostic에서 지우는 기능이다. 이 경로는 prompt body에 적용하는 privacy rule이나 응답 placeholder 복원이 아니다. `ocx:src/lib/outbound-credential-registry.ts:206`, `ocx:src/server/responses/terminal-error-redaction.ts:103`, `ocx:src/server/responses/terminal-error-redaction.ts:208`, `ocx:src/plugins/upstream-hooks.ts:15` | gap | OBSERVED | +| CAP-quota-display | 구독·키 quota 및 usage 화면 | `/v1/magpie/quotas`와 usage API 및 GUI Usage plugin. loopback 또는 공유 승인 및 key scope, kept/live 분기. Usage UI가 quota reading과 ledger를 표시한다. `mgp:internal/gateway/gateway.go:1131`, `mgp:internal/gateway/gateway.go:1326`, `mgp:internal/gateway/usage_api.go:59`, `mgp:plugins/usage/usage.go:10`, `mgp:internal/gui/assets/plugins/usage/page.js:783` | 관리 route registry, `/api/provider-quotas`→provider quota probe/observations, `/api/usage` rollup. GUI provider/usage 및 tray가 값을 소비한다. 설정된 provider의 quota/usage 표시 범위에서 일치한다. `ocx:src/server/management/route-registry.ts:298`, `ocx:src/server/management/route-registry.ts:396`, `ocx:src/server/management/provider-routes.ts:879`, `ocx:src/providers/quota.ts:209`, `ocx:gui/src/pages/Tray.tsx:109`, `ocx:gui/src/pages/Providers.tsx:361` | parity | OBSERVED | +| CAP-usage-per-key | 공유 proxy의 caller key 사용량 조회 | `/v1/magpie/usage/requests`에서 held key는 자기 ID로 필터된다. offset/limit 및 cursor feed가 있고 summary는 scope가 좁은 키를 이 route로 안내한다. `mgp:internal/gateway/gateway.go:1133`, `mgp:internal/gateway/usage_api.go:59`, `mgp:internal/gateway/usage_api.go:74`, `mgp:internal/gateway/usage_api.go:99` | `/v1/usage`와 `/v1/usage/windows`를 등록하고 key admission과 동일 key로 rollup한다. 여기서 추적한 OCX 응답은 집계이고 Magpie는 자기 caller의 행/변경 피드를 제공한다. `ocx:src/server/index/serve-options.ts:843`, `ocx:src/server/hub-usage.ts:10`, `ocx:src/server/hub-usage.ts:30`, `ocx:src/server/hub-usage.ts:57` | partial | OBSERVED | +| CAP-gateway-statusline | Claude Code session route + cached quota | GET/POST `/v1/magpie/statusline`. key-scoped quota admission, Claude Code stdin의 session_id, 해당 caller의 최근 route, kept quota를 텍스트/JSON으로 합친다. `mgp:internal/gateway/gateway.go:1142`, `mgp:internal/gateway/statusline.go:46`, `mgp:internal/gateway/statusline.go:76`, `mgp:internal/gateway/statusline.go:97` | A5. 관리 quota와 data-plane key-scoped usage는 이미 있다. 해당 입구는 session_id로 최근 실제 route를 조회해 CLI statusline으로 렌더하지 않는다. `ocx:src/server/management/provider-routes.ts:879`, `ocx:src/server/index/serve-options.ts:843`, `ocx:src/server/hub-usage.ts:57` | gap | OBSERVED | + +### 부재 확인 명령 + +모든 명령은 기준 `9e0e298ef9`의 export를 대상으로 repo workdir에서 실행했다. 아래 `O`를 먼저 선언하면 실행한 절대 경로 인수가 재현된다. 네 검색 루트는 `src`, `gui/src`, `docs-site/src`, `structure`다. 각 행의 실제 등록·동작 비교는 위 인벤토리의 OCX 열에 있다. + +```sh +O=/Users/jun/Developer/new/700_projects/opencodex/.tmp/chase/opencodex-dev + +# A1 — exit 0. outbound-credential-registry와 terminal-error-redaction hit만 확인. +rg -n -i 'RedactPersonal|RedactWords|Masking\.Wanted|request[-_ ]masking|mask(Request|Prompt)|mask(Secrets|Personal)|restorePlaceholders|request.*PII|outbound.*PII' "$O/src" "$O/gui/src" "$O/docs-site/src" "$O/structure" + +# A2a — exit 1. +rg -n -i 'opencode[-_ ]auth[-_ ]plugin|@opencode-ai/plugin|loadPiPlugin|pi[-_ ](extension|package).*provider|plugin[-_ ]provider[-_ ]host' "$O/src" "$O/gui/src" "$O/docs-site/src" "$O/structure" + +# A2b — exit 1. 광역 marketplace 검색의 주요 근접 hit는 Codex 자체 plugins-doctor와 로컬 plugin 문서. +rg -n -i '@magpie-community/|plugins\.json|checkPluginUpdates|autoUpdatePlugins|installPluginPackage|pluginRegistryUrl' "$O/src" "$O/gui/src" "$O/docs-site/src" "$O/structure" + +# A3 — exit 1. +rg -n -i 'register.*(RequestBody|ResponseEvent|ResponseBody|Middleware)|middleware-(param-override|model-map|word-guard|think-tags|codex-history)|gatewayMiddleware' "$O/src" "$O/gui/src" "$O/docs-site/src" "$O/structure" + +# A5 — exit 1. +rg -n -i '/v1/magpie/statusline|/api/.*/statusline|sessionRoute.*statusline|gateway.*statusline' "$O/src" "$O/gui/src" "$O/docs-site/src" "$O/structure" + +# A6 — exit 1. +rg -n -i '/v1/(embeddings|rerank)|/v1/magpie/native|\bdispatch(Rerank|Embeddings)\b' "$O/src" "$O/gui/src" "$O/docs-site/src" "$O/structure" +``` + +### 주요 동작 경계 + +- **Codex 시작과 이어가기**. Magpie는 `/backend-api/codex`에서 모델 카탈로그와 native account relay를 별도로 판단한다. WS에서 이어진 요청은 소켓 안의 항목과 합쳐지고 누락된 ID는 새 소켓에서 전체 대화를 보낼 수 있도록 구조화된 오류를 받는다. HTTP `previous_response_id` 저장과 소켓의 turn 보관은 다른 수명이다. OpenCodex의 WS 제어도 네이티브 지원을 먼저 검사한다. `mgp:internal/gateway/codex_backend.go:69`, `mgp:internal/gateway/responses_ws.go:461`, `mgp:internal/gateway/responses_ws.go:529`, `mgp:internal/gateway/prev_response.go:24`, `ocx:src/server/responses/native-response-control.ts:45`. +- **Claude Messages SSE와 구독**. Magpie는 tool call, text, thinking, signature를 각기 다른 stream event로 관리한다. 자체 Claude 구독의 subprocess는 provider/account owner와 대화에 매칭하며 이어가기 시 저장본도 확인한다. OpenCodex는 per-turn subprocess에서 재생 가능한 도구 호출을 포착해 외부 클라이언트에 되돌린다. 로컬 auth나 워크스페이스가 여러 호출자에게 공유될 때 프로세스 재사용의 경계를 별도로 설계해야 한다. `mgp:internal/gateway/anthropic.go:1496`, `mgp:internal/gateway/anthropic.go:1803`, `mgp:internal/gateway/claude_subscription.go:7402`, `ocx:src/adapters/claude-cli/adapter.ts:22`, `ocx:src/adapters/claude-cli/adapter.ts:223`. +- **같은 후보 재시도와 다음 후보**. Magpie `retryable`의 HTTP/body 분류, `holdWriter.passing` 경계, affinity 재호출, cooldown 적용이 별개다. OpenCodex의 `refused-ambiguous`는 전송 증거의 경계다. 안전하게 재전송할 수 있는 것으로 판단된 케이스에서만 후보 선택과 회복 표시를 개선하는 편이 적합하다. `mgp:internal/gateway/fallback.go:2158`, `mgp:internal/gateway/fallback.go:3789`, `mgp:internal/gateway/gateway.go:5703`, `ocx:src/lib/request-failure-model.ts:146`, `ocx:src/server/responses/reset-replay.ts:229`. +- **추가 비교 표면인 Realtime**. Magpie의 첫 분기는 normal HTTP 요청을 426으로 반환하고 유효한 WebSocket을 단일 모델로 고정한다. key/account scope와 업스트림 연결 후보를 먼저 확인한다. OpenCodex는 standalone과 call-create 후 sideband join을 별도 경로로 등록한다. `mgp:internal/gateway/realtime.go:146`, `mgp:internal/gateway/realtime.go:183`, `mgp:internal/gateway/realtime.go:219`, `ocx:src/server/index/serve-options.ts:1612`, `ocx:src/server/index/serve-options.ts:1649`. +- **설계 기록에서 가져올 검증 항목**. `LESSONS.md`는 캐시 엔트리 재사용 시 읽는 값 전부의 소유·범위가 맞아야 함, 매 요청·poll에 추가되는 비용은 호출 빈도로 평가, stream fixture에는 프로토콜이 허용하는 차이를 반영, telemetry allow-list를 권고한다. `gateway-routing.md`의 WS/Realtime/continuation 구획, `claude-subscription-bridge.md`의 resume/취소/프로세스 예산, `plugin-runtime.md`의 조립과 실패 처리, `gateway-middleware.md`의 hook 제약과 비용은 후속 구현의 검증 입력이다. 문서 수치는 runtime 측정으로 간주하지 않았다. `mgp:LESSONS.md:301`, `mgp:LESSONS.md:385`, `mgp:LESSONS.md:431`, `mgp:LESSONS.md:532`, `mgp:docs/subsystems/gateway-routing.md:3254`, `mgp:docs/subsystems/claude-subscription-bridge.md:1498`, `mgp:docs/subsystems/claude-subscription-bridge.md:1827`, `mgp:docs/subsystems/plugin-runtime.md:438`, `mgp:docs/subsystems/gateway-middleware.md:45`. + +## Gap candidates + +| ID | 빠진 기능과 가치 | 노력·근거 | 예상 경로와 의존성 | 위험과 범위 | +| --- | --- | --- | --- | --- | +| L6-1 | 일반 combo에서 이미 따뜻한 세션 대상을 선택적으로 우선 유지. high. 한 개발자의 긴 코딩 대화에서 불필요한 cache misses를 줄이고 팀에서는 다른 key에 바인딩이 섞이지 않게 한다. | M. 기존 pool/키 affinity 및 JEV pin을 참고해 group target 선택과 해제·관측 계약을 추가한다. | `src/combos/resolve.ts` 인접 모듈, `src/server/responses/core-combo.ts`, `src/providers/cache-affinity.ts`. 실제 cache read/write 관측과 owner-bound session key가 필요하다. | cooldown, 모델 호환, 키 scope, sealed replay ownership은 선행 조건이다. provider가 cache 정보를 생략하면 unknown으로 유지한다. `core.ts` ratchet과 Lab import 경계를 지킨다. | +| L6-2 | Claude Code statusline에 현재 세션의 실제 route와 기존 quota snapshot을 함께 표시. high. 단일 사용자와 key로 공유하는 팀이 도구를 벗어나지 않고 판단할 수 있다. | M. read model과 bounded client CLI glue가 필요하다. | `src/server/hub-usage.ts` 인접의 data-plane handler, `src/providers/quota.ts`, `src/cli/claude.ts`. 최근 route를 인증된 세션과 묶어야 한다. | opt-in 설치, 기존 statusline 보존, 출력에 account email/credential 금지, held key 데이터 범위 적용, 요청 시 새 vendor quota probe 금지. | +| L6-3 | 명시적으로 활성화한 body filter와 필요 시 reply hook 계약. med. 첫 적용은 좁은 param override와 model alias이며 word guard, thinking/Responses history는 각각 별도 예시다. | L. 미들웨어 순서, 요청·응답의 framing, CPU/body budget, 오류 정책 및 native/translated WS와 SSE의 공통 의미를 검증해야 한다. | `src/plugins/`의 독립 등록 seam, `src/server/responses/request-prepare.ts` 및 encoder 인접 모듈. 구성 권한, 이전 상태 및 모델 선택 순서를 정한다. | policy filter는 실패 시 차단 의미를 명시한다. 등록이 없는 단일-provider 경로는 timer/parse 부담을 지지 않게 한다. SSE tool/reasoning/terminal frame 보존과 file-size ratchet이 필요하다. | +| L6-4 | 기본 off인 요청 masking의 제한적 버전. high. 개인 프롬프트의 알려진 secret/선택 단어 예방과 팀 key별 정책이 유용하다. | L. 1차는 명시한 텍스트 필드와 deterministic 규칙으로 제한한다. 가역 placeholder stream 처리, 재시도 간 동일성, 도구 args, 실제 모델 선택은 각각 경계를 둔다. | `src/server/inference/` admission 인접, `src/server/responses/request-prepare.ts` 및 client encoders, `src/lib/redact.ts`. A1의 로깅/오류 처리와 별도의 데이터 계약이 필요하다. | 허용된 pre-upstream body 범위 및 복원 소유권이 먼저다. 원문 미보관, 로그·trace privacy, local-only 목적지 및 실패 시 무전송. detector 다운로드와 auto-update는 이 후보에 포함하지 않는다. | +| L6-5 | 실제 Claude CLI의 반복 기동 비용을 줄이는 선택형 세션 reuse. high. 같은 사용자의 긴 tool-turn 대화에 가장 직접적이다. | XL. 계정/호출자/세션 소유권, 취소·중복 요청·crash·idle drain, sandbox, tool 결과 매칭이 필요하다. | `src/adapters/claude-cli/`, `src/server/responses/run-turn-execution.ts` 인접 모듈, 공통 CLI runner. 공식 실행 계약 및 현재 stateless path의 비교 측정이 선행한다. | 사용자 구독·크레딧 소비에 대한 기존 동의 유지. client tool approval을 유지한다. 복수 로그인·기기 공유 또는 vendor 지원이 불명확한 surface는 별도 maintainer 판단이 필요하다. | +| L6-6 | 버전 고정과 명시 설치가 가능한 provider-extension ABI. med. 기존 OCX adapter로 지원하지 않는 provider를 빠르게 추가하는 데 가치가 있다. | XL. lifecycle/RPC/backpressure, auth ownership, SDK version, 실패 격리, schema/stream fidelity를 검증해야 한다. | `src/plugins/`, `src/adapters/registry.ts`의 좁은 등록점, 별도 provider host. 먼저 정적 plugin manifest와 최소 ABI가 필요하다. | 범용 OpenCode/pi 호환은 API 경계를 리뷰한 뒤 선택한다. subprocess 경계에 더해 OS 권한 및 secret 배포 범위를 따로 정한다. auto-update는 L6-7과 독립이다. | +| L6-7 | **reject candidate**. 외부 marketplace에서 온 임의 코드를 자동 추적·업데이트. low. 릴리스별 모듈 provenance와 복구 경로를 잃으면 로컬 proxy의 운영 비용이 더 커진다. | XL. 검증 가능한 package provenance, consent, rollback, 호환성 및 update 통제면이 필요하다. | L6-6이 성립할 경우에만 `src/plugins/`의 명시적 version pin/install 범위를 검토한다. | default-on 갱신과 provider auth를 묶는 설계는 현 범위에서 채택하지 않는다. | +| L6-8 | **reject candidate**. generic vendor-native path와 OpenAI-shaped retrieval 전체를 묶어 추격. low. 기본 Codex/Claude Code 코딩 turn에서 이 표면의 사용 사례가 확인되지 않았다. | L. 실제 제품 요구가 생기면 embeddings/rerank의 typed endpoint를 먼저 좁혀 산정할 수 있다. | `src/server/index/`와 protocol-specific handlers. explicit caller/model policy 및 사용량 계약이 필요하다. | 임의 vendor path는 기존 model/account budget 및 권한과 동등한 정책을 별도 검증해야 한다. 추론 proxy 범위에서 이를 우선할 사용 사례는 확인되지 않았다. | + +## OpenCodex-ahead + +- **재전송의 물리적 증거**. 같은 HTTP status나 첫 출력 시점만으로 처리 여부를 판정하지 않는다. native Responses의 default-off `retryOnReset`, self-contained 판단과 send budget은 고의로 도입된 구분이다. Magpie의 더 적극적인 회전은 이 gate를 완화할 근거가 되지 않는다. `ocx:src/lib/request-failure-model.ts:146`, `ocx:src/server/responses/reset-replay.ts:112`, `ocx:src/server/responses/reset-replay.ts:229`. +- **Codex의 네이티브 중간 제어**. WS 지원을 켠 로컬 pipeline에서 대상과 프레임이 허용될 때 steer/inject가 연결된다. Magpie에서 읽은 client WS contract는 create와 interrupt까지다. `ocx:src/server/index/websocket-handler.ts:227`, `ocx:src/server/responses/native-response-control.ts:45`, `mgp:internal/gateway/responses_ws.go:283`. +- **Gemini 입구 범위**. `/v1`/`/v1beta` parser와 Interactions 경로가 있다. Gemini embed 메서드는 인식한 후 501을 반환한다. `ocx:src/server/gemini-native-paths.ts:8`, `ocx:src/server/index/gemini-routes.ts:48`, `ocx:src/server/index/gemini-routes.ts:81`, `mgp:internal/gateway/gateway.go:2636`. + +## 최신 사례 (Aside) + +조회일은 2026-11-23이다. Aside `1.26.1115.1556` 및 codemode `0.9.2`, 명시 `u0/local`의 읽기 전용 공개 URL 조회를 사용했다. 날짜는 UTC의 publication 또는 merge 날짜다. Magpie 기준 commit 시각은 12:44:17 UTC다. 별도 저장소의 package는 Magpie commit과 같은 고정점으로 취급하지 않았다. + +| 게시일 | release/commit/PR | 공개 근거 | 조회일 | 확인 내용 | OpenCodex 관련성 | 신뢰도 | +| --- | --- | --- | --- | --- | --- | --- | +| 2026-11-23 | Magpie v0.1.4717 / `e18f4841` | [릴리스](https://github.com/yetone/magpie-releases/releases/tag/v0.1.4717), [커밋](https://github.com/yetone/magpie/commit/e18f4841f68fc722dbb4e9e0e1f426289def39b9) | 2026-11-23 | Antigravity third-party quota 종료를 model-scoped rest로 처리한다. pinned code의 관련 분기가 있다. `mgp:internal/gateway/routing.go:1371`, `mgp:internal/gateway/routing.go:2082` | 200 안의 quota signal도 provider가 붙인 명시 근거로 분류하고 cooldown 범위를 모델에 제한할 수 있다. | 높음, 공개 changelog와 pinned 구현 | +| 2026-11-23 | Magpie v0.1.4714 / `8bda3d55` / `#5812` | [릴리스](https://github.com/yetone/magpie-releases/releases/tag/v0.1.4714), [커밋](https://github.com/yetone/magpie/commit/8bda3d5550fe04dc492d0bc18e3b5420a6ebe3b6), [사용자 보고](https://github.com/yetone/magpie/issues/5812) | 2026-11-23 | 11월 9일 사용자가 Copilot→OpenAI 대화에서 긴 item ID로 400을 보고했다. pinned source는 번역 시 plain ID 처리와 해당 refusal 처리 모두 가진다. 이슈의 상태는 조회 시 open이었다. `mgp:internal/gateway/gateway.go:9045`, `mgp:internal/gateway/gateway.go:9236`, `mgp:internal/gateway/codex_backend.go:3349` | 변환 시 opaque ID ownership과 safe repair를 테스트할 공개 fixture 사례다. | 구현 높음, 사용자 환경 재현 미검증 | +| 2026-11-23 | `4f442937` / `#7535` | [커밋](https://github.com/yetone/magpie/commit/4f442937ae2b1597fe37b922d8f58ac1b3c9538a) | 2026-11-23 | Esc 이후 다른 turn에서도 저장된 Claude 세션을 이어가도록 수정했다. pinned docs와 resume/letGo 경로가 뒤따른다. `mgp:docs/subsystems/claude-subscription-bridge.md:1525`, `mgp:internal/gateway/claude_subscription.go:2070`, `mgp:internal/gateway/claude_subscription.go:3708` | L6-5가 session ownership과 취소 후 새 요청을 테스트해야 하는 이유다. | 높음, 커밋·소스. latency는 미측정 | +| 2026-11-23 | Magpie `#7572`, open | [gateway 사용자 보고](https://github.com/yetone/magpie/issues/7572) | 2026-11-23 | plugin 자체 쓰기와 path-based reload가 겹치면 host가 되풀이 재시작한다는 보고다. pinned tree에서 path stamp와 stale host 분기를 확인했다. `mgp:internal/plugin/pathstamp.go:39`, `mgp:internal/plugin/host.go:1018` | 새 plugin host는 소스 변경과 데이터 쓰기, 기존 in-flight와 확장 교체를 별개 상태로 다뤄야 한다. | 중간, 증상은 사용자 보고 | +| 2026-11-23 | Magpie v0.1.4720 | [릴리스](https://github.com/yetone/magpie-releases/releases/tag/v0.1.4720) | 2026-11-23 | **post-head** 게시. web key 수명과 UI 탐색 변경을 발표했다. | 공개 시점 정리에 사용. runtime parity 행에 반영하지 않았다. | 높음, 릴리스 문구 기준 | +| 2026-11-23 | agy-cli 0.1.114 / `8b47ce7` / dist `d9604e5` | [plugin 커밋](https://github.com/magpie-community/plugins/commit/8b47ce71a73d7bdc216c82d6a2f7abe407c12fdc), [dist 커밋](https://github.com/magpie-community/plugins/commit/d9604e5693eb99167b27e0d75c2752781503fd57), [publish workflow](https://github.com/magpie-community/plugins/blob/main/.github/workflows/publish.yml) | 2026-11-23 | CLI quota 종료 문구를 structured rate limit으로 표기한 plugin 수정이 별도 dist에 나타났다. workflow는 main push에서 dist와 npm 게시를 각각 수행한다. | provider churn을 gateway 밖에 둘 수 있다는 공개 사례다. 설치나 자동 적용 여부는 Magpie의 gate에 달려 있다. | 높음, 커밋과 workflow | +| 2026-11-19 | community PR `#1352` / Kiro 0.1.41 | [merged PR](https://github.com/magpie-community/plugins/pull/1352) | 2026-11-23 | 여러 계정에서 만료에 가까운 월간 plan credit을 trial credit보다 먼저 쓰게 하는 변경이다. | quota를 단일 percentage로 축약하면 운영 정책이 사라진다. plan, expiry, credit 종류를 구분할 근거다. | 높음, merge 확인. 실사용 미측정 | +| 2026-11-22 | CLIProxyAPI v8.1.1 / `8cab158f`, `254d0c2c` | [경쟁 구현 릴리스](https://github.com/router-for-me/CLIProxyAPI/releases/tag/v8.1.1) | 2026-11-23 | Responses tool output의 Claude `cache_control` 보존과 scheduler plugin이 선택을 거절했을 때 다음 plugin으로 넘기는 동작을 발표했다. | 번역에서 cache hint 전달과 선택 거절 시 fallback을 각각 비교할 실제 선례다. | 높음, 릴리스 차원. CPA 세부 분석은 L1/L2 | +| 조회 시 main | Param Override 0.1.0 / Model Map 0.1.1 / Word Guard 0.1.1 / Think Tags 0.1.2 / Codex History 0.1.2 | [Param Override](https://github.com/magpie-community/plugins/tree/main/packages/param-override), [Model Map](https://github.com/magpie-community/plugins/tree/main/packages/model-map), [Word Guard](https://github.com/magpie-community/plugins/tree/main/packages/word-guard), [Think Tags](https://github.com/magpie-community/plugins/tree/main/packages/think-tags), [Codex History](https://github.com/magpie-community/plugins/tree/main/packages/codex-history) | 2026-11-23 | manifest와 JS export 확인. 각각 조건부 body 조작, 요청·응답 모델명 매핑, 단어 검사, reply thinking tag 처리, provider별 Responses history 조정이다. Codex History 기본 providers/aliases는 빈 객체다. | L6-3의 request/onProvider/onEvent/onResponse 경계를 정할 외부 사례다. | 높음, 조회한 소스. pinned Magpie와 패키지별 지원 조합 미실행 | + +## Deferred checks + +- 네 프로토콜 각 쌍의 도구·서명·media·usage fixture 전체. WS의 account별 upstream socket 재사용, HTTP/WS parity, 막힌 stream과 backpressure는 소스에서 일부만 확인했다. +- Ollama의 NDJSON 종료 및 think 필드, Realtime의 vendor별 프로토콜 세션과 packet/usage 합산, media/retrieval/decisions/systemone 각각의 호환성. +- Claude bridge의 OS별 TUI/print 전환, 여러 계정 저장/교체, restart handoff와 RAM/idle 한도, MCP 세션 수명. Google 및 Copilot OAuth 갱신 시점과 계정당 quota 정밀 비교. +- Plugin host의 전체 OpenCode API 및 pi extension 호환 범위, 패키지별 prompt/event 동작, 서명 및 공급망 검증, 업데이트 동시성, moejs per-event latency. Codex History의 패키지 버전과 pinned core 간 조합. +- Gateway LAN·mTLS·OIDC, admin mutation, MCP variants, archive·OTLP·remote quota refresh, statusline 설치와 사용성. 공유/클라이언트 설치 및 release 배포의 전체 대조는 L7 범위다. +- 10월 17일 Aside 기록이 연결한 Linux.do thread의 사용자 비교. 새로 읽은 공개 GitHub 보고는 위 표에 포함했다. + +## NOT RUN + +- Build, test, server 시작, 실제 모델 요청, Claude/Codex CLI 실행, OAuth 로그인, plugin 설치·실행·업데이트, reset/credit 사용, GUI QA 및 latency/비용 측정을 실행하지 않았다. +- Linux.do는 `/Users/jun/.local/bin/codemode --account u0 --host local --cwd /Users/jun/Developer/new/700_projects/opencodex --code -`에서 `browse.readText({url:"https://linux.do/t/topic/3012827",fresh:true})` 및 `.json` 경로가 모두 HTTP 403, `blockKind: auth`를 반환했다. 공개 검색 응답도 검색 결과 대신 접근 안내만 반환했다. 그 thread의 보고를 503 원인이나 발생률의 증거로 사용하지 않았다. diff --git a/devlog/_plan/261123_proxy_upstream_catchup/007_magpie_clients.md b/devlog/_plan/261123_proxy_upstream_catchup/007_magpie_clients.md new file mode 100644 index 00000000000..764de54cf33 --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/007_magpie_clients.md @@ -0,0 +1,265 @@ +# 007 — Magpie 클라이언트와 배포 + +L7 · 2026-11-23 KST · Magpie `3377e77eb6` (`v0.1.4721`) ↔ OpenCodex `origin/dev@9e0e298ef9`. +`mgp:`와 `ocx:`는 `.tmp/chase/` 아래의 핀 고정 소스를 가리킨다. 상태는 행에 적힌 기능 단위의 판정이다. + +## 1. 요약 + +1. Codex는 두 프로젝트 모두 선택한 홈의 TOML과 모델 카탈로그를 관리하고 복원을 지원한다. Magpie의 차이는 기존 ChatGPT 로그인 옆에 모델을 합치는 모드와 앱 쿼터 차단 시 provider 전환을 같은 클라이언트 흐름에 둔 점이다. +2. Claude Code는 Magpie가 일반 실행에도 효력이 있는 `settings.json`을 편집한다. OpenCodex는 `ocx claude`의 프로세스 환경과 별도 first-party 설정 경로가 있어, 기본 실행까지 연결하고 싶은 사용자에게 소유권과 복원 조건을 명확히 보여줄 가치가 있다. +3. 이주 비용은 공급자 설정과 계정 자격 증명에서 갈린다. OpenCodex는 CC Switch keyless preview/apply/restore를 이미 제공한다. Magpie의 차이는 앱 간 발견 화면과 Codex·Claude 계정 묶음 import다. +4. 소규모 팀은 LAN 키, 원격 모델 목록, 접속 안내를 함께 쓰는 Magpie 흐름과 OpenCodex의 Hub 초대 및 Home/Child enrollment를 비교해야 한다. 기존 키·승인 계약을 살린 접속 동선 개선이 먼저다. +5. relay 링크의 검토 화면은 반복 입력을 줄인다. endpoint와 키 취급, 충돌 표시, 사용자 확인이 설계 조건이다. +6. Raycast YAML 연결은 양쪽에 있고 OpenCodex는 preview 및 journal restore가 있다. 새 agent 추가는 Zed처럼 구체적인 수요와 config 계약이 있는 경우가 유력하다. +7. MCP·skills Library, 암호화된 설정 동기화, 대화형 TUI는 확인된 표면 차이다. 이 작업의 개인 Codex/Claude 사용자와 소규모 프록시 팀 기준으로는 앞선 이주·연결 작업이 우선이다. +8. GUI·tray·Docker·업데이트 확인·현지화는 이미 겹친다. 10월 비교 기록에서 본 distroless·약 30 MB·단일 importer 주장은 이 핀과 공개 릴리스 자산으로 대체한다. + +## 2. 표면 맵 + +### 실행 및 등록 + +| 표면 | Magpie 등록과 분기 | OpenCodex 대응 | +|---|---|---| +| 실행 진입 | `main.go:25` → `internal/cli/main.go:221,362,604`. `app/gui/tray/panel/-Embedding`, `tui`, `web`, `serve`. `internal/cli/gui_on.go`와 `gui_off.go`, `Makefile:17,57,60,120,148`에서 native GUI와 `nogui` 빌드를 구분한다. | `ocx:src/cli/dispatch.ts:328,418,423,596,603,657,762,879,921`에서 status/sync/connect/service/tray/update/provider/integration/claude 분기. Desktop은 Tauri가 창과 runtime lifecycle을 올린다. `ocx:desktop/src-tauri/src/lib.rs:309,422,430` | +| Agent 조작 | `ls/list`는 감지된 항목, `agents`는 전체 등록 목록, ` [field] [value/default]`는 `Find/Apply/Disconnect`, agent launch는 `Starter`. TUI는 Bubble Tea에서 감지된 항목과 picker 사용. `mgp:internal/cli/main.go:637,719,757,791,885`, `internal/agent/agents.go:301`, `internal/tui/tui.go:162,192,489` | `ocx integration` CLI와 Connect 화면 API, native `PUT /api/native-integrations/{claude,grok,codex,claude-desktop}`, managed `GET/PUT /api/client-integrations/{id}` 및 export. `ocx:src/server/management-api.ts:396`, `src/server/management/native-integration-routes.ts:1005,1016,1098`, `src/server/management/integration-routes.ts:748,1162` | +| Agent 관리 GUI | `GET /api/state`, `POST /api/set` → `Find/Pick`, `GET /api/drift`, `POST /api/agents/{rescan,stage/{id},cli/{id},telemetry/{id},restart/{id},arrange,here}`, `GET /api/agents/{cli,install,preview/{id}}` 및 `POST /api/agents/{connect,disconnect,disconnect-offline,keep,reapply}/{id}`. Desktop 격리, 프로필 save/use/rename/remove 및 sync도 연결한다. `mgp:internal/gui/api.go:1224,1384,1404,1438,1452,1518,1574,1601,1635,1671,1714,2741` | Client state/preview/restore/restore preview/journal, Aside profile, Pi sync, 별도 `/api/gateway-clients`. `ocx:src/server/management/integration-routes.ts:298,574,748,802,830,915,966,1016` | +| 설정·계정 이주 | `GET /api/importapps/discovery`, `GET/POST /api/importapps`, `POST /api/login/{action}`, `/api/settings/account-discovery`. `accounts/account`와 provider CLI. `mgp:internal/gui/importapps.go:27`, `internal/gui/providers.go:1754,3459,3729`, `internal/gui/api.go:1914`, `internal/cli/main.go:654,656,678` | `ocx provider import-cc-switch`와 `ocx account import`. `ocx:src/cli/provider.ts:659`, `src/cli/account.ts:510`, `src/server/management/oauth-account-routes.ts:1130` | +| 링크 | `magpie://import` OS handler + `GET /api/import/{id}`, `POST /api/import/icon`, CLI `import`. `ccswitch://`는 별도 호환 등록이다. `mgp:build/darwin/Info.plist:21`, `internal/gui/scheme_windows.go:16`, `site/public/install.sh:508`, `internal/gui/app.go:789,833`, `internal/gui/importlink.go:57`, `internal/ccswitchlink/link.go:1` | GUI 내부 hash navigation, Link join 및 Hub invite. `ocx:gui/src/app-routing.ts:100,120`, `src/server/management/link-routes.ts:725`, `src/cli/hub.ts:239` | +| 원격 | `POST /api/settings/{lan,join}`, `GET /join`와 `GET/POST /v1/magpie/join`, `Remote magpie` provider preset, desktop의 `GET/POST /api/remote` 및 `POST /api/remote/forget`. `mgp:internal/gui/api.go:1746,2853`, `internal/gui/join.go:16`, `internal/gateway/gateway.go:1179`, `internal/provider/presets.go:814`, `internal/gui/remote.go:270` | `ocx connect`, `ocx link`, `ocx hub` 및 `src/remote/` 자료 계약. Link Home/Child와 Hub/client는 별도 동선. `ocx:src/cli/dispatch.ts:423`, `src/cli/link.ts:512`, `src/cli/hub.ts:239,381`, `src/remote/hub-management-relay.ts:3,59` | +| 백업·동기화 | `/api/backup/{export,import}`, `/api/autobackup[/{action}]`, `/api/davsync[/{action}]`. CLI `backup/restore, webdav/dav, s3, github`. `mgp:internal/gui/backup.go:24,82,122,205`, `internal/cli/main.go:692,703` | `ocx sync`는 Codex catalog 및 연결 runtime 방향의 sync. Desktop profile은 명시적으로 export/import한다. `ocx:src/cli/dispatch.ts:418`, `src/codex/sync.ts:103`, `src/cli/claude-desktop.ts:915,927` | +| Library | `GET /api/library`, `POST /api/library/{what}/{action}`와 auth/check/config 전용 handlers. 서버·도구 토글, env/hooks/plugins, skills, rules, commands, subagents, instructions, project presets, 전체 sync. CLI `library/lib`와 `mcp`, 원격 Library snapshot도 별도. `mgp:internal/gui/library.go:221,654,724,742,759,815,869,898,939,1006,1045`, `internal/cli/main.go:462,690`, `internal/provider/remote_library.go:15` | `ocx claude desktop` profile 및 picker, `ocx agent` surface. `ocx:src/cli/claude-desktop.ts:58,630`, `src/server/management/native-integration-routes.ts:783,1106`, `src/server/management/codex-agent-role-routes.ts:2` | +| 표시·배포 | Wails SystemTray + window/panel, browser UI, TUI, CLI. `/api/update`와 `/api/update/{notes,check,install,using}`, `update` CLI, Docker tag workflow. `mgp:internal/gui/app.go:334,637,663,695`, `internal/cli/web_cli.go:21,29,225`, `internal/gui/update.go:960`, `internal/cli/main.go:688`, `.github/workflows/docker.yml:3` | Tauri tray, 별도 Windows CLI tray, React dashboard와 package/App updater. `ocx:desktop/src-tauri/src/startup.rs:1521`, `src/tray/windows.ts:639,737`, `src/server/index/serve-options.ts:1910`, `src/server/management/config-routes.ts:998,1008,1053` | + +### Agent 등록 인덱스 + +`mgp:internal/agent/agents.go:321–416`의 정적 constructor 호출 93개를 아래에 기록했다. 분류와 줄 번호는 해당 constructor의 진입부를 뜻한다. 쓰기 동작은 이어지는 adapter에서 확인한다. 실제 감지는 `Detected`의 agent별 override 또는 파일/디렉터리, 로그인 신호 및 실행 바이너리 앞단을 거친다. 등록 목록에는 importer와 launcher 등도 있다. `All`은 설치 상태에 상관없이 항목을 만들고, 이동한 adapter를 제외한 다음 plugin·WSL·OMP/QwenPaw/Hermes/Claude 프로필 항목을 더한다. `ClientsIn`는 nested/WSL 항목을 마케팅상의 agent 수와 달리 집계하며, `others`는 사용량/UA 식별용이다. 설치·쓰기 성공률은 미측정이다. `mgp:internal/agent/agents.go:196,241,258,287,318,416`, `internal/agent/agent.go:466,685`, `internal/agent/wsl.go:1187,1338`. + +OpenCodex 등록 비교는 24개 export ID와 native 4개를 출발점으로 한다. export 범위와 client-specific managed writer는 `INTEGRATION_CLIENTS`, 경로 resolver, 별도 gateway-client surface로 확인한다. `ocx:src/clients/client-ids.ts:2`, `src/integrations/registry.ts:199,288,532`, `src/server/management/integration-routes.ts:748`, `src/server/management/native-integration-routes.ts:69`. + +| `onMachineAll` 등록 | adapter 진입점 | +|---|---| +| +| `claude` | `mgp:internal/agent/claude.go:696` | +| `claudeDesktop` | `mgp:internal/agent/claudedesktop.go:134` | +| `claudeScience` | `mgp:internal/agent/claudescience.go:613` | +| `codex` | `mgp:internal/agent/codex.go:92` | +| `gemini` | `mgp:internal/agent/gemini.go:23` | +| `agy` | `mgp:internal/agent/agy.go:234` | +| `dim` | `mgp:internal/agent/dim.go:127` | +| `antigravity` | `mgp:internal/agent/antigravity.go:261` | +| `opencode` | `mgp:internal/agent/agents.go:1432` | +| `openChamber` | `mgp:internal/agent/openchamber.go:162` | +| `mimocode` | `mgp:internal/agent/agents.go:1472` | +| `deveco` | `mgp:internal/agent/agents.go:1492` | +| `pi` | `mgp:internal/agent/agents.go:1507` | +| `stepcode` | `mgp:internal/agent/stepcode.go:27` | +| `mothx` | `mgp:internal/agent/mothx.go:47` | +| `penguin` | `mgp:internal/agent/penguin.go:118` | +| `aside` | `mgp:internal/agent/aside.go:12` | +| `omo` | `mgp:internal/agent/omo.go:20` | +| `primeAgent` | `mgp:internal/agent/primeagent.go:25` | +| `mu` | `mgp:internal/agent/mu.go:28` | +| `goose` | `mgp:internal/agent/agents.go:1813` | +| `cursor` | `mgp:internal/agent/agents.go:1909` | +| `cursorLocal` | `mgp:internal/agent/cursorlocal.go:282` | +| `zed` | `mgp:internal/agent/zed.go:25` | +| `vscode` | `mgp:internal/agent/vscode.go:128` | +| `vscodeInsidersAgent` | `mgp:internal/agent/vscode.go:130` | +| `vscodium` | `mgp:internal/agent/vscode.go:132` | +| `zooCode` | `mgp:internal/agent/zoocode.go:60` | +| `copilotJetBrains` | `mgp:internal/agent/copilotjetbrains.go:69` | +| `air` | `mgp:internal/agent/air.go:139` | +| `airIDE` | `mgp:internal/agent/air.go:170` | +| `copilot` | `mgp:internal/agent/agents.go:1947` | +| `crush` | `mgp:internal/agent/agents.go:2110` | +| `dsh` | `mgp:internal/agent/dsh.go:97` | +| `dsbot` | `mgp:internal/agent/dsbot.go:95` | +| `reasonix` | `mgp:internal/agent/reasonix.go:80` | +| `commandCode` | `mgp:internal/agent/commandcode.go:24` | +| `fx` | `mgp:internal/agent/fx.go:95` | +| `omp` | `mgp:internal/agent/omp.go:143` | +| `devin` | `mgp:internal/agent/devin.go:24` | +| `hermes` | `mgp:internal/agent/hermes.go:53` | +| `morph` | `mgp:internal/agent/morph.go:34` | +| `kimi` | `mgp:internal/agent/kimi.go:236` | +| `qwen` | `mgp:internal/agent/qwen.go:150` | +| `muse` | `mgp:internal/agent/muse.go:33` | +| `empryo` | `mgp:internal/agent/empryo.go:33` | +| `nanobot` | `mgp:internal/agent/nanobot.go:53` | +| `miniq` | `mgp:internal/agent/miniq.go:73` | +| `paimon` | `mgp:internal/agent/paimon.go:55` | +| `ante` | `mgp:internal/agent/ante.go:87` | +| `astrbot` | `mgp:internal/agent/astrbot.go:111` | +| `qwenpaw` | `mgp:internal/agent/qwenpaw.go:211` | +| `openClaw` | `mgp:internal/agent/openclaw.go:241` | +| `jcode` | `mgp:internal/agent/jcode.go:179` | +| `vibe` | `mgp:internal/agent/vibe.go:224` | +| `miniMax` | `mgp:internal/agent/minimax.go:81` | +| `droid` | `mgp:internal/agent/droid.go:378` | +| `cline` | `mgp:internal/agent/cline.go:55` | +| `qoder` | `mgp:internal/agent/qoder.go:41` | +| `qoderCN` | `mgp:internal/agent/qoder.go:45` | +| `grok` | `mgp:internal/agent/grok.go:225` | +| `kigi` | `mgp:internal/agent/kigi.go:25` | +| `grokApp` | `mgp:internal/agent/grokapp.go:170` | +| `zcode` | `mgp:internal/agent/zcode.go:67` | +| `workbuddy` | `mgp:internal/agent/workbuddy.go:50` | +| `workbuddyAI` | `mgp:internal/agent/workbuddy.go:61` | +| `codebuddy` | `mgp:internal/agent/codebuddy.go:39` | +| `pencil` | `mgp:internal/agent/pencil.go:34` | +| `paseo` | `mgp:internal/agent/paseo.go:110` | +| `openPencil` | `mgp:internal/agent/openpencil.go:81` | +| `openBot` | `mgp:internal/agent/openbot.go:83` | +| `craftAgents` | `mgp:internal/agent/craftagents.go:106` | +| `obsidian` | `mgp:internal/agent/obsidian.go:94` | +| `tuanjieCowork` | `mgp:internal/agent/tuanjiecowork.go:55` | +| `newMax` | `mgp:internal/agent/newmax.go:85` | +| `liveAgent` | `mgp:internal/agent/liveagent.go:96` | +| `raycast` | `mgp:internal/agent/raycast.go:52` | +| `kiroCrew` | `mgp:internal/agent/kirocrew.go:370` | +| `t3code` | `mgp:internal/agent/t3code.go:123` | +| `openMausBot` | `mgp:internal/agent/openmausbot.go:136` | +| `avibe` | `mgp:internal/agent/avibe.go:63` | +| `kun` | `mgp:internal/agent/kun.go:196` | +| `nowledgeMem` | `mgp:internal/agent/nowledgemem.go:155` | +| `hanako` | `mgp:internal/agent/hanako.go:75` | +| `atomcode` | `mgp:internal/agent/atomcode.go:52` | +| `ocr` | `mgp:internal/agent/ocr.go:39` | +| `snow` | `mgp:internal/agent/snow.go:56` | +| `alma` | `mgp:internal/agent/alma.go:836` | +| `shelley` | `mgp:internal/agent/shelley.go:442` | +| `cindy` | `mgp:internal/agent/cindy.go:128` | +| `aionui` | `mgp:internal/agent/aionui.go:107` | +| `cherryStudio` | `mgp:internal/agent/cherrystudio.go:169` | +| `lody` | `mgp:internal/agent/lody.go:106` | + +WSL 후보 registry `wslKinds`는 Claude Science, Codex, Pi, OmO, Prime Agent, mu, StepCode, Claude Code, OpenCode, MiMo Code, Kimi, Qwen, omp, Crush, Hermes, Morph, Grok, Kigi, Droid, fx, Command Code, MiniMax Code, dsh, Empryo, nanobot, Paimon, miniQ, Ante, Muse, Qoder/Qoder CN, CodeBuddy, Cline, AtomCode, Open Code Review, Snow, Gemini CLI, Antigravity CLI, Goose, MothX, PenguinHarness, Reasonix를 포함한다. distro probe에서 발견된 kind와 이름이 있는 omp 프로필만 instance가 생긴다. Plugin 정의는 `pluggedAgents`에서 설치된 plugin set과 합쳐진다. `mgp:internal/agent/wsl.go:472,1194,1208`, `internal/agent/plugged.go:93`. + +### 설정 형식과 연결·복원 계약 + +| 구현 묶음 | 어디를 어떻게 쓰는가 | +|---|---| +| Codex | `CODEX_HOME/config.toml`의 top-level 및 provider table과 `magpie-models.json`. ChatGPT 로그인 유지와 provider 전환을 분기한다. `mgp:internal/agent/wsl.go:113`, `internal/agent/codex.go:265,672,1854,1926,2057` | +| Claude Code | `CLAUDE_CONFIG_DIR/settings.json`에서 env와 모델, tier, subagent를 부분 수정한다. 별도 프로필은 감지 후 각 디렉터리로 분리한다. `mgp:internal/agent/wsl.go:123`, `internal/agent/claude.go:710,2024`, `internal/agent/claude_dirs.go:59` | +| OpenCode 및 파생 구현 | `openCodeLike`가 JSON provider와 모델 선택 쌍을 담당한다. v2 전환 및 OpenCode 계열 차이는 별도 adapter다. Pi 계열은 `piLikeKeyed`, Goose는 YAML config writer를 쓴다. `mgp:internal/agent/agents.go:1257,1432,1472,1492,1632,1819`, `internal/agent/opencode_v2.go` | +| Raycast, Zed | Raycast는 YAML `providers` sequence 항목, Zed는 JSON 모델 및 provider 블록과 플랫폼 credential helper. `mgp:internal/agent/raycast.go:52,183,232`, `internal/agent/zed.go:51,86` | +| 다른 쓰기 유형 | Qwen `settings.json` JSON, Kimi·Grok·Vibe·Jcode TOML, Hermes·MiniMax YAML, Cline provider/state JSON, NewMax·AionUI SQLite, Lody 앱 import handoff. 인덱스의 진입부 기준이며 앱 버전별 전체 schema는 보류했다. `mgp:internal/agent/qwen.go:150`, `internal/agent/kimi.go:236`, `internal/agent/grok.go:225`, `internal/agent/vibe.go:224`, `internal/agent/jcode.go:179`, `internal/agent/hermes.go:53`, `internal/agent/minimax.go:81`, `internal/agent/cline.go:55`, `internal/agent/newmax.go:85`, `internal/agent/aionui.go:107`, `internal/cli/main.go:735` | +| 공통 계약 | 연결은 명시적 `ConnectHow`/picker 또는 agent CLI 조작에서 시작한다. 이미 연결된 상태는 유지하고, 재연결 → agent Join → remote → model/provider pick 순서로 선택한다. `Apply`는 adapter setter를 실행하고 적용값을 기록한다. `Disconnect`는 adapter Unwire 또는 공유 기본 경로를 사용하고 user disconnect를 기억한다. `mgp:internal/agent/applied.go:109,710,749,895,923` | +| 충돌·롤백 | `Drift`는 외부 변경, 연결 끊김, 우회 및 도달 실패를 구분한다. 의도적인 agent picker 변경이나 손으로 만든 provider의 예외가 있다. GET drift와 Keep/Reapply를 연결한다. 일부 adapter는 config·stash 등 지정 파일을 `edit.Atomically`로 되돌린다. `peek/forgetValues`는 성공 후 같은 stash 값만 소비하고 `unstash`는 별도 방식이다. GUI Disconnect preview는 native plan 또는 격리 diff이며 offline native 경로는 plan revision을 검사한다. `mgp:internal/agent/applied.go:144,194,225,254,499`, `internal/agent/agent.go:837`, `internal/edit/file.go:332`, `internal/agent/stash.go:113,128,144`, `internal/gui/api.go:1438,1574,1601,1643` | + +### 세 클라이언트 E2E 소스 경로 + +1. **Codex** (`CAP-client-config-codex`) + + - Magpie의 등록은 `agents.go:326` → `codexIn`이다. Agents의 Connect 또는 CLI model pick으로 시작한다. `Join`은 native 로그인과 catalog를 함께 쓰는 경로이며, 별도 provider 경로는 `model_provider`, `model_catalog_json`, `model`과 소유한 `openai_base_url`을 설정한다. 쿼터가 막혀 앱이 요청을 보내지 못하는 상황의 provider 전환 조건과, 쿼터 회복 시 복귀 조건이 구현돼 있다. 이전 provider/모델/카탈로그/effort를 보관하고 복원 시 사용자 변경과 catalog 파일 존재를 확인한다. `mgp:internal/gui/api.go:1635`, `internal/cli/main.go:760,791`, `internal/agent/codex.go:265,672,1761,1859,1926,1986,2037,2259,2282,2962`. + - OpenCodex의 Native toggle은 desired state 기록 → `syncModelsToCodex` → catalog preflight 및 `injectCodexConfig`, OFF는 `restoreNativeCodexAsync`로 간다. absent desired state는 ON이고 hub/sibling 및 외부 소유 설정에 대한 gate가 있다. restore는 자체 journal, desired-state 재확인, catalog/history 처리로 이어진다. `ocx:src/server/management/native-integration-routes.ts:404,423,447,488,1102`, `src/codex/desired-state.ts:63,80,139`, `src/codex/sync.ts:103,115,235,308`, `src/codex/inject/restore.ts:269,583,616,747`. + +2. **Claude Code** (`CAP-client-config-claude`) + + - Magpie의 `claudeIn`이 Claude 홈을 해석한다. Connect/model pick은 base URL, auth token, top-level model, tier·subagent를 JSON leaf 단위로 쓴다. 기존 sign-in 유지 설정에서 token 처리가 달라진다. 첫 실행 mark는 연결에서 실제로 추가한 경우에 한해 복원한다. 로컬 managed settings의 우선순위 충돌은 `Check`에서 보고하고, Unwire는 stashed endpoint/token/model/tier와 소유한 statusline·effort를 처리한다. `mgp:internal/agent/agents.go:323`, `internal/agent/claude.go:710,762,788,1784,1856,2024,2081,2547,2556,2713`. + - OpenCodex `ocx claude` → `withClaudeContextSettings` → `spawnClaude`는 launch env에 proxy 주소, auth 및 model 정보를 전달한다. `PUT /api/native-integrations/claude`는 기본 ON인 inbound를 토글하며 OFF에서 marker-owned subagent 파일을 정리한다. 별도 first-party 설정 reconcile 및 intercept는 local management, role과 intercept enablement gate를 거친다. 이 차이가 vendor env 설정의 상시 연결 UX에 해당한다. `ocx:src/cli/dispatch.ts:921`, `src/cli/claude.ts:248,296,340,926,952`, `src/server/management/native-integration-routes.ts:197,1016,1074`, `src/server/management/claude-intercept-routes.ts:5,11,29`, `src/server/management/agent-settings-routes.ts:1660,1683,1762`, `src/claude/first-party-settings.ts:46`, `src/claude/intercept/settings.ts:224,277`. + +3. **Raycast** (`CAP-client-config-raycast`) + + - Magpie의 등록은 `agents.go:399` → `raycast`다. 앱 bundle 또는 사용자 디렉터리를 감지하고 명시적 provider connect에서 `~/.config/raycast/ai/providers.yaml`에 `magpie` provider와 모델 목록, `/v1` 주소를 연결한다. 지원되지 않는 YAML shape의 오류를 반환하고, 재동기화 때 이미 붙은 항목과 추가 필드를 병합한다. Disconnect는 그 항목과 비게 된 sequence를 제거한다. 개별 모델 고르기는 Raycast 쪽에서 이루어진다. `mgp:internal/agent/raycast.go:52,70,86,128,183,232,262`. + - OpenCodex는 Raycast가 만든 `ai` 디렉터리로 감지 범위를 좁히고, `PUT /api/client-integrations/raycast`의 명시적 `enabled`/overwrite/plan binding에 따라 mutate한다. builder는 `providers[id=opencodex]`를 대상으로 모델 목록을 쓴다. YAML을 다시 직렬화하는 경로와 공유 journal/restore preview가 있다. `ocx:src/server/management/integration-routes.ts:915,966,1016,1162,1196,1230`, `src/integrations/registry.ts:460`, `src/clients/config-export/raycast.ts:40,99`, `src/integrations/mutation-plan.ts:169`. + +## 3. 기능 인벤토리 + +Magpie의 provider 설정 탐색과 계정 탐색은 별개다. `NoAccountDiscovery` / `MAGPIE_NO_ACCOUNTS`는 자체 로그인 읽기를 gate하고 Codex auth 및 Claude credentials reader에서 확인한다. Providers 후보 목록은 `DiscoverSources`에 등록된 설정 파일을 읽는다. 명시적 batch 이주에는 CLI 확인이 있으며 Codex refresh 방식과 access-only의 세션 영향을 사용자에게 구분해 알린다. `mgp:internal/settings/accounts.go:14,35`, `internal/provider/discovery.go:36`, `internal/provider/codex_store.go:520`, `internal/provider/claude_dirs.go:67,77`, `internal/provider/importapps.go:79,100`, `internal/cli/accounts_cli.go:635,657,672`. + +| CAP | 기능 | Magpie 진입 · 구현 · gate | OpenCodex 진입 · 구현 · gate 또는 부재 확인 | 상태 | 근거 | +|---|---|---|---|---|---| +| CAP-client-config-codex | 영구 config, catalog, native 복귀, 로그인 옆 모델 모드 | Agents Connect/model pick → `codexIn`과 `Join/Unwire`. 로그인/쿼터와 명시적 연결에 따른 분기. `mgp:internal/gui/api.go:1635`, `internal/agent/codex.go:265,1761,1859,1926,1986,2037,2282` | Native PUT → desired state → sync/inject/restore. unset=ON, hub/sibling/외부 소유 gate. 구현 차이는 위 E2E 참조. `ocx:src/server/management/native-integration-routes.ts:404,488,1102`, `src/codex/desired-state.ts:63,80`, `src/codex/sync.ts:115,308` | partial | OBSERVED | +| CAP-client-config-claude | 일반 CLI 실행에 적용되는 설정과 복원 | Agents Connect/CLI pick → `claudeIn`이 JSON env/model을 변경한다. 기존 로그인 유지 옵션과 managed config 충돌 진단. `mgp:internal/gui/api.go:1635`, `internal/agent/claude.go:710,762,2024,2556,2713` | `ocx claude` launch env 및 native inbound 토글, 별도 first-party 설정 경로가 gate를 만족할 때 디스크에 적용된다. `ocx:src/cli/dispatch.ts:921`, `src/cli/claude.ts:926`, `src/server/management/native-integration-routes.ts:197,1016`, `src/server/management/claude-intercept-routes.ts:5`, `src/claude/first-party-settings.ts:46` | partial | OBSERVED | +| CAP-client-config-raycast | YAML provider 항목과 모델 목록 | Agent setter → YAML sequence merge/unwire. 앱 또는 디렉터리 감지, 연결 요청 시 쓰고 연결된 경우만 Sync. `mgp:internal/agent/raycast.go:52,70,86,183,232` | 관리 PUT → id 기반 contribution. `ai` 디렉터리 감지, 명시적 toggle과 충돌/plan gate. 두 구현의 YAML merge 범위에 차이. `ocx:src/integrations/registry.ts:460`, `src/clients/config-export/raycast.ts:99`, `src/server/management/integration-routes.ts:1162,1196,1230` | partial | OBSERVED | +| CAP-client-config-zed | Zed 로컬 설정을 proxy에 연결 | Agents setter → `settings.json`의 모델 선택 및 custom provider, platform credential helper. Magpie model pick에서 쓰고 native pick/Disconnect에서 복원한다. `mgp:internal/agent/agents.go:346`, `internal/agent/zed.go:51,70,86,103` | A7. `ocx:src/providers/registry/entries-core.ts:248`와 `src/providers/zed.ts:4`는 upstream Zed Hosted AI. `ocx:src/clients/client-ids.ts:2` 및 `src/integrations/registry.ts:288`의 client writer에 Zed가 없다. | gap | OBSERVED | +| CAP-client-config-roster | client 등록, 감지, 확장 | `agents` 및 Agents UI → `All/Detected`, app/WSL/profile/plugin 추가. 적용은 명시적 agent action. `mgp:internal/cli/main.go:637,641`, `internal/agent/agents.go:258,287,321`, `internal/agent/agent.go:466` | `integration`, client routes → registry와 resolver. write는 scope와 enabled 입력을 확인한다. `ocx:src/cli/dispatch.ts:879`, `src/clients/client-ids.ts:2`, `src/integrations/registry.ts:199,288`, `src/server/management/integration-routes.ts:1162,1196` | partial | OBSERVED | +| CAP-client-config-drift | 변경 감지, 유지, 재적용, preview/restore | `/api/drift`, `/api/agents/{action}/{id}` → 기록 비교 및 Keep/Reapply; native preview revision, 일부 adapter의 atomic write. `mgp:internal/gui/api.go:1438,1574,1620,1643`, `internal/agent/applied.go:194,225,254,499` | managed `preview/journal/restore`, explicit overwrite 및 plan binding. Native Codex restore도 ownership gate를 갖는다. `ocx:src/server/management/integration-routes.ts:830,915,966,1016,1196,1230`, `src/integrations/ownership.ts`, `src/codex/inject/restore.ts:269,616` | partial | OBSERVED | +| CAP-import-cc-switch | CC Switch provider 설정 이주 | `GET/POST /api/importapps` → read-only DB reader → 선택된 provider/key 조합 import, 재조회/중복 처리. `mgp:internal/gui/importapps.go:48,70`, `internal/provider/importapps.go:87,131,279,589` | `ocx provider import-cc-switch` → byte-level keyless projection, 명시적 source, 기본 preview, apply/restore와 journal. `ocx:src/cli/provider.ts:659`, `src/cli/provider-cc-switch-import.ts:72,86,99`, `src/providers/cc-switch-import.ts:747,855` | partial | OBSERVED | +| CAP-import-local-discovery | Providers 페이지에서 타 앱 설정 후보 발견 | Providers desktop window에서 분당 최대 한 번 조회. Alma, agy, CC Switch, Claude Code, Codex 기본 검색, OpenCode auth는 picker를 열 때만. fingerprint 힌트 → review → 선택. `mgp:internal/gui/assets/app.js:10802,10824,10840,10857`, `internal/gui/importapps.go:30,48,70`, `internal/provider/importapps.go:79,100,131` | A8. `ocx:src/cli/provider-cc-switch-import.ts:81,86`은 CC Switch 파일을 명시하는 CLI. `ocx:src/codex/routing-healer.ts:150,206`은 자체 config repair, `src/server/management/provider-routes.ts:896,1133`은 proxy provider 목록/저장이다. | gap | OBSERVED | +| CAP-import-account-batch | Codex·Claude 파일 기반 계정 이주, CLIProxyAPI·Sub2API·CodexBar | GUI `POST /api/login/{action}` import와 `magpie accounts import` → `ImportLogins`; 요청으로 제공된 파일에서 Sub2API platform/credentials, CodexBar, claude-swap, native/CPA/Cockpit 형식을 해석. Codex access-only 별도 분기, per-entry validation. `mgp:internal/gui/providers.go:3459,3729`, `internal/cli/accounts_cli.go:674`, `internal/provider/login_import.go:101,129,182,264,338,367,652` | A3b. `ocx account import` → `POST /api/oauth/accounts/import` → registry가 Antigravity의 지정 형식만 수락한다. Codex native-main 관리와 CTA는 이 batch format ingestion을 제공하지 않는다. `ocx:src/cli/account.ts:510`, `src/cli/account-extended.ts:638`, `src/server/management/oauth-account-routes.ts:1130,1158`, `src/oauth/account-import/registry.ts:12` | gap | OBSERVED | +| CAP-import-account-antigravity | Antigravity 계정 이주 | `magpie accounts import antigravity`와 GUI import 분기는 관찰했다. exact Cockpit scope의 유효성 및 동등한 복원 계약은 보류. `mgp:internal/cli/main.go:112`, `internal/cli/accounts_cli.go:647,678`, `internal/provider/google_import.go:178` | `POST /api/oauth/accounts/import` → registry/service → Google Antigravity adapter. provider 및 format gate. `ocx:src/server/management/oauth-account-routes.ts:1130`, `src/oauth/account-import/registry.ts:14`, `src/oauth/account-import/service.ts:27` | unknown | OBSERVED-partial | +| CAP-deeplink-import | relay/provider 사전 채우기와 지정 후 저장 | OS scheme/`magpie import` → `ParseImport`(preset 또는 custom endpoints) → one-shot preview/Replace 표시 → explicit Add, CLI `-y` 선택. HTTPS landing의 fragment로 전달한다. `mgp:build/darwin/Info.plist:21`, `site/public/import.html:79,143`, `internal/gui/app.go:789,833`, `internal/gui/importlink.go:30,57`, `internal/gui/assets/app.js:11092,11140`, `internal/provider/importurl.go:54,71`, `internal/cli/providers_cli.go:1820` | A1. `ocx:gui/src/app-routing.ts:100,120`은 앱 내부 navigation이고, `src/server/management/provider-routes.ts:1133`은 이미 열린 management UI/API에서 입력 요소를 저장한다. Link join은 연결 enrollment다. `ocx:src/server/management/link-routes.ts:725` | gap | OBSERVED | +| CAP-remote-proxy-share | 모델 목록·라우팅을 팀/기기간 공유 | LAN 명시 활성화 → `ConfigureLAN`/key → `Remote magpie` preset과 endpoint 채움. 별도 Join password를 설정하면 `/join`으로 caller key를 받는다. `mgp:internal/gui/api.go:2853`, `internal/access/access.go:1015`, `internal/gui/join.go:16`, `internal/gateway/gateway.go:1179`, `internal/provider/presets.go:814`, `internal/provider/provider.go:1943`, `internal/provider/remote_magpie.go:77` | Hub 초대는 `runtimeRole=hub`, origin, live attestation을 확인 후 발행. Home/Child Link는 join/probe/confirm-host/apply, CLI connect와 별도 enrollment. 기본 role standalone. `ocx:src/cli/hub.ts:239,251,284,309,332`, `src/cli/dispatch.ts:423`, `src/server/management/link-routes.ts:725,809,814,819`, `src/config/proxy-env.ts:32` | partial | OBSERVED | +| CAP-remote-admin-window | 타 호스트 관리 Web UI를 앱에서 열기 | native GUI에서만 `/api/remote` 등록 → URL/key 검증, probe 성공 후 별도 창. data-plane preset과 권한이 별도다. `mgp:internal/gui/api.go:1746`, `internal/gui/remote.go:270,279,309,319,324` | Hub Relay read/credential 및 Link management route가 있다. 타 원격 UI의 직접 개창과 전체 scope는 보류. `ocx:src/remote/hub-management-relay.ts:3,59`, `src/server/hub-relay-auth.ts:32,54`, `src/link/management-routes.ts` | unknown | OBSERVED-partial | +| CAP-config-sync-encrypted | WebDAV/S3/GitHub passphrase 동기화 | `/api/davsync/{action}`와 CLI `webdav/s3/github` → Configure/Preview/Sync/Undo. 저장된 setup이 있고 manual이 아닐 때 기본 3분, follow-server 가능. backend 선택 후 PBKDF2-SHA256 기반 AES-256-GCM bundle을 읽고 쓴다. `mgp:internal/gui/backup.go:205,215,245,273`, `internal/cli/main.go:703`, `internal/davsync/dav.go:138`, `internal/davsync/davsync.go:64,147,874,1466,1519,1813`, `internal/backup/backup.go:388,411,469` | A4. `ocx:src/cli/dispatch.ts:418` → `src/codex/sync.ts:103`은 catalog/config reconcile. `src/cli/claude-desktop.ts:915,927`의 versioned profile 파일과 `src/server/management/link-routes.ts:830`의 Child ops는 범용 암호화 저장소 sync를 수행하지 않는다. | gap | OBSERVED | +| CAP-library-mcp | MCP 서버·tool 정책을 여러 agent에 관리 배포 | GUI Library server assignments → `ServerAgents`/`syncMCP`. 명시적 선택, target 지원 여부, owned manifest, 외부 항목 충돌 및 optional MCP router를 확인한다. `mgp:internal/gui/library.go:759,815,853`, `internal/library/sync.go:230,251,283,353,376,973` | A5. `ocx:src/server/management/codex-agent-role-routes.ts:2`의 role model 및 `src/cli/claude-desktop.ts:68,73`의 picker는 client별 MCP catalog/assignment를 제공하지 않는다. | gap | OBSERVED | +| CAP-library-skills | Library skill 배포와 Claude Desktop manifest reconcile | Library skill install/assign → `InstallSkills`/`syncSteps`. 일반 target은 공유 `.agents/skills` dedup, Desktop target은 기존 native 계정의 manifest/plugin roots에 복사, 변경된 복사와 무관한 skill을 보호한다. `mgp:internal/gui/library.go:922,939,1045`, `internal/library/skills.go:718,1550,2237`, `internal/library/sync.go:135,148,154`, `internal/library/desktop_skills.go:45,59,167,250,274,305,328` | A5b. `ocx:src/claude/desktop-3p-library.ts:20` 및 `src/claude/desktop-picker-profile.ts:159`는 3P config profile library를 다룬다. `src/server/management/native-integration-routes.ts:783,1106`의 toggle 대상도 routing 설정이다. | gap | OBSERVED | +| CAP-surface-tray | 시스템 tray / 메뉴바와 조작 | `magpie tray` → `Run(false)` → Wails tray, usage/빠른 panel; native GUI 빌드 필요. `mgp:internal/cli/main.go:621`, `internal/gui/app.go:334,637,663,695`, `Makefile:17,57,60` | Tauri startup이 지원 tray를 붙이고, Windows 별도 `ocx tray install/start`에서 PowerShell tray 시작. 두 제품의 menu/panel 범위 차이. `ocx:desktop/src-tauri/src/startup.rs:1521`, `desktop/src-tauri/src/tray.rs:75`, `src/cli/dispatch.ts:603`, `src/tray/windows.ts:639,737,798` | partial | OBSERVED | +| CAP-surface-tui | 대화형 터미널 agent/model picker | `magpie tui` → `runTUI` → `tui.Run`; 감지된 agent·picker를 Bubble Tea에 표시. 명시적 subcommand. `mgp:internal/cli/main.go:294,610`, `internal/tui/tui.go:162,192,489` | A6. `ocx:src/cli/dispatch.ts:328,418,879`의 command별 status/sync/integration 및 `gui/src/pages/integrations/IntegrationsOverview.tsx:854` GUI는 터미널 picker에 해당하지 않는다. | gap | OBSERVED | +| CAP-surface-cli | 비대화형 진단·클라이언트 관리 명령 | `magpie ls/agents/status`, explicit field setters와 default 복원. `mgp:internal/cli/main.go:637,641,686,757,791,885` | `ocx status/integration/export` 및 native toggles. explicit mutation과 supported import/export 범위. CLI 조작 표면 수준의 동등성. `ocx:src/cli/dispatch.ts:328,879`, `src/cli/registry.ts:573`, `src/server/management/integration-routes.ts:1196` | parity | OBSERVED | +| CAP-surface-web | 브라우저에서 proxy 관리 | `magpie web`, `serve --web` → loopback 기본 `3430`, web session/key guard. `mgp:internal/cli/main.go:612,674`, `internal/cli/web_cli.go:21,29,225`, `internal/gui/web.go:264,416,436` | server에서 GUI dist를 제공하고 세션 bootstrap 및 ingress 정책을 적용한다. `ocx:src/server/index/serve-options.ts:440,1910`, `src/server/gui-static.ts:48,179,195` | parity | OBSERVED | +| CAP-distribution-docker | 컨테이너의 서비스 진입, 상태와 영속 경로 | Dockerfile은 Debian slim runtime + `/magpie serve`, `/config`, 3425/3430과 healthcheck. version builds와 stable/daily tag promotion. `mgp:Dockerfile:36,68,78,80,85`, `.github/workflows/docker.yml:3`, `.github/workflows/docker-stable.yml:12`, `.github/workflows/docker-daily.yml:14` | Bun runtime image + `start --port 10100`, homes volumes와 healthcheck. tag cadence의 동등성은 별도다. `ocx:Dockerfile:75,80,101,104,107` | parity | OBSERVED | +| CAP-release-channels | 채널에 따른 릴리스 선택과 배포 | `v*` tag dispatch → 별도 release repo 빌드·발행·mirror. site worker stable/daily 정책, Docker tag workflow가 feed를 조회한다. `mgp:.github/workflows/release.yml:10,49,131,165`, `site/worker.js:780,877`, `.github/workflows/docker-stable.yml:27,45` | dispatch release workflow의 latest/preview channel 검증 및 publish gate, package refresh는 이 채널을 사용한다. `ocx:.github/workflows/release.yml:10,151,241,1196`, `src/update/refresh-scheduler.ts:63,127` | partial | OBSERVED | +| CAP-auto-update | 주기적 확인, staging, 설치·재시작 | desktop/web start → updater loop. 기본 360분 체크, `NoAutoUpdate/NoAutoDownload` 및 별도 `AutoRestart` gate, install endpoint와 idle 대기. `mgp:internal/gui/app.go:613`, `internal/gui/web.go:145`, `internal/gui/update.go:204,208,244,731,1024`, `internal/gui/update_wait.go:236`, `internal/settings/settings.go:601,3066` | package startup refresh와 management check/run/status, Desktop 비-debug background checks와 별도 설치. Windows headless Desktop updater는 명시적으로 실행하고 GUI trust key로 staged MSI까지 검증. `ocx:src/server/index.ts:878`, `src/server/management/config-routes.ts:998,1008,1053`, `desktop/src-tauri/src/lib.rs:279,290,433`, `desktop/src-tauri/src/updater.rs:354,513`, `src/cli/dispatch.ts:657`, `src/desktop-update/headless.ts:131,186,208` | partial | OBSERVED | +| CAP-i18n | Web UI locale 선택 폭 | settings의 언어 선택 또는 시스템을 따르는 5종. `mgp:internal/gui/api.go:1794`, `internal/gui/assets/i18n.js:22447,22460`, `internal/uilang/uilang.go:14` | React 진입의 LanguageProvider → 저장된 locale/브라우저 값과 typed catalogs. GUI 목록은 한국어를 포함한 11종. `ocx:gui/src/main.tsx:18`, `gui/src/i18n/shared.ts:6,24`, `gui/src/i18n/provider.tsx:6,13,25`, `gui/src/i18n/catalogs.ts:26` | ocx-ahead | OBSERVED | +| CAP-onboarding-client | 첫 공급자·클라이언트 설정 | Agents 화면의 Add Provider, Providers discovery review 및 import preview, explicit Connect, Claude의 연결 완료 시 해당 onboarding mark 처리. `mgp:internal/gui/assets/app.js:1608,1961,10802,10840,11092`, `internal/gui/api.go:1647`, `internal/agent/claude.go:788,2081` | Home 체크리스트와 SetupHub, Connect에서 수동 설정. 체크리스트 hide/show 유지, Desktop launch 경로, 연결 대상에 따른 notice gate가 있다. `ocx:gui/src/pages/Home.tsx:79,89,150`, `gui/src/pages/SetupHub.tsx:54,109`, `gui/src/App.tsx:472,479`, `desktop/src-tauri/src/startup.rs:1479` | partial | OBSERVED | + +### 부재 확인 명령 + +OpenCodex `9e0e298ef9` export에서 실행했다. `O=/Users/jun/Developer/new/700_projects/opencodex/.tmp/chase/opencodex-dev`이다. 각 행의 정확한 argv는 `rg -n -i -g '!*.test.*' "$P" "$O/src" "$O/gui/src" "$O/desktop/src-tauri" "$O/docs-site/src" "$O/structure"`이며 `P`에 표의 패턴 전문을 한 인자로 넘겼다. closest equivalent의 차이는 인벤토리 각 행에 있다. + +| 확인 ID | 정확한 패턴 | exit | 결과 | +|---|---|---|---| +| A1 | `magpie://\|ccswitch://\|opencodex://\|ocx://\|protocol_scheme\|tauri.plugin.deep.link\|CFBundleURLSchemes` | 1 | 일치 0 | +| A3b | `codexbar\|sub2apiEntry\|parseLoginImport\|ImportCodexAccessOnly\|cliproxyapi` | 0 | CLIProxyAPI wire/identity 참조. `src/adapters/google-antigravity-wire.ts:89`, `src/providers/claude-cli-identity.ts:14` 등에 있고 registry importer에는 없음 | +| A4 | `davsync\|webdav\|follow.server\|sync passphrase\|encrypted sync\|S3 sync\|GitHub sync` | 1 | 일치 0 | +| A5 | `skill(s)?/(agents\|install)\|library/(servers\|skills)\|syncDesktopSkills\|local-agent skills\|managed MCP server library` | 1 | 일치 0 | +| A5b | `local-agent-mode-sessions\|skills-plugin\|desktopSkillRoots\|skills/agents` | 1 | 일치 0 | +| A6 | `bubbletea\|ink\.render\|blessed\.screen\|runTUI\|case ["']tui["']\|ocx tui` | 1 | 일치 0 | +| A7 | `zed/settings\|zed\.dev\|zedConfig\|case ["']zed["']\|["']zed["'] *:` | 0 | 14건. Zed upstream/provider 등록과 문서, client 등록 별도 확인 | +| A8 | `readClaudeSettings\|readCodexConfig\|readOpenCodeAuth\|importapps\|import.?from.?apps\|provider.?import.?preview` | 0 | 3건. routing healer의 config read 2건, CC Switch 명시적 CLI preview 1건 | + +표 안의 `\|`는 Markdown 열 이스케이프다. 실제 정규식의 alternation은 `|`이다. + + +## 4. Gap candidates + +평가는 L7의 제안이다. 구현을 채택할 경우 client/management 모듈에 두고 `src/router.ts`·`src/server/lifecycle.ts`·`src/server/responses/core.ts`의 Lab 비의존 경계를 지킨다. ratchet 여유가 없는 파일에서는 sibling module을 사용한다. 실제 자격 증명, 신원·크레딧·평판에 영향을 주는 동작은 사용자 확인과 privacy scan 범위를 설계에 포함한다. + +| ID · CAP | 후보 | 가치 · 규모 | 적용 지점 · 의존성 · 위험 | +|---|---|---|---| +| L7-1 · CAP-client-config-claude | 일반 `claude` 실행을 연결하는 opt-in preview/apply/restore와 per-home 상태 표시 | high · L, 설정 우선순위·auth mode·기존 first-party 경로를 조정 | `src/claude/`, `src/server/management/native-integration-routes.ts`의 sibling, Connect UI. tracked env leaf ownership, 실패 시 원본 복원, `CLAUDE_CONFIG_DIR` footprint, 사용자의 기존 로그인과 launch env 유지. | +| L7-2 · CAP-import-account-batch | Codex·Claude용 명시적 batch migration. 형식별 adapter와 결과 receipt | high · L, 계정 식별·중복·부분 실패 대응 | `src/oauth/account-import/`, `src/cli/account-extended.ts`, Accounts UI. opt-in credential intake와 provider parity 검증, 결과 redaction. | +| L7-3 · CAP-import-local-discovery / CAP-import-cc-switch | keyless 앱 발견·리뷰. 시작은 기존 CC Switch importer와 Claude/Codex provider 설정 | high · M, 기존 importer 재사용과 안전한 source adapters | `src/providers/cc-switch-import*.ts`, `src/server/management/provider-routes.ts`의 sibling, Providers UI. 명시적 review 후 apply, source file allowlist, 브라우저에는 metadata만. OpenCode auth로 확대는 별도 승인/모델. | +| L7-4 · CAP-deeplink-import | relay preset의 endpoint·model review, 이후 OS 링크 transport 선택 | high · M, schema와 cross-platform 진입/승인 경계 | `desktop/src-tauri/`, `gui/src/pages/Providers.tsx`, `src/server/management/provider-routes.ts`의 sibling. 목적지 검증 재사용, 키는 링크에서 직접 넣지 않는 형태부터 검토, 식별자 충돌·링크 재사용 방어. | +| L7-5 · CAP-client-config-codex / CAP-client-config-drift | native Codex Connect에서 ownership·계정 모드·쿼터로 인해 다른 상태가 되는 이유와 복원 preview 표시 | high · M, 기존 desired state/restore 계약의 GUI projection | `src/codex/desired-state.ts`, `src/codex/inject/restore.ts` 주변 read-only projection, Connect UI. 기존 외부 소유권 refusal과 history 보호, catalog/실제 transport 상태 구분. Magpie의 automatic provider 전환 복제를 전제로 삼지 않는다. | +| L7-6 · CAP-remote-proxy-share | Hub/Link의 팀 접속 안내를 하나의 사용자 흐름으로 묶고 remote catalog 준비 상태를 표시 | med · M, enrollment/data-plane authority를 재사용 | `src/cli/hub.ts`, `src/link/`, `src/remote/`, Connect UI. origin/host 검증과 key scope 유지, `/join` 복제 전 포트와 권한 분리 확인. | +| L7-7 · CAP-client-config-zed | Zed custom provider export 및 opt-in 연결 | med · M, OS 별 credential 지원과 JSON merge 검증 | `src/clients/config-export/`, `src/integrations/registry.ts` 및 Connect. 기존 Zed upstream ID와 client ID의 구분, 설정에서 사용자 모델 선택 보존. | +| L7-8 · CAP-config-sync-encrypted | reject candidate · 범용 양방향 cloud settings/sign-in sync | low · XL, 암호화 키·충돌·부분 적용·rollback 제품 필요 | `src/config/` 외 선택적 subsystem이 필요. 잔존/새 credentials와 per-machine paths의 병합 위험이 크고, 현재 Hub/Link가 해결하는 연결 관리와 제품 범위가 다르다. | +| L7-9 · CAP-library-mcp / CAP-library-skills | reject candidate · 전체 MCP/skills 및 Cowork manifest 관리자 | low · XL, 여러 agent별 schema·외부 도구 실행·manifest ownership | `src/clients/`와 `src/integrations/` 밖의 별도 제품 영역. MCP 실행/네트워크와 skill 출처 승인이 추가로 필요하며 Codex/Claude 프록시 이주를 직접 줄이지 않는다. | +| L7-10 · CAP-surface-tui | reject candidate · 대화형 별도 TUI | low · L, cross-platform terminal UX와 추가 유지보수 | `src/cli/`. CLI+GUI가 기존 flow를 제공하며 동일한 preview/restore와 localization을 두 번째 UI에 유지하는 비용이 크다. | +| L7-11 · CAP-client-config-roster | reject candidate · 등록 수 맞추기 | low · XL, agent별 파일·플랫폼·릴리스 변경 추적 | `src/clients/`, `src/integrations/`. 잘못된 설치 감지와 오탐 쓰기의 영향을 고려하면 L7-7 같은 사용 근거가 있는 adapter부터 범위를 정한다. | + +## 5. OpenCodex-ahead + +- `CAP-i18n`의 GUI 언어 선택 폭. 위 판정은 배포된 모든 화면의 번역 품질까지 비교한 결과가 아니다. `ocx:gui/src/i18n/shared.ts:6`, `gui/src/i18n/catalogs.ts:26`. +- `CAP-import-cc-switch`의 keyless preview/restore journal과 `CAP-client-config-drift`의 plan-bound mutation/journal. 이주 시 credential 사용을 늦추거나 충돌을 검토하는 데 재사용할 수 있다. `ocx:src/cli/provider-cc-switch-import.ts:86,99`, `src/providers/cc-switch-import.ts:747,855`, `src/server/management/integration-routes.ts:915,966,1016,1230`. +- `CAP-auto-update`에서 GUI와 동일 trust root를 쓰는 Windows headless 경로, staging 재검증 및 drain. Magpie도 별도 서명·설치 모듈이 있으므로 전체 서명 체계 또는 Windows 설치 성공률 우위는 판정하지 않았다. `ocx:src/desktop-update/trust.ts:8,15`, `src/desktop-update/headless.ts:131,178,208`, `mgp:internal/update/signed.go`. +- `CAP-remote-proxy-share`의 Home/Child enrollment와 개별 child ops 자체가 기존 자산이다. 이를 암호화 cloud sync 또는 generic remote admin window와 동일시하지 않는다. `ocx:src/server/management/link-routes.ts:725,809,814,819,830`, `src/link/management-routes.ts`. + +## 6. 최신 사례 (Aside) + +`aside-codemode 0.9.2`, 명시적 `u0/local`, 공개 URL만 조회했다. 이 자료는 pinned source 판정과 별개다. 릴리스 페이지의 공개 asset 표와 code tag는 별도 저장소를 가리키므로 version 이름과 관찰된 게시 시각을 함께 기록했다. + +| 발행일 | 릴리스/PR/이슈 | 출처 | 열람일 KST | 관찰 | OpenCodex 관련성 | 신뢰도 | +|---|---|---|---|---|---|---| +| 2026-11-23 UTC | Magpie v0.1.4720, release repo `7c8b974` | [GitHub release](https://github.com/yetone/magpie-releases/releases/tag/v0.1.4720) | 2026-11-23 | Web 로그인 유효기간과 키 위치 안내 개선을 기록했다. 바로 앞 버전들도 release list에 보이며, 이 페이지의 CLI 자산은 약 90–100 MB, DMG는 약 46–51 MB 범위다. 게시 시각 12:46 UTC는 Magpie 핀 commit 12:44 UTC 뒤다. **post-head publication**. Web guard 자체는 `mgp:internal/gui/web.go:264,416`에서 확인했다. | 관리 UI 세션이 만료되거나 이동할 때 다시 연결하는 UX, distribution footprint | 높음, 공식 notes/asset 표. 실행 검증 없음 | +| 2026-10-08 UTC | Magpie merged #1311 | [Qwen Code managed agent PR](https://github.com/yetone/magpie/pull/1311) | 2026-11-23 | Qwen의 JSON config에 모델 목록·auth type을 연결하고 원상 복구하는 adapter 추가. pinned `mgp:internal/agent/qwen.go:150`과 `internal/agent/agents.go:366`에 등록 확인. | roster 확대의 비용은 파일 존재 검사를 넘어 모델·auth 설정의 rollback까지 포함한다. | 높음, merged PR 및 등록 대조 | +| 2026-11-05 UTC | Magpie open #5302 | [Hook-only config detection](https://github.com/yetone/magpie/issues/5302) | 2026-11-23 | hook만 있는 설정에서 Kimi/OpenClaw가 `magpie ls`에 보였다는 사용자 보고. pin의 공통 detector가 `pathOwn` 조건하에 config 경로를 먼저 인정하는 분기는 관찰했다. `mgp:internal/agent/agent.go:466,475,478`. 두 앱에서의 재현은 확인 범위 밖이다. | 발견 단계의 confidence와 실제 연결 가능성을 구분한다. | 중간, 공개 보고와 공통 소스 경로 | +| 2026-10-12~15 | Linux.do #3012827 | [Linux.do 토론](https://linux.do/t/topic/3012827) | 2026-11-23 | cpa+cc-switch와 Claude 공식 구독, Codex relay, Pi·dsh를 함께 쓰던 사용자가 Magpie로의 이주를 검토한다고 적었다. | 설정/계정 이주의 분리와 cross-client onboarding 수요 | 낮음, 개별 사용자 보고 | +| 2026-11-23 UTC | CC Switch v4.0.40, `f19a9d4` | [CC Switch release](https://github.com/farion1231/cc-switch/releases/tag/v4.0.40) | 2026-11-23 | Grok 공식 카드의 계정 관리 및 기본 로그인 복원, 설치 감지와 버전 확인 분리, Antigravity CLI plugin 관리가 릴리스 노트에 있다. `ccs:src-tauri/src/grok_auth.rs:1,42`에서 auth 파일 대상 확인. 상태에 따른 복원 실행은 미검증. | 계정 단위의 이주와 설치 상태가 확정되기 전 관리 UI 차단을 줄이는 경쟁 사례 | 공식 발표는 높음, 사용자 환경 효과는 미측정 | + +## 7. Deferred checks + +- 등록 인덱스의 나머지 adapter 전체에 대해 실제 키·경로·충돌 정책을 검증하는 작업. 특히 Windows/WSL 경로 매핑, 프로필별 파일, agent binary restart, plugin이 built-in adapter를 대체하는 경우, Cline state store와 NewMax/AionUI DB migration. +- Magpie Codex history retag/mirror의 모든 조건, Codex App의 버전별 모델 picker/쿼터 전환, Claude의 force-login 및 isolated Desktop, Raycast renderer의 주석 보존 범위와 Zed의 플랫폼별 credential store. +- Relay link의 vendor별 landing 패키지와 사용자 확인, Remote Magpie 권한별 quota/usage/Library follow의 전체 표. `CAP-remote-admin-window` 동등성 및 `CAP-import-account-antigravity`의 format parity는 unknown으로 유지한다. +- 암호화 sync의 backend별 concurrent write/네트워크 단절 시 의미, backup archive 용량과 성능, Library의 native/project/WSL 동시 적용, tool/router·marketplace의 모든 subcommand, UI/tray locale 완전성. +- Release asset의 서명 실물 검증, container tag 전파 지연, installer/update/rollback 체감 시간, Docker·GUI 모드에서 웹과 gateway를 같이 열었을 때의 전 과정. + +## 8. NOT RUN + +- 빌드, 테스트, 서버/앱/TUI 실행, 실제 홈 설정 변경, import·sync·install·release·LAN 접속·custom protocol 실행. +- Aside에서 게시자·사용자 report의 재현과 인증된 화면, 다운로드 및 asset 실행. 두 `browse.exec` 호출 모두 codemode 외부 envelope가 `ENOMARKER / partial:[no-marker]`를 반환했다. 각 호출의 `raw.stdout` 안 native Aside `type:final` 레코드를 독립적으로 파싱해 URL별 `contentVerified:true`, 본문, 세부 페이지의 DOM 날짜를 확인했다. 바깥 envelope는 완전성 증거로 사용하지 않았다. diff --git a/devlog/_plan/261123_proxy_upstream_catchup/008_opencodex_baseline.md b/devlog/_plan/261123_proxy_upstream_catchup/008_opencodex_baseline.md new file mode 100644 index 00000000000..7463d025ed2 --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/008_opencodex_baseline.md @@ -0,0 +1,213 @@ +# 008 — OpenCodex 기준 기능 인벤토리 + +분석 기준은 `origin/dev` `9e0e298ef9720cfeaa1209f090a68e4d1965d2a1` (2026-11-21 KST)의 `.tmp/chase/opencodex-dev/` export다. `ocx:` 경로와 줄은 모두 이 export에 상대적이다. `structure/INDEX.md:43–135`에서 데이터 경로와 어댑터를, `:137–183`에서 클라이언트·운영 경로를 찾고 실제 등록부·핸들러·설정 해석으로 확인했다. + +## 요약 + +- Codex는 Responses HTTP/SSE와 opt-in WebSocket을 같은 라우팅 파이프라인으로 사용한다. 네이티브 응답·compact와 어댑터 변환·휴대 가능한 이력 경로가 있다. +- Claude Code는 Messages와 `count_tokens`를 사용한다. 일반 변환, 자격 증명과 요청 조건을 충족하는 native Messages, Antigravity 전용 직접 인코딩이 각각 등록돼 있다. +- Chat Completions, Gemini generateContent/Interactions, Ollama 호환 ingress가 같은 모델·키 정책을 사용한다. Gemini embedding 동작은 등록된 메서드에서 501을 반환한다. +- Codex·Anthropic·일반 OAuth·공급자 API 키 풀은 교체 범위와 승인 조건이 다르다. 캐시 친화성, 쿼터 냉각, 콤보 재시도는 각각 선택·전송 경계에 반영된다. +- Codex 및 Claude 설정 외에도 24개 선언형 config export, 별도 native/gateway 연결, Remote Link의 설정 소유권과 복구가 있다. +- 공유 설치는 이름 있는 데이터 키, 모델 범위, 키별 사용량, 관리자 인증, Hub·Child 연결을 제공한다. 조직별 청구·사용자 관리는 비교 검증 대기다. +- 로컬 플러그인은 공급자 전송 훅을 등록한다. Compatibility Lab은 요청 처리에서 분리된 활성화 게이트와 fixture·live 증거 경로를 갖는다. +- Windows/macOS/Linux 서비스와 Docker 배포, Desktop 트레이·업데이트 경로가 있다. 열린 계획의 이행 상태는 기준 소스로 개별 확인했다. + +## 표면 맵 + +| 등록 그룹 | 진입점과 담당 경로 | +| --- | --- | +| Codex | `POST /v1/responses`, `POST /v1/responses/compact`, `/v1/responses` WS upgrade. `ocx:src/server/index/serve-options.ts:562,1261,1411` | +| Anthropic / OpenAI Chat | `POST /v1/messages[?beta=true]`, `POST /v1/messages/count_tokens`, `POST /v1/chat/completions`. `ocx:src/server/index/serve-options.ts:1485–1582` | +| Gemini | `/v1beta/models` 목록·단일 모델 GET, `/v1beta/models/:model:*`와 `/v1/models/:model:*` POST, `/v1beta/interactions` 및 `/v1/interactions` 생성·조회·삭제·취소. `ocx:src/server/gemini-native-paths.ts:18–57` / `ocx:src/server/index/serve-options.ts:676` | +| Ollama | `GET /api/version`, `GET /api/tags`, `POST /api/show`, `POST /api/chat`, `POST /api/generate`. 데이터 플레인 선처리. `ocx:src/server/ollama-native-paths.ts:8–17` / `ocx:src/server/index/serve-options.ts:672–681` | +| 검색·미디어 | `POST /v1/alpha/search`, `/v1/images/{generations,edits}`, `GET /v1/opencodex/artifacts/:id`, `POST /v1/audio/transcriptions`, `/v1/audio/transcriptions/stream` WS, `POST /v1/live`, `POST /v1/realtime/calls`, `/v1/live`·`/v1/realtime` WS 및 call sideband. `ocx:src/server/index/serve-options.ts:1299–1409,1584–1659` | +| 조회·상태 | `/healthz`, `/readyz`, `/v1/models`, `/v1/catalog`, `/v1/usage`, `/v1/usage/windows`, `/v1/hub-state`. `ocx:src/server/index/serve-options.ts:608–669,761–930` | +| 관리·설치 | `/api/` handler chain과 route registry가 관리 route family를 등록한다. 인증·페어링, config/storage/diagnostics, provider/model/key/quota, 콤보/정책/프로토콜/Advisor, 앱 설정/통합, Link/Workspace, Lab/telemetry/usage, 서비스/업데이트/시스템. `ocx:src/server/management-api.ts:136–250,372–414` / `ocx:src/server/management/route-registry.ts:98` | +| UI | Home, Setup, Advanced, Dashboard, Startup, Providers, Models, Subagents, Advisor, Logs, Usage, Storage, Remote Link, Remote Workspace, Codex Settings, Integrations. API 키·프로토콜·콤보·routing profile 등은 관리 페이지 하위에서 제공. `ocx:gui/src/App.tsx:689–708` / `ocx:gui/src/pages/ApiKeys.tsx:1` / `ocx:gui/src/pages/AdvancedHub.tsx:1` | +| 연결 type | Native `codex`, `claude`, `claude-desktop`, `grok`. Gateway `antigravity`/`agy`와 Cursor는 전용 연결 처리. export roster는 Qoder/Qoder CN, WorkBuddy/WorkBuddy AI, OpenCode, Pi, OMP, Hermes, OpenClaw, Kimi, Gajae, DSH, MCode, ZCode, Command Code, Prime, Aside, Raycast, omo, Cline, Kilo, Droid, Gentle Shell, T3 Code. `ocx:src/server/management/native-integration-routes.ts:69,1005–1108` / `ocx:src/server/management/integration-routes.ts:748–754` / `ocx:src/clients/client-ids.ts:2–6` / `ocx:src/integrations/gateway-clients/index.ts:14–40` | +| CLI·장치 | `ocx start`, 서비스·shim·restore, connect/link/sync/disconnect, `remote-workspace`, `message`, `lab`, 통합 및 관리 capability. Workspace의 pair 및 agent WS는 데이터 리스너에서 별도 처리. `ocx:src/cli/registry.ts:12–202` / `ocx:src/cli/capabilities.ts:1` / `ocx:src/server/index/serve-options.ts:429–559` | + +### 모든 등록 outbound adapter + +`ocx:src/server/adapter-resolve.ts:48–90`에서 route/model wire override를 반영한 뒤 `ocx:src/adapters/registry.ts:229–239`가 `provider.adapter`에 맞는 factory를 생성한다. `contractParent`는 호환성 계약 계승이다. 별도 생성자가 있으면 실제 전송도 별도다. + +| 등록 ID | wire 또는 전송 경계 | factory와 구현 | +| --- | --- | --- | +| `openai-responses`, `azure`, `azure-openai` | Responses passthrough·Azure deployment | `ocx:src/adapters/registry.ts:119–124,135–142` / `ocx:src/adapters/openai-responses/passthrough.ts:162`, `ocx:src/adapters/azure.ts:15–41` | +| `openai-chat`, `ollama-native`, `anthropic`, `google` | Chat, Ollama, Messages, Google | `ocx:src/adapters/registry.ts:102–129` / `ocx:src/adapters/openai-chat.ts:94–102`, `ocx:src/adapters/ollama-native.ts:1205–1213`, `ocx:src/adapters/anthropic.ts:1044–1053`, `ocx:src/adapters/google.ts:918,1016,1249–1285` | +| `m365-copilot`, `workbuddy-ai`, `mimo-free` | 별도 factory, Chat 계약 계승 | `ocx:src/adapters/registry.ts:83–91,158–161` / `ocx:src/adapters/m365-copilot.ts:20–32`, `ocx:src/adapters/workbuddy.ts:12–19`, `ocx:src/adapters/mimo-free.ts:230–249` | +| `kiro`, `cursor`, `devin`, `zed`, `command-code` | 각 공급자의 wire 또는 클라이언트 세션 경로 | `ocx:src/adapters/registry.ts:97–101,130–157` / `ocx:src/adapters/kiro/adapter.ts:55`, `ocx:src/adapters/cursor.ts:132–170`, `ocx:src/adapters/devin.ts:700–743`, `ocx:src/adapters/zed.ts:277–305`, `ocx:src/adapters/command-code.ts:707–718` | +| `codebuddy`, `qoder`, `claude-cli` | coding agent child, CodeBuddy stream-json 계열 계약 | `ocx:src/adapters/registry.ts:92–96,162–179` / `ocx:src/adapters/codebuddy/adapter.ts:99–112`, `ocx:src/adapters/qoder/adapter.ts:470–480`, `ocx:src/adapters/claude-cli/adapter.ts:184–196` | +| `step-cli`, `agy-acp` | length-prefixed SDK stdio, Antigravity CLI ACP | `ocx:src/adapters/registry.ts:166–187` / `ocx:src/adapters/step-cli/adapter.ts:85–104`, `ocx:src/adapters/agy-acp/adapter.ts:159–184` | +| `dsh-account` | 별도 factory, Anthropic 계약 계승 | `ocx:src/adapters/registry.ts:189–192` / `ocx:src/adapters/dsh-account.ts:17–53` | + +## 기능 인벤토리 + +각 행의 `n/a`는 L8 단면의 타 프로젝트 비교 판정에 적용한다. `OBSERVED`는 지정 revision의 등록과 동작 조건을 소스에서 확인했다는 뜻이다. `OBSERVED-partial`과 `unknown`은 읽은 범위로 전체 계약을 확정하기 어려운 행에 붙였다. 비교 evidence 열의 `—`는 L1–L7의 대응 태그를 009에서 결합하는 자리다. + +### (a) Wire·translation + +| CAP tag | 기능 | Reference evidence | OpenCodex evidence · 진입 → 구현 → 게이트 | Status | Evidence | +| --- | --- | --- | --- | --- | --- | +| CAP-wire-responses-http | Codex Responses JSON/SSE, native 및 변환 | — | `ocx:src/server/index/serve-options.ts:1411–1445` → `ocx:src/server/responses/core.ts:30–69` → `ocx:src/server/responses/core-pipeline.ts:104–143`에서 passthrough 표시와 compaction 조건에 따라 native 실행 또는 adapter exchange. Responses 활성 상태 고정 `ocx:src/protocols/settings.ts:53–56`. | n/a | OBSERVED | +| CAP-wire-responses-ws | 인바운드 WS와 native upstream WS | — | `ocx:src/server/index/serve-options.ts:562–604`에서 data auth·Origin·slot 후 upgrade. `ocx:src/config/feature-flags.ts:3–13` 기본 off, 꺼진 경우 426. `ocx:src/server/index/websocket-handler.ts:265–277,359–421`는 `response.create`를 Responses 처리로 연결하고 프레임을 보낸다. 상류의 별도 판정과 연결은 `ocx:src/server/responses/ws-upstream.ts:127–160,234`에 있다. | n/a | OBSERVED | +| CAP-wire-responses-steering | mid-turn steer·function result injection | — | `ocx:src/server/index/websocket-handler.ts:227–275`에서 `response.steer`·`response.inject`, native control과 Link 거절 조건 검사. steering 전용 상류 연결을 idle pool에서 제외 `ocx:src/server/responses/ws-upstream.ts:234–235`. | n/a | OBSERVED | +| CAP-wire-responses-replay | replay scope·compact·portable 이력 | — | 익명 loopback은 WS마다 별도 replay scope를 발급하고, 키가 있는 호출은 principal을 해석한다 `ocx:src/server/index/serve-options.ts:583–604`. compact 전용 진입 `:1261–1283` / 일반 turn의 compaction recovery와 routed compaction에 따른 분기 `ocx:src/server/responses/core.ts:46–66`, `ocx:src/server/responses/core-pipeline.ts:86–114`. | n/a | OBSERVED | +| CAP-wire-messages | Claude Messages JSON/SSE, native·bridge | — | `ocx:src/server/index/serve-options.ts:1504–1536`에서 admission·Origin·turn → `ocx:src/server/claude-messages.ts:1158–1227,1316,1482,1573`에서 native/Antigravity direct/Responses bridge 후 Anthropic JSON·SSE 재인코딩. `ocx:src/server/claude-messages.ts:209–221`에서 Messages 거절을 공통 처리한다. `ocx:src/protocols/settings.ts:53–60,92–116`은 Messages 선택, direct 기본 on, 일반 managed native 기본 off와 활성 Anthropic pool의 native 기본값을 규정. OAuth native는 별도 자격·공식 목적지 검사 `ocx:src/server/messages-native-eligibility.ts:99–115,133–141`. | n/a | OBSERVED | +| CAP-wire-count-tokens | Messages·Gemini 토큰 수 | — | `ocx:src/server/index/serve-options.ts:1486–1501` → `ocx:src/server/claude-messages.ts:1684–1755` / 조건을 충족한 Anthropic 호출은 native `count_tokens`, 다른 경로는 계산할 body를 실제 wire에 맞춰 투영. Gemini는 인가와 body budget을 거쳐 로컬 계산 `ocx:src/server/index/gemini-routes.ts:81–95`. | n/a | OBSERVED | +| CAP-wire-chat-completions | Chat JSON/SSE, native와 교차 wire | — | `ocx:src/server/index/serve-options.ts:1544–1576` → native eligibility alebo Chat→Responses→Chat JSON/SSE `ocx:src/server/chat-completions.ts:309–365,431,578,780,861`. 기본 native의 key/local·adapter·콤보 제한 `ocx:src/server/chat-native-eligibility.ts:34–46` / `nativeChatCombos`는 기본 off `ocx:src/protocols/settings.ts:88,105`. | n/a | OBSERVED | +| CAP-wire-gemini | Gemini 모델 조회, generateContent 및 streaming | — | `ocx:src/server/index/gemini-routes.ts:59–145`는 `x-goog-api-key`/`?key=` 정규화, scope와 Origin, Chat bridge/Antigravity native 분기, SSE 또는 JSON 배열을 식별한다 (`:35–48,113–135`). ingress 기본 on, native Antigravity 자체는 opt-in `ocx:src/protocols/settings.ts:49–50,116`. `embedContent`·`batchEmbedContents`는 parser가 받아도 dispatcher에서 501 `ocx:src/server/gemini-native-paths.ts:18` / `ocx:src/server/index/gemini-routes.ts:86–95`. | n/a | OBSERVED | +| CAP-wire-gemini-interactions | Interactions 상태와 SSE | — | collection POST, item GET/DELETE, cancel POST `ocx:src/server/gemini-native-paths.ts:20–37`. 동일 data admission을 적용 `ocx:src/server/index/gemini-routes.ts:66–79,139–143`. `ocx:src/server/gemini-interactions-inbound.ts:62,210`의 Chat 변환·소유자 범위 상태. | n/a | OBSERVED | +| CAP-wire-ollama | Ollama version/list/show/chat/generate | — | `ocx:src/server/ollama-native-paths.ts:8–17` → `ocx:src/server/index/ollama-routes.ts:41–82`에서 data admission·메타/생성 분기 → `ocx:src/server/ollama-inbound.ts:101,164,188`에서 Chat bridge, buffered JSON 또는 스트림. 모델 표시·실행 범위 `ocx:src/server/ollama-route-policy.ts:23–67`. | n/a | OBSERVED | +| CAP-wire-realtime | OpenAI voice, WebRTC·WS·dictation | — | `ocx:src/server/index/serve-options.ts:1584–1659` 및 `ocx:src/server/live.ts:13–30,316–383`에서 create·standalone·call join을 구별. upstream open `ocx:src/server/index/live-sideband.ts:331` / HTTP dictation `ocx:src/server/audio-transcriptions.ts:80,162`. 공급자/model 일반 텍스트 라우팅과 독립된 OpenAI sidecar 계열이다. | n/a | OBSERVED | +| CAP-wire-images-search | 이미지 생성·수정·artifact, hosted search | — | `ocx:src/server/index/serve-options.ts:1299–1409` → `ocx:src/server/images.ts:249,501,691`의 CCA/xAI 등 조건부 경로와 `ocx:src/server/search.ts:64`의 검색 경로. 보조 검색 backend roster와 자격 조건 `ocx:src/web-search/backends.ts:33–96` / xAI 이미지 기본 모델·quality 조건 `ocx:src/images/xai-client.ts:32,92–102`. | n/a | OBSERVED | +| CAP-wire-adapter-matrix | 모델별 wire와 outbound 확장 범위 | — | 위 adapter 21개, `ocx:src/server/adapter-resolve.ts:48–90`과 `ocx:src/providers/registry.ts:160–207`의 모델별 wire 선택 → `ocx:src/server/responses/adapter-dispatch.ts:131,342`에서 adapter request 구성. `runTurn` factory는 `ocx:src/server/responses/core-pipeline.ts:128–138`에서 따로 실행한다. `ocx:src/adapters/registry.ts:207–239`에 계약 상속·실제 factory 경계. | n/a | OBSERVED | +| CAP-wire-google-vertex | Gemini direct, Antigravity CCA, Vertex | — | `google` factory `ocx:src/adapters/registry.ts:125–129` → `ocx:src/adapters/google.ts:1140,1249–1285,1500–1502`의 generate/stream method, Vertex 선택 및 replay scope. 전송 함수 분리 `ocx:src/adapters/google-http.ts:250–277`. 인증 획득의 전체 조합은 후속 확인 대상이다. | unknown | OBSERVED-partial | +| CAP-subscription-cli-bridge | CLI 자체 로그인과 코딩 도구 세션 | — | `claude-cli`, `codebuddy`, `qoder`, `step-cli`, `agy-acp`가 어댑터로 등록된다. `claude-cli`와 `step-cli`는 로컬 CLI가 자격을 소유하고 `agy-acp`는 turn별 child. `ocx:src/adapters/registry.ts:92–96,162–187` / `ocx:src/server/adapter-resolve.ts:85–90`. Claude Code ingress와 함께 사용할 수 있는 별도의 egress다. | n/a | OBSERVED | + +### (b) Auth·credential pools·routing + +| CAP tag | 기능 | Reference evidence | OpenCodex evidence · 진입 → 구현 → 게이트 | Status | Evidence | +| --- | --- | --- | --- | --- | --- | +| CAP-auth-oauth | 공급자 login registry와 갱신 | — | `ocx:src/oauth/login-cli.ts:152,187,237`와 `ocx:src/server/management/oauth-account-routes.ts:264–278,364,446` → `ocx:src/oauth/index.ts:265–403`. 등록 ID는 `m365-copilot`, `workbuddy-ai`, `dsh-account`, `command-code`, `orcarouter-oauth`, `xai`, `anthropic`, `anthropic2`, `kimi`, `meta-muse`, `nous`, `kiro`, `google-antigravity`, `cursor`, `zed`, `devin`, `github-copilot`, `chatgpt`. public/code/device 허용 판정과 공급자 갱신 정책 `:422–449` / 시작 `:1635,1889`, 토큰 snapshot·갱신 잠금 `:708–760,876,1019`. 등록은 로그인 방식이나 proactive refresh의 동일성을 의미하지 않는다. | n/a | OBSERVED | +| CAP-auth-key-custom | 외부 API key·로컬/custom 공급자 | — | `ocx:src/oauth/login-cli.ts:290,327–362`에서 preset을 공급자 설정으로 합성하고 키 로그인을 처리. `ocx:src/server/management-api.ts:394–395` provider/model 관리와 `ocx:src/server/adapter-resolve.ts:85–90` factory를 공유한다. preset의 모델별 wire/default 해석 `ocx:src/providers/registry.ts:130–207`. | n/a | OBSERVED | +| CAP-auth-codex-pool | ChatGPT OAuth pool/direct와 OpenAI API 키 | — | canonical `openai`의 `codexAccountMode` 기본값은 `pool`이며 `openai-apikey`와 분리한다 `ocx:src/providers/registry.ts:207–217`. `ocx:src/server/management/route-registry.ts:103–136`, `ocx:src/oauth/index.ts:397–402` → `ocx:src/server/responses/core-auth.ts:234,492,591`. 계정 조회·pause·priority·pin·쿼터 제어 및 요청별 mode/credential 해석. 정확한 account-qualified model은 풀 선택을 우회한다 `ocx:src/router.ts:511–523` / plan·credit 자격 검사는 `ocx:src/codex/routing/selection.ts:62–106`. | n/a | OBSERVED | +| CAP-auth-anthropic-pool | Anthropic primary·Pool 2과 native OAuth | — | `ocx:src/oauth/index.ts:318–319`, `ocx:src/server/management/oauth-account-routes.ts:556,796,911–939` → `ocx:src/oauth/anthropic-routing.ts:1637–1719`의 선택·affinity·429/refusal. instance pool `enabled`와 `nativeMessages`·rollout은 `ocx:src/protocols/settings.ts:92–108` / native OAuth는 first-party 목적지에 한정 `ocx:src/server/messages-native-eligibility.ts:99–115`. | n/a | OBSERVED | +| CAP-auth-generic-pool | 일반 OAuth 계정 pool·로컬 import | — | `ocx:src/server/management/oauth-account-routes.ts:556,656,911–939,1130` → `ocx:src/oauth/generic-account-failover.ts:172,206,227–280,365–372`의 provider/quorum 검사, reactive failover와 별도 `oauthAccountFailover.enabled` proactive preference. round-robin·fill-first·reset-first 코드가 있다. 외부 계정 파일 import는 `google-antigravity`의 `cockpit-tools` 형식을 지정하는 별도 registry `ocx:src/oauth/account-import/types.ts:3–4`, `ocx:src/oauth/account-import/registry.ts:12–17` / login-first/import-first는 OAuth provider entry마다 다르다 `ocx:src/oauth/index.ts:281–284,310–313,326–329,379–385`. | n/a | OBSERVED | +| CAP-auth-key-pool | 공급자 API-key pool과 교체 | — | `ocx:src/server/management/oauth-account-routes.ts:1243–1370`의 목록·추가·pause·active·삭제 → `ocx:src/providers/key-failover.ts:392,491,603,962–1041`. `apiKeyPoolStrategy`와 유효한 후보를 기준으로 순서를 정하며 429·401·Anthropic 청구 거부의 교체 조건이 각각 있다. 전송 직전 선택 identity 재확인 `ocx:src/providers/api-key-selection.ts:88–120,156`. | n/a | OBSERVED | +| CAP-quota-cooldown | 공급자·계정 한도와 냉각 | — | Codex quota/clear/reset routes `ocx:src/server/management/route-registry.ts:111–127` → `ocx:src/codex/routing/cooldown-math.ts:153–256`의 outcome 분류·Retry-After·reset·cap, pool recovery `ocx:src/server/responses/core-codex-account.ts:430–495,689`. 여러 공급자 snapshot·개별 key/account read `ocx:src/providers/quota.ts:105,236,544`. 상류 회복과 UI 주기 읽기는 독립 경로다. | n/a | OBSERVED | +| CAP-quota-refresh-reset | 자동 리프레시·소모 승인 경계 | — | 설정과 reset 소비 route `ocx:src/server/management/route-registry.ts:114–127,163–166` / quota 자동 worker/status `ocx:src/codex/quota-auto-refresh.ts:107–123,326,415`. 공급자 Accounts 화면 live polling은 `ocx:gui/src/quota-live-refresh-pref.ts:36`, `ocx:gui/src/hooks/useProviderAccountPools.ts:1158`의 viewer 설정으로 켜지며 수동 강제 리프레시와 다르다. 실제 소모 권한은 별도다. | n/a | OBSERVED | +| CAP-model-routing | selector·alias·모델 카탈로그 | — | `ocx:src/server/index/serve-options.ts:761,930`, `ocx:src/router.ts:437–478,511–603,723–754`에서 명시적 policy/qualified model·provider alias·선택 모델·compact 경로를 분리한다. 모델별 adapter override는 `ocx:src/server/adapter-resolve.ts:48–90`. | n/a | OBSERVED | +| CAP-combos | 명시적 콤보와 여러 placement 정책 | — | `ocx:src/server/management-api.ts:407–408`의 decision/combo handler → `ocx:src/server/responses/core.ts:78–109`, `ocx:src/combos/resolve.ts:482–567`의 후보 순서. `failover`, `round-robin`, `random`, `least-used`, `reset-window`, `jev` config 전략 `ocx:src/types/config.ts:1467` / `jev` 수량 신호는 추가 설정 `ocx:src/combos/types.ts:609–611`. | n/a | OBSERVED | +| CAP-failover | 콤보·policy 실패 처리와 사용자 hop 제한 | — | 콤보가 정한 후보 실행의 turn lease `ocx:src/server/responses/core.ts:94–111`, policy selector의 명시적 진입 `ocx:src/router.ts:437–478`. model/provider 변경 분류·설정 범위, 기본 허용과 hop refusal `ocx:src/routing/fallback-policy.ts:69–113,210–256`. 같은 pool 안에서 계정/key를 재선택하는 경로는 위 pool 태그에 있다. | n/a | OBSERVED | + +### (c) Client config·연결·Desktop + +| CAP tag | 기능 | Reference evidence | OpenCodex evidence · 진입 → 구현 → 게이트 | Status | Evidence | +| --- | --- | --- | --- | --- | --- | +| CAP-client-config-codex | Codex CLI/App/SDK 설정·되돌리기 | — | `ocx:src/server/management/native-integration-routes.ts:1102`, `ocx:src/cli/registry.ts:14–17,64–69,124–126` → `ocx:src/codex/inject.ts:194`, `ocx:src/codex/inject/plan.ts:135`, `ocx:src/codex/inject/restore.ts:583`. managed injection과 provider-ID 허용을 구별하며 복구가 history에서 쓰는 table을 유지할 수 있다. | n/a | OBSERVED | +| CAP-client-config-claude | Claude Code on/off와 설정 적용 | — | `ocx:src/server/management/native-integration-routes.ts:1016–1044`와 `ocx:src/server/management/route-registry.ts:149–169` → `ocx:src/claude/claude-code-block.ts:13`. `enabled` 저장 경로 공유. `ocx claude` 런처는 프록시 `ANTHROPIC_BASE_URL`과 실행 환경을 준비한다 `ocx:src/cli/registry.ts:613`, `ocx:src/cli/claude.ts:183,247–262`. macOS `launchctl` 환경 적용은 `ocx:src/server/system-env.ts:243–276`의 기존 사용자 설정 보호 분기를 통과한다. Messages ingress 설정 해석은 `ocx:src/protocols/settings.ts:53–60`. Claude Desktop에는 status/apply·picker·gateway model 별도 surface가 있다. | n/a | OBSERVED | +| CAP-client-config-other | 24개 파일 통합·native·gateway | — | `ocx:src/clients/client-ids.ts:2–6` → `ocx:src/integrations/registry.ts:298–304,432–458` 같은 client별 path/detection → `/api/client-integrations` preview/history/restore `ocx:src/server/management/integration-routes.ts:748–754,802,915,966–1038`에서 writer의 apply/refresh/disable/restore `ocx:src/integrations/writer.ts:528–554,659,1037–1065`. native 추가 연결과 gateway는 별도 처리 `ocx:src/server/management/native-integration-routes.ts:1098–1108`, `ocx:src/server/management/gateway-client-routes.ts:12–46`. | n/a | OBSERVED | +| CAP-client-import-cc-switch | CC-Switch 공급자 마이그레이션 | — | `ocx provider import-cc-switch` 등록 `ocx:src/cli/provider.ts:659–661` → SQLite/JSON 소스 reader `ocx:src/providers/cc-switch-import-source.ts:536,545,972` → `ocx:src/providers/cc-switch-import.ts:747,772`의 import·journal. 기본 preview, 명시적 `--apply`/`--restore`, Child mutation 제한 `ocx:src/cli/provider-cc-switch-import.ts:57–99`. 대상은 keyless provider entry다. | n/a | OBSERVED | +| CAP-client-config-sync | Hub/Child route intent·sync·restore | — | `ocx:src/cli/registry.ts:142–202`와 `ocx:src/server/management/route-to-routes.ts:94–122` → `ocx:src/client/route-intent-apply.ts:68,110,273`에서 Home intent를 로컬 파일과 native 설정으로 물질화. sync와 disconnect에서 client별 선택·소유권을 사용한다. | n/a | OBSERVED | +| CAP-mcp | MCP 작업 메시지·코딩 공급자 도구 | — | `ocx message mcp` `ocx:src/cli/registry.ts:20–22` → `ocx:src/cli/message-mcp-command.ts:6–39`의 explicit CLI/home 조건과 Windows 제한. `ocx:src/messaging/mcp-queue-server.ts:1`은 queue MCP 구현. 별개인 공급자 어댑터 도구 경로는 `ocx:src/adapters/coding-agent/mcp-server.ts:1`, `ocx:src/adapters/cursor/mcp-manager.ts:1`. 여러 client의 MCP 설정을 동기화하는 범위는 보류했다. | n/a | OBSERVED | +| CAP-skills-prompts | Codex 프롬프트 레이어와 skill catalog 입력 | — | `/api/codex-prompt` 조회·toggle·custom·base import/adopt `ocx:src/server/management/codex-prompt-routes.ts:285–403,506–529`. `ocx:src/server/responses/skills-snapshot.ts:50,83,202`은 세션이 식별될 때 incoming skill catalog를 처리하며 기본은 `per_session` `ocx:src/types/config.ts:418–426`. | n/a | OBSERVED | +| CAP-desktop-tray | Tauri shell·트레이·로그인 실행 | — | `ocx:desktop/src-tauri/src/lib.rs:323–330,360–367,427–434`의 updater/트레이/복구 등록과 OS별 tray 모듈 `:29–44` / sidecar 소유 경계 `ocx:desktop/src-tauri/src/proxy.rs:1`. GUI에는 startup/companion·tray 상태 표면이 있다 `ocx:gui/src/App.tsx:693–695` / `ocx:src/server/management-api.ts:413–414`. | n/a | OBSERVED | +| CAP-desktop-update | Tauri 검증 업데이트와 설치 소유권 | — | GUI invoke check/install `ocx:desktop/src-tauri/src/lib.rs:274–296` → `ocx:desktop/src-tauri/src/updater.rs:314–348`의 acquisition·서명·설치 결과 경계. `ocx:src/desktop-update/cli.ts:103`의 headless 경로와 `ocx:src/desktop-update/headless.ts:180,247–255`의 Windows MSI, runtime ownership와 version readback. npm/service 업데이트는 축 (e). | n/a | OBSERVED | + +### (d) Gateway·affinity·reliability + +| CAP tag | 기능 | Reference evidence | OpenCodex evidence · 진입 → 구현 → 게이트 | Status | Evidence | +| --- | --- | --- | --- | --- | --- | +| CAP-cache-affinity | provider·key 단위 캐시 친화성 | — | `ocx:src/providers/api-key-selection.ts:18–32,88–120,156`의 실제 선택 → `ocx:src/providers/cache-affinity.ts:83–108,156–194`의 mode·consult·record·release. 기본 `auto`이며 OAuth/forward 및 2개 미만 key pool은 제외한다. dispatch에서 credential generation을 재검증한다. | n/a | OBSERVED | +| CAP-sticky-session | Codex 및 OAuth 대화 고정 | — | Codex quota 재바인딩 조건 `ocx:src/codex/routing/cache-affinity.ts:36–57`, 저장 가능 scope `ocx:src/codex/routing/thread-affinity-store.ts:370` / Anthropic 선택/기록 `ocx:src/oauth/anthropic-routing.ts:1637–1654` / 일반 OAuth는 명시적 enable 및 account eligibility `ocx:src/oauth/generic-session-affinity.ts:36–82,103–116`. | n/a | OBSERVED | +| CAP-concurrency | 전역 turn/세션 lane과 WS admission | — | ingress 호출 `ocx:src/server/index/serve-options.ts:1439–1445,1533–1536,1690` → `ocx:src/server/lifecycle.ts:34–36,177,335–368`의 active turn 256·lane 64와 lifecycle. WS 128과 capacity-pressure idle reclamation `ocx:src/codex/websocket-registry.ts:6–45` / 보호된 native control socket은 회수 후보에서 제외. | n/a | OBSERVED | +| CAP-request-pacing | provider·model·key 속도와 동시성 제어 | — | `/api/provider-request-pacing` `ocx:src/server/management/provider-key-pacing-routes.ts:9–12`와 공급자 설정 → `ocx:src/providers/request-pacing.ts:10–35,196–240,346–367,414,531`의 큐 상한·대기 시간·interval·concurrency 및 body 종료시 lease. | n/a | OBSERVED | +| CAP-rate-limit-handling | Retry-After·bounded wait·회전 | — | `ocx:src/providers/key-failover.ts:361–392,713–829,962–1041`의 Retry-After, 정책별 delay와 대체 키 / Codex `ocx:src/codex/routing/cooldown-math.ts:184–256` / Anthropic `ocx:src/oauth/anthropic-routing.ts:1658–1704`. 계정·key·요청 별 한도와 회수 조건이 다르다. | n/a | OBSERVED | +| CAP-reset-retry | 전송 리셋·ambiguous replay 판단 | — | `ocx:src/server/responses/passthrough-dispatch.ts:776–785` → `ocx:src/server/responses/reset-replay.ts:37,112–171,201–230`의 provider tool 실행, 독립 replay 가능성, `retryOnReset` grant 검사. 상류 WS에도 별도 gate `ocx:src/server/responses/codex-ws-exchange.ts:369` 및 `ocx:src/server/responses/codex-ws-wire.ts:485–513`. | n/a | OBSERVED | +| CAP-fingerprints | provider별 호환 헤더와 연결 식별 | — | Claude Code session/OS/arch와 Antigravity UA `ocx:src/adapters/client-fingerprint.ts:20–66,96–122` 및 소비처 `ocx:src/adapters/anthropic.ts:652`, `ocx:src/adapters/google-antigravity-wire.ts:12` / Grok wire identity 및 선택 `ocx:src/providers/xai-transport.ts:32–48,105–117`. TLS는 `ocx:src/lib/provider-tls-profile.ts:19–68,165`의 목적지와 설정·런타임 gate를 통과하는 Antigravity 한정 경로. | n/a | OBSERVED | +| CAP-provider-egress | 공급자별 egress와 적용 한계 | — | `ocx:src/server/responses/fetch-helpers.ts:200–209`의 outbound rewrite 위치와 `ocx:src/lib/provider-egress.ts:160–204,276–316`의 목적지별 egress 처리. `ocx:src/server/responses/ws-upstream.ts:96–157`에 WS 별도 판단. token exchange·quota 일부·프로세스 기반 어댑터 예외 지도 `ocx:structure/transports/inventory.md:192–219`. | unknown | OBSERVED-partial | +| CAP-plugin-host | 로컬 ESM hook 등록과 활성화 | — | `ocx:src/cli/index.ts:559` → `ocx:src/plugins/loader.ts:270–339`: POSIX에서 신뢰 경로와 파일 조건을 통과한 `.ts/.js/.mjs`에 `setup(context)`를 호출. `OCX_PLUGINS=0` 및 Windows autoload 차단. 실패된 setup의 hook 정리, shutdown 등록. `ocx:src/plugins/upstream-hooks.ts:38–64,118` / inference HTTP/WS hook 소비 `ocx:src/server/responses/fetch-helpers.ts:200–209`, `ocx:src/server/responses/ws-upstream.ts:160–198`. scheduler hook/API의 별도 조사는 보류했다. | n/a | OBSERVED | +| CAP-compatibility-lab | opt-in Lab과 fixture·live 증거 | — | `ocx:src/server/index.ts:860–868`에서 Bun.serve와 같은 동기 turn의 활성화, `ocx:src/lib/lab-activation.ts:75–95,167–192`에서 routing profile 또는 automation enabled를 읽고 passive/compatibility slot 등록. Core import 경계의 소스 오라클은 `ocx:tests/lab/core-lab-boundary.test.ts:1`이다. 관리 on-demand `ocx:src/server/management-api.ts:136,410`. `ocx:src/cli/lab.ts:564`의 conformance/live/task layer, fixture provider/suite `ocx:src/lab/conformance/fixture-provider.ts:3–23`, `ocx:src/lab/conformance/suite-manifest.ts:27`, 관측 증거 저장 `ocx:src/lab/observe/from-conformance.ts:137,278`. 정적 manifest는 fixture assertion과 Lab scenario 증거 종류를 구별한다 `ocx:src/compatibility/manifest.ts:11–16,154–158`. | n/a | OBSERVED | + +### (e) Management·공유·운영 + +| CAP tag | 기능 | Reference evidence | OpenCodex evidence · 진입 → 구현 → 게이트 | Status | Evidence | +| --- | --- | --- | --- | --- | --- | +| CAP-management-api | 관리 REST와 데이터 인증 분리 | — | `/api/` branch `ocx:src/server/index/serve-options.ts:681–755` → registry와 handler chain `ocx:src/server/management/route-registry.ts:98`, `ocx:src/server/management-api.ts:372–414` → admin token/GUI session `ocx:src/server/management-auth.ts:234–297,625–634`. 데이터 token과 non-loopback 필요 판정 `ocx:src/server/auth-cors.ts:383–446,755–800`. | n/a | OBSERVED | +| CAP-config-hot-reload | 관리 mutation과 특정 provider live reload | — | provider route `ocx:src/server/management/route-registry.ts:498`, `ocx:src/server/management/provider-routes.ts:942–1005`는 runtime에 귀속된 local capability로 디스크의 특정 provider를 검증·재채택한다. CLI login 알림은 지원 provider와 식별된 runtime에 한정 `ocx:src/oauth/login-cli.ts:69–101`. 일반 파일 감시 범위는 보류했다. | n/a | OBSERVED | +| CAP-catalog-discovery | data key의 read-only catalog/models와 hub 기능 | — | `ocx:src/server/index/serve-options.ts:761–930,1035`에서 catalog/usage/hub-state/model 조회에 data admission과 범위를 적용한다. Hub는 feature source를 광고 `ocx:src/remote/features.ts:50–88`. `GET /api/quota-pool`은 별도 관리 읽기 `ocx:src/server/management-api.ts:166–169` / `ocx:src/remote/features.ts:32`. | n/a | OBSERVED | +| CAP-dashboard | Dashboard 제공 및 UI 범위 | — | `ocx:src/server/index/serve-options.ts:1841–1927`의 미등록 데이터 경로 및 정적 UI 처리 → `ocx:gui/src/App.tsx:689–708` 등록 페이지. Models의 Combos/Routing/Compatibility 하위 탭은 `ocx:gui/src/pages/Models.tsx:2669,2689,2709`, Integrations의 API Keys와 Claude/Claude Desktop은 `ocx:gui/src/pages/Integrations.tsx:195–214`에 연결된다. 원격 화면에서 principal/대상에 따른 읽기·쓰기 조건을 둔다. | n/a | OBSERVED | +| CAP-usage-per-key | 여러 data key·사용량과 모델 범위 | — | `/api/keys` issue/list/rotation/update/revoke `ocx:src/server/management/oauth-account-routes.ts:1392–1558` → 공급자·모델 제한과 기본 비허용 metered combo grant `ocx:src/types/config.ts:336–362`, `ocx:src/server/admission-model-scope.ts:69–82,254` → configured key id에만 usage rollup `ocx:src/server/management/api-key-usage.ts:64–113,209`. 공급자 pool key와 다른 자격 종류다. | n/a | OBSERVED | +| CAP-tenant-billing | 조직·사용자·그룹·청구 | — | 확인한 범위는 운영자 관리 키, model scope, provider/model/account 비용 추정 `ocx:src/usage/summary.ts:205–270`, 설정 기반 send spend ledger `ocx:src/server/responses/request-spend.ts:89–113,269–294`. 이 기능 조합을 사용자별 로그인·그룹·잔액과 정산의 근거로 사용할 수 없다. 아래 검색 범위 참조. | unknown | OBSERVED-partial | +| CAP-observability | 요청 이력·사용량·비용 추정 및 메트릭 | — | `/api/logs`, `/api/usage`, device/source facets `ocx:src/server/management/logs-usage-routes.ts:128–175,200–247` / request log와 usage ledger 연결 `ocx:src/server/request-log.ts:517,634,684–748,1475,1626` / `ocx:src/usage/client.ts:2–22`의 client 분류와 app 집계 `ocx:src/usage/summary.ts:1604–1607,1763`. `/api/metrics` 관리 읽기는 `metricsExport.enabled === true` opt-in `ocx:src/config/feature-flags.ts:24–26`, `ocx:src/server/management/metrics-routes.ts:3–14`. | n/a | OBSERVED | +| CAP-telemetry | 집계 전송·notice와 사용자 opt-out | — | `/api/telemetry` GET/PUT와 profile `ocx:src/server/management/telemetry-routes.ts:7–33` → consent 판정 `ocx:src/telemetry/consent.ts:58–123`, 주기·UTC day `ocx:src/telemetry/scheduler.ts:43–50,137,321–343`. 환경 opt-out·decline은 off, 미결정은 notice 이전 off/이후 default-on. 요청별 로컬 usage 이력과 독립한다. | n/a | OBSERVED | +| CAP-request-privacy | outbound request 의미와 로컬 log redaction | — | Canonical ChatGPT forward의 `store: false` 및 replay 정리 `ocx:src/adapters/openai-responses/canonical-forward.ts:80–83,222–230`는 해당 wire의 조건이다. 기본 이메일 마스킹 `ocx:src/lib/privacy.ts:43–44`는 관리/CLI 투영, redaction `ocx:src/lib/redact.ts:413–463`과 요청 log `ocx:src/server/request-log.ts:1200–1202,1626`는 저장·표시 경계. Claude inbound debug는 별도 flag와 bounded capture `ocx:src/claude/inbound-debug.ts:87–103` / provider 데이터 보존 정책에 대한 보증 범위는 확인하지 않았다. | n/a | OBSERVED | +| CAP-remote-pairing | Remote Link 및 Hub 클라이언트 enrollment | — | `ocx connect`와 `ocx link` `ocx:src/cli/registry.ts:142–174` → `ocx:src/server/management/link-routes.ts:720–746,804–842`의 join/probe/host confirm/apply/issue/recover. SSH/link 리스너가 routing 연결을 소유 `ocx:src/server/index/link-listener.ts:119,169–177`. `ocx:src/remote/hub-management-relay.ts:23–67`의 method/path 허용과 enrollment proof, `ocx:src/config/feature-flags.ts:8–13`의 Link WS 이중 opt-in. | n/a | OBSERVED | +| CAP-remote-workspace | Hub runtime과 paired workspace executor | — | `/api/remote-workspace` status/pairing/device/session + peer agent ingress `ocx:src/server/management/remote-workspace-routes.ts:39–103`, `ocx:src/server/index/serve-options.ts:429–559`. hub 역할과 `OCX_REMOTE_WORKSPACE_ENABLED=1` 동시 필요 `ocx:src/remote-control/workspace-activation.ts:4–8` / mutation GUI session과 별도 agent token. hub session과 executor 경계 `ocx:src/remote-control/workspace-runtime.ts:18–30`, `ocx:src/remote-control/workspace-hub.ts:292,428`, `ocx:src/remote-control/workspace-executor.ts:88` / CLI runtime roster `ocx:src/cli/registry.ts:180–188`. | n/a | OBSERVED | +| CAP-deploy-docker | 컨테이너 배포 및 상태 볼륨 | — | `ocx:Dockerfile:75–107`의 런타임 이미지, 두 볼륨·10100 및 `ocx start` entry. HTTP `/healthz`와 정확한 GET `/readyz` `ocx:src/server/index/serve-options.ts:608–669` / 원격 bind 시 데이터 인증 검사 `ocx:src/server/auth-cors.ts:400–446`. | n/a | OBSERVED | +| CAP-deploy-service | launchd/systemd/Windows manager와 recovery | — | `ocx service` `ocx:src/cli/registry.ts:106–124` → `ocx:src/service/cli.ts:82–93,231,263–307,372`의 플랫폼별 install/repair/restart와 serving 신원 확인. 기본 off sentinel `ocx:src/config/feature-flags.ts:29–31`은 관리 서비스에서 `ocx:src/cli/index.ts:759` → `ocx:src/service/health-sentinel-launch.ts:55,99–134` / Desktop recovery 판독은 `ocx:src/service/desktop-recovery.ts:102–156`. | n/a | OBSERVED | +| CAP-update-recovery | package update의 owner-aware 복구 | — | `/api/update/{check,run,status}` `ocx:src/server/management/config-routes.ts:998–1053` → `ocx:src/update/job.ts:523–546,625`의 stale/pinned process 판단 → `ocx:src/update/job-supervised-restart.ts:43,102–112`에서 manager 우선과 supervised 결과를 보존한다. `ocx update`에는 plan/explicit apply와 Desktop 분기 등록 `ocx:src/cli/registry.ts:313–314`. | n/a | OBSERVED | + +## Known weak spots + +열려 있는 단위는 당시 시점의 계획·관측이다. 표의 상태는 기준 export에 있는 구현과 같은 요청에서 확인한 공개 기록으로 판단했다. + +| 열린 단위 | 계획에 남은 범위 | 기준에서 확인한 구현 상태 | +| --- | --- | --- | +| Google protocol CPA parity · `ocx:devlog/_plan/261115_google_protocol_cpa_parity/000_plan.md:12–28,76–85` | 예전 base에서 없던 Gemini ingress, Interactions, API fidelity. Live·native Interactions egress·background 실행은 계획에서 유보. | **기준에 구현 있음.** `3732baf029` (#8742), `e73546464e` (#8771)의 generateContent·countTokens·Interactions resource 등록과 Chat bridge 확인. Embedding 메서드는 501. `ocx:src/server/gemini-native-paths.ts:18–57`, `ocx:src/server/index/gemini-routes.ts:81–143`. 유보한 기능은 개별 검증 대기. | +| Realtime Live · `ocx:devlog/_plan/261006_realtime_live_compat/000_plan.md:3–10,21–28` | 외부에서 만든 call sideband join의 자격 증명과 연속성. public `/v1/live/sessions`는 계획 외. | **기준에 구현 있음.** `38455fb245` (#6678)의 미등록 call을 caller-owned auth로 우선 해석하는 분기 `ocx:src/server/live.ts:685–722,953–956`. OpenAI create/standalone/join은 `ocx:src/server/index/serve-options.ts:1612–1659`에 있다. 해당 app-server 빌드의 실제 수신·음성은 이번 lane에서 실행하지 않았다. | +| Grok media·quota parity · `ocx:devlog/_plan/261121_grok_media_quota_parity/000_plan.md:20–34` | Imagine 2.0/Video 1.5와 reset-credit DTO. 신규 Grok 음성/STT/TTS는 범위 외. | **주요 변경 출하 기록 있음.** v2.100.8의 #9013, image wire 기본값·quality 처리 소스 확인 `ocx:src/images/xai-client.ts:32,92–102`. 영상·reset DTO 세부항목과 실제 vendor 응답은 유보. | +| Translated reset retry · `ocx:devlog/_plan/261004_translated_reset_retry/000_plan.md:22–32` | 공통 ambiguous resend gate와 예산의 translated 경로 연결. | **공통 fence와 native 소비 확인, 전체 호출처 확인 대기.** `ocx:src/server/responses/reset-replay.ts:37,112–171,201–230`, `ocx:src/server/responses/passthrough-dispatch.ts:776–785`, `ocx:src/server/responses/adapter-dispatch.ts:342,663`. 계획 작성자가 기록한 테스트 결과는 이번 lane의 실행 증거에 포함하지 않았다. | +| Usage apps/log chips · `ocx:devlog/_plan/261107_usage_apps_logs/000_plan.md:7–18,25–30` | 현재 선택을 유지하면서 첫 진입 기본 all/all, app 통계, log client chip. | **기준에 구현 있음.** 기본값 `ocx:gui/src/pages/Usage.tsx:127–128`, 집계 `ocx:src/usage/summary.ts:1604–1607,1763`, chip `ocx:gui/src/pages/Logs.tsx:942`. | +| Automatic update parity · `ocx:devlog/_plan/261107_auto_update_parity/000_plan.md:3–12,70–78` | desktop/package/linked 설치를 포괄하는 사용자 제어 자동 활성화와 상태 안내. | **부분 구현.** Desktop 백그라운드 check와 명시적 install invoke `ocx:desktop/src-tauri/src/lib.rs:274–296,430–434`, package job `ocx:src/update/job.ts:625`, Link idle update policy `ocx:src/cli/registry.ts:167–172`. 범위를 모두 잇는 통일 자동화는 이 증거로 확정할 수 없다. | +| Windows health recovery · `ocx:devlog/_plan/261012_windows_health_recovery/000_roadmap.md:3–16,24–35` | 관리 프로세스가 listen 상태로 멈춘 경우 opt-in sentinel로 복구. 원래 production hang 재현은 문서에도 미확정. | **기준에 opt-in 구현 있음.** `ocx:src/config/feature-flags.ts:29–31`, `ocx:src/cli/index.ts:759`, `ocx:src/service/health-sentinel-launch.ts:99–134`. Windows live와 원래 hang 원인은 미검증. | +| Remote Link Child auth/Windows · `ocx:devlog/_plan/261121_fb2100_remote_link_auth/000_roadmap.md:3–12` | Windows probe·로컬 제어, Child의 로컬 status/relay 권한 경계. | **#8972·#8999·#8985는 기준 조상에 포함.** `a8f689f2c7` (#9018), Windows probe `ocx:src/link/remote-platform.ts:26,59`, Child relay/status `ocx:src/client/machine-listener.ts:134,338–357`, `ocx:gui/src/pages/RemoteLink.tsx:31,283`. #8998의 Windows AF_UNIX 실행은 별도 확인 대기. | + +## Gap candidates + +확정 gap 0건. 태그별 상대 구현의 entry·impl·gate는 L1–L7이 공급하고 009에서 결합한다. 다음 검색은 coordinator가 더 좁힐 표면을 고르는 데 사용할 수 있다. grep 결과와 가까운 동작을 같이 기록했으며 상태는 `unknown`이다. + +아래는 소스 스캔과 비교 후보의 연결이다. 명령은 아래의 `pattern` 값마다 실행했고 모두 `rg_exit=1`이었다. `--max-count 2`는 매치 출력량 제한이고 이 검색의 범위는 아래 세 소스 루트와 지정 파일 유형에 한정한다. + +```sh +pin=/Users/jun/Developer/new/700_projects/opencodex/.tmp/chase/opencodex-dev +rg -n -i --max-count 2 -g '!*.svg' -g '!*.json' "$pattern" "$pin/src" "$pin/gui/src" "$pin/desktop/src-tauri/src" +``` + +```text +L8-1 v1/(embeddings|rerank) +L8-2 magpie://|ccswitch://|register_deep_link|deep_link +L8-3 WebDAV|S3Config|github.gist +L8-4 CREATE TABLE( IF NOT EXISTS)? (users|groups|tenants|invoices)|stripe.checkout +L8-5 BidiGenerateContent|generativelanguage.*\.Live|v1/live/sessions +``` + +| 후보 ID · CAP tag | 가까운 기준 구현과 남은 계약 | 가치 · 예상 규모 | 구현 위치·의존·위험 | +| --- | --- | --- | --- | +| L8-1 · CAP-wire-embeddings-rerank | Gemini embed/batch embed 등록은 501 `ocx:src/server/gemini-native-paths.ts:18`, `ocx:src/server/index/gemini-routes.ts:86–95`. 호환 query/model, embedding API와 rerank의 각각 peer 증거 필요. | 중 · M, 신규 wire와 usage 처리 | ingress와 provider adapter, data-key 모델 범위와 body cap. `serve-options.ts` 기존 크기 한도 확인. | +| L8-2 · CAP-deeplink-import | Link join/issue `ocx:src/server/management/link-routes.ts:725,824`, 파일 기반 CC-Switch import `ocx:src/cli/provider-cc-switch-import.ts:57–99`. OS URL scheme에서 유입되는 공유 payload 계약은 별도 추적. | 중 · M, 플랫폼별 ingress와 preview | Desktop shell+import owner, preview·승인 연결, URI에 credential 넣지 않는 취급 규칙. | +| L8-3 · CAP-cloud-sync | `ocx:src/client/route-intent-apply.ts:110,273`의 enrollment 후 로컬 설정 반영. 별도 원격 blob store와 암호화 sync 계약을 peer에서 확인해야 한다. | 중 · L, 암호화·충돌과 여러 저장소 | `src/client`, `src/integrations`의 소유권, secret 보관과 네트워크 경로. | +| L8-4 · CAP-tenant-billing | 이름 있는 여러 데이터 키와 rollup `ocx:src/server/management/oauth-account-routes.ts:1392–1558`, `ocx:src/server/management/api-key-usage.ts:64–113`. 그룹·신원·잔액·정산은 별도 제품 계약. **Reject candidate** · 현 단위의 로컬 운영 및 작은 팀 범위에서 self-serve 상업 청구는 별도 제품 결정이 필요. | 낮음 · XL, 상태/계정/청구 운영 | Management/usage 영역. 권한 모델, 개인정보, 거래·회계 정합성 의존. | +| L8-5 · CAP-wire-gemini-live | Gemini generateContent 스트림 `ocx:src/server/index/gemini-routes.ts:113–143`, OpenAI realtime `ocx:src/server/live.ts:13–30`. Gemini Live와 OpenAI `/v1/live/sessions` 비교는 서로 다른 표면으로 확인해야 한다. | 낮음 · L, 별도 양방향 세션과 자격·미디어 | Gemini 경로와 realtime owner, WS admit·취소·로그 privacy. 기준 계획에서 Live는 유보. | + + +## OpenCodex-ahead items + +비교 판정 후보는 Codex Responses의 native/bridge/compact/replay와 opt-in mid-turn 제어, native login/desktop ownership 복원, Lab의 fixture와 live evidence 계약, 그리고 Remote Link와 Workspace의 독립 등록이다. 각 대응 태그의 비교 쪽 근거를 결합하기 전까지 ahead 판정은 0건이다. + +## 최신 사례 (Aside) + +아래 날짜는 공개 게시·병합 날짜(UTC), 조회일은 2026-11-23 KST다. `post-head`는 기준 OpenCodex revision 이후 사례다. 공개 릴리스나 이슈가 말하는 동작과 로컬 소스에서 확인한 범위를 각각 적었다. + +| 게시일 | 릴리스·커밋·PR | 공개 URL | 조회일 | 관측 내용 | 기준판과의 관계 | 신뢰도 | +| --- | --- | --- | --- | --- | --- | --- | +| 2026-11-21 | v2.100.8 · `9e0e298` · #9013 | [OpenCodex v2.100.8](https://github.com/lidge-jun/opencodex/releases/tag/v2.100.8) | 2026-11-23 | Imagine 2.0·Video 1.5와 quota/reset parity를 포함한 npm 릴리스 기록. | `f3a47c6759`가 기준 조상이며 이미지 기본값·quality gate가 `ocx:src/images/xai-client.ts:32,92–102`에 있다. | 높음 · 릴리스와 소스 | +| 2026-11-21 | #8993 · `8be812e247` | [OpenCodex PR #8993](https://github.com/lidge-jun/opencodex/pull/8993) | 2026-11-23 | 공급자 Accounts/API Keys 탭의 quota 읽기를 기본 15초 cadence로 추가. 일반 조회와 강제 refresh를 구분한다. | `ocx:gui/src/quota-live-refresh-pref.ts:36`, `ocx:gui/src/hooks/useProviderAccountPools.ts:1158`에서 구현 확인. | 높음 · 병합 PR과 소스 | +| 2026-11-23 | #9069 · open · post-head | [OpenCode keyless loopback 동작 보고](https://github.com/lidge-jun/opencodex/issues/9069) | 2026-11-23 | 보고자는 keyless loopback 설정에서 모델 목록은 보이지만 OpenCode의 첫 요청이 빈 키로 거절된다고 보고했다. | `ocx:src/clients/config-export.ts:738–760`에서 keyless 경로가 env reference를 출력하는 분기 확인. 해당 OpenCode 빌드의 실제 동작은 미실행. | 중간 · 사용자 보고와 분기 일치 | +| 2026-11-23 | #9074 · open · post-head | [Keyless 검색 backend 제안](https://github.com/lidge-jun/opencodex/issues/9074) | 2026-11-23 | OAuth 세션 또는 Exa 키가 필요 없는 opt-in 검색 backend 요청. | 기준의 등록과 backend 자격 조건은 `ocx:src/web-search/backends.ts:33–96`. 제안 기능을 기준 비교 상태에 반영하지 않았다. | 중간 · 기능 요청, 현재 roster 확인 | +| 2026-10-14 | #7090 · closed | [Codex App WS admission 보고](https://github.com/lidge-jun/opencodex/issues/7090) | 2026-11-23 | v2.83–2.84의 128 incoming WS에 idle 연결이 남아 새 세션이 503 이후 HTTP로 넘어갔다는 보고. | 기준은 기존 cap과 함께 압력 시 idle LRU 회수를 구현한다 `ocx:src/codex/websocket-registry.ts:6–45`. | 높음 · 이슈 내용과 기준 소스 확인, 라이브 미실행 | +| 2026-10-16 | #7258 · closed | [IPv6 loopback 비활성화의 startup 보고](https://github.com/lidge-jun/opencodex/issues/7258) | 2026-11-23 | v2.87.0에서 IPv6 loopback 비활성화 시 service startup의 cross-home probe가 불확정 상태를 냈다는 보고. | 기준 probe는 loopback family availability를 확인한다 `ocx:src/cli/cross-home-owner.ts:257–279`. 사용자의 IPv6 환경은 재현하지 않았다. | 높음 · 이슈 내용과 기준 소스 확인 | +| 2026-09-28 | #6196 · closed as not planned | [Codex App quota gate 보고](https://github.com/lidge-jun/opencodex/issues/6196) | 2026-11-23 | Mac 앱 로그인 계정 quota 소진 시 다른 공급자 모델을 선택해도 composer가 비활성화됐다는 보고. | 기준에 desktop compatibility/runtime 관리 route가 있다 `ocx:src/server/management-api.ts:399–403`. 해당 앱 빌드·계정에서 복구 여부는 미확인. | 중간 · 사용자 보고 | +| 2026-10-08 | #6740 · closed as not planned | [Windows pooled Codex 502 보고](https://github.com/lidge-jun/opencodex/issues/6740) | 2026-11-23 | v2.80.0 사용 중 upstream frame 도착 후 간헐적 502와 latency 증가. 보고 자체는 원인을 확정하지 않았다. | 기준의 정상적인 pre-output quota/transient 회복 후보 조건 `ocx:src/server/responses/core-codex-account.ts:430–495`와 terminal 후 분류/관측을 비교할 입력이다. | 중간 · 사용자 보고 | +| 2026-10-12 | Linux.do topic 3012827 | [OpenCodex·magpie·CPA+cc-switch 사용자 토론](https://linux.do/t/topic/3012827) | 2026-11-23 | 여러 도구를 조합한 구성과 magpie의 다계정 체감이 언급됐다. | 응답이 이미 전달됐는지, 같은 계정 및 환경인지 알 수 없다. 기준 OpenCodex에는 ambiguous resend guard가 있다 `ocx:src/server/responses/reset-replay.ts:112–171,201–230`. | 낮음 · 커뮤니티 경험 | +| 2026-11-22 | CLIProxyAPI v8.1.1 · `6eb8554` · post-head | [CLIProxyAPI v8.1.1](https://github.com/router-for-me/CLIProxyAPI/releases/tag/v8.1.1) | 2026-11-23 | Linux dynamic plugin 배포와 `PickAuth`가 decline 할 때 다음 scheduler plugin으로 진행하는 변경. | 핀의 scheduler에 해당 분기 존재 `cpa:internal/pluginhost/scheduler.go:11–45`. 기준 OpenCodex의 가까운 확장 seam은 HTTP/WS upstream rewrite다 `ocx:src/plugins/loader.ts:317–334`. | 높음 · 릴리스와 소스 | +| 2026-11-23 | cc-switch v4.0.40 · `f19a9d4` · #9321 · post-head | [cc-switch v4.0.40](https://github.com/farion1231/cc-switch/releases/tag/v4.0.40) | 2026-11-23 | Grok 공식 카드를 xAI OAuth 계정에 결속하고 native CLI 로그인과 stash를 바꾼다. | 핀의 private auth+stash mutation `ccs:src-tauri/src/services/provider/grok_direct.rs:368–377`. OpenCodex의 Grok route integration과 xAI OAuth login은 각각 `ocx:src/server/management/native-integration-routes.ts:1098`, `ocx:src/oauth/index.ts:310–317`. | 높음 · 릴리스와 파일 apply 분기 확인 | +| 2026-11-18 | sub2api v0.2.23 · `5af9afb` | [sub2api v0.2.23](https://github.com/Wei-Shaw/sub2api/releases/tag/v0.2.23) | 2026-11-23 | OpenAI 첫 출력 전 idle timeout에 1회 account failover를 적용하고 stream read에 따라 idle clock을 갱신하는 변경. | 핀에서 first-output timeout과 `SafeToFailoverAfterWrite`가 있다 `s2a:backend/internal/service/openai_first_output_timeout.go:278–287`. 기준 OpenCodex의 재시도 grant와 physical replay 조건은 별도로 비교할 항목이다. | 높음 · 릴리스와 분기 소스 | +| 2026-11-23 | magpie v0.1.4717 · `0599b94` · post-head | [magpie v0.1.4717](https://github.com/yetone/magpie-releases/releases/tag/v0.1.4717) | 2026-11-23 | 제3자 모델 quota 초과 시 reset까지 그 모델을 쉬게 하는 gateway 동작. | 핀에서 rest 판정 owner를 찾았다 `mgp:internal/gateway/routing.go:1541–1547`. 이 배포판의 모델 단위 pause 전체는 유보. OpenCodex 기준은 `ocx:src/providers/key-failover.ts:962–1041`, `ocx:src/oauth/generic-account-failover.ts:259–280`의 대상 구분과 비교할 수 있다. | 중간 · 릴리스와 소스 위치 확인 | + +Aside account `u0` / local, codemode `0.9.2`. 렌더링 batch 외부 응답은 `indeterminate`와 `partial=["no-marker"]`를 반환했다. 동일 출력의 per-page final 레코드에서 `contentVerified=true`인 본문·날짜와 닫힌 탭(`5/5`, `5/5`, `2/2`)을 확인했다. 최신 공개 이슈와 peer 릴리스 날짜 일부는 `browse.readText`의 GitHub 공개 API JSON(`complete=true`)으로 재확인했다. 이 조회는 기간 전체 이슈의 완전한 집계를 의미하지 않는다. + +## Deferred checks + +- 21개 outbound factory의 전체 옵션, 모델별 wire override·계약별 fixture assertion, 구독 및 regional Vertex 인증 variant를 runtime까지 따라가는 일. +- Responses native/translated의 모든 replay·compact·실패 hop 조합, Claude의 모든 tool schema·SSE error·count·thinking recovery 조합, Gemini Interactions의 TTL과 background 지원 경계. +- Hub/Child의 전체 trust·권한 및 config 파일 형식별 replay, remote workspace 런타임별 허용 도구와 executor 격리, native Desktop 플랫폼별 recovery·package signing. +- 전체 관리 verb와 위임 권한 조합, 별도 신원/조직 경계, probe 기반 쿼터의 vendor별 정확도, 과금·잔액·정산의 제품 범위. +- peer release의 개별 runtime trace, CAP 태그 상대측 증거와 합친 parity/partial/gap/ahead 판정. + +## NOT RUN + +- 빌드, 테스트, 서버, fixture 실행, WebSocket/live OAuth/실제 provider 호출, OS 서비스와 updater 동작 검증. +- Aside의 최근 open issue 목록 렌더링에서 요구한 최소 본문 조건은 미충족했다. 공개 GitHub 이슈 API 재조회로 위 두 건을 확보했다. 공개 브라우징의 계정 변경·외부 전송·다운로드·custom protocol 호출은 수행하지 않았다. diff --git a/devlog/_plan/261123_proxy_upstream_catchup/009_gap_matrix.md b/devlog/_plan/261123_proxy_upstream_catchup/009_gap_matrix.md new file mode 100644 index 00000000000..b0e6f786c3d --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/009_gap_matrix.md @@ -0,0 +1,166 @@ +# 009 — Gap matrix, 우선순위, 단계 배치, 비채택 목록 + +Unit `261123_proxy_upstream_catchup` · coordinator 종합 · 입력: 001–008 (레인 L1–L8, `gpt-6.2-sol` xhigh) + +## 판정 규칙 + +- 행 하나는 사용자 관점 능력 하나다. 레인 후보(`L-`)는 `CAP-` 태그로 묶었고, 같은 능력을 여러 프로젝트가 보여 주면 출처에 모두 적었다 (예: G-012는 CPA L2-1과 sub2api L4-04). +- 근거 열은 레인 문서의 후보 id다. 실제 `path:line` 인용은 해당 레인 문서의 인벤토리와 absence receipt에 있다. 인용 2,402개는 `.tmp/chase/` 고정 사본에 대해 전부 해석됐다 (`verify_citations.mjs`, unresolved 0). +- 008(L8)이 OpenCodex 쪽 증거의 기준이다. L8은 `rg` 패턴 5종(embeddings/rerank, deep link, WebDAV/S3, tenant/billing 테이블, Gemini Live)에 대해 고정 트리 `src gui/src desktop/src-tauri/src` 범위의 absence receipt를 남겼다 (008 Gap candidates). 각 행의 "없음" 주장은 해당 레인 문서의 receipt를 따른다. +- 가치는 대상 사용자 기준이다: Codex/Claude Code를 로컬 proxy로 쓰는 개인, 그리고 proxy 하나를 공유하는 소규모 팀. 노력은 레인 추정(S/M/L/XL)을 따르되 병합 행은 큰 쪽을 택했다. +- 단계 열: `0X0` = 채택하여 해당 단계 문서에 배치, `DEFER` = 수요·선행 조건 확인 뒤 재평가, `REJECT` = 제품 범위 밖, `CLOSED` = 고정 head의 OpenCodex에 이미 있어 gap이 아님 (감사에서 확인). + +## 우선순위 규칙 + +1. **클라이언트 마찰을 먼저 다룬다 (로드맵 판단).** magpie(별 40k, 2026-11-23)와 cc-switch는 설정 전환·이주를 전면에 둔다. 레인 003·007의 날짜가 붙은 보고와 Aside 10월 기록(Linux.do에서 503과 설정 마찰을 이유로 든 사례)은 설정·이주 마찰이 있다는 정성적 신호다. 이것이 이탈의 최상위 원인이라는 순위나 빈도를 보여 주지는 않는다. 010을 먼저 두는 것은 그 신호에 근거한 판단이다. +2. **런타임 신뢰성은 공유 인프라부터.** 계정 선택 snapshot·lease(040)가 cache affinity(050), 호출자 상한(070)의 선행 조건이다. +3. **OpenCodex가 앞선 계약은 건드리지 않는다.** fail-closed `refused-ambiguous` 재전송 게이트, Responses WS steer/inject, Kiro wire, Vertex 서비스 계정, xAI OAuth/Responses replay는 유지한다 (아래 "이전 기록 정합"). magpie의 투명 rotation(전송 오류 후 후보 교체)은 채택하지 않는다; 006 요약 3번이 두 동작 차이만으로 503/중복 과금 빈도를 판단할 수 없다고 기록했다. +4. **동의가 필요한 행동은 기본 off.** 계정 자격 증명 이동(G-004), 실제 CLI 세션 유지(G-021), masking(G-035), 알림 외부 전송(G-030)은 명시적 opt-in과 AGENTS_INSTALL.md의 consent 규칙을 따른다. + +## Gap matrix + +| ID | CAP | 갭 | 출처 | 근거 (lane 후보) | 가치 | 노력 | 단계 | +|---|---|---|---|---|---|---|---| +| G-001 | CAP-client-config-codex · CAP-client-config-claude · CAP-client-config-drift | Codex·Claude Code 앱별 현재 목적지(proxy/native/remote), 소유권, drift 사유, 복원 미리보기를 한 화면에서 보기 | CCS · MGP | 003 L3-1 · 007 L7-5 | high | M | 010 | +| G-002 | CAP-client-config-claude | 기존 first-party 토글(`gui/src/pages/ClaudeCode.tsx:293`, rollback `agent-settings-routes.ts:1760`)에 빠진 것: 적용 전 `settings.json` 변경 preview와 `CLAUDE_CONFIG_DIR`(home)별 상태 표시 | MGP · CCS | 007 L7-1 · 003 인벤토리 · audit r1 #1 | high | M | 010 | +| G-003 | CAP-import-local-discovery · CAP-import-cc-switch | 설치된 앱(CC Switch, Claude/Codex 설정 등)의 공급자 설정을 자동 발견하고 검토 후 가져오기 | MGP · CCS | 007 L7-3 | high | M | 020 | +| G-004 | CAP-import-account-batch | Codex·Claude 계정 자격 증명의 명시적 일괄 가져오기와 결과 receipt (현재 account-import는 소수 형식) | MGP | 007 L7-2 | high | L | 020 | +| G-005 | CAP-deeplink-import | OS 링크(`ocx://` 류)로 relay/공급자 preset을 열어 미리보기 후 적용 | MGP · CCS | 007 L7-4 · 003 L3-2 · 008 L8-2 | high | M | 020 | +| G-006 | CAP-endpoint-speed-test | 공급자 후보 URL의 응답 시간·상태·실패를 같은 조건에서 비교하는 측정 화면 | CCS | 003 L3-3 | high | M | 020 | +| G-007 | CAP-remote-proxy-share | Hub 초대를 링크로 열어 origin을 미리 본 뒤 기존 Hub pairing으로 잇고, 원격 카탈로그 준비 상태 표시 | MGP · CCS | 007 L7-6 · 003 L3-2(Home 연결 부분) | med | M | 020 | +| G-008 | CAP-client-config-gemini | Gemini CLI를 로컬/Home proxy에 연결하고 원복하는 enable/disable | CCS | 003 L3-4 | med | M | 030 | +| G-009 | CAP-client-config-zed | Zed custom provider export와 opt-in 연결 | MGP | 007 L7-7 | med | M | 030 | +| G-010 | CAP-mcp-client-sync | Codex/Claude Code의 선택된 MCP 항목 읽기·변경 미리보기·명시적 적용 | CCS | 003 L3-8 | med | L | 030 | +| G-011 | CAP-config-import-export · CAP-backup-local | 관리 항목을 고르는 로컬 백업 번들과 복원 미리보기 (credential 기본 제외) | CCS | 003 L3-6 | med | M | 030 | +| G-012 | CAP-credential-proxy | 같은 provider pool 안에서 credential/계정별 upstream proxy·noProxy를 로그인·refresh·실행에 일관 적용 | CPA · S2A | 002 L2-1 · 004 L4-04 | high | L | 040 | +| G-013 | CAP-cooldown-persistence | API key pool의 확인된 quota cooldown을 재시작·live recycle 후 복원 | CPA | 002 L2-2 | high | M | 040 | +| G-014 | CAP-account-concurrency | Codex·Claude OAuth 계정별 동시 실행 lease와 bounded wait (Kiro에만 존재하는 lease 원리 일반화) | S2A | 004 L4-01 | high | L | 040 | +| G-015 | CAP-credential-pool-weighted · CAP-load-aware-selection | 기존 operator priority tier(`codex/routing/selection.ts:249`, `auth-api/routes.ts:204`) 안에서 정적 weight와 실시간 in-flight 부하로 고르기 (priority·pin·quota 계약 유지, G-014 이후) | S2A · CPA | 004 L4-02 · 002 L2-5 | high | L | 040 | +| G-016 | CAP-credential-files | 계정별 모델 eligibility·refresh 결과를 보여주는 진단 DTO와 명시적 검증 UI | CPA | 002 L2-3 | med | M | 040 | +| G-017 | CAP-failover | 앱별 fallback 경로 순서와 현재 후보·제외 사유 가시성 | CCS | 003 L3-9 | med | M | 040 | +| G-018 | CAP-cache-affinity | 일반 combo에서 이미 따뜻한 세션 대상을 유지하는 선택형 cache affinity | MGP | 006 L6-1 | high | M | 050 | +| G-019 | CAP-antigravity-replay | Antigravity signed context 복원 심화: 이전 문맥·part 위치 대조, native call 복원, snapshot 조건부 갱신 | CPA | 001 L1-1 | high | L | 050 | +| G-020 | CAP-xai-reasoning-replay | client가 돌려주지 않은 완료 turn의 call/reasoning을 xAI 경로에서 보강 | CPA | 001 L1-2 | med | M | 050 | +| G-021 | CAP-claude-cli-session | 실제 Claude CLI의 계정별 장기 세션 reuse/resume (현재 매 턴 stateless) | MGP | 006 L6-5 | high | XL | 050 | +| G-022 | CAP-wire-multimodal-input | 첨부만 있는 turn, file-backed 첨부, PDF, 다중 tool-result modality의 거절/보존 일관화 | CPA | 001 L1-4 | high | M | 060 | +| G-023 | CAP-wire-gemini-interactions-upstream | Gemini Interactions의 공급자 네이티브 egress (현재 local ID 경로) | CPA | 001 L1-5 | med | L | 060 | +| G-024 | CAP-wire-xai-upstream-ws | xAI upstream WebSocket과 native continuation으로 history 재전송 감소 | CPA | 001 L1-3 | med | L | 060 | +| G-025 | CAP-caller-concurrency | 공유 proxy에서 **발급 키 단위** 동시 turn 상한 (opt-in). 여러 키를 한 사람으로 묶는 집계는 G-057로 보류 | S2A | 004 L4-03 | med | L | 070 | +| G-026 | CAP-usage-per-key · CAP-key-budget | 발급 키별 request/token 예산과 거절 이유 (USD ceiling은 가격 근거 확정 후) | S2A | 005 L5-1 | high | L | 070 | +| G-027 | CAP-key-expiry | 발급 키 만료 시각·상태와 진행 중 WS/rotation 경계 | S2A | 005 L5-2 | high | M | 070 | +| G-028 | CAP-admin-audit | 키 발급/스코프/폐기와 설정 변경의 구조화된 관리 감사 이벤트 | S2A | 005 L5-4 | med | M | 070 | +| G-029 | CAP-statusline | Claude Code statusline에 현재 세션의 실제 route와 quota snapshot 표시 (opt-in) | MGP | 006 L6-2 | high | M | 080 | +| G-030 | CAP-ops-alerts | 기존 metrics의 실패·지연·429 신호에 임계치와 최근 상태를 붙인 운영 알림 (기본 off) | S2A | 005 L5-3 | med | M | 080 | +| G-031 | CAP-usage-event-export | 외부 집계기가 cursor로 읽는 관리 전용 usage event export — 이미 있음: `/api/request-history`의 `nextCursor`(`request-history-routes.ts:90`), `/api/logs` 증분 cursor(`request-log-cursor.ts:67`, process epoch 기준) | CPA | 002 L2-6 · audit r1 #2 | med | M | CLOSED | +| G-032 | CAP-usage-native-sessions | proxy를 거치지 않은 Codex/Claude 네이티브 세션 사용량을 출처 표시와 함께 집계 | CCS | 003 L3-5 | med | L | 080 | +| G-033 | CAP-management-mcp | usage/health/key metadata만 노출하는 읽기 전용 관리 MCP | S2A | 005 L5-5 | low | L | 080 | +| G-034 | CAP-payload-overrides · CAP-middleware | 운영자가 지정하는 post-translation payload default/drop과 명시 활성 **요청** body filter seam (응답 hook은 G-059) | CPA · MGP | 002 L2-4 · 006 L6-3 | med | L | 090 | +| G-035 | CAP-request-masking | 기본 off 요청 masking: 명시 필드의 deterministic 규칙, 원문 미보관, 실패 시 무전송 | MGP | 006 L6-4 | high | L | 090 | +| G-036 | CAP-gemini-explicit-cache | Gemini 명시적 cache API와 생성 계정 고정 | S2A | 004 L4-05 | low | XL | DEFER | +| G-037 | CAP-wire-embeddings-rerank | embeddings/rerank typed endpoint (magpie 등록 `mgp:internal/gateway/gateway.go:1218`; OpenCodex Gemini embed는 별도로 501) | MGP | 008 L8-1 · 006 L6-8 | med | M | DEFER | +| G-038 | CAP-wire-gemini-live | Gemini Live 양방향 세션 — peer 구현 미확인 제품 후보 (CPA Gemini 등록 `cpa:internal/api/server_routes.go:148`에 Live 없음) | — (peer 미확인) | 008 L8-5 | low | L | DEFER | +| G-039 | CAP-provider-extension-abi | 버전 고정 provider-extension ABI (OpenCode/pi 플러그인 호환) | MGP | 006 L6-6 | med | XL | DEFER | +| G-040 | CAP-sync-webdav · CAP-sync-s3 | 운영자가 실행하는 WebDAV/S3 스냅샷 백업·복원 (G-011 형식 위) | CCS | 003 L3-7 · 008 L8-3 | med | L | DEFER | +| G-041 | CAP-ip-allowlist | 발급 키별 IP 제한 | S2A | 005 L5-6 | low | M | DEFER | +| G-042 | CAP-wire-xai-speech | 범용 xAI TTS endpoint | CPA | 001 L1-6 | low | M | REJECT | +| G-043 | CAP-wire-legacy-completions | legacy `/v1/completions` facade | CPA | 001 L1-7 | low | S | REJECT | +| G-044 | CAP-wire-claude-cch | Claude CCH 재서명 | CPA | 001 L1-8 | low | M | REJECT | +| G-045 | CAP-oauth-siwc | Codex credential의 secondary SIWC bind/renew | CPA | 002 L2-7 | low | L | REJECT | +| G-046 | CAP-control-plane · CAP-credential-store-backends | Home control plane과 다중 backend credential/config mirror | CPA | 002 L2-8 | low | XL | REJECT | +| G-047 | CAP-plugin-host · CAP-plugin-distribution | native ABI plugin host, 원격 artifact 배포, marketplace 자동 업데이트 | CPA · MGP | 002 L2-9 · 006 L6-7 | low | XL | REJECT | +| G-048 | CAP-client-fingerprint | TLS fingerprint·client identity 위장 profile | S2A | 004 L4-R1 | low | L | REJECT | +| G-049 | CAP-tenant-billing | 셀프 가입/RBAC, 그룹 상품·구독, 잔액·결제·환불·리딤·promo | S2A | 005 L5-7 · 008 L8-4 | low | XL | REJECT | +| G-050 | CAP-platform-ops | 공지 포털, 운영 UI 전면 복제, 프롬프트 원문 감사, Postgres/Redis 의무화, DB setup wizard | S2A | 005 L5-8 | low | XL | REJECT | +| G-051 | CAP-wire-vendor-generic | 임의 vendor-native path 일괄 passthrough | MGP | 006 L6-8 | low | L | REJECT | +| G-052 | CAP-library-mcp · CAP-library-skills · CAP-prompt-profiles | MCP/skills Library, skills marketplace, 전역 지침 profile 전환 관리자 | MGP · CCS | 007 L7-9 · 003 L3-11 | low | XL | REJECT | +| G-053 | CAP-surface-tui | 대화형 별도 TUI | MGP | 007 L7-10 | low | L | REJECT | +| G-054 | CAP-client-config-roster | 지원 agent 수 맞추기 (60+ roster) | MGP | 007 L7-11 | low | XL | REJECT | +| G-055 | CAP-session-manager | 범용 세션 index·본문 검색·삭제·재실행 | CCS | 003 L3-10 | low | XL | REJECT | +| G-056 | CAP-client-plugin-management | 모든 클라이언트의 플러그인/마켓 설치·업데이트 관리 | CCS | 003 L3-12 | low | XL | REJECT | +| G-057 | CAP-caller-owner-aggregation | 운영자가 관리하는 owner 매핑으로 여러 발급 키를 한 사용자 slot으로 묶기 (sub2api user slot `s2a:backend/internal/handler/openai_gateway_handler.go:614`) | S2A | 004 L4-03 · audit r1 #3 | med | M | DEFER | +| G-058 | CAP-config-sync-encrypted | 양방향 클라우드 설정·sign-in 동기화 | MGP | 007 L7-8 · audit r1 #6 | low | XL | REJECT | +| G-060 | CAP-deeplink-home-link | SSH Link(Home/Child) 초대 링크 — alias·confirmed host 기반 enrollment(`ocx:src/server/management/link-routes.ts:165`)를 링크로 여는 진입점 | CCS | 003 L3-2 · audit r3 #4 | low | M | DEFER | +| G-059 | CAP-middleware-response | 응답 측 hook (SSE/WS framing 보존 계약 포함) | MGP | 006 L6-3 · audit r1 #9 | med | L | DEFER | + +집계: 전체 60건 · 채택 34건 (단계 010–090) · 보류 9건 · 비채택 16건 · 이미 있음(CLOSED) 1건. + +## 단계 배치와 의존 관계 + +| 단계 | 주제 | 갭 | 선행 단계 | 배치 이유 | +|---|---|---|---|---| +| [010](010_client_connection.md) | 클라이언트 연결 상태와 Claude 기본 실행 preview | G-001, G-002 | — | 설정·이주 마찰 신호(정성적)에 대응하는 첫 단계. 020·030이 이 화면과 journal 계약을 쓴다. | +| [020](020_migration_onboarding.md) | 이주·온보딩: 발견, 일괄 가져오기, 딥링크, 속도 측정, 팀 접속 | G-003 … G-007 | 010 | 가져온 설정은 010의 연결 화면에서 적용·확인된다. | +| [030](030_client_coverage.md) | 클라이언트 범위와 설정 이식성: Gemini CLI, Zed, MCP 동기화, 로컬 백업 | G-008 … G-011 | 010 | 010의 writer/journal/restore 계약을 재사용한다. | +| [040](040_pool_scheduling_egress.md) | 계정 풀 스케줄링과 egress: 계정별 proxy, cooldown 보존, 동시 실행 lease, 가중·부하 선택, 진단, failover 가시성 | G-012 … G-017 | — | 050·070이 쓰는 계정 선택 snapshot과 lease를 만든다. | +| [050](050_session_cache_continuity.md) | 세션 연속성과 캐시: combo cache affinity, Antigravity/xAI replay, Claude CLI 세션 reuse | G-018 … G-021 | 040 | affinity는 040의 선택 snapshot·lease 위에서만 안전하다. | +| [060](060_wire_fidelity.md) | wire 충실도: 첨부 전용 turn, Gemini Interactions egress, xAI upstream WS | G-022 … G-024 | 040 | G-024의 xAI upstream WS는 040의 계정별 egress(G-012)·강제 HTTP·pacing 정책을 따라야 한다. G-022·G-023은 040 없이 시작해도 된다. | +| [070](070_shared_proxy_governance.md) | 공유 프록시 거버넌스: 발급 키 단위 동시 상한, 키 예산, 키 만료, 관리 감사 | G-025 … G-028 | 040 | 040은 lease 구현(용량 계산)만 제공한다. 호출자 신원은 발급 키이며 키 간 집계는 G-057로 보류. | +| [080](080_observability.md) | 관측성: Claude Code statusline, 운영 알림, 네이티브 세션 사용량, 읽기 전용 관리 MCP | G-029, G-030, G-032, G-033 | 070 | statusline·MCP의 키 범위와 actor는 070의 키 수명·감사 계약이 정한다. | +| [090](090_request_policy.md) | 요청 정책: payload override/미들웨어 seam, 요청 masking | G-034, G-035 | 060, 070 | 변환 후 hook 위치는 060 이후 확정되고 키별 정책은 070의 키 모델을 쓴다. | + +```mermaid +flowchart LR + P010[010 연결 상태] --> P020[020 이주·온보딩] + P010 --> P030[030 클라이언트 범위] + P040[040 계정 풀·egress] --> P050[050 세션·캐시] + P040 --> P070[070 공유 거버넌스] + P070 --> P080[080 관측성] + P040 --> P060[060 wire 충실도] + P060 --> P090[090 요청 정책] + P070 --> P090 +``` + +클라이언트 트랙(010→020/030)과 런타임 트랙(040→050/060/070)은 서로 독립이므로 두 구현 단위로 병렬 진행할 수 있다. 같은 트랙 안에서는 번호 순서를 지킨다. + +## 보류(DEFER), 비채택(REJECT), 이미 있음(CLOSED) 근거 + +| ID | 판정 | 근거 | +|---|---|---| +| G-036 | DEFER | Gemini cache 리소스는 TTL·소유권·유료 side effect를 함께 복제해야 하고(004 L4-05), Gemini SDK 직접 사용자 수요가 확인되지 않았다. 060 이후 수요가 생기면 재평가. | +| G-037 | DEFER | Gemini embed는 등록돼 있지만 501을 반환한다(008 L8-1). 코딩 turn에서 사용 사례가 확인되지 않았다(006 L6-8). 요청이 들어오면 typed endpoint부터 산정. | +| G-038 | DEFER | peer 구현이 고정 head에서 확인되지 않은 제품 후보다(CPA Gemini 등록에 Live 없음, 008 L8-5 `unknown`). 기존 계획도 Live를 유보했다. peer trace가 생기면 재평가. | +| G-039 | DEFER | provider host는 lifecycle/RPC/auth ownership/실패 격리가 모두 필요한 XL이다(006 L6-6). 090의 seam이 자리 잡은 뒤 최소 manifest부터 검토. | +| G-040 | DEFER | 운영자가 실행하는 스냅샷 업로드·복원만 남겼다(003 L3-7, L). 030의 G-011 백업 형식이 먼저다. 양방향 sync는 G-058로 분리. | +| G-031 | CLOSED | `/api/request-history`가 영속 usage 행과 `nextCursor`를 주고 `/api/logs`는 reset 신호가 있는 증분 cursor를 준다(감사 r1 #2). 남는 것은 재시작을 넘는 forward checkpoint 보장뿐이며, 외부 집계 수요가 생기면 그 보장만 새 행으로 연다. | +| G-041 | DEFER | reverse proxy·tunnel별 주소 신뢰가 먼저 정리돼야 하고, 키 범위·만료(070)가 더 큰 효과를 낸다(005 L5-6). | +| G-057 | DEFER | 070은 발급 키 단위 상한으로 시작한다. OpenCodex admission 주체는 secret에서 파생된 키 단위다(`ocx:src/server/auth-cors.ts:483`). 여러 키를 한 사람으로 묶으려면 운영자 owner 매핑이 먼저 필요하다(감사 r1 #3). | +| G-060 | DEFER | SSH Link enrollment는 SSH alias와 확인된 host가 필요해 URL 하나로 안전하게 넘기기 어렵다. 팀 접속은 Hub pairing(G-007)으로 먼저 해결한다(감사 r3 #4). | +| G-059 | DEFER | 응답 hook은 SSE tool/reasoning/terminal frame과 WS framing 보존 계약이 따로 필요하다(006 L6-3, 감사 r1 #9). 090의 요청 seam이 자리 잡은 뒤 평가. | +| G-042 | REJECT | 음성 생성 지출이 따르고 코딩 proxy 주 경로의 이득이 낮다(001 L1-6). | +| G-043 | REJECT | 대상 클라이언트에서 연결 가치를 확인하지 못했다(001 L1-7). | +| G-044 | REJECT | native passthrough와 routed Messages의 역할이 이미 구분되며, 재서명은 client provenance·공급자 계약 문제를 만든다(001 L1-8). | +| G-045 | REJECT | 필요로 하는 사용자군을 확인하지 못했고 별도 consent·토큰 수명주기가 든다(002 L2-7). | +| G-046 | REJECT | HA control plane과 외부 credential 저장은 로컬 proxy·소규모 공유와 다른 제품이다(002 L2-8). | +| G-047 | REJECT | Bun 기본 경로에 배포·심사·rollback 부담을 더한다. 임의 코드 자동 업데이트는 provenance를 잃는다(002 L2-9, 006 L6-7). | +| G-048 | REJECT | 외부 서비스가 관찰하는 client identity를 합성하는 기능은 호환성 목표 밖이다(004 L4-R1). | +| G-049 | REJECT | 상거래·테넌트 운영은 단일 사용자 로컬 proxy 범위 밖이다. 팀 비용 통제는 G-026으로 다룬다(005 L5-7, 008 L8-4). | +| G-050 | REJECT | 인프라·마이그레이션 부담이 크고 기존 UI/metrics/Docker로 시작할 수 있다(005 L5-8). | +| G-051 | REJECT | 임의 vendor path는 모델·계정 예산과 동등한 정책 검증이 따로 필요하다(006 L6-8). | +| G-052 | REJECT | 외부 도구 실행과 skill 출처 승인이 필요한 별도 제품 영역이다. 선택적 MCP 적용은 G-010으로 좁혔다(007 L7-9, 003 L3-11). | +| G-053 | REJECT | CLI+GUI가 같은 흐름을 제공하며 두 번째 UI 유지 비용이 크다(007 L7-10). | +| G-054 | REJECT | 등록 수 경쟁은 오탐 쓰기 위험을 늘린다. 근거 있는 adapter(G-008, G-009)부터 추가한다(007 L7-11). | +| G-055 | REJECT | 원문 보관·파기 권한이 필요하다. 사용량 메타데이터는 G-032로 좁혔다(003 L3-10). | +| G-058 | REJECT | 양방향 설정·sign-in 동기화는 암호화 키·충돌·credential 병합 제품이다(007 L7-8). 스냅샷 백업(G-040)과 분리했다(감사 r1 #6). | +| G-056 | REJECT | 외부 marketplace 접근과 새 실행 권한을 도입한다(003 L3-12). | + +## 이전 기록 정합 (`devlog/_chase/20_cli-proxy-api.md`, 2026-06-29 `00114be`) + +| 이전 항목 | 이번 판정 | 근거 | +|---|---|---| +| Antigravity replay 깊이 (CPA 667줄 vs ocx 136줄) | 범위 축소: OpenCodex에 세션별 다중 서명·재시작 snapshot·오류 시 제거가 생겼다. 남은 차이는 문맥·part 위치 대조, native call 복원, snapshot 조건부 갱신 → G-019 | 001 요약 2번, L1-1 | +| vertex OAuth 없음 | **닫힘.** Vertex JSON 등록, OS credential store, JWT 교환, bearer 전송 구현 | 002 요약 1번 | +| xai forward-only / replay·WS 미확인 | **부분 닫힘.** Grok Responses 선택과 replay 정규화 존재. 남은 차이는 세션 보강(G-020)과 upstream WS(G-024) | 001 요약 3번, 002 요약 2번 | +| Responses WS→SSE | 양쪽 보유, OpenCodex는 steer/inject까지 | 001 요약 1번, 006 요약 2번 | +| kiro | OpenCodex 선행 유지 | 001 요약 7번 | + +## 증거 한계 + +- 레인 문서 001–008은 모두 `최신 사례 (Aside)` 행을 갖는다 (행 수 5–13). 웹 보고는 고정 head 이후 것이면 확정 상태를 바꾸지 않았다. +- 가치·노력은 레인 추정이며 사용자 조사나 계측 데이터로 검증하지 않았다. +- 보안 관련 메모는 레인별로 없음(전원 "Scratch note: no"). + +## NOT RUN + +- 어떤 프로젝트도 빌드·실행하지 않았다. 모든 비교는 소스 읽기와 Aside 공개 페이지 열람이다. +- 갭별 실제 사용자 영향(예: 503 빈도, 캐시 미스율)은 측정하지 않았다. +- OpenCodex 테스트 스위트, `bun run typecheck`, `structure:check`는 이 문서 단위에서 실행하지 않았다(코드 변경 없음). diff --git a/devlog/_plan/261123_proxy_upstream_catchup/010_client_connection.md b/devlog/_plan/261123_proxy_upstream_catchup/010_client_connection.md new file mode 100644 index 00000000000..70ba5b2d387 --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/010_client_connection.md @@ -0,0 +1,115 @@ +# 010 — 클라이언트 연결 상태와 Claude 기본 실행 preview + +**Gaps:** G-001, G-002 +**Depends on:** none +**Size:** M + +> 줄 번호와 줄 수는 OpenCodex `origin/dev` `9e0e298ef9` 기준이며, 줄 수는 ratchet의 `countLines`(`ocx:scripts/file-size-ratchet.ts:109`)로 센 값이다. 구현 단위를 열 때 현재 `dev`에서 다시 확인한다. + +## Goal + +Desktop/GUI의 한 화면에서 Codex와 Claude Code가 지금 어디로 가는지(OpenCodex proxy, native 로그인, Remote Link Home), 누가 설정을 소유하는지, 원하는 상태와 실제 파일이 왜 다른지, 되돌리면 어떤 키가 어떻게 바뀌는지를 본다. Claude Code의 기존 first-party 토글은 켜기 전에 `settings.json`에서 바뀔 키를 미리 보여 주고, 사용자가 명시적으로 등록한 Claude home마다 상태를 보여 준다. + +## Why + +- **G-001** — cc-switch는 앱별 카드에서 직접/라우팅 전환과 현재 상태를 보여 주고(`003` L3-1, `ccs:src-tauri/src/services/provider/mod.rs:7720–7804`), magpie는 `/api/drift`와 Keep/Reapply로 drift를 다룬다(`007` L7-5, `mgp:internal/gui/api.go:1438,1574`). OpenCodex에는 desired state, inject, restore 계약이 이미 있다(`ocx:src/codex/desired-state.ts:63`, `ocx:src/codex/inject/restore.ts:269`, `ocx:src/server/management/integration-routes.ts:830`). 빠진 것은 "왜 다른지"를 한곳에서 읽는 projection이다. +- **G-002** — magpie는 일반 실행에 효력이 있는 `settings.json` env/model을 편집한다(`mgp:internal/agent/claude.go:710,762`, `007` L7-1). OpenCodex에도 first-party 토글이 이미 있다: GUI `toggleFirstParty`(`ocx:gui/src/pages/ClaudeCode.tsx:293`), reconciler(`ocx:src/claude/first-party-settings.ts:46`), rollback 캡처(`ocx:src/server/management/agent-settings-routes.ts:1760`). 빠진 것은 적용 전 preview와 home별 상태다 (감사 r1 #1). + +## Changes + +| 경로 | 의도 | 내용 | +|---|---|---| +| `src/server/management/connection-status-routes.ts` | NEW | `GET /api/connections` 읽기 전용 projection | +| `src/codex/connection-projection.ts` | NEW | `desired-state.ts`·`inject/restore.ts` 판정을 drift 사유 코드로 변환. 쓰기 없음 | +| `src/claude/connection-projection.ts` | NEW | first-party settings, intercept, desktop binding 상태를 home별로 변환 | +| `src/claude/first-party-preview.ts` | NEW | `reconcileClaudeFirstPartySettings`와 같은 입력으로 dry-run해 바뀔 키와 변경 종류만 계산 | +| `src/server/management/agent-settings-routes.ts` | MODIFY | 1925줄. `PUT /api/claude-code` 처리부(`ocx:src/server/management/agent-settings-routes.ts:1760`) 옆에 preview 위임 한 줄. apply·rollback은 그대로 | +| `src/server/management/route-registry.ts` | MODIFY | `/api/claude-code` 항목(`ocx:src/server/management/route-registry.ts:149`) 옆에 `GET /api/claude-code/first-party/preview`, `GET /api/connections` 등록 (`mutates: false`) | +| `gui/src/pages/ClaudeCode.tsx` | MODIFY | `toggleFirstParty`(`ocx:gui/src/pages/ClaudeCode.tsx:293`) 앞에 preview 확인 단계와 home별 상태 배지 | +| `src/server/management/native-integration-routes.ts` | MODIFY | 1142줄. `handleCodexToggle`(`ocx:src/server/management/native-integration-routes.ts:404`) 결과 envelope에 projection 링크만 추가. 새 로직 없음 | +| `src/claude/auth-detect.ts` | MODIFY | `claudeConfigDir`(`ocx:src/claude/auth-detect.ts:99`)는 그대로 두고, 등록된 추가 home 목록을 읽는 helper를 옆에 둔다 | +| `gui/src/pages/integrations/ConnectionsPanel.tsx` | NEW | 클라이언트별 카드, drift 사유, 되돌리기 변경 종류 | +| `gui/src/i18n/*.ts` | MODIFY | 새 문구, 10개 locale 모두 (ratchet exempt) | + +Home 선택 규칙 (감사 r2 #5): 기본 home은 현재 프로세스 환경의 `claudeConfigDir(env)`이다. 추가 home은 사용자가 설정 `claudeCode.extraConfigDirs`(새 config leaf)에 명시적으로 등록한 경로만 쓴다. OpenCodex가 디스크를 탐색해 home을 찾지 않는다. preview는 기존 토글이 실제로 쓰는 home, 즉 기본 home에 묶인다. + +스케치: + +```ts +type ConnectionView = { + client: "codex" | "claude-code" | "claude-desktop"; + home?: string; // claude만: 등록된 config dir 경로 + desired: "proxy" | "native" | "remote-home" | "unset"; + observed: "proxy" | "native" | "remote-home" | "foreign" | "missing"; + owner: "opencodex" | "external" | "hub" | "none"; + driftReasons: Array<"external_owner" | "account_mode" | "quota_block" | "file_edited" | "pending_restart">; + restorePreview?: Array<{ file: string; key: string; change: "add" | "update" | "remove" }>; // 값은 담지 않음 +}; +``` + +### Before / After + +`ocx:gui/src/pages/ClaudeCode.tsx:293` — 지금은 토글이 바로 PUT한다. + +```ts +// before +const toggleFirstParty = async () => { + if (!state || firstPartyInFlight.current) return; + firstPartyInFlight.current = true; + setFirstPartyPending(true); + setStatus(""); + const requested = !state.cliFirstParty; + try { + const response = await fetch(`${apiBase}/api/claude-code`, { method: "PUT", /* … */ }); +``` + +```ts +// after (sketch) +const toggleFirstParty = async () => { + if (!state || firstPartyInFlight.current) return; + firstPartyInFlight.current = true; // preview 전에 잠가 중복 클릭을 막는다 + setFirstPartyPending(true); + setStatus(""); + const requested = !state.cliFirstParty; + try { + if (requested) { + const preview = await fetchJson(`${apiBase}/api/claude-code/first-party/preview`); // 쓰기 없음 + if (!(await confirmChanges(preview.changes))) return; // {file, key, change}만 표시. 취소해도 finally가 해제 + } + const response = await fetch(`${apiBase}/api/claude-code`, { method: "PUT", /* 기존 그대로 */ }); + /* … */ + } finally { // 기존 finally(ClaudeCode.tsx:330): 잠금·pending 해제 + firstPartyInFlight.current = false; + setFirstPartyPending(false); + } +``` + +## Dependencies + +없음. 020(가져온 설정의 적용 결과)과 030(writer/journal 재사용)이 이 단계를 쓴다. + +## Acceptance + +- Codex native 토글이 외부 소유 때문에 거절된 상태에서 Connections 화면이 `external_owner` 사유와 소유 파일 경로를 보여 준다. +- Claude first-party 토글을 켜기 전에 바뀔 `settings.json` 키와 변경 종류(add/update/remove)가 보이고 값은 보이지 않는다. preview 호출 전후로 파일 바이트가 같다. +- preview 요청이 네트워크·서버 오류로 실패하면 토글 잠금과 pending 상태가 풀리고 오류 문구가 보이며, PUT은 호출되지 않는다. +- `claudeCode.extraConfigDirs`에 두 번째 home을 등록하면 각 home의 상태가 따로 보인다. 등록하지 않은 경로는 나타나지 않는다. +- 적용·rollback 결과는 기존 테스트 그대로 통과한다. + +## Verification + +- 신규 `tests/server/connection-status-routes.test.ts`, `tests/claude-integration/claude-first-party-preview.test.ts` (`scripts/test-layout/layout.json`과 `tests/fixtures/test-layout-expected*.json` shard 등록) +- 기존 회귀: `tests/codex-integration/codex-inject-*.test.ts`, `tests/claude-integration/`의 first-party settings 테스트 +- `bun run typecheck`, `bun run test:changed`, `bun run structure:check`, `bun run lint:gui`; GUI 변경이라 PR에 스크린샷 + +## Risks + +- **File-size ratchet:** 캡에 없는 파일은 2000줄 이상이면 실패하고(`NEW_OVERSIZED`), 캡 파일은 캡을 넘으면 실패한다(`tests/fixtures/file-size-baseline.json`). `agent-settings-routes.ts`는 1925줄로 여유 74줄이다. 로직은 sibling 파일에 둔다. +- **Lab 경계:** `tests/lab/core-lab-boundary.test.ts`의 보호 목록(`ocx:tests/lab/core-lab-boundary.test.ts:23`: `src/router.ts`, `src/server/lifecycle.ts`, `src/server/responses/core.ts`, `src/server/management-api.ts`)에서 `src/lab/`으로 가는 import가 직접이든 간접이든 생기면 안 된다. `route-registry.ts`는 `management-api.ts`가 읽으므로 새 route 모듈은 namespace별 지연 로드 규칙을 따른다. +- **Privacy:** projection과 preview는 경로·키 이름·변경 종류만 돌려준다. 값, email, 토큰은 없다. +- **중복 구현 금지:** first-party apply/rollback을 새로 만들지 않는다. + +## Non-goals + +- magpie식 자동 provider 전환. +- 다른 클라이언트(Gemini CLI, Zed)는 030. 계정 자격 증명 이동은 020(G-004). diff --git a/devlog/_plan/261123_proxy_upstream_catchup/020_migration_onboarding.md b/devlog/_plan/261123_proxy_upstream_catchup/020_migration_onboarding.md new file mode 100644 index 00000000000..70a7b8403a9 --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/020_migration_onboarding.md @@ -0,0 +1,112 @@ +# 020 — 이주·온보딩: 발견, 일괄 가져오기, 링크, 속도 측정, 팀 접속 + +**Gaps:** G-003, G-004, G-005, G-006, G-007 +**Depends on:** 010 +**Size:** L + +> 줄 번호와 줄 수는 OpenCodex `origin/dev` `9e0e298ef9` 기준이며, 줄 수는 ratchet의 `countLines`(`ocx:scripts/file-size-ratchet.ts:109`)로 센 값이다. 구현 단위를 열 때 현재 `dev`에서 다시 확인한다. + +## Goal + +다른 도구에서 넘어오는 사용자가 키를 다시 입력하지 않고 기존 공급자 설정을 발견·검토·가져오고, Codex/Claude 계정 파일을 일괄 가져온다. 공유받은 링크로 공급자 preset이나 Hub 접속을 미리 보고 확인한 뒤에만 기존 흐름을 시작한다. 공급자 후보 URL의 응답 시간을 같은 조건에서 비교한다. + +## Why + +- **G-003** — magpie는 Providers 화면에서 CC Switch·Claude Code·Codex 설정 후보를 발견한다(`mgp:internal/gui/importapps.go:30,48,70`). OpenCodex는 파일을 명시하는 CLI만 있다(`ocx:src/cli/provider-cc-switch-import.ts:81`, `ocx:src/providers/cc-switch-import.ts:747`) (`007` L7-3). +- **G-004** — magpie `ImportLogins`는 Sub2API·CPA·CodexBar·claude-swap 형식을 해석한다(`mgp:internal/provider/login_import.go:101,129,182`). OpenCodex registry는 Antigravity 형식만 받는다(`ocx:src/oauth/account-import/registry.ts:12`) (`007` L7-2). +- **G-005** — magpie(`mgp:build/darwin/Info.plist:21`, `mgp:internal/gui/importlink.go:30`)와 cc-switch(`ccs:src-tauri/src/deeplink/parser.rs:15–74`)는 OS 링크로 preset을 연다. OpenCodex에는 OS scheme 등록이 없다 (`008` L8-2 absence receipt). +- **G-006** — cc-switch `test_api_endpoints`는 URL 배열을 warm-up 후 병렬 timed GET으로 비교한다(`ccs:src-tauri/src/services/speedtest.rs:26–122`). OpenCodex probe는 단일 공급자 연결/모델 호출이다 (`003` L3-3). +- **G-007** — magpie는 LAN 키·원격 모델·접속 안내를 한 흐름에 둔다(`mgp:internal/gui/join.go:16`). OpenCodex Hub 초대는 `ocx connect --management-url … --pairing-code-stdin` 명령을 만든다(`ocx:src/cli/hub.ts:236`). G-007은 Hub pairing 링크와 원격 카탈로그 준비 표시로 좁혔다. cc-switch L3-2의 SSH Link(Home/Child) 부분은 alias·confirmed host가 필요한 다른 흐름이라(`ocx:src/server/management/link-routes.ts:165`) G-060으로 보류했다 (감사 r3 #4). + +## Changes + +| 경로 | 의도 | 내용 | +|---|---|---| +| `src/providers/import-discovery/` | NEW | source adapter `{id, detect(), readKeyless(), fingerprint}`. 1차: cc-switch(기존 importer 재사용), Claude Code settings, Codex config.toml | +| `src/server/management/provider-import-routes.ts` | NEW | `GET /api/provider-import/candidates`(metadata만), `POST …/preview`, `POST …/apply` | +| `src/server/management/provider-routes.ts` | MODIFY 금지 | 1989줄, 여유 10줄. 새 route는 위 sibling에만 둔다 (`ocx:src/server/management/provider-routes.ts:1133`의 저장 경로를 호출만 함) | +| `src/oauth/account-import/types.ts` | MODIFY | `AccountImportAdapter`(`ocx:src/oauth/account-import/types.ts:89`)는 provider가 Antigravity 리터럴이고 Cockpit 레코드만 받는다. provider·format을 union으로 넓히고 adapter가 `parseDocument(raw)`를 직접 갖게 한다 | +| `src/oauth/account-import/service.ts` | MODIFY | 서비스가 항상 Cockpit 문서를 파싱하는 단계(`ocx:src/oauth/account-import/service.ts:36`)를 adapter의 `parseDocument` 호출로 바꾼다. provider/format 판정이 파싱보다 먼저인 순서는 유지 | +| `src/oauth/account-import/registry.ts` | MODIFY | 등록 표(`ocx:src/oauth/account-import/registry.ts:12`)를 `Map`으로 바꾸고 `codex-auth-json`, `claude-credentials` adapter 등록. 결과 receipt `{imported, skipped:{reason}, duplicates}` | +| `src/oauth/account-import/codex-auth-json-adapter.ts` | NEW | Codex `auth.json` 파싱, 저장은 Codex 계정 저장소 `saveCodexAccountCredential`(`ocx:src/codex/account-store.ts:248`) | +| `src/oauth/account-import/claude-credentials-adapter.ts` | NEW | Claude credentials 파싱, 저장은 OAuth 저장소 `saveAccountCredential`(`ocx:src/oauth/store.ts:1420`) | +| `src/cli/account-extended.ts` | MODIFY | 기존 import 진입(`ocx:src/cli/account-extended.ts:638`)에 `--format ` 일괄 입력 | +| `src/links/preset-link.ts` | NEW | 두 payload를 분리 파싱 (아래 스케치) | +| `desktop/src-tauri/src/lib.rs` | MODIFY | plugin 체인(`ocx:desktop/src-tauri/src/lib.rs:310`)에 deep-link plugin 등록, 이벤트를 GUI review dialog로 전달. `single_instance` 콜백(`:310`)이 두 번째 실행의 URL을 넘기도록 확장 | +| `desktop/src-tauri/tauri.conf.json` | MODIFY | 앱 identifier(`ocx:desktop/src-tauri/tauri.conf.json:5`) 아래에 URL scheme 선언 | +| `gui/src/pages/Providers.tsx` | MODIFY | 컴포넌트 진입(`ocx:gui/src/pages/Providers.tsx:227`)에서 sibling `ProviderImportPanel.tsx`, `PresetLinkDialog.tsx`, `EndpointSpeedTest.tsx`를 렌더만 | +| `src/server/management/endpoint-speed-routes.ts` | NEW | `POST /api/providers/speed-test` URL 배열, 동시성 상한·timeout·warm-up GET. 모델 호출 없음 | +| `src/cli/hub.ts` | MODIFY | `runInvite`(`ocx:src/cli/hub.ts:239`)가 명령 문자열과 함께 `hub-invite` 링크도 출력. 기존 명령 출력은 유지 | + +링크 payload (감사 r2 #1에서 분리): + +```ts +// provider preset: 공급자 저장 흐름(provider-routes 저장 경로)으로 이어진다. +type ProviderPresetLinkV1 = { v: 1; kind: "provider-preset"; name: string; baseUrl: string; + protocol: "openai-chat" | "openai-responses" | "anthropic"; models?: string[] }; // apiKey 없음 + +// Hub 초대: 기존 Hub pairing(ocx connect, hub.ts:236)으로 이어진다. SSH Link join(/api/link/join, alias 필요)과는 다른 흐름이다. +type HubInviteLinkV1 = { v: 1; kind: "hub-invite"; dataUrl: string; managementUrl: string; clients?: string[] }; +// pairing code는 링크에 넣지 않는다. dialog에서 사용자가 붙여 넣는다. +``` + +### Before / After + +`ocx:src/oauth/account-import/registry.ts:12` — 지금은 provider·format 한 쌍만 받는다. + +```ts +// before +const antigravityAdapter = createAntigravityAccountImportAdapter(); +export function resolveAccountImportAdapter(provider: string, format: string): AccountImportRegistryResult { + if (provider !== ACCOUNT_IMPORT_PROVIDER) return { ok: false, code: "unsupported_provider" }; + if (format !== ACCOUNT_IMPORT_FORMAT) return { ok: false, code: "unsupported_format" }; + return { ok: true, adapter: antigravityAdapter }; +} +``` + +```ts +// after (sketch) +const ADAPTERS = new Map([ // key: `${provider}\u0000${format}` + [key(ACCOUNT_IMPORT_PROVIDER, ACCOUNT_IMPORT_FORMAT), createAntigravityAccountImportAdapter()], + [key("codex", "codex-auth-json"), createCodexAuthJsonImportAdapter()], // → saveCodexAccountCredential + [key("anthropic", "claude-credentials"), createClaudeCredentialsImportAdapter()], // → saveAccountCredential +]); +export function resolveAccountImportAdapter(provider: string, format: string): AccountImportRegistryResult { + const adapter = ADAPTERS.get(key(provider, format)); // Map이라 prototype 키(`__proto__` 등)가 섞이지 않는다 + if (adapter) return { ok: true, adapter }; + return [...ADAPTERS.values()].some(a => a.provider === provider) + ? { ok: false, code: "unsupported_format" } : { ok: false, code: "unsupported_provider" }; +} +// service.ts:36: parseCockpitAccountDocument(request.document) → resolved.adapter.parseDocument(request.document) +``` + +## Dependencies + +010. 가져오기 결과는 Connections 화면에서 적용 상태를 확인한다. + +## Acceptance + +- CC Switch가 설치된 홈에서 Providers 화면이 후보를 보여 주고, 고른 항목만 preview 후 적용된다. 키 값은 브라우저로 전송되지 않는다. +- Codex `auth.json` 여러 개를 `ocx account import --format codex-auth-json`으로 넣으면 receipt가 중복·실패 사유를 항목별로 보여 준다. +- fixture `provider-preset` 링크를 열면 review dialog가 뜨고 확인 전에는 저장이 없다. +- fixture `hub-invite` 링크를 열면 data/management origin과 선택 클라이언트가 먼저 보이고, 사용자가 pairing code를 넣고 확인한 뒤에만 기존 Hub pairing이 시작된다. `/api/link/join`은 호출되지 않는다. +- pairing이 끝나면 마법사가 원격 카탈로그 상태(사용 가능한 모델 수, 준비 여부)를 보여 준다. 카탈로그가 비어 있으면 그 이유를 보여 준다. +- 속도 측정은 usage ledger 행을 만들지 않는다. + +## Verification + +- 신규 `tests/providers/import-discovery.test.ts`, `tests/server/account-import-codex.test.ts`, `tests/providers/preset-link.test.ts`, `tests/server/endpoint-speed-routes.test.ts` +- 기존 회귀: `tests/providers/cc-switch-import.test.ts`, `tests/cli/cli-provider-cc-switch-import.test.ts`, `tests/server/account-import*.test.ts` +- `bun run typecheck`, `bun run test:changed`, `bun run structure:check`, `bun run lint:gui`, `bun run privacy:scan` +- Tauri 변경은 import graph로 보이지 않으므로 PR에 `ci:full` + +## Risks + +- **File-size ratchet:** 캡에 없는 파일은 2000줄 이상이면 실패하고(`NEW_OVERSIZED`), 캡 파일은 캡을 넘으면 실패한다(`tests/fixtures/file-size-baseline.json`). `provider-routes.ts` 1989줄(여유 10), `oauth-account-routes.ts` 1567줄 — 둘 다 늘리지 않는다. +- **Lab 경계:** `tests/lab/core-lab-boundary.test.ts`의 보호 목록(`ocx:tests/lab/core-lab-boundary.test.ts:23`: `src/router.ts`, `src/server/lifecycle.ts`, `src/server/responses/core.ts`, `src/server/management-api.ts`)에서 `src/lab/`으로 가는 import가 직접이든 간접이든 생기면 안 된다. +- **Consent:** 계정 자격 증명 일괄 가져오기는 명시 입력 파일만 받는다. 자동 탐색 대상은 키 없는 공급자 설정뿐이다. +- **Privacy:** receipt와 로그에 email·token을 남기지 않는다. 링크에 키·pairing code를 넣지 않는다. + +## Non-goals + +- OpenCode auth 플러그인 자격 증명, MCP/Skill 링크 (G-052 비채택), 클라우드 동기화 (G-040 보류). diff --git a/devlog/_plan/261123_proxy_upstream_catchup/030_client_coverage.md b/devlog/_plan/261123_proxy_upstream_catchup/030_client_coverage.md new file mode 100644 index 00000000000..90d879cb1fb --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/030_client_coverage.md @@ -0,0 +1,91 @@ +# 030 — 클라이언트 범위와 설정 이식성: Gemini CLI, Zed, MCP 동기화, 로컬 백업 + +**Gaps:** G-008, G-009, G-010, G-011 +**Depends on:** 010 +**Size:** L + +> 줄 번호와 줄 수는 OpenCodex `origin/dev` `9e0e298ef9` 기준이며, 줄 수는 ratchet의 `countLines`(`ocx:scripts/file-size-ratchet.ts:109`)로 센 값이다. 구현 단위를 열 때 현재 `dev`에서 다시 확인한다. + +## Goal + +Gemini CLI와 Zed를 opt-in으로 OpenCodex에 연결하고 원복한다. 여러 파일을 쓰는 연결이 중간에 프로세스가 죽어도 다음 시작 때 일관된 상태로 돌아온다. Codex/Claude Code의 MCP 서버 항목을 읽고 고른 항목만 적용한다. 관리 설정을 골라 로컬 백업 번들로 내보내고 복원 전 변경을 본다. + +## Why + +- **G-008** — cc-switch는 `.gemini/.env`와 `settings.json`을 함께 다룬다(`ccs:src-tauri/src/gemini_config.rs:9–19,258–262`). OpenCodex에는 Gemini CLI 파일 연결이 없다 (`003` 인벤토리: gap). +- **G-009** — magpie는 Zed `settings.json`에 custom provider를 쓴다(`mgp:internal/agent/zed.go:51,70`). OpenCodex client 목록에 Zed가 없다(`ocx:src/clients/client-ids.ts:2`, `ocx:src/integrations/registry.ts:288`) (`007` L7-7). +- **G-010** — cc-switch `McpService`는 Claude `mcpServers`, Codex `[mcp_servers.*]`로 투영한다(`ccs:src-tauri/src/services/mcp.rs:51,276–287`). OpenCodex에는 전역 MCP 항목을 읽고 재투영하는 표면이 없다 (`003` L3-8). +- **G-011** — cc-switch는 백업 생성·검증·복원을 제공한다(`ccs:src-tauri/src/database/backup.rs:581–619`). OpenCodex는 raw `config export/import`만 있다(`ocx:src/cli/config-command.ts:246`) (`003` L3-6). + +## Changes + +| 경로 | 의도 | 내용 | +|---|---|---| +| `src/clients/client-ids.ts` | MODIFY | `EXPORT_CLIENT_IDS`(`ocx:src/clients/client-ids.ts:2`)에 `"gemini-cli"`, `"zed"`. exhaustive union이므로 같은 PR에서 모든 소비자와 i18n을 갱신하고 개수는 목록에서 파생 | +| `src/integrations/registry.ts` | MODIFY | `INTEGRATION_CLIENTS`(`ocx:src/integrations/registry.ts:288`)에 두 항목 | +| `src/clients/config-export.ts` | MODIFY | `EXPORT_CLIENTS: Record`(`ocx:src/clients/config-export.ts:1504`)에 두 spec 등록. 이 맵도 exhaustive라 빠지면 typecheck가 실패한다 | +| `src/clients/config-export/gemini-cli.ts` | NEW | Gemini CLI export spec (dotenv + settings.json 미리보기) | +| `src/clients/config-export/zed.ts` | NEW | Zed export spec (custom provider 블록 미리보기, upstream Zed provider id와 구분) | +| `src/integrations/writer.ts` | MODIFY | `commit`(`ocx:src/integrations/writer.ts:155`)의 단일 파일 순서(파일 → ownership → journal, `:147`) 앞에 다중 파일 recovery record 단계를 둔다 (아래) | +| `src/integrations/multi-file-recovery.ts` | NEW | 기존 transaction seam(`io.beginTransaction`, `ocx:src/integrations/writer.ts:155`; 다중 파일 선례 `ocx:src/integrations/cline-io.ts:131`)을 써서 쓰기 전에 `{opId, files:[{path, preImageSnapshot, intendedHash}], priorRecord, journalEntry}`를 durable하게 기록하고, 파일·ownership(`ocx:src/integrations/writer.ts:180`)·journal 모두 commit 뒤 완료 표시. 시작 시 미완료 record를 복구 | +| `src/integrations/gemini-cli-io.ts` | NEW | dotenv + JSON 두 파일을 하나의 recovery record로 쓴다 | +| `src/integrations/zed-settings.ts` | NEW | Zed JSON(주석 허용) merge, 사용자 모델 선택 보존 | +| `src/integrations/mcp/` | NEW | `read.ts`, `plan.ts`(선택 항목 diff), `apply.ts`(writer 경유) | +| `src/cli/config-command.ts` | MODIFY | `handleConfigCommand`(`ocx:src/cli/config-command.ts:246`)에 `backup [--include …]`, `restore --preview` 하위 명령. 구현은 sibling `config-backup.ts` | +| `gui/src/pages/integrations/` | NEW 패널 | Gemini CLI·Zed 카드(기존 `FileIntegrationPage.tsx` 재사용), MCP 패널, 백업 패널 | + +다중 파일 복구 규칙 (감사 r2 #6, r3 #5): 복구 단위는 파일, ownership record, journal row 전체다. 미완료 record가 있으면 ownership은 `priorRecord`로, journal은 해당 opId 행을 "recovered" 상태로 기록해 파일 상태와 맞춘다. 파일은 각 파일의 현재 해시를 `intendedHash`, `preImageSnapshot`과 비교한다. 현재 바이트가 우리가 쓴 값이면 pre-image로 되돌린다. pre-image와 같으면 그대로 둔다. 둘 다 아니면 사용자가 그사이 고친 것이므로 건드리지 않고 충돌로 보고한다. + +### Before / After + +`ocx:src/clients/client-ids.ts:2` — client 목록에 Gemini CLI와 Zed가 없다. + +```ts +// before +export const EXPORT_CLIENT_IDS = [ + "qoder", "qoder-cn", "workbuddy", "workbuddy-ai", "opencode", "pi", "omp", "hermes", + "openclaw", "kimi", "gajae", "dsh", "mcode", "zcode", "commandcode", "prime", "aside", + "raycast", "omo", "cline", "kilo", "droid", "gentle-shell", "t3code", +] as const; +``` + +```ts +// after (sketch) +export const EXPORT_CLIENT_IDS = [ + /* 기존 24개 그대로 */ "t3code", + "gemini-cli", "zed", +] as const; +// EXPORT_CLIENTS(config-export.ts:1504)와 INTEGRATION_CLIENTS(registry.ts:288)는 둘 다 Record<…Id, …>이므로 +// 두 spec(config-export/gemini-cli.ts, zed.ts)과 두 integration 항목이 없으면 typecheck가 실패한다. +// gemini-cli의 writer는 multi-file-recovery를 거쳐 .env와 settings.json을 한 작업으로 쓴다. +``` + +## Dependencies + +010의 journal/restore 계약과 Connections 화면을 재사용한다. + +## Acceptance + +- Gemini CLI 연결을 켰다 끄면 두 파일이 원래 바이트로 돌아온다. +- fixture: dotenv를 쓴 직후 프로세스를 종료하고 재시작하면 dotenv가 pre-image로 복구되고 JSON은 그대로이며, 그사이 사용자가 고친 무관한 키는 남는다. +- fixture: 첫 파일의 ownership·journal bookkeeping까지 commit된 뒤 종료하면, 재시작 후 ownership은 이전 record로 돌아가고 journal의 해당 작업은 recovered로 표시되어 디스크 파일과 일치한다. +- Zed 연결 후 사용자가 고른 모델이 유지된다. +- MCP 패널은 고른 항목만 적용하고 서버 명령을 실행하지 않는다. +- 백업 번들은 기본적으로 credential을 제외하고 복원 전 변경 목록을 보여 준다. + +## Verification + +- 신규 `tests/cli/gemini-cli-integration-io.test.ts`, `tests/cli/zed-integration-settings.test.ts`, `tests/cli/mcp-client-sync-plan.test.ts`, `tests/cli/config-backup.test.ts`, `tests/cli/integration-multi-file-recovery.test.ts` +- 기존 회귀: `tests/cli/cli-integration-preview.test.ts`, `tests/cli/cli-capability-integration-workflows.test.ts`, `tests/ci-workflows/skill-ocx.test.ts` (CLI capability 추가 시 `bun run skill:surface`) +- `bun run typecheck`, `bun run test:changed`, `bun run structure:check`, `bun run lint:gui` + +## Risks + +- **Union exhaustiveness:** `EXPORT_CLIENT_IDS`와 i18n·개수가 다른 브랜치와 동시에 바뀌면 merge 뒤 typecheck가 깨진다. +- **File-size ratchet:** 캡에 없는 파일은 2000줄 이상이면 실패하고(`NEW_OVERSIZED`), 캡 파일은 캡을 넘으면 실패한다(`tests/fixtures/file-size-baseline.json`). `writer.ts` 1094줄, `registry.ts` 604줄 — recovery와 adapter는 sibling. +- **Lab 경계:** `tests/lab/core-lab-boundary.test.ts`의 보호 목록(`ocx:tests/lab/core-lab-boundary.test.ts:23`: `src/router.ts`, `src/server/lifecycle.ts`, `src/server/responses/core.ts`, `src/server/management-api.ts`)에서 `src/lab/`으로 가는 import가 직접이든 간접이든 생기면 안 된다. +- **Privacy:** MCP 항목의 env·header 값은 표시와 로그에서 가린다. + +## Non-goals + +- 범용 MCP/Skills Library (G-052 비채택), 원격 저장소 동기화 (G-040 보류), roster 맞추기 (G-054 비채택). diff --git a/devlog/_plan/261123_proxy_upstream_catchup/040_pool_scheduling_egress.md b/devlog/_plan/261123_proxy_upstream_catchup/040_pool_scheduling_egress.md new file mode 100644 index 00000000000..e578cf9186d --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/040_pool_scheduling_egress.md @@ -0,0 +1,107 @@ +# 040 — 계정 풀 스케줄링과 egress + +**Gaps:** G-012, G-013, G-014, G-015, G-016, G-017 +**Depends on:** none +**Size:** XL (구현 단위 둘: 040a = G-012, G-013, G-016 · 040b = G-014 → G-015, G-017) + +> 줄 번호와 줄 수는 OpenCodex `origin/dev` `9e0e298ef9` 기준이며, 줄 수는 ratchet의 `countLines`(`ocx:scripts/file-size-ratchet.ts:109`)로 센 값이다. 구현 단위를 열 때 현재 `dev`에서 다시 확인한다. + +## Goal + +같은 provider pool 안에서 계정마다 다른 upstream proxy를 쓴다. 확인된 quota cooldown이 재시작 뒤에도 유지된다. Codex·Claude OAuth 계정에 동시 실행 상한과 짧은 대기열이 생기고, 기존 priority tier 안에서 정적 weight와 실시간 부하로 계정을 고른다. 계정별 eligibility·refresh·cooldown 진단과 최근 fallback 결정의 후보·제외 사유를 본다. + +## Why + +- **G-012** — CPA는 credential에 `proxy_url`을 저장해 로그인·refresh·실행에 쓴다(`cpa:sdk/auth/manager.go:54–71`, `cpa:internal/runtime/executor/helps/proxy_helpers.go:36–69`). sub2api도 계정별 proxy를 고른다 (`004` L4-04). OpenCodex egress는 provider 단위다(`ocx:src/lib/provider-egress.ts:160`) (`002` L2-1). +- **G-013** — CPA는 cooldown을 선택적으로 복원한다(`cpa:sdk/cliproxy/service_lifecycle.go:86–99`). OpenCodex는 process-local map이다(`ocx:src/providers/api-key-cooldowns.ts:2`) (`002` L2-2). +- **G-014** — sub2api는 계정 lease와 WaitPlan으로 동시 실행을 집행한다(`s2a:backend/internal/service/gateway_scheduling.go:708,754`). OpenCodex는 Kiro에만 계정 lease가 있다(`ocx:src/oauth/kiro-account-load.ts:84`, `ocx:src/server/responses/request-transport.ts:214`) (`004` L4-01). sub2api issue #8552(2026-11-06)는 동시 실행 수와 TTFT가 함께 오른 보고다. +- **G-015** — sub2api priority → load → LRU(`s2a:backend/internal/service/gateway_scheduling.go:652,738`), CPA weighted RR(`cpa:sdk/cliproxy/auth/scheduler_weighted.go:7–30`). OpenCodex에는 operator priority가 이미 있다(`ocx:src/codex/auth-api/routes.ts:204`, `selectPriorityTier` `ocx:src/codex/routing/selection.ts:249`). 빠진 것은 tier 안 weight와 부하다 (감사 r1 #8). +- **G-016** — CPA `/credentials`는 models/status/refresh/verify를 준다(`cpa:internal/api/handlers/management/auth_files_v8.go:546,612`). OpenCodex `/api/oauth/accounts`에는 eligibility·refresh 결과 DTO가 없다 (`002` L2-3). +- **G-017** — cc-switch는 앱별 큐와 circuit breaker 상태를 보여 준다(`ccs:src-tauri/src/proxy/provider_router.rs:73–188`). OpenCodex fallback 정책(`ocx:src/routing/fallback-policy.ts:211`)은 결정 근거를 화면에 내지 않는다 (`003` L3-9). + +## Changes + +| 경로 | 의도 | 내용 | +|---|---|---| +| `src/types/pool-account.ts` | NEW | `{egress?: {proxy?: string; noProxy?: string[]}; weight?: number; maxConcurrent?: number}` | +| `src/types/config.ts` | MODIFY | 1939줄(여유 60). 계정/키 레코드에 위 타입 참조 한 필드씩 (`OcxApiKeyEntry` 근처 `ocx:src/types/config.ts:336` 패턴) | +| `src/lib/provider-egress.ts` | MODIFY | `resolveProviderEgress`(`ocx:src/lib/provider-egress.ts:160`)의 context에 `account?: {id, egress?}` 추가: request override → account → provider → env | +| `src/server/responses/fetch-helpers.ts` | MODIFY | `egressFor`(`ocx:src/server/responses/fetch-helpers.ts:362`)가 선택된 계정의 `{id, egress}`를 넘긴다 | +| `src/lib/provider-outbound.ts` | MODIFY | refresh·quota 조회 등 비요청 outbound(`ocx:src/lib/provider-outbound.ts:301`, `ocx:src/providers/quota/vendor-probes-key.ts:23`)도 계정 egress를 쓴다 | +| `src/providers/api-key-cooldowns.ts` | MODIFY | map(`ocx:src/providers/api-key-cooldowns.ts:2`)에 store 주입. 새 `api-key-cooldown-store.ts`가 `{provider, keyId, generation, cooldownUntil}`만 저장, 만료 sweep은 `ocx:src/lib/state-store-registrations.ts:129` 재사용 | +| `src/oauth/account-lease.ts` | NEW | `acquireAccountLease`(`ocx:src/oauth/kiro-account-load.ts:84`)를 namespace 키 `{ns: "account", provider, accountId} \| {ns: "caller", keyId}`로 일반화하고 in-flight 수를 노출 (070이 caller 키를 쓴다) | +| `src/server/responses/request-transport.ts` | MODIFY | 1879줄(여유 120). Kiro 분기(`ocx:src/server/responses/request-transport.ts:214`, `:1508`)를 공용 lease 호출로 교체, 줄 수 증가 없음 | +| `src/server/messages-native-oauth.ts` | MODIFY | `resolveNativeOAuthBinding`(`ocx:src/server/messages-native-oauth.ts:120`) 결과 계정에 lease 획득, 종료·취소 시 해제 | +| `src/codex/routing/selection-weighted.ts` | NEW | `selectPriorityTier`(`ocx:src/codex/routing/selection.ts:249`)가 고른 tier 안에서만 smooth weighted round-robin, 동률은 in-flight 적은 쪽 | +| `src/server/management/account-diagnostics-routes.ts` | NEW | 계정별 `{eligibleModels, lastRefresh:{at, ok, reason}, cooldownUntil, inFlight}` | +| `src/server/management/fallback-routes.ts` | MODIFY | `GET /api/fallback`(`ocx:src/server/management/fallback-routes.ts:33`) 옆에 최근 결정 projection `GET /api/fallback/decisions` | + +선택 snapshot 계약 (감사 r2 #7): 040은 선택 결과로 `{provider, accountId, generation}`만 내보낸다. 호출자·세션 신원은 040이 정하지 않는다 (050·070 참조). + +### Before / After + +`ocx:src/lib/provider-egress.ts:160` — egress는 provider 설정만 본다. + +```ts +// before +export function resolveProviderEgress(context: ProviderEgressContext): ProviderEgress { + const { providerName, provider } = context; + const raw = provider.proxy; + /* inherit | direct | proxy URL 판정 */ +``` + +```ts +// after (sketch) +export function resolveProviderEgress(context: ProviderEgressContext): ProviderEgress { + const { providerName, provider, account } = context; // account?: { id: string; egress?: PoolAccountEgress } + const raw = account?.egress?.proxy !== undefined ? account.egress.proxy : provider.proxy; + /* 같은 판정. noProxy는 account → provider 순으로 합친다 */ +``` + +`ocx:src/oauth/kiro-account-load.ts:84` — lease는 Kiro 전용 모듈에 있다. 새 `src/oauth/account-lease.ts`로 옮기고 Codex·Claude OAuth 경로가 같은 함수를 부른다. + +```ts +// before (kiro-account-load.ts) +if (state.waiters.length === 0 + && (opts.maxConcurrentPerAccount === undefined || state.records.size < opts.maxConcurrentPerAccount)) { + return leaseFor(provider, accountId, key, state, now); +} +``` + +```ts +// after (account-lease.ts, sketch) +export type LeaseKey = { ns: "account"; provider: string; accountId: string } | { ns: "caller"; keyId: string }; +export async function acquireAccountLease(key: LeaseKey, + opts: { maxConcurrent?: number; waitMs?: number; signal?: AbortSignal }): Promise; +export function leaseInFlight(key: LeaseKey): number; // SWRR 동률 판정(account)과 070 상한(caller)에 사용 +``` + +## Dependencies + +없음. 050은 선택 snapshot의 계정·generation을, 060의 G-024와 070은 egress resolver와 lease 구현을 쓴다. + +## Acceptance + +- 같은 Codex pool의 두 계정에 서로 다른 proxy를 지정하면 각 계정의 요청과 refresh가 지정 proxy로 나간다 (로컬 proxy fixture 두 개). +- quota cooldown 중인 키가 있는 상태로 재시작해도 만료 전까지 선택되지 않는다. 키를 교체(generation 변경)하면 cooldown이 따라가지 않는다. +- busy-account fixture: `maxConcurrent: 1`인 계정 A에 turn이 하나 걸려 있을 때 두 번째 turn은 대기 상한 안에서 기다리거나 B로 간다. 상한을 넘으면 명확한 거절 이유를 돌려준다. 설정이 없으면 동작 변화 없음. +- weight fixture: 같은 tier의 A(2)와 B(1)에 대해 SWRR이 처음 6번을 A, B, A, A, B, A로 고른다. 더 높은 priority tier의 계정과 manual pin이 있으면 그쪽이 먼저다. +- 진단 fixture: refresh 실패 계정은 `lastRefresh.ok=false`와 이유, 모델 미허용 계정은 `eligibleModels`에서 빠짐, cooldown 계정은 `cooldownUntil`이 보인다. email·토큰은 없다. +- fallback decisions는 최근 결정의 후보 순서와 제외 사유(cooldown, scope, 이미 시도함)를 보여 준다. + +## Verification + +- 신규 `tests/oauth/account-lease.test.ts`, `tests/providers/api-key-cooldown-store.test.ts`, `tests/codex-integration/codex-selection-weighted.test.ts`, `tests/lib/provider-egress-account.test.ts`, `tests/server/account-diagnostics-routes.test.ts` +- 기존 회귀: `tests/providers/kiro/kiro-account-load.test.ts`, `tests/adapters/key-failover.test.ts`, `tests/server/server-key-failover-e2e.test.ts`, `tests/codex-integration/` routing·selection 테스트 +- `bun run typecheck`, `bun run test:changed`, `bun run structure:check`, `bun run privacy:scan`; 전송 경로라 `ci:full` + +## Risks + +- **File-size ratchet:** 캡에 없는 파일은 2000줄 이상이면 실패하고(`NEW_OVERSIZED`), 캡 파일은 캡을 넘으면 실패한다(`tests/fixtures/file-size-baseline.json`). `request-transport.ts` 1879, `anthropic-routing.ts` 1774, `types/config.ts` 1939 — sibling 모듈로 분리. +- **Lab 경계:** `tests/lab/core-lab-boundary.test.ts`의 보호 목록(`ocx:tests/lab/core-lab-boundary.test.ts:23`: `src/router.ts`, `src/server/lifecycle.ts`, `src/server/responses/core.ts`, `src/server/management-api.ts`)에서 `src/lab/`으로 가는 import가 직접이든 간접이든 생기면 안 된다. lease와 egress는 요청 경로에 들어간다. +- **재전송 계약:** lease 해제와 failover가 엇갈려도 fail-closed `refused-ambiguous` 게이트(`ocx:src/server/responses/reset-replay.ts:112`)를 완화하지 않는다. +- **Privacy:** proxy URL의 인증 정보는 `sanitizeProxyUrlForLog`(`ocx:src/lib/provider-egress.ts:72`)로 가린다. + +## Non-goals + +- 투명 rotation, TLS fingerprint (G-048 비채택), TTFT·실패율 점수화(관측 품질 확보 뒤 별도 단위). diff --git a/devlog/_plan/261123_proxy_upstream_catchup/050_session_cache_continuity.md b/devlog/_plan/261123_proxy_upstream_catchup/050_session_cache_continuity.md new file mode 100644 index 00000000000..9c5767de4dd --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/050_session_cache_continuity.md @@ -0,0 +1,83 @@ +# 050 — 세션 연속성과 캐시 + +**Gaps:** G-018, G-019, G-020, G-021 +**Depends on:** 040 +**Size:** XL (G-021은 별도 구현 단위) + +> 줄 번호와 줄 수는 OpenCodex `origin/dev` `9e0e298ef9` 기준이며, 줄 수는 ratchet의 `countLines`(`ocx:scripts/file-size-ratchet.ts:109`)로 센 값이다. 구현 단위를 열 때 현재 `dev`에서 다시 확인한다. + +## Goal + +긴 코딩 대화에서 combo가 이미 캐시가 따뜻한 대상을 유지해 cache miss를 줄인다. Antigravity와 xAI 경로에서 클라이언트가 돌려주지 않은 reasoning·서명 문맥을 안전하게 복원한다. 실제 Claude CLI를 쓰는 경로에 계정별 세션 재사용 opt-in 모드를 둔다. + +## Why + +- **G-018** — magpie는 대화별로 대상과 계정을 유지하고 cache read/write·TTL을 쓴다 (`006` L6-1). OpenCodex는 Codex 계정(`ocx:src/codex/routing/cache-affinity.ts:36`), JEV pin(`ocx:src/combos/jev-session-pin-config.ts:2`), tool-loop pin(`ocx:src/server/responses/core-combo.ts:790`)이 있으나 일반 combo 대상 affinity는 없다. +- **G-019** — CPA는 이전 문맥·part 위치 대조와 native call 복원을 한다 (`001` L1-1). OpenCodex는 세션별 다중 서명·snapshot·제거가 있다(`ocx:src/adapters/google-antigravity-replay.ts:37,184,344`). +- **G-020** — CPA는 xAI 경로에서 completion을 보강한다 (`001` L1-2). OpenCodex에는 Grok replay 정규화가 있다(`ocx:src/adapters/openai-responses/reasoning.ts:125`, `ocx:src/server/responses/core-replay.ts:114`). +- **G-021** — magpie는 계정별 장기 Claude CLI와 resume을 쓴다 (`006` L6-5). OpenCodex `claude-cli`는 매 턴 stateless다(`ocx:src/server/responses/run-turn-execution.ts:190`). + +## Changes + +| 경로 | 의도 | 내용 | +|---|---|---| +| `src/combos/session-affinity.ts` | NEW | `{callerNamespace, lane, comboId} → {target, accountId, generation, expiresAt}`. `callerNamespace`는 JEV 구현을 공용 helper로 옮겨 함께 쓴다 | +| `src/combos/resolve.ts` | MODIFY | `pickComboTarget`(`ocx:src/combos/resolve.ts:445`)에 affinity 힌트 인자. 기본 off, combo별 설정 | +| `src/server/responses/core-combo.ts` | MODIFY | 1971줄, 2000 전까지 28줄. tool-loop pin 계산(`ocx:src/server/responses/core-combo.ts:790`) 다음에 affinity 조회 한 줄, 기록은 dispatch scope 확인(`:1189`) 뒤 한 줄. 로직은 sibling | +| `src/adapters/google-antigravity-replay-context.ts` | NEW | 문맥 지문·part 위치 대조, native call 복원, snapshot 조건부 갱신 | +| `src/adapters/google-antigravity-replay.ts` | MODIFY | 986줄. 관찰·저장 경로 `observeAntigravityReplay`(`ocx:src/adapters/google-antigravity-replay.ts:718`)에서 새 모듈의 조건부 갱신을 호출 | +| `src/responses/state/xai-turn-supplement.ts` | NEW | 완료 turn 보강. target/credential binding, 동일 turn dedupe, compaction 무효화 | +| `src/adapters/claude-cli/session-pool.ts` | NEW | 계정·호출자·세션 소유권, idle drain, crash 복구, 취소 전파. 기본 off | +| `src/server/responses/run-turn-execution.ts` | MODIFY | `claude-cli` 분기(`ocx:src/server/responses/run-turn-execution.ts:190`)에서 session-pool 사용 여부 선택 | + +Affinity 소유권 (감사 r2 #7, r3 #3): namespace는 JEV pin의 `callerNamespace(admission)`(`ocx:src/server/responses/jev-session-pin.ts:57`)과 같이 admitted principal(`principal:`, `key:`, loopback)과 session lane, comboId로 만든다(`ocx:src/server/responses/jev-session-pin.ts:123`). `currentAdmissionScope()`(`ocx:src/server/responses/core-combo.ts:1189`)는 provider·model 허용 범위일 뿐 신원이 아니므로, 바인딩된 대상의 eligibility 재검사에만 쓴다. 040 snapshot은 계정과 generation만 준다. 우선순위는 tool-loop pin > affinity > 정책 순서다. compaction override와 main hard-lock fallback override 경로는 JEV pin과 같이 affinity를 읽지도 기록하지도 않는다(`ocx:src/server/responses/core-combo.ts:805`). + +### Before / After + +`ocx:src/server/responses/core-combo.ts:790` — tool-loop pin이 없으면 바로 정책 순서로 고른다. + +```ts +// before +const toolLoopPin = options.compactionRoutingOverride || options.mainHardLockFallbackOverride + ? undefined + : toolLoopPinnedPick({ config, comboId, lane: sessionLaneIdFromRequest(req.headers), body, + eligible: target => maySpendOnTarget(target) && targetEligible(target), now: initialNow }); +let pick = toolLoopPin ?? await pickWithWait({ /* … */ }); +``` + +```ts +// after (sketch) — core-combo.ts에는 한 줄, 로직은 combos/session-affinity.ts +// override 경로는 JEV pin(core-combo.ts:805)과 같이 affinity를 읽지도 쓰지도 않는다 +const overrideRoute = options.compactionRoutingOverride || options.mainHardLockFallbackOverride; +const affinityPick = toolLoopPin || overrideRoute ? undefined : comboAffinityPick({ admission: options.admission, comboId, + lane: sessionLaneIdFromRequest(req.headers), eligible: t => maySpendOnTarget(t) && targetEligible(t) }); +let pick = toolLoopPin ?? affinityPick ?? await pickWithWait({ /* … */ }); +``` + +## Dependencies + +040. 바인딩이 가리키는 계정이 교체됐는지(generation) 040 snapshot으로 판단한다. + +## Acceptance + +- affinity를 켠 combo에서 같은 세션의 연속 turn이 같은 대상으로 간다. 대상이 cooldown에 들어가거나 generation이 바뀌면 해제 이유가 metrics에 남고 다음 후보로 간다. 허용 범위가 똑같은 두 발급 키가 같은 session lane을 써도 바인딩이 섞이지 않는다. tool-loop pin이 있으면 그쪽이 이긴다. +- Antigravity: 같은 인자의 tool call이 반복되는 fixture에서 서명이 위치 기준으로 복원된다. 불일치면 기존처럼 제거하고 진행한다. +- xAI: reasoning item을 빠뜨린 다음 turn에서 보강되고 같은 turn이 두 번 보강되지 않는다. +- Claude CLI 세션 재사용을 켜면 같은 세션의 두 번째 turn이 프로세스를 새로 띄우지 않는다. 끄면 기존 동작. + +## Verification + +- 신규 `tests/codex-integration/combo-session-affinity.test.ts`, `tests/adapters/google/google-antigravity-replay-context.test.ts`, `tests/responses/xai-turn-supplement.test.ts`, `tests/adapters/claude-cli-session-pool.test.ts` +- 기존 회귀: `tests/adapters/google/google-antigravity-replay.test.ts`, `tests/codex-integration/combos.test.ts`, `tests/codex-integration/combo-cooldown-reprobe.test.ts`, `tests/responses/` replay 테스트 +- `bun run typecheck`, `bun run test:changed`, `bun run structure:check`; Claude CLI는 subprocess라 `ci:full` + +## Risks + +- **File-size ratchet:** 캡에 없는 파일은 2000줄 이상이면 실패하고(`NEW_OVERSIZED`), 캡 파일은 캡을 넘으면 실패한다(`tests/fixtures/file-size-baseline.json`). `core-combo.ts`는 1971줄로 28줄 여유다. 이 단계의 추가는 두 줄 이내로 한다. +- **Lab 경계:** `tests/lab/core-lab-boundary.test.ts`의 보호 목록(`ocx:tests/lab/core-lab-boundary.test.ts:23`: `src/router.ts`, `src/server/lifecycle.ts`, `src/server/responses/core.ts`, `src/server/management-api.ts`)에서 `src/lab/`으로 가는 import가 직접이든 간접이든 생기면 안 된다. +- **Consent:** G-021은 사용자 Claude 구독을 장기 프로세스로 유지하므로 명시 opt-in이다. 한 로그인을 여러 사람이 공유하는 구성은 지원하지 않는다. +- **Privacy:** 서명·reasoning 원문은 로그에 남기지 않는다. + +## Non-goals + +- 영속 replay 저장소, Gemini 명시적 cache API (G-036 보류). diff --git a/devlog/_plan/261123_proxy_upstream_catchup/060_wire_fidelity.md b/devlog/_plan/261123_proxy_upstream_catchup/060_wire_fidelity.md new file mode 100644 index 00000000000..95204941e3e --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/060_wire_fidelity.md @@ -0,0 +1,88 @@ +# 060 — wire 충실도: 첨부 전용 turn, Gemini Interactions egress, xAI upstream WS + +**Gaps:** G-022, G-023, G-024 +**Depends on:** 040 +**Size:** L + +> 줄 번호와 줄 수는 OpenCodex `origin/dev` `9e0e298ef9` 기준이며, 줄 수는 ratchet의 `countLines`(`ocx:scripts/file-size-ratchet.ts:109`)로 센 값이다. 구현 단위를 열 때 현재 `dev`에서 다시 확인한다. + +## Goal + +Codex와 Claude Code의 첨부 전용 turn, file-backed 첨부, PDF, 여러 modality의 tool result가 대상 공급자 능력에 맞게 보존되거나 전송 전에 명확히 거절된다. Gemini Interactions를 공급자 네이티브로 보내는 opt-in 모드와 xAI upstream WebSocket 전송을 제공한다. + +## Why + +- **G-022** — CPA translator는 첨부 단독 turn과 다중 modality tool result를 변환한다 (`001` L1-4). OpenCodex의 `checkRepresentable`(`ocx:src/protocols/guard.ts:17`)과 Claude inbound(`ocx:src/claude/inbound.ts:64`)는 경로별로 다르다. +- **G-023** — CPA는 Interactions를 공급자로 보낸다 (`001` L1-5). OpenCodex는 local ID로 처리하고 리소스 조회도 로컬이다(`ocx:src/server/gemini-interactions-inbound.ts:209`: "never forwarded upstream"). +- **G-024** — CPA `xai_websockets_executor`는 upstream WS를 쓴다 (`001` L1-3). OpenCodex xAI는 HTTP다(`ocx:src/providers/xai-transport.ts:21`). + +## Changes + +| 경로 | 의도 | 내용 | +|---|---|---| +| `src/protocols/attachment-capability.ts` | NEW | 대상별 첨부 능력 `{image, pdf, file, toolResultImage}` | +| `src/protocols/guard.ts` | MODIFY | `checkRepresentable`(`ocx:src/protocols/guard.ts:17`)이 능력 표로 판정해 보존/413/400 구분 | +| `src/claude/inbound.ts` | MODIFY | 첨부 변환 지점(`ocx:src/claude/inbound.ts:64`, `:291`)에서 file-backed 첨부와 tool-result modality 보존 | +| `src/protocols/codecs/gemini-interactions-egress.ts` | NEW | Interactions 요청을 공급자 wire로 encode | +| `src/protocols/codecs/gemini-interactions.ts` | MODIFY | 770줄. `interactionsToChat`(`ocx:src/protocols/codecs/gemini-interactions.ts:318`) 옆에서 모드별 분기만 | +| `src/server/gemini-interactions-inbound.ts` | MODIFY | 연쇄 POST의 previous id 처리(`ocx:src/server/gemini-interactions-inbound.ts:86`)와 `handleGeminiInteractionResource`(`ocx:src/server/gemini-interactions-inbound.ts:209`): native 모드에서는 owner 확인 뒤 local id → upstream id 매핑으로 GET/DELETE/cancel을 공급자에 전달. local 모드는 그대로 | +| `src/providers/xai-ws-transport.ts` | NEW | Bun bounded WS, transcript/ID 수명, WS→SSE terminal·fallback | +| `src/providers/xai-transport.ts` | MODIFY | `isXaiResponsesDestination`(`ocx:src/providers/xai-transport.ts:21`) 옆에 transport 선택 | +| `src/server/responses/fetch-helpers.ts` | MODIFY | `egressFor`(`ocx:src/server/responses/fetch-helpers.ts:362`)를 WS 연결에도 적용 | + +Interactions native 모드 의미 (감사 r2 #8, r3 #6): create는 공급자 id를 받아 `{localId, upstreamId, ownerKey, provider, destination, accountId, generation}`로 저장한다(040 snapshot). GET/DELETE/cancel은 owner가 다르면 기존처럼 없는 id로 응답한다. owner가 같으면 생성 때와 같은 admission(`ocx:src/server/index/gemini-routes.ts:73`)에 더해, 지금 키 범위가 묶인 destination을 아직 허용하는지 다시 확인한 뒤 저장된 계정·generation으로만 전달하며, 그 계정이 제거됐거나 generation이 바뀌었으면 다른 계정으로 보내지 않고 409 `interaction_binding_unavailable`을 돌려준다. + +연쇄 POST (`previous_interaction_id`, 감사 r4 #3): local 모드는 지금처럼 저장된 history로 요청을 다시 만든다(`ocx:src/server/gemini-interactions-inbound.ts:86`). native 모드는 local previous id로 binding을 찾고, owner와 현재 destination 정책을 다시 확인한 뒤, 매핑된 upstream id를 묶인 계정으로 보낸다. binding이 없거나 계정을 쓸 수 없으면 409이며 history 재구성으로 몰래 바꾸지 않는다. 설정은 `providers..interactionsEgress`이며 값은 `local`(기본)과 `native`다. + +### Before / After + +`ocx:src/protocols/guard.ts:17` — 판정은 feature 표현 가능성만 보고, 대상 공급자의 첨부 능력은 보지 않는다. + +```ts +// before +export function checkRepresentable(input: { inbound: Protocol; requestPath: readonly ProtocolHop[]; + features: Iterable; policy: "legacy" | "reject" }): RepresentableVerdict { + if (input.policy !== "reject") return { ok: true }; + const { effects } = featureEffectsForPath(input.inbound, input.requestPath, input.features); + const features = unrepresentableFeatures(effects); + return features.length === 0 ? { ok: true } : { ok: false, features, reasonCodes: ["feature-unrepresentable"] }; +} +``` + +```ts +// after (sketch) +export function checkRepresentable(input: { /* 기존 필드 */; attachments?: AttachmentCapability }): RepresentableVerdict { + const attachment = input.attachments ? attachmentVerdict(input.features, input.attachments) : undefined; + if (attachment && !attachment.ok) return attachment; // 첨부 전용 turn은 policy와 무관하게 send 전 400/413 + if (input.policy !== "reject") return { ok: true }; + /* 기존 판정 그대로 */ +} +``` + +## Dependencies + +040. G-024의 WS는 040의 계정별 egress, 강제 HTTP, pacing을 따라야 한다 (감사 r1 #4). G-022와 G-023은 040 없이 먼저 시작할 수 있다. 090의 outbound filter 위치는 이 단계의 codec 변경 뒤 확정한다. + +## Acceptance + +- 첨부만 있는 Codex turn을 이미지 미지원 대상에 보내면 업스트림 호출 전에 400과 이유가 나온다. 지원 대상에서는 첨부가 보존된다 (공급자별 fixture). +- `interactionsEgress: native`에서 create → GET → cancel → DELETE가 upstream id로 왕복한다. 다른 키 소유자의 id는 없는 id로 응답한다. pool의 active 계정이 바뀐 뒤에도 후속 조작과 연쇄 tool-result POST는 생성 계정으로 가고, 그 계정이 사라졌으면 409다. 생성 뒤 키 범위를 좁혀 destination이 더 이상 허용되지 않으면 GET/DELETE/cancel/연쇄 POST 모두 upstream send 0회로 거절된다. 기본값에서는 동작 변화 없음. +- xAI WS 모드에서 연속 turn이 history 전체를 재전송하지 않는다. WS 실패 시 HTTP로 돌아가되 이미 보낸 turn을 암묵적으로 재전송하지 않는다. +- fixture: 강제 HTTP 설정이 있으면 WS를 열지 않는다. pacing 설정이 있으면 WS 프레임도 같은 간격을 지킨다. 계정 egress proxy가 지정되면 WS 연결도 그 proxy를 쓴다. + +## Verification + +- 신규 `tests/responses/protocol-attachment-capability.test.ts`, `tests/adapters/google/google-interactions-egress.test.ts`, `tests/server/gemini-interactions-native-resource.test.ts`, `tests/providers/xai-ws-transport.test.ts` +- 기존 회귀: `tests/responses/protocol-guard.test.ts`, `tests/claude-integration/claude-inbound-*.test.ts`, Gemini Interactions codec 테스트, `tests/responses/openai-responses-passthrough.test.ts` (캡 4809줄; 새 케이스는 sibling 파일) +- `bun run typecheck`, `bun run test:changed`, `bun run structure:check`; WS는 `ci:full` + +## Risks + +- **File-size ratchet:** 캡에 없는 파일은 2000줄 이상이면 실패하고(`NEW_OVERSIZED`), 캡 파일은 캡을 넘으면 실패한다(`tests/fixtures/file-size-baseline.json`). `openai-responses-passthrough.test.ts`는 캡 파일이다. +- **Lab 경계:** `tests/lab/core-lab-boundary.test.ts`의 보호 목록(`ocx:tests/lab/core-lab-boundary.test.ts:23`: `src/router.ts`, `src/server/lifecycle.ts`, `src/server/responses/core.ts`, `src/server/management-api.ts`)에서 `src/lab/`으로 가는 import가 직접이든 간접이든 생기면 안 된다. +- **재전송:** xAI WS fallback은 fail-closed 재전송 게이트를 따른다. +- **Privacy:** 첨부 바이너리·경로를 로그에 남기지 않는다. + +## Non-goals + +- 범용 TTS, legacy completions (G-042, G-043 비채택), Gemini Live (G-038 보류), embeddings/rerank (G-037 보류). diff --git a/devlog/_plan/261123_proxy_upstream_catchup/070_shared_proxy_governance.md b/devlog/_plan/261123_proxy_upstream_catchup/070_shared_proxy_governance.md new file mode 100644 index 00000000000..170bc2c71f3 --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/070_shared_proxy_governance.md @@ -0,0 +1,116 @@ +# 070 — 공유 프록시 거버넌스: 발급 키 단위 동시 상한, 키 예산, 키 만료, 관리 감사 + +**Gaps:** G-025, G-026, G-027, G-028 +**Depends on:** 040 +**Size:** L + +> 줄 번호와 줄 수는 OpenCodex `origin/dev` `9e0e298ef9` 기준이며, 줄 수는 ratchet의 `countLines`(`ocx:scripts/file-size-ratchet.ts:109`)로 센 값이다. 구현 단위를 열 때 현재 `dev`에서 다시 확인한다. + +## Goal + +proxy 하나를 여러 사람이 쓰는 팀이 발급 키마다 동시 실행 상한, request/token 예산, 만료 시각을 정하고, 키와 설정 변경을 감사 기록으로 본다. 정책이 없는 설치의 동작은 바뀌지 않는다. + +## Why + +- **G-025** — sub2api는 인증 사용자 기준 slot을 HTTP와 WS turn에 집행한다(`s2a:backend/internal/handler/openai_gateway_handler.go:614`) (`004` L4-03). OpenCodex admission 주체는 secret에서 파생된 키 단위다(`ocx:src/server/auth-cors.ts:483`). 070은 키 단위 상한을 만들고 키 간 집계는 G-057로 보류한다 (감사 r1 #3). +- **G-026** — sub2api는 키별 누적 비용과 5h/1d/7d window를 검사한다 (`005` L5-1). OpenCodex의 spend reservation ledger는 physical send 단위로 token을 예약하고(`ocx:src/lib/spend-reservation-ledger.ts:158`), 그 identity 범위는 upstream credential이다(`ocx:src/server/responses/request-spend.ts:174`). 발급 키 window와 request 수는 이 ledger로 표현되지 않는다 (감사 r3 #2). 그래서 별도 차원을 만들되 ledger의 durable 예약·unresolved 규칙을 그대로 따른다. +- **G-027** — sub2api는 키 만료를 인증 middleware에서 검사한다(`s2a:backend/internal/service/api_key_service.go:590`). OpenCodex 만료는 rotation 대기 secret에만 있다(`ocx:src/types/config.ts:365`) (`005` L5-2). +- **G-028** — sub2api는 관리 이벤트를 기록한다 (`005` L5-4). OpenCodex에는 구조화된 관리 감사 저장이 없다(`ocx:src/server/management/route-registry.ts:352`). + +## Changes + +| 경로 | 의도 | 내용 | +|---|---|---| +| `src/types/api-key-policy.ts` | NEW | `{maxConcurrentTurns?, budget?: {window: "5h" \| "1d" \| "7d"; requests?; tokens?}, expiresAt?}` | +| `src/types/config.ts` | MODIFY | `OcxApiKeyEntry`(`ocx:src/types/config.ts:336`)에 `policy?: ApiKeyPolicy` 한 필드 | +| `src/server/auth-cors.ts` | MODIFY | 1540줄. 키 principal 결정 지점(`ocx:src/server/auth-cors.ts:483`)에서 정책을 admission 결과에 첨부 | +| `src/server/key-admission.ts` | NEW | 만료·동시 상한 판정, 예산은 ledger reservation 호출. 동시 상한은 040 `account-lease.ts`를 `{ns: "caller", keyId}` 키로 재사용 | +| `src/lib/key-window-budget.ts` | NEW | 발급 키 window 차원 `{keyId, window, requests, tokens}`. 같은 state-directory SQLite lease 아래 durable 예약, settle, unresolved residue | +| `src/server/responses/request-spend.ts` | MODIFY | 물리 send 직전의 blocking 예약 지점 세 곳 — `bookedLedger.reserve`(`ocx:src/server/responses/request-spend.ts:342`, `ocx:src/server/responses/request-spend.ts:590`)와 이미 enforce 중인 정책의 seed 경로 `ensureSeed` → `reserveSeed`(`ocx:src/server/responses/request-spend.ts:555`, `ocx:src/server/responses/request-spend.ts:407`) — 에서 같은 send의 token ceiling을 key-window에도 예약하고 terminal usage로 정산. 사후 보고 경로 `reportFromSeed`(`ocx:src/server/responses/request-spend.ts:493`)에서는 예약할 수 없으므로 아래 규칙을 따른다 | +| `src/server/index/serve-options.ts` | MODIFY | standalone Realtime·dictation WS는 자체 인증 뒤 `tryAdmitTurn`을 직접 부른다(`ocx:src/server/index/serve-options.ts:1690`). 그 직후, upstream socket 결정(`ocx:src/server/index/serve-options.ts:1706`) 전에 `admitKeyTurn` 호출 (만료·상한, 090의 wire 거절) | +| `src/server/admitted-http-turn.ts` | MODIFY | `createAdmittedHttpTurn`(`ocx:src/server/admitted-http-turn.ts:15`) 시작 시 `admitKeyTurn`, 종료·취소 시 정산·해제 | +| `src/server/index/websocket-handler.ts` | MODIFY | 프레임별 turn 시작(`ocx:src/server/index/websocket-handler.ts:320`)에서 handshake admission을 재사용하지 않고 매 turn `admitKeyTurn`을 다시 호출 (만료·예산·상한) | +| `src/storage/admin-audit.ts` | NEW | `{at, actorKind, action, targetKind, targetId, result}` allowlist 필드만, retention | +| `src/server/management/route-registry.ts` | MODIFY | `mutates: true` 항목(예: `ocx:src/server/management/route-registry.ts:167`) 실행 뒤 audit hook | +| `gui/src/pages/ApiKeys.tsx` | MODIFY | 컴포넌트(`ocx:gui/src/pages/ApiKeys.tsx:131`)에서 sibling `ApiKeyPolicyEditor.tsx` 렌더 | + +예산 계약 (감사 r2 #2, r3 #2): + +- **request 단위:** turn admission에서 1건을 원자적으로 예약한다. retry·failover로 physical send가 늘어도 turn당 1건이다. turn이 업스트림에 한 번도 가지 않고 끝나면 해제한다. +- **token 단위:** request preparation이 `inputTokens + outputCeilingTokens`를 정한 뒤(기존 send 예약과 같은 시점) send마다 예약하고, terminal usage로 정산한다. usage frame을 잃은 send는 unresolved로 남아 한도에서 빠지지 않는다. +- **seed 재사용·재결합:** key-window 예약은 ledger와 같은 `sendId`에 묶는다. seed가 재사용되면 새 예약을 만들지 않고, retire·rebind(`ocx:src/server/responses/request-spend.ts:400`)되면 예약도 함께 옮겨 정확히 한 번만 계산한다 (감사 r5 #1). +- **사후 보고 send:** transport가 dispatch 뒤에야 보고하는 retry(`reportFromSeed`)는 hard ceiling으로 막을 수 없다. token 예산이 있는 키에서는 그런 transport-owned retry를 끄고(예약 없는 추가 send 0회), 끌 수 없는 경로는 admission에서 거절한다 (감사 r4 #2). +- **window:** 예약은 admission 시각의 window에 속한다. window는 고정 경계(5h는 UTC 0시 기준 5시간 단위, 1d·7d는 UTC 0시)로 굴러가며, 경계를 넘은 진행 중 turn의 정산은 원래 window에 반영된다. + +```ts +export async function admitKeyTurn(key: AuthenticatedKey | undefined, now: number): Promise< + | { ok: true; lease: AttachableLease } // turn lease에 attach. 정산은 request spend tracker가 terminal usage로, 미사용 예약 반환은 lease 종료 시 + | { ok: false; status: 401 | 429; reason: "key_expired" | "budget_exhausted" | "caller_concurrency" }>; +// 거절은 refusal log에 reason을 남기고, Claude Code 요청이면 Messages 형식 오류로 돌려준다. +// 정책 없는 키와 무인증 loopback 요청은 즉시 ok (기존 동작) +``` + +### Before / After + +`ocx:src/server/admitted-http-turn.ts:41` — turn lease에는 workflow lease만 붙고, 응답이 다른 소유자에게 넘어가면(`isTransferred`) 여기서 해제하지 않는다. + +```ts +// before +if (workflow?.admitted) lease.attach(workflow.lease); +try { + const response = await runAdmittedBodyWork(req, policy, configuredLimit(), () => work(lease), /* … */); + if (!lease.isTransferred()) lease.release(); + return response; +} catch (error) { lease.release(); throw error; } +``` + +```ts +// after (sketch) +if (workflow?.admitted) lease.attach(workflow.lease); +const keyTurn = await admitKeyTurn(admittedKeyOf(req), Date.now()); // 040 lease 획득이 async이므로 await. 정책 없는 키는 no-op lease +if (!keyTurn.ok) { + lease.release(); + // workflow 거절(admitted-http-turn.ts:39)과 같은 경로: Messages 형식 정규화와 refusal log + return withCors(await normalizeMessagesProxyRefusal(req, map(keyRefusalResponse(keyTurn, refusalLog))), req, policy); +} +lease.attach(keyTurn.lease); +bindKeyTurnToSpendTracker(keyTurn.lease, req); // AdmissionLease.release()는 usage를 받지 않으므로 정산은 request spend tracker가 맡는다 +// keyTurn.lease는 turn lease가 끝날 때(전송이 넘겨진 경우 그 소유자가 끝낼 때) 함께 끝난다: +// physical send가 있었으면 terminal usage로 settle, 하나도 없었으면 request 예약을 반환한다. +try { /* runAdmittedBodyWork … 기존 그대로 */ } catch (error) { lease.release(); throw error; } +``` + +## Dependencies + +040. 040은 lease 구현(용량 계산)만 제공한다. 호출자 신원은 발급 키다. + +## Acceptance + +- 정책이 없는 설치에서 요청 경로 동작이 바뀌지 않는다 (기존 admission 테스트 통과). +- request 예산이 1 남은 키로 동시에 두 turn을 시작하면 정확히 하나만 통과하고 다른 하나는 429 `budget_exhausted`다. +- token 예산이 한 turn의 ceiling만큼만 남은 키로 동시에 두 turn을 시작하면 하나만 token 예약에 성공한다. retry가 일어나도 request 수는 1로 남는다. +- fixture: workflow spend ceiling과 발급 키 token cap이 동시에 걸린 상태에서 seed 경로로 들어온 send가 두 한도 모두에 한 번씩만 예약되고, seed가 재사용되어도 key-window 사용량이 늘지 않는다. +- fixture: 첫 send가 마지막 token 허용량을 쓴 뒤 transport-owned retry가 필요해지면 추가 send는 0회이고 429 `budget_exhausted`로 끝난다. +- Realtime·dictation WS도 만료된 키에서 upstream socket을 열지 않는다. +- 재시작 뒤에도 window 사용량이 ledger 기준으로 유지되고, window가 지나면 다시 허용된다. +- 열린 WS 세션에서 키 만료 시각이 지나면 그 뒤 프레임의 새 turn은 401 `key_expired`이고, 이미 진행 중인 turn은 끝까지 간다. +- `maxConcurrentTurns: 1` 키의 동시 두 번째 turn은 429 `caller_concurrency`다. +- Claude Code(Messages) 요청이 키 정책으로 거절되면 Messages 형식 오류를 받고, request log에 거절 reason이 남는다. +- 키 발급·폐기와 설정 변경이 감사 목록에 나오며 요청 원문·credential·계정 식별자가 없다. + +## Verification + +- 신규 `tests/server/key-admission.test.ts`, `tests/server/key-admission-websocket.test.ts`, `tests/lib/key-window-budget.test.ts`, `tests/storage/admin-audit.test.ts` +- 기존 회귀: `tests/server/` auth·admission·API key 테스트, spend reservation ledger 테스트 +- `bun run typecheck`, `bun run test:changed`, `bun run structure:check`, `bun run privacy:scan`, `bun run lint:gui` + +## Risks + +- **File-size ratchet:** 캡에 없는 파일은 2000줄 이상이면 실패하고(`NEW_OVERSIZED`), 캡 파일은 캡을 넘으면 실패한다(`tests/fixtures/file-size-baseline.json`). `auth-cors.ts` 1540, `types/config.ts` 1939 — 로직은 sibling. `spend-reservation-ledger.ts`는 수정하지 않는다. +- **Lab 경계:** `tests/lab/core-lab-boundary.test.ts`의 보호 목록(`ocx:tests/lab/core-lab-boundary.test.ts:23`: `src/router.ts`, `src/server/lifecycle.ts`, `src/server/responses/core.ts`, `src/server/management-api.ts`)에서 `src/lab/`으로 가는 import가 직접이든 간접이든 생기면 안 된다. admission은 요청 경로다. +- **잘못된 귀속:** 무인증 loopback이나 익명 키를 사용자로 묶지 않는다. +- **USD 예산:** 가격 근거와 정산 규칙이 없으므로 1차는 request/token만. + +## Non-goals + +- 키 간 owner 집계 (G-057 보류), 사용자 계정·RBAC·결제 (G-049 비채택), IP 제한 (G-041 보류). diff --git a/devlog/_plan/261123_proxy_upstream_catchup/080_observability.md b/devlog/_plan/261123_proxy_upstream_catchup/080_observability.md new file mode 100644 index 00000000000..0aaf5edac63 --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/080_observability.md @@ -0,0 +1,80 @@ +# 080 — 관측성: Claude Code statusline, 운영 알림, 네이티브 세션 사용량, 읽기 전용 관리 MCP + +**Gaps:** G-029, G-030, G-032, G-033 +**Depends on:** 070 +**Size:** L + +> 줄 번호와 줄 수는 OpenCodex `origin/dev` `9e0e298ef9` 기준이며, 줄 수는 ratchet의 `countLines`(`ocx:scripts/file-size-ratchet.ts:109`)로 센 값이다. 구현 단위를 열 때 현재 `dev`에서 다시 확인한다. + +## Goal + +Claude Code 사용자가 statusline에서 현재 세션의 실제 대상과 quota를 본다. 운영자는 실패·지연·429 임계치 알림을 켤 수 있고, proxy를 거치지 않은 네이티브 Codex/Claude 세션 사용량도 출처 표시와 함께 본다. 관리 권한이 있는 에이전트는 읽기 전용 MCP로 health·usage·키 metadata를 조회한다. + +## Why + +- **G-029** — magpie는 Claude Code statusline에 route와 quota/cache를 보여 준다 (`006` L6-2). OpenCodex에는 quota와 usage 읽기가 있으나(`ocx:src/server/hub-usage.ts:10`) statusline 연결이 없다. +- **G-030** — sub2api는 규칙·이벤트·silence를 갖는다 (`005` L5-3). OpenCodex는 metrics export만 있다(`ocx:src/server/request-metrics.ts:15`). +- **G-032** — cc-switch는 proxy 밖 세션 파일에서 비용을 집계한다 (`003` L3-5). +- **G-033** — sub2api는 관리 MCP를 제공한다(`s2a:backend/internal/server/routes/mcp.go:28`) (`005` L5-5). OpenCodex는 CLI와 `skills/ocx/`로 같은 정보를 준다(`ocx:skills/ocx/SKILL.md:174`). +- **G-031**은 CLOSED다: `/api/request-history`와 `/api/logs`가 cursor 조회를 이미 제공한다 (감사 r1 #2). + +## Changes + +| 경로 | 의도 | 내용 | +|---|---|---| +| `src/server/statusline-route.ts` | NEW | 인증된 키로 `{route:{provider, model}, quota:{window, remainingPct}}`. 기존 snapshot만 읽고 vendor probe 없음 | +| `src/providers/quota-snapshot-read.ts` | NEW | snapshot 읽기 helper. `src/providers/quota.ts`는 캡 558줄에 닿아 있어 수정하지 않는다 | +| `src/cli/claude-statusline.ts` | NEW | `ocx claude statusline install\|uninstall`, 기존 statusline 보존·복원 | +| `src/cli/claude.ts` | MODIFY | 970줄. 하위 명령 등록 한 줄 (명령 진입 `cmdClaude` `ocx:src/cli/claude.ts:849`) | +| `src/server/ops-alerts.ts` | NEW | metrics window 임계치, 소음 억제, 회복 상태. 기본 off. 외부 webhook은 명시 설정 | +| `src/server/request-metrics.ts` | MODIFY | 프로토콜·결과 분류(`ocx:src/server/request-metrics.ts:15`)를 ops-alerts가 구독하도록 listener 노출 | +| `src/usage/native-session-import.ts` | NEW | 사용자가 지정한 세션 디렉터리를 metadata만 읽음. 요청 경로 밖, 중복 식별, 추정치 표시 | +| `src/server/management/mcp-readonly.ts` | NEW | health·usage·키 metadata 3개 tool. 관리 권한 필요, inference 키 거부, 070 감사 기록 | +| `skills/ocx/SKILL.md` | MODIFY | 새 CLI 표면 (`ocx:skills/ocx/SKILL.md:174` 섹션) 문서와 `bun run skill:surface` | + +### Before / After + +`ocx:src/cli/claude.ts:849` — `ocx claude`는 하위 명령 없이 바로 실행 경로로 간다. + +```ts +// before +export async function cmdClaude(args: string[]): Promise { + const config = loadConfig(); + const clientState = readClientConnectionState(); + /* preflight → native 또는 proxy 실행 */ +``` + +```ts +// after (sketch) +export async function cmdClaude(args: string[]): Promise { + if (args[0] === "statusline") return cmdClaudeStatusline(args.slice(1)); // install | uninstall, claude-statusline.ts + const config = loadConfig(); + /* 기존 그대로 */ +``` + +## Dependencies + +070. statusline 데이터 범위는 키 정책을 따르고, 관리 MCP 호출은 070 감사 이벤트를 남긴다. + +## Acceptance + +- statusline 설치 뒤 Claude Code 하단에 현재 route와 quota가 보이고, uninstall하면 이전 statusline 설정이 복원된다. 출력에 email·credential이 없다. +- 알림 fixture: 429 비율이 임계치를 넘는 metrics 시퀀스에서 알림이 한 번 발생하고, 정상 시퀀스가 이어지면 회복 이벤트가 한 번 발생한다. 알림을 켜지 않으면 타이머와 외부 전송이 없다. +- 네이티브 세션 사용량은 "proxy 밖" 출처로 따로 표시되고 proxy usage와 이중 집계되지 않는다. +- 관리 키로 MCP의 세 tool을 읽을 수 있고, inference 전용 키는 거부된다. 쓰기 tool은 없다. + +## Verification + +- 신규 `tests/server/statusline-route.test.ts`, `tests/cli/claude-statusline.test.ts`, `tests/server/ops-alerts.test.ts`, `tests/usage/native-session-import.test.ts`, `tests/server/mcp-readonly.test.ts` +- `tests/ci-workflows/skill-ocx.test.ts` (`bun run skill:surface:check`) +- `bun run typecheck`, `bun run test:changed`, `bun run structure:check`, `bun run privacy:scan` + +## Risks + +- **File-size ratchet:** 캡에 없는 파일은 2000줄 이상이면 실패하고(`NEW_OVERSIZED`), 캡 파일은 캡을 넘으면 실패한다(`tests/fixtures/file-size-baseline.json`). `src/providers/quota.ts`는 캡 558줄에 닿아 있어 한 줄도 늘릴 수 없다. `usage/log.ts` 1965줄. +- **Lab 경계:** `tests/lab/core-lab-boundary.test.ts`의 보호 목록(`ocx:tests/lab/core-lab-boundary.test.ts:23`: `src/router.ts`, `src/server/lifecycle.ts`, `src/server/responses/core.ts`, `src/server/management-api.ts`)에서 `src/lab/`으로 가는 import가 직접이든 간접이든 생기면 안 된다. 관리 MCP 모듈은 `management-api.ts`가 namespace별로 지연 로드해야 한다. 알림 타이머는 opt-in 활성화 때만 시작한다. +- **Privacy:** 네이티브 세션 import는 본문을 읽지 않는다. + +## Non-goals + +- 범용 세션 매니저 (G-055 비채택), 관리 쓰기 MCP, 새 usage export API (G-031 CLOSED). diff --git a/devlog/_plan/261123_proxy_upstream_catchup/090_request_policy.md b/devlog/_plan/261123_proxy_upstream_catchup/090_request_policy.md new file mode 100644 index 00000000000..56ee9c58c98 --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/090_request_policy.md @@ -0,0 +1,77 @@ +# 090 — 요청 정책: outbound payload rule·요청 filter seam, 요청 masking + +**Gaps:** G-034, G-035 +**Depends on:** 060, 070 +**Size:** L + +> 줄 번호와 줄 수는 OpenCodex `origin/dev` `9e0e298ef9` 기준이며, 줄 수는 ratchet의 `countLines`(`ocx:scripts/file-size-ratchet.ts:109`)로 센 값이다. 구현 단위를 열 때 현재 `dev`에서 다시 확인한다. + +## Goal + +운영자가 특정 공급자/모델 요청에 반복되는 소수의 default·drop 규칙을 지정하고, 명시적으로 등록한 요청 filter를 실제 outbound body가 만들어진 지점에서 실행한다. 기본 off인 요청 masking으로 지정 패턴을 업스트림 전송 전에 가리고, 실패하면 물리적 전송이 한 번도 일어나지 않는다. + +## Why + +- **G-034** — CPA `payload` 설정(`002` L2-4)과 magpie `moejs`(`006` L6-3)는 변환 후 body 규칙을 준다. OpenCodex는 effort 정책(`ocx:src/server/effort-policy.ts:170`)과 outbound URL/headers hook(`ocx:src/plugins/upstream-hooks.ts:15`)뿐이다. +- **G-035** — magpie는 요청 masking을 한다(`mgp:internal/masking/masking.go:381`) (`006` L6-4). OpenCodex의 redaction은 로그·오류용이다(`ocx:src/server/responses/terminal-error-redaction.ts:103`). + +## Changes + +Outbound body는 `request-prepare.ts`가 아니라 adapter의 `buildRequest`에서 만들어지고, retry·recovery·OAuth refresh가 다시 만들며, native Messages는 따로 보낸다 (감사 r2 #3, r3 #1). 그래서 filter는 body가 만들어지거나 다시 만들어지는 모든 지점 뒤, 물리적 send 앞에 둔다. dispatcher에 들어가지 않는 경로는 admission에서 거절한다. + +| 경로 | 의도 | 내용 | +|---|---|---| +| `src/config/schema/payload-rules.ts` | NEW | `{match:{provider, model?, protocol?}, set?: Record, drop?: path[]}`, allowlist 경로만 | +| `src/plugins/outbound-filters.ts` | NEW | core 소유 slot `registerOutboundFilter({id, run})`. 등록이 없으면 호출 0회. 결과 `{ok: true; request} \| {ok: false; reason}` | +| `src/server/responses/adapter-dispatch.ts` | MODIFY | 1992줄, 여유 7줄. 첫 `buildRequest`(`ocx:src/server/responses/adapter-dispatch.ts:342`) 결과와 retry 재생성(`:663`) 결과에 각각 `applyOutboundFilters` 한 줄. 캐시된 same-target 재사용(`:660`)은 이미 필터된 요청이다 | +| `src/server/messages-native.ts` | MODIFY | native Messages 물리 send(`ocx:src/server/messages-native.ts:769`) 앞 `activeRequest`에 한 줄 | +| `src/server/responses/passthrough-dispatch.ts` | MODIFY | 1968줄(여유 31). 네 재생성 지점 모두에 한 줄씩: 첫 `buildRequest`(`ocx:src/server/responses/passthrough-dispatch.ts:390`), recovery 재생성(`ocx:src/server/responses/passthrough-dispatch.ts:1137`), Codex credential replay 재생성(`ocx:src/server/responses/passthrough-dispatch.ts:1308`), OAuth refresh 재생성(`ocx:src/server/responses/passthrough-dispatch.ts:1409`) | +| `src/server/key-admission.ts` (070) | MODIFY | masking이 켜진 키가 위 dispatcher를 거치지 않는 경로(image 생성 등, 그리고 standalone Realtime·dictation WS)를 요청하면 거절. 070이 HTTP·Responses WS turn과 standalone WS(`serve-options.ts:1690` 직후, upstream socket 결정 전)에 이미 연결한 `admitKeyTurn`에 경로 판정만 추가 | +| `src/server/inference/request-masking.ts` | NEW | deterministic 규칙(정규식 목록, 지정 필드), 원문 미보관. filter로 등록됨. 기본 off, 키별 정책은 070 키 모델 | +| `gui/src/pages/` 설정 | NEW 패널 | 규칙 편집과 dry-run (실제 요청 없음) | + +1차 지원 wire: 변환 adapter 경로(Responses↔Chat/Messages/Gemini), native Messages, Responses passthrough. 그 밖의 경로(예: realtime, image 생성)는 masking이 켜진 키라면 admission에서 거절하고, payload rule은 적용하지 않는다고 문서에 명시한다. + +### Before / After + +`ocx:src/server/responses/adapter-dispatch.ts:342` — build 결과가 바로 send 준비로 간다. + +```ts +// before +initialRequest = await transportState.activeAdapter.buildRequest(parsed, { /* … */ }); +refreshRequestToolAliases(initialRequest); +``` + +```ts +// after (sketch) — 같은 한 줄을 :663, passthrough :390/:1137/:1308/:1409, messages-native :769에도 +initialRequest = applyOutboundFiltersOrThrow(await transportState.activeAdapter.buildRequest(parsed, { /* … */ }), filterCtx); +refreshRequestToolAliases(initialRequest); +// applyOutboundFiltersOrThrow: 등록된 filter가 없으면 같은 객체를 그대로 반환. 실패하면 OutboundFilterRefusal을 던져 send 전에 종료. +``` + +## Dependencies + +060 (codec 변경 뒤 outbound 지점 확정), 070 (키별 정책 모델). + +## Acceptance + +- 규칙이 없는 설치에서 세 지점의 `applyOutboundFilters`는 같은 객체를 돌려주고 추가 parse·타이머가 없다. +- payload rule로 특정 모델 요청의 필드를 drop하면 그 요청에만 적용되고, 응답 SSE의 tool/reasoning/terminal frame은 그대로다. +- masking 규칙 오류 fixture: 첫 build에서 실패하면 물리적 fetch가 0회다. 첫 send가 끝난 뒤 retry·recovery·OAuth refresh 재생성에서 filter가 실패하면 **추가** fetch가 0회다 (adapter-dispatch, passthrough의 recovery·credential replay·OAuth refresh 각각). native Messages 경로도 같다. +- masking이 켜진 키로 범위 밖 wire를 호출하면 admission에서 거절되고 dispatcher가 호출되지 않는다. standalone Realtime·dictation WS에서는 upstream socket이 한 번도 열리지 않는다. + +## Verification + +- 신규 `tests/config/payload-rules.test.ts`, `tests/lib/plugin-outbound-filters.test.ts`, `tests/server/request-masking.test.ts`, `tests/server/request-masking-zero-send.test.ts` +- 기존 회귀: `tests/lib/plugin-upstream-hooks.test.ts`, `tests/lab/core-lab-boundary.test.ts` +- `bun run typecheck`, `bun run test:changed`, `bun run structure:check`, `bun run privacy:scan` + +## Risks + +- **File-size ratchet:** 캡에 없는 파일은 2000줄 이상이면 실패하고(`NEW_OVERSIZED`), 캡 파일은 캡을 넘으면 실패한다(`tests/fixtures/file-size-baseline.json`). `adapter-dispatch.ts`는 1992줄로 여유 7줄이다. 이 단계의 추가는 두 호출 줄로 끝나야 하며, 넘치면 먼저 기존 코드를 sibling으로 옮긴다. `passthrough-dispatch.ts` 1968줄. +- **Lab 경계:** `tests/lab/core-lab-boundary.test.ts`의 보호 목록(`ocx:tests/lab/core-lab-boundary.test.ts:23`: `src/router.ts`, `src/server/lifecycle.ts`, `src/server/responses/core.ts`, `src/server/management-api.ts`)에서 `src/lab/`으로 가는 import가 직접이든 간접이든 생기면 안 된다. filter slot은 `src/server/passive-route-linker.ts`와 같은 core 소유 등록 패턴으로만 채운다. +- **Privacy:** masking 전 원문을 로그·trace에 남기지 않는다. detector 다운로드·자동 업데이트 없음. + +## Non-goals + +- 응답 측 hook과 placeholder 복원 (G-059 보류), 플러그인 marketplace (G-047 비채택), provider-extension ABI (G-039 보류). diff --git a/devlog/_plan/261123_proxy_upstream_catchup/build_index.mjs b/devlog/_plan/261123_proxy_upstream_catchup/build_index.mjs new file mode 100644 index 00000000000..96bb943f1ce --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/build_index.mjs @@ -0,0 +1,77 @@ +#!/usr/bin/env node +// Builds index.html from 009_gap_matrix.md and the 0X0 phase docs. No network, no deps. +// Usage: node build_index.mjs +import { readFileSync, writeFileSync, readdirSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +const dir = dirname(fileURLToPath(import.meta.url)); +const read = (f) => readFileSync(join(dir, f), "utf8"); +const esc = (s) => String(s).replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); +const md = (s) => esc(s).replace(/\x60([^\x60]+)\x60/g, "$1").replace(/\*\*([^*]+)\*\*/g, "$1"); + +const matrix = read("009_gap_matrix.md"); +let header = null; +const rows = []; +for (const line of matrix.split("\n")) { + if (!header && /^\|\s*ID\s*\|/.test(line)) header = line.split("|").slice(1, -1).map((c) => c.trim()); + const m = line.match(/^\|\s*(G-\d{3})\s*\|/); + if (m) { const c = line.split("|").slice(1, -1).map((x) => x.trim()); if (c.length >= 7) rows.push(c); } +} +const phaseCol = header ? header.length - 1 : 7; + +const phases = readdirSync(dir).filter((f) => /^0[1-9]0_.*\.md$/.test(f)).sort().map((f) => { + const t = read(f); + const title = (t.match(/^#\s+(.*)$/m) || [, f])[1]; + const gaps = ((t.match(/^\*\*Gaps:\*\*(.*)$/m) || [, ""])[1].match(/G-\d{3}/g)) || []; + const dep = ((t.match(/^\*\*Depends on:\*\*(.*)$/m) || [, "—"])[1]).trim(); + const size = ((t.match(/^\*\*Size:\*\*(.*)$/m) || [, ""])[1]).trim(); + const goal = ((t.split(/^## Goal\s*$/m)[1] || "").trim().split(/\n\s*\n/)[0] || "").replace(/\n/g, " "); + return { f, id: f.slice(0, 3), title, gaps, dep, size, goal }; +}); +const research = readdirSync(dir).filter((f) => /^00\d_.*\.md$/.test(f)).sort(); + +const counts = { total: rows.length, adopted: rows.filter((r) => /^0\d0$/.test(r[phaseCol].replace(/[\x60*]/g, ""))).length }; +const ph = (r) => r[phaseCol].replace(/[\x60*]/g, ""); +counts.defer = rows.filter((r) => ph(r) === "DEFER").length; +counts.reject = rows.filter((r) => ph(r) === "REJECT").length; +counts.closed = rows.filter((r) => ph(r) === "CLOSED").length; + +const vClass = (v) => (/high|높/i.test(v) ? "hi" : /med|중/i.test(v) ? "md" : "lo"); +const html = '\n' + +'OpenCodex upstream catch-up roadmap
' + +'

OpenCodex upstream catch-up roadmap

CLIProxyAPI · cc-switch · sub2api · magpie 대비 부족한 점과 단계별 따라잡기 · generated from 009_gap_matrix.md by build_index.mjs
' + +'
' + counts.total + 'gaps
' + counts.adopted + 'adopted
' + counts.defer + 'deferred
' + counts.reject + 'rejected
' + counts.closed + 'already in OpenCodex
' + phases.length + 'phases
' + +'

Phase timeline

' + phases.map((p) => + '
' + p.id + (p.size ? ' · ' + esc(p.size) : '') + '

' + md(p.title.replace(/^0\d0\s*[—-]\s*/, "")) + '

' + + '

depends on: ' + md(p.dep) + '

' + md(p.goal.slice(0, 320)) + '

' + p.gaps.map((g) => '').join("") + '
').join("") + '
' + +'

Gap matrix

' + +'' + (header || []).map((h, i) => '').join("") + '' + + rows.map((r) => { const ph = r[phaseCol].replace(/[\x60*]/g, ""); return '' + + r.map((c, i) => { if (i === phaseCol && /^0\d0$/.test(ph)) { const p = phases.find((x) => x.id === ph); return ''; } + if (header && /가치|value/i.test(header[i] || "")) return ''; return ''; }).join("") + ''; }).join("") + +'
' + esc(h) + '
' + ph + '' + md(c) + '' + md(c) + '
' + +'

Research documents

' + +'
\n'; +writeFileSync(join(dir, "index.html"), html); +console.log("index.html: " + rows.length + " gaps, " + phases.length + " phases"); diff --git a/devlog/_plan/261123_proxy_upstream_catchup/check-selftest.mjs b/devlog/_plan/261123_proxy_upstream_catchup/check-selftest.mjs new file mode 100644 index 00000000000..4401b19d953 --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/check-selftest.mjs @@ -0,0 +1,46 @@ +#!/usr/bin/env node +// Regression cases for check.mjs: copies this unit to a temp dir, injects one defect per case, +// and asserts check.mjs exits as expected. Usage: node check-selftest.mjs +import { cpSync, mkdtempSync, readFileSync, writeFileSync, existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import { spawnSync } from "node:child_process"; + +const dir = dirname(fileURLToPath(import.meta.url)); +const pinned = resolve(dir, "../../../.tmp/chase/opencodex-dev"); +const cases = [ + { name: "baseline passes", expect: 0, edit: () => {} }, + { name: "anchor without line number fails", expect: 1, edit: (d) => sub(d, "080_observability.md", "ocx:src/cli/claude.ts:849", "ocx:src/cli/claude.ts:") }, + { name: "pin absent + earlier NEW creator passes", expect: 0, pin: false, edit: () => {} }, + { name: "pin absent + creator removed fails", expect: 1, pin: false, edit: (d) => sub(d, "070_shared_proxy_governance.md", "| \x60src/server/key-admission.ts\x60 | NEW", "| \x60src/server/key-admission-x.ts\x60 | NEW") }, + { name: "dependency mismatch fails", expect: 1, edit: (d) => sub(d, "060_wire_fidelity.md", "**Depends on:** 040", "**Depends on:** none") }, + { name: "adopted gap missing from phase doc fails", expect: 1, edit: (d) => sub(d, "040_pool_scheduling_egress.md", "**Gaps:** G-012, ", "**Gaps:** ") }, + { name: "non-adopted id in phase doc fails", expect: 1, edit: (d) => sub(d, "090_request_policy.md", "**Gaps:** G-034, G-035", "**Gaps:** G-034, G-035, G-059") }, + { name: "network resource in html fails", expect: 1, edit: (d) => sub(d, "index.html", "", "") }, + { name: "phase doc without before/after sketch fails", expect: 1, edit: (d) => sub(d, "060_wire_fidelity.md", "// before\nexport function checkRepresentable", "export function checkRepresentable") }, + { name: "MODIFY row without anchor fails", expect: 1, edit: (d) => sub(d, "040_pool_scheduling_egress.md", "(\x60ocx:src/server/messages-native-oauth.ts:120\x60)", "") }, +]; +function sub(d, file, a, b) { + const p = join(d, file); + const t = readFileSync(p, "utf8"); + if (!t.includes(a)) throw new Error("selftest anchor missing in " + file + ": " + a); + writeFileSync(p, t.split(a).join(b)); +} +let bad = 0; +for (const c of cases) { + const root = mkdtempSync(join(tmpdir(), "ocx-catchup-check-")); + const d = join(root, "unit"); + cpSync(dir, d, { recursive: true }); + let src = readFileSync(join(d, "check.mjs"), "utf8"); + const target = c.pin === false ? join(root, "no-such-pin") : pinned; + src = src.replace('resolve(dir, "../../../.tmp/chase/opencodex-dev")', JSON.stringify(target)); + writeFileSync(join(d, "check.mjs"), src); + c.edit(d); + const r = spawnSync(process.execPath, [join(d, "check.mjs")], { encoding: "utf8" }); + const ok = r.status === c.expect; + if (!ok) bad++; + console.log((ok ? "ok " : "FAIL ") + c.name + " (exit " + r.status + ", expected " + c.expect + ")" + (ok ? "" : "\n" + r.stdout + r.stderr)); +} +if (!existsSync(pinned)) console.log("note: pinned export absent; pin-present cases ran against a missing path"); +process.exit(bad ? 1 : 0); diff --git a/devlog/_plan/261123_proxy_upstream_catchup/check.mjs b/devlog/_plan/261123_proxy_upstream_catchup/check.mjs new file mode 100644 index 00000000000..5343abd9ae6 --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/check.mjs @@ -0,0 +1,162 @@ +#!/usr/bin/env node +// Mechanical gate for devlog/_plan/261123_proxy_upstream_catchup (c6). +// Usage: node check.mjs (run from any cwd; resolves paths relative to this file) +import { readFileSync, existsSync, readdirSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const dir = dirname(fileURLToPath(import.meta.url)); +const errors = []; +const fail = (m) => errors.push(m); +const read = (f) => readFileSync(join(dir, f), "utf8"); + +// 1. research docs present, cite both sides, carry NOT RUN +const research = ["000_plan.md","001_cliproxyapi_wire.md","002_cliproxyapi_ops.md","003_ccswitch.md","004_sub2api_gateway.md","005_sub2api_platform.md","006_magpie_gateway.md","007_magpie_clients.md","008_opencodex_baseline.md","009_gap_matrix.md"]; +const refPrefix = {"001":"cpa:","002":"cpa:","003":"ccs:","004":"s2a:","005":"s2a:","006":"mgp:","007":"mgp:"}; +for (const f of research) { + if (!existsSync(join(dir, f))) { fail("missing research doc " + f); continue; } + const t = read(f); + if (!/NOT RUN/.test(t)) fail(f + ": no NOT RUN section"); + const n = f.slice(0, 3); + if (refPrefix[n]) { + if (!t.includes(refPrefix[n])) fail(f + ": no " + refPrefix[n] + " reference citation"); + if (!/ocx:[\w./-]+:\d+/.test(t)) fail(f + ": no ocx:: citation"); + } + if (n === "008" && !/ocx:[\w./-]+:\d+/.test(t)) fail(f + ": baseline has no ocx path:line citation"); +} + +// 2. gap matrix rows: | G-xxx | ... | phase | (phase = 0X0 | REJECT | DEFER) +const matrix = existsSync(join(dir, "009_gap_matrix.md")) ? read("009_gap_matrix.md") : ""; +const rows = new Map(); +for (const line of matrix.split("\n")) { + const m = line.match(/^\|\s*(G-\d{3})\s*\|(.*)\|\s*$/); + if (!m) continue; + const cells = m[2].split("|").map((c) => c.trim()); + if (cells.length < 6) continue; // other tables (e.g. DEFER/REJECT reasons) cite ids too + const phase = cells[cells.length - 1].replace(/[\x60*]/g, ""); + if (rows.has(m[1])) fail("duplicate matrix id " + m[1]); + rows.set(m[1], { phase, cells }); + if (cells.length < 6) fail(m[1] + ": matrix row has fewer than 7 columns"); + if (!/^(0[1-9]0|REJECT|DEFER|CLOSED)$/.test(phase)) fail(m[1] + ": phase cell '" + phase + "' must be 0X0, REJECT, DEFER or CLOSED"); +} +if (rows.size === 0) fail("009_gap_matrix.md has no G-xxx rows"); + +// 3. phase docs: decade docs 0X0_*.md with a "Gaps:" line +const phaseDocs = readdirSync(dir).filter((f) => /^0[1-9]0_.*\.md$/.test(f)).sort(); +const usedPhases = new Set([...rows.values()].map((r) => r.phase).filter((p) => /^0\d0$/.test(p))); +const seen = new Map(); +const decades = phaseDocs.map((f) => f.slice(0, 3)); +for (let i = 0; i < decades.length; i++) { + const want = String((i + 1) * 10).padStart(3, "0"); + if (decades[i] !== want) fail("phase docs not contiguous: expected " + want + " got " + decades[i]); +} +for (const p of usedPhases) if (!decades.includes(p)) fail("matrix references phase " + p + " but no " + p + "_*.md exists"); +for (const f of phaseDocs) { + const t = read(f); + const p = f.slice(0, 3); + const g = t.match(/^\*\*Gaps:\*\*(.*)$/m); + if (!g) { fail(f + ": no **Gaps:** line"); continue; } + const ids = [...g[1].matchAll(/G-\d{3}/g)].map((x) => x[0]); + if (ids.length === 0) fail(f + ": **Gaps:** line lists no ids"); + for (const id of ids) { + if (!rows.has(id)) fail(f + ": " + id + " not in matrix"); + else if (rows.get(id).phase !== p) fail(f + ": " + id + " assigned to " + rows.get(id).phase + " in matrix"); + if (seen.has(id)) fail(id + " appears in both " + seen.get(id) + " and " + f); + seen.set(id, f); + } + for (const h of ["## Goal","## Why","## Changes","## Dependencies","## Acceptance","## Verification","## Risks","## Non-goals"]) { + if (!t.includes(h)) fail(f + ": missing section '" + h + "'"); + } + // Before/After: inside Changes, a quoted pinned anchor plus a "// before" and a "// after" code block. + const ba = ((t.split(/^## Changes\s*$/m)[1] || "").split(/^## /m)[0].split(/^### Before \/ After\s*$/m)[1]) || ""; + if (!ba) fail(f + ": no '### Before / After' subsection in Changes"); + else { + if (!/ocx:[\w./@-]+:[1-9]\d*/.test(ba)) fail(f + ": Before / After names no ocx:: location"); + const blocks = [...ba.matchAll(/```\w*\n([\s\S]*?)```/g)].map((x) => x[1]); + if (!blocks.some((b) => /^\/\/ before/m.test(b))) fail(f + ": Before / After has no '// before' code block"); + if (!blocks.some((b) => /^\/\/ after/m.test(b))) fail(f + ": Before / After has no '// after' code block"); + } +} +for (const [id, r] of rows) if (/^0\d0$/.test(r.phase) && !seen.has(id)) fail(id + ": adopted for " + r.phase + " but absent from that phase doc"); +for (const [id, r] of rows) if (!/^0\d0$/.test(r.phase) && seen.has(id)) fail(id + ": " + r.phase + " in matrix but listed in " + seen.get(id)); + +// 3b. declared dependencies: 009 phase table "| [0X0](file) | topic | gaps | deps | why |" must match each doc's **Depends on:** and point backwards +const normDeps = (s) => (s.match(/0[1-9]0/g) || []).sort().join(","); +const tableDeps = new Map(); +for (const line of matrix.split("\n")) { + const m = line.match(/^\|\s*\[(0[1-9]0)\]\(([^)]+)\)\s*\|/); + if (!m) continue; + const cells = line.split("|").slice(1, -1).map((c) => c.trim()); + tableDeps.set(m[1], normDeps(cells[3] || "")); + if (!existsSync(join(dir, m[2]))) fail("009 phase table links missing doc " + m[2]); +} +for (const f of phaseDocs) { + const p = f.slice(0, 3); + const dl = (read(f).match(/^\*\*Depends on:\*\*(.*)$/m) || [, null])[1]; + if (dl === null) { fail(f + ": no **Depends on:** line"); continue; } + const deps = normDeps(dl); + if (!tableDeps.has(p)) fail("009 phase table has no row for " + p); + else if (tableDeps.get(p) !== deps) fail(f + ": Depends on '" + deps + "' differs from 009 table '" + tableDeps.get(p) + "'"); + for (const d of deps ? deps.split(",") : []) { + if (Number(d) >= Number(p)) fail(f + ": depends on later or same phase " + d); + if (!decades.includes(d)) fail(f + ": depends on missing phase " + d); + } +} + +// 3c. Changes tables: every MODIFY row names a pinned anchor; every ocx: anchor resolves when the pinned export is present +const pinned = resolve(dir, "../../../.tmp/chase/opencodex-dev"); +const havePinned = existsSync(pinned); +let anchors = 0; +for (const f of phaseDocs) { + const t = read(f); + const sec = (t.split(/^## Changes\s*$/m)[1] || "").split(/^## /m)[0]; + for (const line of sec.split("\n")) { + if (!line.startsWith("| `")) continue; + const cells = line.replace(/\\\|/g, "\u0000").split("|").map((x) => x.trim()); + const path = cells[1] || "", intent = cells[2] || ""; + if (!/^MODIFY/.test(intent) || path.includes("*")) continue; + const files = [...path.matchAll(/`([^`]+\.[a-z]+)`/g)].map((x) => x[1]); + if (files.length === 0) fail(f + ": MODIFY row names no concrete file: " + path); + for (const file of files) { + const esc = file.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const anchored = new RegExp("ocx:" + esc + ":[1-9]\\d*").test(line); + const inPin = havePinned && existsSync(join(pinned, file)); + if (inPin || (!havePinned && anchored)) { + if (!anchored) fail(f + ": MODIFY " + file + " has no matching ocx:" + file + ": anchor"); + } else { + const creator = phaseDocs.filter((g) => g < f).find((g) => new RegExp("\\| `" + file.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "`[^|]*\\| NEW").test(read(g))); + if (!creator) fail(f + ": MODIFY " + file + " is not in the pinned export and no earlier phase creates it"); + } + } + } + for (const m of t.matchAll(/ocx:([\w./@-]+):(\d*)/g)) { + if (!/^[1-9]\d*$/.test(m[2])) { fail(f + ": anchor without a positive line number: " + m[0]); continue; } + anchors++; + if (!havePinned) continue; + const p = join(pinned, m[1]); + if (!existsSync(p)) { fail(f + ": anchor file missing in pinned export: " + m[0]); continue; } + const n = readFileSync(p, "utf8").split("\n").length; + if (+m[2] < 1 || +m[2] > n) fail(f + ": anchor line out of range: " + m[0]); + } +} +console.log("phase anchors=" + anchors + (havePinned ? " (resolved against pinned export)" : " (pinned export absent: syntax only)")); + +// 4. index.html: exists, offline, relative links resolve +if (!existsSync(join(dir, "index.html"))) fail("missing index.html"); +else { + const h = read("index.html"); + for (const m of h.matchAll(/<(script|link|img|iframe)\b[^>]*(src|href)="(https?:)?\/\/[^"]+"/gi)) fail("index.html loads a network resource: " + m[0].slice(0, 80)); + for (const m of h.matchAll(/href="([^"#]+)(#[^"]*)?"/g)) { + const t = m[1]; + if (/^(https?:|mailto:)/.test(t)) continue; + if (!existsSync(resolve(dir, decodeURIComponent(t)))) fail("index.html link target missing: " + t); + } + for (const id of rows.keys()) if (!h.includes(id)) fail("index.html does not show " + id); + for (const d of decades) if (!h.includes(d)) fail("index.html does not show phase " + d); +} + +const count = (k) => [...rows.values()].filter((r) => r.phase === k).length; +const adopted = [...rows.values()].filter((r) => /^0\d0$/.test(r.phase)).length; +console.log("gaps=" + rows.size + " adopted=" + adopted + " defer=" + count("DEFER") + " reject=" + count("REJECT") + " closed=" + count("CLOSED") + " phases=" + decades.length + " (" + decades.join(",") + ")"); +if (errors.length) { console.error(errors.map((e) => "FAIL " + e).join("\n")); process.exit(1); } +console.log("check.mjs: OK"); diff --git a/devlog/_plan/261123_proxy_upstream_catchup/index.html b/devlog/_plan/261123_proxy_upstream_catchup/index.html new file mode 100644 index 00000000000..a1437ed2d04 --- /dev/null +++ b/devlog/_plan/261123_proxy_upstream_catchup/index.html @@ -0,0 +1,2 @@ + +OpenCodex upstream catch-up roadmap

OpenCodex upstream catch-up roadmap

CLIProxyAPI · cc-switch · sub2api · magpie 대비 부족한 점과 단계별 따라잡기 · generated from 009_gap_matrix.md by build_index.mjs
60gaps
34adopted
9deferred
16rejected
1already in OpenCodex
9phases

Phase timeline

010 · M

클라이언트 연결 상태와 Claude 기본 실행 preview

depends on: none

Desktop/GUI의 한 화면에서 Codex와 Claude Code가 지금 어디로 가는지(OpenCodex proxy, native 로그인, Remote Link Home), 누가 설정을 소유하는지, 원하는 상태와 실제 파일이 왜 다른지, 되돌리면 어떤 키가 어떻게 바뀌는지를 본다. Claude Code의 기존 first-party 토글은 켜기 전에 settings.json에서 바뀔 키를 미리 보여 주고, 사용자가 명시적으로 등록한 Claude home마다 상태를 보여 준다.

020 · L

이주·온보딩: 발견, 일괄 가져오기, 링크, 속도 측정, 팀 접속

depends on: 010

다른 도구에서 넘어오는 사용자가 키를 다시 입력하지 않고 기존 공급자 설정을 발견·검토·가져오고, Codex/Claude 계정 파일을 일괄 가져온다. 공유받은 링크로 공급자 preset이나 Hub 접속을 미리 보고 확인한 뒤에만 기존 흐름을 시작한다. 공급자 후보 URL의 응답 시간을 같은 조건에서 비교한다.

030 · L

클라이언트 범위와 설정 이식성: Gemini CLI, Zed, MCP 동기화, 로컬 백업

depends on: 010

Gemini CLI와 Zed를 opt-in으로 OpenCodex에 연결하고 원복한다. 여러 파일을 쓰는 연결이 중간에 프로세스가 죽어도 다음 시작 때 일관된 상태로 돌아온다. Codex/Claude Code의 MCP 서버 항목을 읽고 고른 항목만 적용한다. 관리 설정을 골라 로컬 백업 번들로 내보내고 복원 전 변경을 본다.

040 · XL (구현 단위 둘: 040a = G-012, G-013, G-016 · 040b = G-014 → G-015, G-017)

계정 풀 스케줄링과 egress

depends on: none

같은 provider pool 안에서 계정마다 다른 upstream proxy를 쓴다. 확인된 quota cooldown이 재시작 뒤에도 유지된다. Codex·Claude OAuth 계정에 동시 실행 상한과 짧은 대기열이 생기고, 기존 priority tier 안에서 정적 weight와 실시간 부하로 계정을 고른다. 계정별 eligibility·refresh·cooldown 진단과 최근 fallback 결정의 후보·제외 사유를 본다.

050 · XL (G-021은 별도 구현 단위)

세션 연속성과 캐시

depends on: 040

긴 코딩 대화에서 combo가 이미 캐시가 따뜻한 대상을 유지해 cache miss를 줄인다. Antigravity와 xAI 경로에서 클라이언트가 돌려주지 않은 reasoning·서명 문맥을 안전하게 복원한다. 실제 Claude CLI를 쓰는 경로에 계정별 세션 재사용 opt-in 모드를 둔다.

060 · L

wire 충실도: 첨부 전용 turn, Gemini Interactions egress, xAI upstream WS

depends on: 040

Codex와 Claude Code의 첨부 전용 turn, file-backed 첨부, PDF, 여러 modality의 tool result가 대상 공급자 능력에 맞게 보존되거나 전송 전에 명확히 거절된다. Gemini Interactions를 공급자 네이티브로 보내는 opt-in 모드와 xAI upstream WebSocket 전송을 제공한다.

070 · L

공유 프록시 거버넌스: 발급 키 단위 동시 상한, 키 예산, 키 만료, 관리 감사

depends on: 040

proxy 하나를 여러 사람이 쓰는 팀이 발급 키마다 동시 실행 상한, request/token 예산, 만료 시각을 정하고, 키와 설정 변경을 감사 기록으로 본다. 정책이 없는 설치의 동작은 바뀌지 않는다.

080 · L

관측성: Claude Code statusline, 운영 알림, 네이티브 세션 사용량, 읽기 전용 관리 MCP

depends on: 070

Claude Code 사용자가 statusline에서 현재 세션의 실제 대상과 quota를 본다. 운영자는 실패·지연·429 임계치 알림을 켤 수 있고, proxy를 거치지 않은 네이티브 Codex/Claude 세션 사용량도 출처 표시와 함께 본다. 관리 권한이 있는 에이전트는 읽기 전용 MCP로 health·usage·키 metadata를 조회한다.

090 · L

요청 정책: outbound payload rule·요청 filter seam, 요청 masking

depends on: 060, 070

운영자가 특정 공급자/모델 요청에 반복되는 소수의 default·drop 규칙을 지정하고, 명시적으로 등록한 요청 filter를 실제 outbound body가 만들어진 지점에서 실행한다. 기본 off인 요청 masking으로 지정 패턴을 업스트림 전송 전에 가리고, 실패하면 물리적 전송이 한 번도 일어나지 않는다.

Gap matrix

IDCAP갭출처근거 (lane 후보)가치노력단계
G-001CAP-client-config-codex · CAP-client-config-claude · CAP-client-config-driftCodex·Claude Code 앱별 현재 목적지(proxy/native/remote), 소유권, drift 사유, 복원 미리보기를 한 화면에서 보기CCS · MGP003 L3-1 · 007 L7-5highM010
G-002CAP-client-config-claude기존 first-party 토글(gui/src/pages/ClaudeCode.tsx:293, rollback agent-settings-routes.ts:1760)에 빠진 것: 적용 전 settings.json 변경 preview와 CLAUDE_CONFIG_DIR(home)별 상태 표시MGP · CCS007 L7-1 · 003 인벤토리 · audit r1 #1highM010
G-003CAP-import-local-discovery · CAP-import-cc-switch설치된 앱(CC Switch, Claude/Codex 설정 등)의 공급자 설정을 자동 발견하고 검토 후 가져오기MGP · CCS007 L7-3highM020
G-004CAP-import-account-batchCodex·Claude 계정 자격 증명의 명시적 일괄 가져오기와 결과 receipt (현재 account-import는 소수 형식)MGP007 L7-2highL020
G-005CAP-deeplink-importOS 링크(ocx:// 류)로 relay/공급자 preset을 열어 미리보기 후 적용MGP · CCS007 L7-4 · 003 L3-2 · 008 L8-2highM020
G-006CAP-endpoint-speed-test공급자 후보 URL의 응답 시간·상태·실패를 같은 조건에서 비교하는 측정 화면CCS003 L3-3highM020
G-007CAP-remote-proxy-shareHub 초대를 링크로 열어 origin을 미리 본 뒤 기존 Hub pairing으로 잇고, 원격 카탈로그 준비 상태 표시MGP · CCS007 L7-6 · 003 L3-2(Home 연결 부분)medM020
G-008CAP-client-config-geminiGemini CLI를 로컬/Home proxy에 연결하고 원복하는 enable/disableCCS003 L3-4medM030
G-009CAP-client-config-zedZed custom provider export와 opt-in 연결MGP007 L7-7medM030
G-010CAP-mcp-client-syncCodex/Claude Code의 선택된 MCP 항목 읽기·변경 미리보기·명시적 적용CCS003 L3-8medL030
G-011CAP-config-import-export · CAP-backup-local관리 항목을 고르는 로컬 백업 번들과 복원 미리보기 (credential 기본 제외)CCS003 L3-6medM030
G-012CAP-credential-proxy같은 provider pool 안에서 credential/계정별 upstream proxy·noProxy를 로그인·refresh·실행에 일관 적용CPA · S2A002 L2-1 · 004 L4-04highL040
G-013CAP-cooldown-persistenceAPI key pool의 확인된 quota cooldown을 재시작·live recycle 후 복원CPA002 L2-2highM040
G-014CAP-account-concurrencyCodex·Claude OAuth 계정별 동시 실행 lease와 bounded wait (Kiro에만 존재하는 lease 원리 일반화)S2A004 L4-01highL040
G-015CAP-credential-pool-weighted · CAP-load-aware-selection기존 operator priority tier(codex/routing/selection.ts:249, auth-api/routes.ts:204) 안에서 정적 weight와 실시간 in-flight 부하로 고르기 (priority·pin·quota 계약 유지, G-014 이후)S2A · CPA004 L4-02 · 002 L2-5highL040
G-016CAP-credential-files계정별 모델 eligibility·refresh 결과를 보여주는 진단 DTO와 명시적 검증 UICPA002 L2-3medM040
G-017CAP-failover앱별 fallback 경로 순서와 현재 후보·제외 사유 가시성CCS003 L3-9medM040
G-018CAP-cache-affinity일반 combo에서 이미 따뜻한 세션 대상을 유지하는 선택형 cache affinityMGP006 L6-1highM050
G-019CAP-antigravity-replayAntigravity signed context 복원 심화: 이전 문맥·part 위치 대조, native call 복원, snapshot 조건부 갱신CPA001 L1-1highL050
G-020CAP-xai-reasoning-replayclient가 돌려주지 않은 완료 turn의 call/reasoning을 xAI 경로에서 보강CPA001 L1-2medM050
G-021CAP-claude-cli-session실제 Claude CLI의 계정별 장기 세션 reuse/resume (현재 매 턴 stateless)MGP006 L6-5highXL050
G-022CAP-wire-multimodal-input첨부만 있는 turn, file-backed 첨부, PDF, 다중 tool-result modality의 거절/보존 일관화CPA001 L1-4highM060
G-023CAP-wire-gemini-interactions-upstreamGemini Interactions의 공급자 네이티브 egress (현재 local ID 경로)CPA001 L1-5medL060
G-024CAP-wire-xai-upstream-wsxAI upstream WebSocket과 native continuation으로 history 재전송 감소CPA001 L1-3medL060
G-025CAP-caller-concurrency공유 proxy에서 발급 키 단위 동시 turn 상한 (opt-in). 여러 키를 한 사람으로 묶는 집계는 G-057로 보류S2A004 L4-03medL070
G-026CAP-usage-per-key · CAP-key-budget발급 키별 request/token 예산과 거절 이유 (USD ceiling은 가격 근거 확정 후)S2A005 L5-1highL070
G-027CAP-key-expiry발급 키 만료 시각·상태와 진행 중 WS/rotation 경계S2A005 L5-2highM070
G-028CAP-admin-audit키 발급/스코프/폐기와 설정 변경의 구조화된 관리 감사 이벤트S2A005 L5-4medM070
G-029CAP-statuslineClaude Code statusline에 현재 세션의 실제 route와 quota snapshot 표시 (opt-in)MGP006 L6-2highM080
G-030CAP-ops-alerts기존 metrics의 실패·지연·429 신호에 임계치와 최근 상태를 붙인 운영 알림 (기본 off)S2A005 L5-3medM080
G-031CAP-usage-event-export외부 집계기가 cursor로 읽는 관리 전용 usage event export — 이미 있음: /api/request-history의 nextCursor(request-history-routes.ts:90), /api/logs 증분 cursor(request-log-cursor.ts:67, process epoch 기준)CPA002 L2-6 · audit r1 #2medMCLOSED
G-032CAP-usage-native-sessionsproxy를 거치지 않은 Codex/Claude 네이티브 세션 사용량을 출처 표시와 함께 집계CCS003 L3-5medL080
G-033CAP-management-mcpusage/health/key metadata만 노출하는 읽기 전용 관리 MCPS2A005 L5-5lowL080
G-034CAP-payload-overrides · CAP-middleware운영자가 지정하는 post-translation payload default/drop과 명시 활성 요청 body filter seam (응답 hook은 G-059)CPA · MGP002 L2-4 · 006 L6-3medL090
G-035CAP-request-masking기본 off 요청 masking: 명시 필드의 deterministic 규칙, 원문 미보관, 실패 시 무전송MGP006 L6-4highL090
G-036CAP-gemini-explicit-cacheGemini 명시적 cache API와 생성 계정 고정S2A004 L4-05lowXLDEFER
G-037CAP-wire-embeddings-rerankembeddings/rerank typed endpoint (magpie 등록 mgp:internal/gateway/gateway.go:1218; OpenCodex Gemini embed는 별도로 501)MGP008 L8-1 · 006 L6-8medMDEFER
G-038CAP-wire-gemini-liveGemini Live 양방향 세션 — peer 구현 미확인 제품 후보 (CPA Gemini 등록 cpa:internal/api/server_routes.go:148에 Live 없음)— (peer 미확인)008 L8-5lowLDEFER
G-039CAP-provider-extension-abi버전 고정 provider-extension ABI (OpenCode/pi 플러그인 호환)MGP006 L6-6medXLDEFER
G-040CAP-sync-webdav · CAP-sync-s3운영자가 실행하는 WebDAV/S3 스냅샷 백업·복원 (G-011 형식 위)CCS003 L3-7 · 008 L8-3medLDEFER
G-041CAP-ip-allowlist발급 키별 IP 제한S2A005 L5-6lowMDEFER
G-042CAP-wire-xai-speech범용 xAI TTS endpointCPA001 L1-6lowMREJECT
G-043CAP-wire-legacy-completionslegacy /v1/completions facadeCPA001 L1-7lowSREJECT
G-044CAP-wire-claude-cchClaude CCH 재서명CPA001 L1-8lowMREJECT
G-045CAP-oauth-siwcCodex credential의 secondary SIWC bind/renewCPA002 L2-7lowLREJECT
G-046CAP-control-plane · CAP-credential-store-backendsHome control plane과 다중 backend credential/config mirrorCPA002 L2-8lowXLREJECT
G-047CAP-plugin-host · CAP-plugin-distributionnative ABI plugin host, 원격 artifact 배포, marketplace 자동 업데이트CPA · MGP002 L2-9 · 006 L6-7lowXLREJECT
G-048CAP-client-fingerprintTLS fingerprint·client identity 위장 profileS2A004 L4-R1lowLREJECT
G-049CAP-tenant-billing셀프 가입/RBAC, 그룹 상품·구독, 잔액·결제·환불·리딤·promoS2A005 L5-7 · 008 L8-4lowXLREJECT
G-050CAP-platform-ops공지 포털, 운영 UI 전면 복제, 프롬프트 원문 감사, Postgres/Redis 의무화, DB setup wizardS2A005 L5-8lowXLREJECT
G-051CAP-wire-vendor-generic임의 vendor-native path 일괄 passthroughMGP006 L6-8lowLREJECT
G-052CAP-library-mcp · CAP-library-skills · CAP-prompt-profilesMCP/skills Library, skills marketplace, 전역 지침 profile 전환 관리자MGP · CCS007 L7-9 · 003 L3-11lowXLREJECT
G-053CAP-surface-tui대화형 별도 TUIMGP007 L7-10lowLREJECT
G-054CAP-client-config-roster지원 agent 수 맞추기 (60+ roster)MGP007 L7-11lowXLREJECT
G-055CAP-session-manager범용 세션 index·본문 검색·삭제·재실행CCS003 L3-10lowXLREJECT
G-056CAP-client-plugin-management모든 클라이언트의 플러그인/마켓 설치·업데이트 관리CCS003 L3-12lowXLREJECT
G-057CAP-caller-owner-aggregation운영자가 관리하는 owner 매핑으로 여러 발급 키를 한 사용자 slot으로 묶기 (sub2api user slot s2a:backend/internal/handler/openai_gateway_handler.go:614)S2A004 L4-03 · audit r1 #3medMDEFER
G-058CAP-config-sync-encrypted양방향 클라우드 설정·sign-in 동기화MGP007 L7-8 · audit r1 #6lowXLREJECT
G-060CAP-deeplink-home-linkSSH Link(Home/Child) 초대 링크 — alias·confirmed host 기반 enrollment(ocx:src/server/management/link-routes.ts:165)를 링크로 여는 진입점CCS003 L3-2 · audit r3 #4lowMDEFER
G-059CAP-middleware-response응답 측 hook (SSE/WS framing 보존 계약 포함)MGP006 L6-3 · audit r1 #9medLDEFER

Research documents

From 9c3ddc4f5656fb69c60670cf09fe369d24784838 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Wed, 25 Nov 2026 10:22:05 +0900 Subject: [PATCH 02/60] test: stabilize Link preflight and standalone stop checks (#9064) * test(stop): isolate independent standalone ownership cases * test(link): expire the relay auth clock after the silent peer receives the probe * test(link): abort a missing relay probe well inside the test timeout --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- .../clients/link-relay-bound-transport.test.ts | 14 +++++++++++--- tests/service/stop-deferred-teardown.test.ts | 18 ++++++++++-------- 2 files changed, 21 insertions(+), 11 deletions(-) diff --git a/tests/clients/link-relay-bound-transport.test.ts b/tests/clients/link-relay-bound-transport.test.ts index 6be9c5064b2..a91c86e98cf 100644 --- a/tests/clients/link-relay-bound-transport.test.ts +++ b/tests/clients/link-relay-bound-transport.test.ts @@ -141,6 +141,7 @@ describe("connection-bound link relay", () => { }); test("a silent actual peer expires only the credential-free auth deadline without touching the body", async () => { + const authTimeoutMs = 20; const seen: Array<{ url: string; authorization: string | undefined; body: string }> = []; let bodyRead = false, bodyCancelled = false; const body = new ReadableStream({ @@ -150,10 +151,17 @@ describe("connection-bound link relay", () => { const record = { url: req.url!, authorization: req.headers.authorization, body: "" }; seen.push(record); req.on("data", chunk => { record.body += chunk.toString(); }); + // Keep the peer silent and expire the caller's clock after the real probe arrives. + req.once("end", () => jest.advanceTimersByTime(authTimeoutMs)); }, async port => { - await expect(fetchBoundLinkRelay(target(port), `http://127.0.0.1:${port}/v1/responses`, { - method: "POST", headers: { authorization: `Bearer ${key}` }, body, - }, { authTimeoutMs: 20 })).rejects.toBeInstanceOf(LinkRelayAuthTimeoutError); + // A missing probe still releases the socket and restores real timers. + const signal = AbortSignal.timeout(2_000); // well inside the 5 s test timeout + jest.useFakeTimers(); + try { + await expect(fetchBoundLinkRelay(target(port), `http://127.0.0.1:${port}/v1/responses`, { + method: "POST", headers: { authorization: `Bearer ${key}` }, body, signal, + }, { authTimeoutMs })).rejects.toBeInstanceOf(LinkRelayAuthTimeoutError); + } finally { jest.useRealTimers(); } expect(seen).toHaveLength(1); expect(new URL(seen[0]!.url, "http://peer").pathname).toBe(LINK_RELAY_AUTH_PATH); expect(seen[0]!.authorization).toBeUndefined(); expect(seen[0]!.body).toBe(""); diff --git a/tests/service/stop-deferred-teardown.test.ts b/tests/service/stop-deferred-teardown.test.ts index 2e2f397efc3..06a69c3df00 100644 --- a/tests/service/stop-deferred-teardown.test.ts +++ b/tests/service/stop-deferred-teardown.test.ts @@ -251,10 +251,7 @@ describe("parent CLI shared teardown completion", () => { expect(JSON.parse(outcome.stdout)).toMatchObject({ runtimeDown: true, service: "stopped", sharedTeardown: "restored" }); }); - test.each([ - ["legacy", ["wrong-home", "wrong-port"]], - ["current", ["stale", "client-role"]], - ] as const)("only a matching %s standalone record permits the ordinary stop after a discovery miss", async (standaloneRecord, mismatches) => { + test.each(["legacy", "current"] as const)("a matching %s standalone record permits the ordinary stop after a discovery miss", async standaloneRecord => { const outcome = await runParentStop({ receipt: true, standaloneRecord, discoveryMiss: true, deadPidReadsNull: true, json: true, response: { success: true }, restore: restoreResult(true) }); expect(outcome.exitCode, outcome.stderr).toBe(0); @@ -262,16 +259,21 @@ describe("parent CLI shared teardown completion", () => { expect(outcome.urls).toHaveLength(1); expect(outcome.signals).toEqual(standaloneRecord === "legacy" ? [] : [process.platform === "win32" ? "taskkill /F" : "SIGTERM"]); expect(JSON.parse(outcome.stdout)).toMatchObject({ runtimeDown: true, proxy: "stopped", sharedTeardown: "restored" }); - for (const mismatch of mismatches) { - if (mismatch === "wrong-home" && process.platform === "win32") continue; + expect(outcome.receiptExists).toBe(false); + }); + + for (const mismatch of ["wrong-home", "wrong-port", "stale", "client-role"] as const) { + test.skipIf(mismatch === "wrong-home" && process.platform === "win32")(`a ${mismatch} standalone record refuses the ordinary stop after a discovery miss`, async () => { const refusal = await runParentStop({ receipt: true, standaloneRecord: mismatch, discoveryMiss: true, managerCascades: true, json: true, response: null, restore: restoreResult(true) }); expect(refusal.exitCode, `${mismatch}: ${refusal.stderr}`).toBe(1); expect(refusal.calls).toMatchObject({ service: 0, killed: 0, native: 0, grok: 0 }); + expect(refusal.signals).toEqual([]); expect(refusal.urls).toEqual([]); + expect(refusal.nonce).toBeUndefined(); expect(JSON.parse(refusal.stdout)).toMatchObject({ runtimeDown: false, proxy: "ownership-refused", sharedTeardown: "skipped" }); - } - }); + }); + } test.each([false, true])("a discovery miss refuses to stop an unclassified live ocx start PID (cascading manager=%s)", async managerCascades => { const outcome = await runParentStop({ receipt: true, noRuntimeRecord: true, discoveryMiss: true, managerCascades, From 394af78520ef86e2c8e73d4dca292497aef182e2 Mon Sep 17 00:00:00 2001 From: Shu Chen Date: Tue, 24 Nov 2026 20:43:54 -0500 Subject: [PATCH 03/60] fix(gui): let the Combos page scroll past suggested combos (#9101) (#9105) Co-authored-by: JUN --- gui/src/styles-combos-workspace.css | 14 +++++++----- gui/tests/combos-workspace-scroll.test.ts | 28 +++++++++++++++++++++++ 2 files changed, 36 insertions(+), 6 deletions(-) create mode 100644 gui/tests/combos-workspace-scroll.test.ts diff --git a/gui/src/styles-combos-workspace.css b/gui/src/styles-combos-workspace.css index 9a254981eba..5f06ce761e3 100644 --- a/gui/src/styles-combos-workspace.css +++ b/gui/src/styles-combos-workspace.css @@ -30,19 +30,21 @@ } /* Revalidation shell: keeps the workspace body stable while aria-busy and an - sr-only status span announce in-flight refreshes to assistive tech. */ + sr-only status span announce in-flight refreshes to assistive tech. + Suggested combos and their notices render above the workspace grid, which keeps + the body's full height. The body scrolls, so whatever sits above the grid scrolls + out of the way and the grid's lower part (the Save / Remove bar) stays reachable. */ .combos-workspace-shell-body { flex: 1 1 auto; min-height: 0; - overflow: hidden; + overflow-x: hidden; + overflow-y: auto; display: flex; flex-direction: column; } -.rb-suggest + .combos-workspace-root { - flex: 1 1 0; - min-height: 0; - height: auto; +.combos-workspace-shell-body > .combos-workspace-root { + flex: 0 0 auto; } .combos-workspace-rail { diff --git a/gui/tests/combos-workspace-scroll.test.ts b/gui/tests/combos-workspace-scroll.test.ts new file mode 100644 index 00000000000..549275616d2 --- /dev/null +++ b/gui/tests/combos-workspace-scroll.test.ts @@ -0,0 +1,28 @@ +/** + * Combos page: content above the workspace grid must not push the grid's bottom out of reach. + * + * Suggested combos (and their notices) render inside `.combos-workspace-shell-body`, above + * `.combos-workspace-root`. The grid keeps the body's full height, so with anything above it + * the grid ends below the viewport. The body used to clip (`overflow: hidden`), leaving the + * lower detail fields and the Save / Remove bar unreachable (#9101). A sibling rule meant to + * shrink the grid never matched, because the suggestions are wrapped in a fieldset, and would + * have squeezed the grid to nothing once "Show all" expanded the list. + * + * Source-text assertions; the rendered geometry was measured in Chromium while fixing this. + */ +import { expect, test } from "bun:test"; +import { effectiveDeclaration, withoutComments } from "./helpers/css-declarations"; + +const css = withoutComments( + await Bun.file(new URL("../src/styles-combos-workspace.css", import.meta.url)).text(), +); + +test("the shell body scrolls, so content above the workspace can scroll out of the way", () => { + expect(effectiveDeclaration(css, ".combos-workspace-shell-body", "overflow-y")).toBe("auto"); + expect(() => effectiveDeclaration(css, ".combos-workspace-shell-body", "overflow")).toThrow("property not found"); +}); + +test("the workspace grid keeps its full height instead of shrinking under the suggestions", () => { + expect(effectiveDeclaration(css, ".combos-workspace-shell-body > .combos-workspace-root", "flex")).toBe("0 0 auto"); + expect(css).not.toMatch(/\.rb-suggest\s*\+\s*\.combos-workspace-root/); +}); From a60574dd7067eb9fd7c4ac545dbf06f8400646f1 Mon Sep 17 00:00:00 2001 From: Arthur tinseau <65445747+atinseau@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:12:06 +0100 Subject: [PATCH 04/60] refactor(combos): move pool-account failure helpers into core-combo-failure (#9088) core-combo.ts sat at 1,971 lines against the 2,000-line file-size threshold. The four helpers that read pool-account evidence after a failed combo send (cooledPoolAccountLabel, cooledGenericOAuthAccountLabel, creditRefusedAnthropicAccountLabel and isAnthropicPoolLocalRefusal) move verbatim next to the failure consumer that already classifies the same responses. The two tests that imported helpers from core-combo.ts now import them from their new module. No behavior changes. Co-authored-by: lidge-jun --- src/server/responses/core-combo-failure.ts | 113 ++++++++++++++++- src/server/responses/core-combo.ts | 118 +----------------- structure/runtime.md | 2 +- tests/routing/always-on-429-failover.test.ts | 3 +- ...server-combo-main-account-cooldown.test.ts | 2 +- 5 files changed, 121 insertions(+), 117 deletions(-) diff --git a/src/server/responses/core-combo-failure.ts b/src/server/responses/core-combo-failure.ts index 351103d65e3..ec67d89adc5 100644 --- a/src/server/responses/core-combo-failure.ts +++ b/src/server/responses/core-combo-failure.ts @@ -16,7 +16,8 @@ import { } from "../../combos/failover"; import { parseRetryAfterMs } from "../../combos"; import type { ConsumedComboFailure, HandleResponsesOptions } from "./core-options"; -import type { OcxUsage } from "../../types"; +import type { OcxConfig, OcxUsage } from "../../types"; +import { codexQuotaScopeForModel, getCodexQuotaHealthSnapshot } from "../../codex/routing"; import { readBoundedResponseBody } from "../../lib/bounded-body"; import { carryAnthropicRefusalCredential } from "../../oauth/anthropic-account-refusal"; import { carryCodexAccountCooldownResponse } from "../../codex/account-cooldown-response"; @@ -44,6 +45,116 @@ import { isXaiLegacyPrivacyError, isXaiPrivacyModeRefusal, xaiPrivacyModeRefusal import { stampMetaMusePlanRefusal } from "../../providers/meta-muse-plan-refusal"; import type { RequestFailureCause } from "../../usage/telemetry-contract"; import { isRewrittenUpstreamError } from "../../adapters/upstream-http-error"; +import { configuredAnthropicInstance } from "../../providers/anthropic-instance"; +import { getAccountSet } from "../../oauth/store"; +import { anthropicRefusalCredentialIsCurrent } from "../../oauth/anthropic-account-refusal"; +import { isAnthropicBillingFailure } from "../../providers/anthropic-billing-refusal"; +import { anthropicRoutingFor, formatAnthropicProviderForLog } from "../../oauth/anthropic-routing"; +import { codexAccountLogLabel, oauthAccountLogLabel } from "../../codex/account-label"; +import { isGenericFailoverProvider, rotateGenericOAuthAccountOn429 } from "../../oauth/generic-account-failover"; +import { MAIN_CODEX_ACCOUNT_ID } from "../../codex/account-id"; +import { providerCodexAccountMode } from "../../providers/registry"; +import { baseProviderLabel } from "../../providers/label"; +import { isCanonicalOpenAiForwardProvider } from "../../providers/openai-tiers"; + +export function cooledPoolAccountLabel(config: OcxConfig, providerName: string, modelId: string, label: string | undefined): string | undefined { + if (!label) return undefined; + const instance = configuredAnthropicInstance(config, providerName); + if (instance && config.providers[providerName]?.authMode === "oauth") { + const matches = getAccountSet(instance)?.accounts.filter(account => + formatAnthropicProviderForLog(instance, account.id) === label) ?? []; + return matches.length === 1 && anthropicRoutingFor(instance).getAnthropicAccountHealthSnapshot(matches[0]!.id) ? label : undefined; + } + const provider = config.providers[providerName]; + if (!provider || !isCanonicalOpenAiForwardProvider(provider)) return undefined; + const quotaScope = codexQuotaScopeForModel(modelId); + // The main account logs as `-main` and is not a `codexAccounts` entry (#8880). In pool + // mode the pool rotates past a cooled main itself, so its 429 is account evidence exactly like a + // pool account's, and parking the target would black out the siblings and main's own recovery for + // the upstream Retry-After (up to 24h). Direct mode serves main without that check, so there the + // target cooldown stays the only guard against re-sending to a spent account. + if (label === `${providerName}-main`) { + return providerCodexAccountMode(providerName, provider) === "pool" + && getCodexQuotaHealthSnapshot(MAIN_CODEX_ACCOUNT_ID, quotaScope) ? label : undefined; + } + const matches = (config.codexAccounts ?? []).filter(account => + `${providerName}-${codexAccountLogLabel(account)}` === label); + return matches.length === 1 + && getCodexQuotaHealthSnapshot(matches[0]!.id, quotaScope) + ? label : undefined; +} + +/** + * The generic OAuth pool's counterpart of `cooledPoolAccountLabel`. Its 429 names one account + * through `accountLogLabel`, but the per-request account budget can end the pool's own rotation + * before the last refused account is recorded. Hand that account to the pool's rotator, which + * cools it under the pool's own Retry-After policy, and spare the target only when the pool still + * has an eligible sibling. The rotator only peeks round-robin here: nothing is sent to that sibling. + * A lone account or an all-cooled pool returns null and cools the target. + */ +export function cooledGenericOAuthAccountLabel( + config: OcxConfig, providerName: string, modelId: string, label: string | undefined, retryAfter: string | undefined, +): string | undefined { + const provider = config.providers[providerName]; + if (!label || !provider || !isGenericFailoverProvider(providerName, provider)) return undefined; + const base = baseProviderLabel(providerName); + const matches = getAccountSet(providerName)?.accounts.filter(account => + oauthAccountLogLabel(account.id, base) === label) ?? []; + return matches.length === 1 + && rotateGenericOAuthAccountOn429(config, providerName, matches[0]!.id, retryAfter, Date.now(), modelId, false) + ? label : undefined; +} + +/** + * A 402 credit-balance refusal names one Anthropic OAuth account -- the evidence the pool already + * accepts on a 403 -- but the pool rotates only on 401/403/429, so the 402 reaches the combo with + * that account still selectable. Cool it under the pool's entitlement backoff and spare the target + * only while a sibling is eligible; a lone account or an exhausted pool still cools the target. + */ +export function creditRefusedAnthropicAccountLabel( + config: OcxConfig, providerName: string, modelId: string, label: string | undefined, + message: string, code: string | null | undefined, response: Response, +): string | undefined { + const instance = configuredAnthropicInstance(config, providerName); + if (!label || !instance || config.providers[providerName]?.authMode !== "oauth" + || !isAnthropicBillingFailure(402, message, code)) return undefined; + const routing = anthropicRoutingFor(instance); + const matches = getAccountSet(instance)?.accounts.filter(account => + formatAnthropicProviderForLog(instance, account.id) === label) ?? []; + return matches.length === 1 + && anthropicRefusalCredentialIsCurrent(response, instance, matches[0]!.id) + && routing.recordAnthropicAccountRefusal(config, matches[0]!.id, 403, null) + && routing.getEligibleAnthropicAccounts(Date.now(), modelId).length > 0 + ? label : undefined; +} + +/** + * True only for the Anthropic OAuth pool's OWN "all accounts cooled" 429. Its Retry-After is the + * earliest per-account cooldown restated (`getAnthropicPoolRetryAfterSeconds`), which the pool + * keeps enforcing locally, so it must not also park the combo target: an account added, resumed or + * cleared a minute later would otherwise sit ignored until the target expired, up to the 24h + * server-delay ceiling. + * + * Provenance, not just current state: the target must be the OAuth pool, no account may have been + * identified for the failure, and the pool must be holding the wait right now. An upstream 429 on + * a pool account always cools and names that account, and an API-key provider never qualifies, so + * a genuine upstream Retry-After still parks the target in full. + */ +export function isAnthropicPoolLocalRefusal( + config: OcxConfig, + providerName: string, + status: number, + failedAccount: string | undefined, + now = Date.now(), +): boolean { + const instance = configuredAnthropicInstance(config, providerName); + return instance !== undefined + && config.providers[providerName]?.authMode === "oauth" + && status === 429 + && failedAccount === undefined + && anthropicRoutingFor(instance).getEligibleAnthropicAccounts(now).length === 0 + && anthropicRoutingFor(instance).getAnthropicPoolRetryAfterSeconds(now) !== null; +} export function sanitizedRetryAfter(value: string | null, now: number): string | undefined { const trimmed = value?.trim(); diff --git a/src/server/responses/core-combo.ts b/src/server/responses/core-combo.ts index e1d59519617..92d1aec8d49 100644 --- a/src/server/responses/core-combo.ts +++ b/src/server/responses/core-combo.ts @@ -82,20 +82,7 @@ import { requestStartComboConfig, snapshotComboAdmission, snapshotComboAdmission import { canDescribeComboImages } from "./request-sidecar-auth"; import { captureRouteStaticPolicy, routeConcreteModel, comboRouteDecisionTrace } from "../../router"; import { memoryModelRouteReason } from "./memory-models"; -import { baseProviderLabel, poolAccountProviderLabel } from "../../providers/label"; -import { getAccountSet } from "../../oauth/store"; -import { anthropicRefusalCredentialIsCurrent } from "../../oauth/anthropic-account-refusal"; -import { configuredAnthropicInstance } from "../../providers/anthropic-instance"; -import { isAnthropicBillingFailure } from "../../providers/anthropic-billing-refusal"; -import { - anthropicRoutingFor, - formatAnthropicProviderForLog, -} from "../../oauth/anthropic-routing"; -import { codexAccountLogLabel, oauthAccountLogLabel } from "../../codex/account-label"; -import { isGenericFailoverProvider, rotateGenericOAuthAccountOn429 } from "../../oauth/generic-account-failover"; -import { codexQuotaScopeForModel, getCodexQuotaHealthSnapshot } from "../../codex/routing"; -import { MAIN_CODEX_ACCOUNT_ID } from "../../codex/account-id"; -import { providerCodexAccountMode } from "../../providers/registry"; +import { poolAccountProviderLabel } from "../../providers/label"; import { isCanonicalOpenAiForwardProvider, OPENAI_CODEX_PROVIDER_ID } from "../../providers/openai-tiers"; import type { AgentTaskRecoveryFailureReason } from "./agent-task-recovery"; import { @@ -116,6 +103,10 @@ import { } from "./core-errors"; import { buildComboChildHeaders, + cooledGenericOAuthAccountLabel, + cooledPoolAccountLabel, + creditRefusedAnthropicAccountLabel, + isAnthropicPoolLocalRefusal, createChildPassthroughCallbackGate, consumeComboFailure, isLateAttributionRefusal, @@ -180,105 +171,6 @@ function resolvedComboDestination(config: OcxConfig, target: { provider: string; } } -export function cooledPoolAccountLabel(config: OcxConfig, providerName: string, modelId: string, label: string | undefined): string | undefined { - if (!label) return undefined; - const instance = configuredAnthropicInstance(config, providerName); - if (instance && config.providers[providerName]?.authMode === "oauth") { - const matches = getAccountSet(instance)?.accounts.filter(account => - formatAnthropicProviderForLog(instance, account.id) === label) ?? []; - return matches.length === 1 && anthropicRoutingFor(instance).getAnthropicAccountHealthSnapshot(matches[0]!.id) ? label : undefined; - } - const provider = config.providers[providerName]; - if (!provider || !isCanonicalOpenAiForwardProvider(provider)) return undefined; - const quotaScope = codexQuotaScopeForModel(modelId); - // The main account logs as `-main` and is not a `codexAccounts` entry (#8880). In pool - // mode the pool rotates past a cooled main itself, so its 429 is account evidence exactly like a - // pool account's, and parking the target would black out the siblings and main's own recovery for - // the upstream Retry-After (up to 24h). Direct mode serves main without that check, so there the - // target cooldown stays the only guard against re-sending to a spent account. - if (label === `${providerName}-main`) { - return providerCodexAccountMode(providerName, provider) === "pool" - && getCodexQuotaHealthSnapshot(MAIN_CODEX_ACCOUNT_ID, quotaScope) ? label : undefined; - } - const matches = (config.codexAccounts ?? []).filter(account => - `${providerName}-${codexAccountLogLabel(account)}` === label); - return matches.length === 1 - && getCodexQuotaHealthSnapshot(matches[0]!.id, quotaScope) - ? label : undefined; -} - -/** - * The generic OAuth pool's counterpart of `cooledPoolAccountLabel`. Its 429 names one account - * through `accountLogLabel`, but the per-request account budget can end the pool's own rotation - * before the last refused account is recorded. Hand that account to the pool's rotator, which - * cools it under the pool's own Retry-After policy, and spare the target only when the pool still - * has an eligible sibling. The rotator only peeks round-robin here: nothing is sent to that sibling. - * A lone account or an all-cooled pool returns null and cools the target. - */ -function cooledGenericOAuthAccountLabel( - config: OcxConfig, providerName: string, modelId: string, label: string | undefined, retryAfter: string | undefined, -): string | undefined { - const provider = config.providers[providerName]; - if (!label || !provider || !isGenericFailoverProvider(providerName, provider)) return undefined; - const base = baseProviderLabel(providerName); - const matches = getAccountSet(providerName)?.accounts.filter(account => - oauthAccountLogLabel(account.id, base) === label) ?? []; - return matches.length === 1 - && rotateGenericOAuthAccountOn429(config, providerName, matches[0]!.id, retryAfter, Date.now(), modelId, false) - ? label : undefined; -} - -/** - * A 402 credit-balance refusal names one Anthropic OAuth account -- the evidence the pool already - * accepts on a 403 -- but the pool rotates only on 401/403/429, so the 402 reaches the combo with - * that account still selectable. Cool it under the pool's entitlement backoff and spare the target - * only while a sibling is eligible; a lone account or an exhausted pool still cools the target. - */ -function creditRefusedAnthropicAccountLabel( - config: OcxConfig, providerName: string, modelId: string, label: string | undefined, - message: string, code: string | null | undefined, response: Response, -): string | undefined { - const instance = configuredAnthropicInstance(config, providerName); - if (!label || !instance || config.providers[providerName]?.authMode !== "oauth" - || !isAnthropicBillingFailure(402, message, code)) return undefined; - const routing = anthropicRoutingFor(instance); - const matches = getAccountSet(instance)?.accounts.filter(account => - formatAnthropicProviderForLog(instance, account.id) === label) ?? []; - return matches.length === 1 - && anthropicRefusalCredentialIsCurrent(response, instance, matches[0]!.id) - && routing.recordAnthropicAccountRefusal(config, matches[0]!.id, 403, null) - && routing.getEligibleAnthropicAccounts(Date.now(), modelId).length > 0 - ? label : undefined; -} - -/** - * True only for the Anthropic OAuth pool's OWN "all accounts cooled" 429. Its Retry-After is the - * earliest per-account cooldown restated (`getAnthropicPoolRetryAfterSeconds`), which the pool - * keeps enforcing locally, so it must not also park the combo target: an account added, resumed or - * cleared a minute later would otherwise sit ignored until the target expired, up to the 24h - * server-delay ceiling. - * - * Provenance, not just current state: the target must be the OAuth pool, no account may have been - * identified for the failure, and the pool must be holding the wait right now. An upstream 429 on - * a pool account always cools and names that account, and an API-key provider never qualifies, so - * a genuine upstream Retry-After still parks the target in full. - */ -export function isAnthropicPoolLocalRefusal( - config: OcxConfig, - providerName: string, - status: number, - failedAccount: string | undefined, - now = Date.now(), -): boolean { - const instance = configuredAnthropicInstance(config, providerName); - return instance !== undefined - && config.providers[providerName]?.authMode === "oauth" - && status === 429 - && failedAccount === undefined - && anthropicRoutingFor(instance).getEligibleAnthropicAccounts(now).length === 0 - && anthropicRoutingFor(instance).getAnthropicPoolRetryAfterSeconds(now) !== null; -} - /** * A combo's execution policy is DECLARED by the combo, not inherited from the single-target * profile. diff --git a/structure/runtime.md b/structure/runtime.md index e2efea6139d..b01e6e63df0 100644 --- a/structure/runtime.md +++ b/structure/runtime.md @@ -504,7 +504,7 @@ This is also why the classifier cannot duplicate visible output. Native byte str Regression coverage: `tests/responses/responses-forward-prompt-envelope.test.ts`, `tests/routing/router-combo-failover-classification.test.ts`, `tests/routing/routing-policy-fallback.test.ts`, `tests/helpers/combo-context-overflow-cases.ts`, and `tests/server/server-combo-failover-e2e.test.ts`. Every combo, routing-profile, subagent and hard-lock hop to another model or provider first passes the [fallback policy](fallback-policy.md#sites). -`src/combos/failover.ts` uses a 10-minute fallback for a spent account usage window (codes `usage_limit_exceeded`, `usage_limit_reached`, `1308`, or `usage limit reached` / `usage limit has been reached` / `token-plan quota has been exhausted` prose, including HTTP 502) and for provider-scoped credential or billing failure codes such as `invalid_api_key` and `insufficient_quota`. This duration does not change failure classification or cooldown scope; upstream retry/reset signals and configured durations retain precedence. It caps explicit upstream `Retry-After` target cooldowns at 24 hours while reset-derived, configured, and fallback cooldowns remain capped at 10 minutes. `src/combos/resolve.ts` omits a target cooldown for a 429 only when the failed child identifies one account in an Anthropic OAuth or canonical Codex pool and that account has a live pool cooldown, or identifies one account in a generic OAuth pool that still has an eligible sibling. `src/server/responses/core-combo.ts` checks the pool's health record before passing that attribution; for a generic OAuth pool it first hands the account (matched through its `accountLogLabel`) to `rotateGenericOAuthAccountOn429`, which cools it under the pool's own Retry-After policy even when the per-request account budget ended rotation before that account was recorded, and attributes the failure only when the rotator names a sibling. Unknown accounts, ambiguous labels, a lone or fully cooled generic OAuth pool, API-key providers, and other failures keep their ordinary target cooldown. An API-key pool needs no attribution: its 429 rotation walks every key inside the attempt, so a 429 reaches the combo only once every key is cooled. Regression coverage: `tests/oauth/generic-oauth-combo-account-cooldown.test.ts`. A 402 is the provider-scoped twin for an Anthropic OAuth pool: the pool rotates only on 401/403/429, so when the failed child identifies one pool account and the failure carries the exact credit-balance refusal (`isAnthropicBillingFailure`), `core-combo.ts` records that account's refusal through the pool's `recordAnthropicAccountRefusal` (the same entitlement backoff a 403 credit refusal gets) and `resolve.ts` omits every target cooldown only while the pool still has an eligible account; a lone account, an exhausted pool, an unidentified account, or any other 402 keeps the provider-scoped cooldown. Regression coverage: `tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts`. The Anthropic OAuth pool's own all-accounts-cooled 429 is an unattributed exception: `isAnthropicPoolLocalRefusal` in `core-combo.ts` requires the `anthropic` provider with `authMode: "oauth"`, status 429, no identified failed account, no eligible pool account and a live pool retry-after. The target then still cools, but for the local fallback instead of the restated per-account `Retry-After`, so a resumed or newly added account is not ignored until a 24-hour target cooldown expires. An upstream 429 on an API-key provider or on an identified pool account keeps its full `Retry-After`. Regression coverage: `tests/routing/always-on-429-failover.test.ts`. Cooldown entries in `src/combos/failover.ts` retain the failure status. The quota-only snapshot query records target/expiry pairs for unexpired 429/402 cooldowns using only cooldown map lookups. Its config-aware wrapper in `src/combos/resolve.ts` applies the picker's provider availability and cached quota checks before dispatch; request eligibility runs lazily only when exhaustion considers a 503, with throwing checks treated as ineligible. Responses exhaustion uses this evidence under the [failover contract](transports/responses-failover.md); ordinary cooldown selection and timing stay unchanged. Opt-in `cooldownReprobe: { enabled: true, intervalMs }` in `src/combos/resolve.ts` permits an initial non-preview request to reserve all-cooled eligible targets once per configured interval (default 300000 ms, range 1000..86400000). The synchronous reservation lives in selection state and resets on proxy restart or selection-state reset; the reserved target keys are carried only by that request's picks; shared cooldowns remain recorded and continue to exclude concurrent requests. Each reservation names the cooldown write's unique revision, not its expiry. A successful dispatch settles through `settleComboReprobeSuccess`, which lifts only that unchanged reserved write; unprobed and re-cooled targets stay recorded, including replacements with an identical Retry-After expiry. Route-level selection without request eligibility disables reprobes, as does the in-flight retry-after-cooldown path, which waits for normal expiry. Nested wait-path and JEV selections retain the same reservation without starting a second reprobe. After ordinary or last-resort-deferral waits and after an awaited JEV decision, selection rechecks provider and request eligibility at the current clock and permits only unchanged-revision bypasses. Preparation first checks available siblings without evaluating cooled targets; a throwing eligibility predicate is ineligible for recovery. Encrypted-task recovery relaxes only payload readability and retains metering, JEV, reasoning-replay and protocol-lane eligibility. Its recovery selection may reserve a reprobe only after Responses ingress, thread-spawn, enabled recovery configuration and non-child-attempt admission pass; refused recovery preserves cooldowns and the reservation. New failures record cooldowns normally, and provider quota, account admission, payload eligibility, metered-spend and cancellation checks remain authoritative. There is no timer; existing send bounds remain. The opt-in may retry a target before its server Retry-After. CLI `--cooldown-reprobe on|off` and `--cooldown-reprobe-interval` control it; omitted management fields preserve it on unrelated saves. Tests: `tests/codex-integration/combo-cooldown-reprobe.test.ts`, `tests/server/server-combo-cooldown-fallback.test.ts` and `tests/cli/cli-combo-parity.test.ts`. A zero-attempt `combo_unavailable` names why each target was skipped. `comboExclusionReasons` in `src/combos/resolve.ts` derives one coarse label per target from the picker's own checks, in picker order: `provider missing`, `provider disabled`, `quota exhausted`, `cooldown`, then `ineligible for this request` when the caller's eligibility predicate refuses it or throws. `NoAvailableComboTargetsError` and `comboUnavailable` append them to the message; the description carries target counts and indices, validated provider-id labels and closed reasons; configured model strings and combo aliases are omitted. Coverage: `tests/responses/responses-combo-exhausted-error.test.ts`. The same pass (`comboExclusion`) also yields machine-readable diagnostics (#7965): `comboUnavailableResponse` in `src/server/responses/core-errors.ts` adds `error.combo = { cause, targets, attempted, causes }` to the unchanged `combo_unavailable` code. A target's class is `quota` (cached quota spent, or a cooldown whose retained status is 429/402), `permission` (cooldown status 401/403), `transient` (any other cooldown, read through `comboTargetCooldownStatus` in `src/combos/failover.ts`), `unsupported` (request-ineligible, including the mandatory `tool_choice` refusals in `core-combo.ts`, where `comboTargetUnavailableCause` lets provider state, quota and live cooldowns keep precedence) or `unavailable` (provider missing or disabled); `cause` is the shared class, `mixed`, or `unknown`. The quota-snapshot exhaustion answer reports `quota` with the targets the ladder dispatched. Counts and closed classes only; no combo id, provider, model or upstream text. Coverage: `tests/responses/responses-combo-unavailable-cause.test.ts`. Ordinary local Codex account-cooldown refusals carry unforgeable process-local Response identity from `src/codex/account-cooldown-response.ts` through combo failure reconstruction. At target cooldown recording only, `core-combo.ts` drops their restated retry/reset metadata and retains capped local backoff; client retry advice and account admission remain unchanged. Main hard-lock, credit, Reserve and transient-policy subclasses are excluded. The [combo cooldown contract](transports/responses-failover.md#single-target-cooldown-retry-ownership) owns this distinction; `tests/server/server-combo-cooldown-recording.test.ts` covers recovery and upstream wire-copy controls. +`src/combos/failover.ts` uses a 10-minute fallback for a spent account usage window (codes `usage_limit_exceeded`, `usage_limit_reached`, `1308`, or `usage limit reached` / `usage limit has been reached` / `token-plan quota has been exhausted` prose, including HTTP 502) and for provider-scoped credential or billing failure codes such as `invalid_api_key` and `insufficient_quota`. This duration does not change failure classification or cooldown scope; upstream retry/reset signals and configured durations retain precedence. It caps explicit upstream `Retry-After` target cooldowns at 24 hours while reset-derived, configured, and fallback cooldowns remain capped at 10 minutes. `src/combos/resolve.ts` omits a target cooldown for a 429 only when the failed child identifies one account in an Anthropic OAuth or canonical Codex pool and that account has a live pool cooldown, or identifies one account in a generic OAuth pool that still has an eligible sibling. `src/server/responses/core-combo-failure.ts` checks the pool's health record before passing that attribution; for a generic OAuth pool it first hands the account (matched through its `accountLogLabel`) to `rotateGenericOAuthAccountOn429`, which cools it under the pool's own Retry-After policy even when the per-request account budget ended rotation before that account was recorded, and attributes the failure only when the rotator names a sibling. Unknown accounts, ambiguous labels, a lone or fully cooled generic OAuth pool, API-key providers, and other failures keep their ordinary target cooldown. An API-key pool needs no attribution: its 429 rotation walks every key inside the attempt, so a 429 reaches the combo only once every key is cooled. Regression coverage: `tests/oauth/generic-oauth-combo-account-cooldown.test.ts`. A 402 is the provider-scoped twin for an Anthropic OAuth pool: the pool rotates only on 401/403/429, so when the failed child identifies one pool account and the failure carries the exact credit-balance refusal (`isAnthropicBillingFailure`), `core-combo-failure.ts` records that account's refusal through the pool's `recordAnthropicAccountRefusal` (the same entitlement backoff a 403 credit refusal gets) and `resolve.ts` omits every target cooldown only while the pool still has an eligible account; a lone account, an exhausted pool, an unidentified account, or any other 402 keeps the provider-scoped cooldown. Regression coverage: `tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts`. The Anthropic OAuth pool's own all-accounts-cooled 429 is an unattributed exception: `isAnthropicPoolLocalRefusal` in `core-combo-failure.ts` requires an Anthropic OAuth instance (`anthropic`, or a configured and enabled `anthropic2` row) with `authMode: "oauth"`, status 429, no identified failed account, no eligible pool account and a live pool retry-after. The target then still cools, but for the local fallback instead of the restated per-account `Retry-After`, so a resumed or newly added account is not ignored until a 24-hour target cooldown expires. An upstream 429 on an API-key provider or on an identified pool account keeps its full `Retry-After`. Regression coverage: `tests/routing/always-on-429-failover.test.ts`. Cooldown entries in `src/combos/failover.ts` retain the failure status. The quota-only snapshot query records target/expiry pairs for unexpired 429/402 cooldowns using only cooldown map lookups. Its config-aware wrapper in `src/combos/resolve.ts` applies the picker's provider availability and cached quota checks before dispatch; request eligibility runs lazily only when exhaustion considers a 503, with throwing checks treated as ineligible. Responses exhaustion uses this evidence under the [failover contract](transports/responses-failover.md); ordinary cooldown selection and timing stay unchanged. Opt-in `cooldownReprobe: { enabled: true, intervalMs }` in `src/combos/resolve.ts` permits an initial non-preview request to reserve all-cooled eligible targets once per configured interval (default 300000 ms, range 1000..86400000). The synchronous reservation lives in selection state and resets on proxy restart or selection-state reset; the reserved target keys are carried only by that request's picks; shared cooldowns remain recorded and continue to exclude concurrent requests. Each reservation names the cooldown write's unique revision, not its expiry. A successful dispatch settles through `settleComboReprobeSuccess`, which lifts only that unchanged reserved write; unprobed and re-cooled targets stay recorded, including replacements with an identical Retry-After expiry. Route-level selection without request eligibility disables reprobes, as does the in-flight retry-after-cooldown path, which waits for normal expiry. Nested wait-path and JEV selections retain the same reservation without starting a second reprobe. After ordinary or last-resort-deferral waits and after an awaited JEV decision, selection rechecks provider and request eligibility at the current clock and permits only unchanged-revision bypasses. Preparation first checks available siblings without evaluating cooled targets; a throwing eligibility predicate is ineligible for recovery. Encrypted-task recovery relaxes only payload readability and retains metering, JEV, reasoning-replay and protocol-lane eligibility. Its recovery selection may reserve a reprobe only after Responses ingress, thread-spawn, enabled recovery configuration and non-child-attempt admission pass; refused recovery preserves cooldowns and the reservation. New failures record cooldowns normally, and provider quota, account admission, payload eligibility, metered-spend and cancellation checks remain authoritative. There is no timer; existing send bounds remain. The opt-in may retry a target before its server Retry-After. CLI `--cooldown-reprobe on|off` and `--cooldown-reprobe-interval` control it; omitted management fields preserve it on unrelated saves. Tests: `tests/codex-integration/combo-cooldown-reprobe.test.ts`, `tests/server/server-combo-cooldown-fallback.test.ts` and `tests/cli/cli-combo-parity.test.ts`. A zero-attempt `combo_unavailable` names why each target was skipped. `comboExclusionReasons` in `src/combos/resolve.ts` derives one coarse label per target from the picker's own checks, in picker order: `provider missing`, `provider disabled`, `quota exhausted`, `cooldown`, then `ineligible for this request` when the caller's eligibility predicate refuses it or throws. `NoAvailableComboTargetsError` and `comboUnavailable` append them to the message; the description carries target counts and indices, validated provider-id labels and closed reasons; configured model strings and combo aliases are omitted. Coverage: `tests/responses/responses-combo-exhausted-error.test.ts`. The same pass (`comboExclusion`) also yields machine-readable diagnostics (#7965): `comboUnavailableResponse` in `src/server/responses/core-errors.ts` adds `error.combo = { cause, targets, attempted, causes }` to the unchanged `combo_unavailable` code. A target's class is `quota` (cached quota spent, or a cooldown whose retained status is 429/402), `permission` (cooldown status 401/403), `transient` (any other cooldown, read through `comboTargetCooldownStatus` in `src/combos/failover.ts`), `unsupported` (request-ineligible, including the mandatory `tool_choice` refusals in `core-combo.ts`, where `comboTargetUnavailableCause` lets provider state, quota and live cooldowns keep precedence) or `unavailable` (provider missing or disabled); `cause` is the shared class, `mixed`, or `unknown`. The quota-snapshot exhaustion answer reports `quota` with the targets the ladder dispatched. Counts and closed classes only; no combo id, provider, model or upstream text. Coverage: `tests/responses/responses-combo-unavailable-cause.test.ts`. Ordinary local Codex account-cooldown refusals carry unforgeable process-local Response identity from `src/codex/account-cooldown-response.ts` through combo failure reconstruction. At target cooldown recording only, `core-combo.ts` drops their restated retry/reset metadata and retains capped local backoff; client retry advice and account admission remain unchanged. Main hard-lock, credit, Reserve and transient-policy subclasses are excluded. The [combo cooldown contract](transports/responses-failover.md#single-target-cooldown-retry-ownership) owns this distinction; `tests/server/server-combo-cooldown-recording.test.ts` covers recovery and upstream wire-copy controls. ## Combo default effort precedence diff --git a/tests/routing/always-on-429-failover.test.ts b/tests/routing/always-on-429-failover.test.ts index 9892d526e6a..7d17aff33a4 100644 --- a/tests/routing/always-on-429-failover.test.ts +++ b/tests/routing/always-on-429-failover.test.ts @@ -17,7 +17,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { clearComboTargetCooldowns, coolComboTarget, isComboTargetInCooldown } from "../../src/combos/failover"; import { createTranslatorBudget } from "../../src/lib/translator-budget"; -import { executeComboResponses, isAnthropicPoolLocalRefusal } from "../../src/server/responses/core-combo"; +import { executeComboResponses } from "../../src/server/responses/core-combo"; +import { isAnthropicPoolLocalRefusal } from "../../src/server/responses/core-combo-failure"; import type { ResponsesDispatchers } from "../../src/server/responses/core-options"; import { clearAnthropicAccountPoolState, diff --git a/tests/server/server-combo-main-account-cooldown.test.ts b/tests/server/server-combo-main-account-cooldown.test.ts index f877e7d04e6..9da44252981 100644 --- a/tests/server/server-combo-main-account-cooldown.test.ts +++ b/tests/server/server-combo-main-account-cooldown.test.ts @@ -9,7 +9,7 @@ import { clearCodexUpstreamHealth, clearCodexUpstreamHealthForAccount, recordCod import { reconcileMainCodexAccountRuntimeState, resetMainCodexAccountIdentityTrackingForTests } from "../../src/codex/account-lifecycle"; import { saveCodexAccountCredential } from "../../src/codex/account-store"; import { handleResponses } from "../../src/server/responses"; -import { cooledPoolAccountLabel } from "../../src/server/responses/core-combo"; +import { cooledPoolAccountLabel } from "../../src/server/responses/core-combo-failure"; import type { OcxConfig } from "../../src/types"; import { responsesSuccess } from "../helpers/combo-failover-upstream"; import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; From 31555ce2ac433e6a18b48468f3815d4ed596fce6 Mon Sep 17 00:00:00 2001 From: OSH <83574029+sedoll@users.noreply.github.com> Date: Wed, 25 Nov 2026 11:34:00 +0900 Subject: [PATCH 05/60] chore(catalog): drop orphaned docstring at end of restore.ts (#8973) The file ended with a doc comment describing "Force Codex's models_cache stale from the on-disk catalog", with no function after it. That behavior lives in invalidateCodexModelsCache (retained-sync.ts); only the stub was left behind. Comment-only change, no runtime effect. Co-authored-by: Claude Sonnet 5.5 Co-authored-by: JUN Co-authored-by: lidge-jun --- src/codex/catalog/restore.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/codex/catalog/restore.ts b/src/codex/catalog/restore.ts index ca7139596e3..1cbdaab1ef6 100644 --- a/src/codex/catalog/restore.ts +++ b/src/codex/catalog/restore.ts @@ -141,5 +141,3 @@ export function restoreCodexCatalog(): { removed: number; kept: number; path: st } return outcome.value; } - -/** Force Codex's models_cache stale from the on-disk catalog. Returns whether a cache write occurred. */ From 50c1079fd3a4e68f0b44349d63f9474bcda1e1cd Mon Sep 17 00:00:00 2001 From: iQuantum <140757050+AyhamJo7@users.noreply.github.com> Date: Wed, 25 Nov 2026 03:39:52 +0100 Subject: [PATCH 06/60] fix(catalog): name a configured Ultrafast tier like the native one (#9104) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(catalog): name a configured Ultrafast tier like the native one A routed model with an explicit ultrafast mapping advertised its tier as "Ultra Fast". Codex CLI builds a slash command from the name (/ultra fast, split on the space, so neither spelling runs) and T3 Code matches the label "Ultrafast" for its speed indicators. The configured tier now takes its name from NATIVE_ULTRAFAST_SERVICE_TIER. Fixes #9100 * docs(catalog): name the routed speed choice Ultrafast in the Codex Desktop guide The configured tier now publishes the native Ultrafast name; the English, Korean and Spanish guides still told users to pick Ultra Fast / Ultra rápido. --------- Co-authored-by: JUN --- docs-site/src/content/docs/es/guides/codex-app-models.md | 4 ++-- docs-site/src/content/docs/guides/codex-app-models.md | 4 ++-- docs-site/src/content/docs/ko/guides/codex-app-models.md | 4 ++-- src/codex/catalog/configured-tiers.ts | 4 +++- .../configured-ultrafast-picker.test.ts | 9 +++++++++ 5 files changed, 18 insertions(+), 7 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/codex-app-models.md b/docs-site/src/content/docs/es/guides/codex-app-models.md index aa8951231ab..c61f473fb09 100644 --- a/docs-site/src/content/docs/es/guides/codex-app-models.md +++ b/docs-site/src/content/docs/es/guides/codex-app-models.md @@ -225,7 +225,7 @@ dependen del proveedor; ni el menú ni una solicitud prueban por sí solos qué ### Selección ultra rápida en el escritorio Codex -Para un proveedor que admita `service_tier: "ultrafast"`, declare esa asignación de cables una vez. opencodex publica entonces **Ultra rápido** en el menú de velocidad nativo Codex del modelo enrutado; no hay necesidad de editar `opencodex-catalog.json` después de cada sincronización. Por ejemplo, fusione estos campos en un proveedor API configurado para GPT-6.1 Sol: +Para un proveedor que admita `service_tier: "ultrafast"`, declare esa asignación de cables una vez. opencodex publica entonces **Ultrafast** en el menú de velocidad nativo Codex del modelo enrutado; no hay necesidad de editar `opencodex-catalog.json` después de cada sincronización. Por ejemplo, fusione estos campos en un proveedor API configurado para GPT-6.1 Sol: ```json { @@ -239,7 +239,7 @@ Para un proveedor que admita `service_tier: "ultrafast"`, declare esa asignació } ``` -La asignación se aplica a todos los modelos Fast-elegibles en ese proveedor. Utilice una entrada de proveedor independiente si solo algunos de sus modelos son compatibles con Ultra Fast. Mantenga el modo rápido de opencodex en **Auto** (omit `fastMode` ) para que la selección de velocidad de la aplicación llegue al proveedor; forzó a Fast a enviar `priority`, y forzó a Default a dejar caer el nivel. Actualizar el catálogo de modelos, reiniciar el escritorio Codex si todavía tiene la lista anterior, seleccione el modelo enrutado y luego elija **Ultra rápido** en su menú de velocidad. El estándar sigue siendo el valor predeterminado. +La asignación se aplica a todos los modelos Fast-elegibles en ese proveedor. Utilice una entrada de proveedor independiente si solo algunos de sus modelos son compatibles con Ultra Fast. Mantenga el modo rápido de opencodex en **Auto** (omit `fastMode` ) para que la selección de velocidad de la aplicación llegue al proveedor; forzó a Fast a enviar `priority`, y forzó a Default a dejar caer el nivel. Actualizar el catálogo de modelos, reiniciar el escritorio Codex si todavía tiene la lista anterior, seleccione el modelo enrutado y luego elija **Ultrafast** en su menú de velocidad. El estándar sigue siendo el valor predeterminado. Solo un cable `service-tier` elegible con una asignación explícita de `ultrafast → ultrafast` agrega esta opción a las filas enrutadas; el soporte Fast ordinario o un nombre similar a GPT es insuficiente. Esa asignación enrutada no se aplica a filas nativas/de cuenta o alias combinados. La eliminación de la asignación o la desactivación del soporte de nivel de servicio de ese modelo elimina la opción enrutada generada tanto del catálogo como de la caché en la siguiente sincronización exitosa. La declaración activa también controla la opción Ultra Fast cuando Codex carga su lista de modelos sobre HTTP. diff --git a/docs-site/src/content/docs/guides/codex-app-models.md b/docs-site/src/content/docs/guides/codex-app-models.md index 8b05177c06e..d3795d14006 100644 --- a/docs-site/src/content/docs/guides/codex-app-models.md +++ b/docs-site/src/content/docs/guides/codex-app-models.md @@ -367,7 +367,7 @@ the menu nor a request alone proves which tier was billed. ### Selecting Ultra Fast in Codex Desktop For a provider that supports `service_tier: "ultrafast"`, declare that wire mapping once. -opencodex then publishes **Ultra Fast** in the routed model's native Codex speed menu; +opencodex then publishes **Ultrafast** in the routed model's native Codex speed menu; there is no need to edit `opencodex-catalog.json` after every sync. For example, merge these fields into an API provider configured for GPT-6.1 Sol: @@ -387,7 +387,7 @@ The mapping applies to every Fast-eligible model on that provider. Use a separat entry if only some of its models support Ultra Fast. Keep opencodex's Fast mode on **Auto** (omit `fastMode`) so the app's speed selection reaches the provider; forced Fast sends `priority`, and forced Default drops the tier. Refresh the model catalog, restart Codex -Desktop if it still has the old list, select the routed model, then choose **Ultra Fast** +Desktop if it still has the old list, select the routed model, then choose **Ultrafast** in its speed menu. Standard remains the default. Only an eligible `service-tier` wire with an explicit `ultrafast → ultrafast` mapping adds diff --git a/docs-site/src/content/docs/ko/guides/codex-app-models.md b/docs-site/src/content/docs/ko/guides/codex-app-models.md index edb4ab872ce..bc8664e331d 100644 --- a/docs-site/src/content/docs/ko/guides/codex-app-models.md +++ b/docs-site/src/content/docs/ko/guides/codex-app-models.md @@ -218,7 +218,7 @@ Fast 또는 Default 강제 모드는 Flex 선택을 덮어씁니다. `ocx sync` ### Codex 데스크톱에서 Ultra Fast 선택 `service_tier: "ultrafast"`를 지원하는 프로바이더에는 전송 매핑을 한 번 설정하면 됩니다. -opencodex가 라우팅 모델의 Codex 기본 속도 메뉴에 **Ultra Fast**를 추가하므로, 동기화할 때마다 +opencodex가 라우팅 모델의 Codex 기본 속도 메뉴에 **Ultrafast**를 추가하므로, 동기화할 때마다 `opencodex-catalog.json`을 직접 수정할 필요가 없습니다. 예를 들어 GPT-6.1 Sol용 API 프로바이더의 기존 설정에 다음 필드를 병합하세요. @@ -238,7 +238,7 @@ opencodex가 라우팅 모델의 Codex 기본 속도 메뉴에 **Ultra Fast**를 Ultra Fast를 지원한다면 별도 프로바이더 항목을 사용하세요. 앱에서 선택한 속도를 전달하려면 opencodex의 Fast 모드를 **Auto**로 유지하세요(`fastMode` 생략). Fast 강제 모드는 `priority`를 전송하고, Default 강제 모드는 tier를 제거합니다. 모델 카탈로그를 새로고침하고, 앱에 이전 -목록이 남아 있다면 Codex 데스크톱을 다시 시작한 뒤 라우팅 모델의 속도 메뉴에서 **Ultra Fast**를 +목록이 남아 있다면 Codex 데스크톱을 다시 시작한 뒤 라우팅 모델의 속도 메뉴에서 **Ultrafast**를 선택하세요. 기본 속도는 Standard로 유지됩니다. 이 선택지를 라우팅 항목에 자동 생성하려면 사용 가능한 `service-tier` 전송 경로와 명시적인 diff --git a/src/codex/catalog/configured-tiers.ts b/src/codex/catalog/configured-tiers.ts index 9cbe3cbfa90..bcfaafa03bd 100644 --- a/src/codex/catalog/configured-tiers.ts +++ b/src/codex/catalog/configured-tiers.ts @@ -5,6 +5,7 @@ import { fastPolicyForModel } from "../../providers/service-tier"; import type { ResolvedFastPolicy } from "../../providers/fastwire"; import { catalogModelSlug, type CatalogModel, type RawEntry } from "./parsing"; import { preserveOperatorUltraFastTiers } from "./operator-tiers"; +import { NATIVE_ULTRAFAST_SERVICE_TIER } from "./native-ultrafast"; const MANAGED_ULTRAFAST = "opencodex_managed_ultrafast"; @@ -50,7 +51,8 @@ export function applyConfiguredUltraFast( if (!configured) return; entry.service_tiers = [...(Array.isArray(entry.service_tiers) ? entry.service_tiers : []), { id: "ultrafast", - name: "Ultra Fast", + // Clients key on the name: Codex CLI makes it a slash command, T3 Code matches "Ultrafast". + name: NATIVE_ULTRAFAST_SERVICE_TIER.name, description: "Higher speed and usage; provider access required", }]; entry.additional_speed_tiers = [ diff --git a/tests/codex-integration/configured-ultrafast-picker.test.ts b/tests/codex-integration/configured-ultrafast-picker.test.ts index 17999c05c55..ccca7dbd7dc 100644 --- a/tests/codex-integration/configured-ultrafast-picker.test.ts +++ b/tests/codex-integration/configured-ultrafast-picker.test.ts @@ -8,6 +8,7 @@ import { captureFastPolicyAuthority, fastPolicyForModel } from "../../src/provid import { decideTier } from "../../src/providers/fastwire"; import { applyProviderConfigHints } from "../../src/codex/catalog/model-hints"; import { configuredUltraFastSlugs, retainedFlexPolicyBySlug } from "../../src/codex/catalog/configured-tiers"; +import { NATIVE_ULTRAFAST_SERVICE_TIER } from "../../src/codex/catalog/native-ultrafast"; import { buildCatalogEntriesFromObservedState, mergeCatalogEntriesFromObservedState, type ObservedCatalogMergeInput } from "../../src/codex/catalog/build-entries"; import type { CatalogModel, RawEntry } from "../../src/codex/catalog/parsing"; import { repoRoot } from "../helpers/repo-root"; @@ -63,6 +64,14 @@ describe("configured Ultra Fast in the native Codex speed picker", () => { .toEqual({ kind: "set", value: "ultrafast" }); }); + // Codex CLI turns a tier name into a slash command and T3 Code matches the label "Ultrafast": + // "Ultra Fast" became `/ultra fast`, which Codex splits on the space and cannot run (#9100). + test("a configured tier carries the native Ultrafast name", () => { + const tier = merge()[0]!.service_tiers.find((t: { id: string }) => t.id === "ultrafast"); + expect(tier.name).toBe(NATIVE_ULTRAFAST_SERVICE_TIER.name); + expect(tier.name).not.toMatch(/\s/); + }); + test.each([ ["ordinary Fast", { fastWire: undefined }], ["unclassified gateway", { modelSupportsServiceTier: {} }], From 9b5861c1a19a75cfdce095c9cb3171baca6b3a72 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 11:40:11 +0900 Subject: [PATCH 07/60] feat(providers): add AI/ML API as a built-in provider (#8935) Adds the `aimlapi` canonical key preset for AI/ML API, carried from #8919 and #7904. Discovery strips the preset's registry static headers whenever discovery targets a different origin. Built-in preset counts in the docs are updated to 113 total and 91 key-based. The owner granted a policy exception for the canonical-preset evidence on 2026-11-25. Co-authored-by: Hugo Co-authored-by: Stan Co-authored-by: Vito Bush <152179873+vito-bush@users.noreply.github.com> --- .../docs/es/getting-started/quickstart.md | 2 +- .../content/docs/es/guides/api-key-catalog.md | 13 +- .../docs/fr/getting-started/quickstart.md | 2 +- .../src/content/docs/fr/guides/providers.md | 2 +- .../docs/getting-started/quickstart.md | 2 +- .../content/docs/guides/api-key-catalog.md | 13 +- .../docs/ja/getting-started/quickstart.md | 2 +- .../src/content/docs/ja/guides/providers.md | 2 +- .../docs/ko/getting-started/quickstart.md | 2 +- .../src/content/docs/ko/guides/providers.md | 2 +- .../docs/ru/getting-started/quickstart.md | 2 +- .../src/content/docs/ru/guides/providers.md | 2 +- .../docs/tr/getting-started/quickstart.md | 2 +- .../src/content/docs/tr/guides/providers.md | 2 +- .../docs/zh-cn/getting-started/quickstart.md | 2 +- .../content/docs/zh-cn/guides/providers.md | 2 +- .../docs/zh-tw/getting-started/quickstart.md | 2 +- .../content/docs/zh-tw/guides/providers.md | 2 +- scripts/test-layout/layout-providers.json | 1 + src/oauth/index.ts | 13 +- src/providers/registry-static-headers.ts | 39 +++ src/providers/registry.ts | 1 + src/providers/registry/entries-extended.ts | 65 +++++ src/providers/routed-config.ts | 7 +- structure/INDEX.md | 6 + structure/manifest.json | 13 + structure/ops/docs-and-release.md | 2 +- structure/providers/aimlapi.md | 19 ++ tests/fixtures/test-layout-expected.json | 1 + tests/providers/aimlapi-provider.test.ts | 233 ++++++++++++++++++ 30 files changed, 431 insertions(+), 27 deletions(-) create mode 100644 src/providers/registry-static-headers.ts create mode 100644 structure/providers/aimlapi.md create mode 100644 tests/providers/aimlapi-provider.test.ts diff --git a/docs-site/src/content/docs/es/getting-started/quickstart.md b/docs-site/src/content/docs/es/getting-started/quickstart.md index 478f662906d..4f045d47283 100644 --- a/docs-site/src/content/docs/es/getting-started/quickstart.md +++ b/docs-site/src/content/docs/es/getting-started/quickstart.md @@ -23,7 +23,7 @@ ocx init `ocx init` te guía por estos pasos: -1. **Elegir un proveedor**: selecciona uno de los 112 preajustes del registro integrado o `custom` para introducir una URL base y un adaptador. +1. **Elegir un proveedor**: selecciona uno de los 113 preajustes del registro integrado o `custom` para introducir una URL base y un adaptador. 2. **Clave API**: pega una clave o indica una variable de entorno como `${ANTHROPIC_API_KEY}`. 3. **Modelo predeterminado**: para proveedores con clave, locales o personalizados, acepta el preajuste o introduce un identificador de modelo. 4. **Puerto del proxy**: `10100` de forma predeterminada. diff --git a/docs-site/src/content/docs/es/guides/api-key-catalog.md b/docs-site/src/content/docs/es/guides/api-key-catalog.md index a4f7bd5974b..c79f046388d 100644 --- a/docs-site/src/content/docs/es/guides/api-key-catalog.md +++ b/docs-site/src/content/docs/es/guides/api-key-catalog.md @@ -9,7 +9,7 @@ de cuentas y los proveedores locales siguen en esa página. Para rotar cuentas de suscripción, consulta [`reset-near-weighted`](/es/reference/configuration/providers/#reset-near-weighted) en los grupos OAuth de Codex y Anthropic. Los grupos de claves API usan sus propios [ajustes de selección de claves](/es/reference/configuration/providers/). -opencodex incluye 112 preajustes integrados: 90 con clave, 18 OAuth, tres locales y uno predeterminado de reenvío a ChatGPT. El selector **Añadir proveedor** abre el formulario del proveedor con clave, valida la credencial cuando el proveedor permite comprobarla y la guarda; cada proveedor tiene su propia validación. Entre ellos: +opencodex incluye 113 preajustes integrados: 91 con clave, 18 OAuth, tres locales y uno predeterminado de reenvío a ChatGPT. El selector **Añadir proveedor** abre el formulario del proveedor con clave, valida la credencial cuando el proveedor permite comprobarla y la guarda; cada proveedor tiene su propia validación. Entre ellos: **ClinePass** utiliza una clave API de Cline con el [catálogo oficial de suscripción](https://docs.cline.bot/getting-started/clinepass) y el [punto final de Chat Completions](https://docs.cline.bot/api/chat-completions), operados por Cline Bot Inc. bajo [los términos de Cline](https://cline.bot/tos). Un id enrutado como `cline-pass/cline-pass/kimi-k3` es intencional: el primer segmento selecciona el proveedor de opencodex, mientras que `cline-pass/kimi-k3` es el identificador de modelo completo que se envía aguas arriba. La cuota de ClinePass se comparte por cuenta entre límites rotativos de 5 horas, semanales y mensuales. Una sonda en vivo del 2026-08-13 verificó que todos los modelos estáticos de ClinePass aceptan `low`, `medium`, `high`, `xhigh` y `max` en el límite de entrada de la pasarela. opencodex conserva los niveles solicitados; cualquier normalización específica del backend sigue siendo responsabilidad de ClinePass. @@ -74,6 +74,7 @@ opencodex incluye 112 preajustes integrados: 90 con clave, 18 OAuth, tres locale | TokenLab | `https://api.tokenlab.sh/v1` | | Modelflare | `https://modelflare.dev/v1` | | AI Stupid Level | `https://aistupidlevel.info/v1` | +| AI/ML API | `https://api.aimlapi.com/v1` | | cheapaimodel | `https://api.cheapaimodel.ai/v1` | | AbliteratedLLM | `https://api.abliteratedllm.dev/v1` | | OpenGateway | `https://apis.opengateway.ai/v1` | @@ -535,6 +536,16 @@ Ollama actualmente documenta salidas estructuradas como no compatibles en Ollama ## Cambios del catálogo y cuotas +**AI/ML API**, operado por Boiler Labs FZ-LLC conforme a sus [condiciones del servicio](https://aimlapi.com/terms-and-conditions), +es una pasarela compatible con OpenAI en `https://api.aimlapi.com/v1`. Crea una [clave de API](https://aimlapi.com/app/keys) +y selecciona **AI/ML API** en `ocx init` o en **Añadir proveedor**, o ejecuta `ocx provider add aimlapi`. +Introduce la clave directamente o como referencia `${AIMLAPI_API_KEY}`. El preajuste usa Chat Completions +y conserva los prefijos de proveedor de los modelos, como `openai/gpt-5.6-terra` (el predeterminado). +La detección de modelos filtra el catálogo público de `GET /v1/models` para incluir las entradas de +Chat Completions. El catálogo público no permite validar las claves de API. +Las solicitudes al destino del preajuste incluyen la cabecera de atribución `X-AIMLAPI-Source`. +Esa cabecera se elimina si el preajuste se configura con otro origen. + **cheapaimodel** es una pasarela de pago por token para modelos abiertos DeepSeek, GLM y Kimi, y Grok, operada por LINKOVA PTE. LTD. Crea una [clave API](https://console.cheapaimodel.ai/keys) con saldo prepago USD y elige el preajuste en init/dashboard u `ocx provider add cheapaimodel`, con clave o `${CHEAPAIMODEL_API_KEY}`. Usa `https://api.cheapaimodel.ai/v1` y [Chat Completions](https://cheapaimodel.ai/docs/api/create-chat-completion) para todos los clientes, no sus rutas Responses/Messages. Descubre por [`GET /v1/models`](https://cheapaimodel.ai/docs/api/list-models), que devuelve 401 sin clave válida. Incluye `deepseek-v4-1-flash`, predeterminado, `glm-5.3`, `glm-5.3-flash`, `kimi-k3` y `grok-4.7`. GLM 5.3 es solo texto; sus imágenes van al sidecar. Kimi K3 usa muestreo propio y no recibe `temperature` ni `top_p`. Se aplican sus [términos](https://cheapaimodel.ai/terms) y [privacidad](https://cheapaimodel.ai/privacy). **AbliteratedLLM** es una API de pago por token para modelos abiertos abliterados (sin rechazos) y de serie, con saldo prepago en USD por tarjeta o criptomoneda. Crea una [clave API](https://abliteratedllm.dev/dashboard/keys) y elige **AbliteratedLLM** en `ocx init` o **Añadir proveedor**, o ejecuta `ocx provider add abliteratedllm`, con la clave o la referencia `${ABLITERATEDLLM_API_KEY}`. El preajuste usa [Chat Completions](https://abliteratedllm.dev/docs/chat-completions) en `https://api.abliteratedllm.dev/v1` para todos los clientes, no sus rutas Responses (sin estado) ni Anthropic Messages, y usa una lista de modelos predefinida: el [`GET /v1/models`](https://abliteratedllm.dev/docs/models) público responde sin clave y no puede validarla, así que el descubrimiento en vivo está desactivado. `glm-5.3-flash-abliterated` es el predeterminado. El 2026-11-15, `GET /v1/models` listaba 15 modelos: `glm-5.3-flash-abliterated`, el único abliterado (marcado `variant: "abliterated"`), y 14 con `provider_label: "Stock model"`, los pesos originales de cada fabricante. Ninguno llevaba la etiqueta "Official DeepSeek API", la que la política de privacidad usa para las solicitudes reenviadas a la API propia de DeepSeek; los modelos listados, incluidos los de DeepSeek, se ejecutan en Fireworks AI con retención cero de datos. `glm-5.3` y `glm-5.3-fast` son solo texto, así que sus imágenes van al sidecar de visión. `reasoning_effort` se envía como `low`, `medium` o `high`; los niveles superiores se envían como `high`. Se aplican las [condiciones](https://abliteratedllm.dev/terms) y la [política de privacidad](https://abliteratedllm.dev/privacy) de AbliteratedLLM. diff --git a/docs-site/src/content/docs/fr/getting-started/quickstart.md b/docs-site/src/content/docs/fr/getting-started/quickstart.md index ab2f8598d00..602ea289365 100644 --- a/docs-site/src/content/docs/fr/getting-started/quickstart.md +++ b/docs-site/src/content/docs/fr/getting-started/quickstart.md @@ -13,7 +13,7 @@ ocx init `ocx init` vous accompagne dans les étapes suivantes : -1. **Choix d’un fournisseur** — sélectionnez l’un des 112 préréglages intégrés au registre, ou `custom` pour saisir une +1. **Choix d’un fournisseur** — sélectionnez l’un des 113 préréglages intégrés au registre, ou `custom` pour saisir une URL de base et un adaptateur. 2. **Clé API** — collez une clé ou référencez une variable d’environnement telle que `${ANTHROPIC_API_KEY}`. 3. **Modèle par défaut** — pour les fournisseurs clés, locaux et personnalisés, acceptez le préréglage ou saisissez un identifiant de modèle. diff --git a/docs-site/src/content/docs/fr/guides/providers.md b/docs-site/src/content/docs/fr/guides/providers.md index dc03db40597..53c39ace106 100644 --- a/docs-site/src/content/docs/fr/guides/providers.md +++ b/docs-site/src/content/docs/fr/guides/providers.md @@ -310,7 +310,7 @@ existante n'est pas concernée. ## 3. Catalogue des clés API -opencodex fournit 112 préréglages intégrés : 90 à clé, 18 OAuth, trois locaux et un préréglage par défaut de +opencodex fournit 113 préréglages intégrés : 91 à clé, 18 OAuth, trois locaux et un préréglage par défaut de transfert ChatGPT. Dans le tableau de bord, le sélecteur **Ajouter un fournisseur** ouvre le tableau de bord du fournisseur à clé, valide la clé et l'enregistre ; la validation dépend du fournisseur. Parmi les entrées notables : diff --git a/docs-site/src/content/docs/getting-started/quickstart.md b/docs-site/src/content/docs/getting-started/quickstart.md index f215bec79b6..2873c05324e 100644 --- a/docs-site/src/content/docs/getting-started/quickstart.md +++ b/docs-site/src/content/docs/getting-started/quickstart.md @@ -21,7 +21,7 @@ ocx init `ocx init` walks you through: -1. **Pick a provider** — choose one of the 112 built-in registry presets or `custom` to type a base +1. **Pick a provider** — choose one of the 113 built-in registry presets or `custom` to type a base URL and adapter. 2. **API key** — paste a key, or reference an environment variable like `${ANTHROPIC_API_KEY}`. 3. **Default model** — for key, local, and custom providers, accept the preset or enter a model id. diff --git a/docs-site/src/content/docs/guides/api-key-catalog.md b/docs-site/src/content/docs/guides/api-key-catalog.md index 38b00768e35..0a457e57483 100644 --- a/docs-site/src/content/docs/guides/api-key-catalog.md +++ b/docs-site/src/content/docs/guides/api-key-catalog.md @@ -9,7 +9,7 @@ stay on that page. For subscription account rotation, see [`reset-near-weighted`](/reference/configuration/providers/#reset-near-weighted) for the Codex and Anthropic OAuth pools. API-key pools use their own [key selection settings](/reference/configuration/providers/). -opencodex ships 112 built-in presets: 90 key-based, 18 OAuth, three local, and one default +opencodex ships 113 built-in presets: 91 key-based, 18 OAuth, three local, and one default ChatGPT-forward preset. The dashboard's **Add provider** picker opens a key provider's dashboard, validates the key where the provider can check one, and stores it. Notable entries: @@ -102,6 +102,7 @@ region-pinned EU routes, is at [opper.ai/models](https://opper.ai/models). Opper | TokenLab | `https://api.tokenlab.sh/v1` | | Modelflare | `https://modelflare.dev/v1` | | AI Stupid Level | `https://aistupidlevel.info/v1` | +| AI/ML API | `https://api.aimlapi.com/v1` | | cheapaimodel | `https://api.cheapaimodel.ai/v1` | | AbliteratedLLM | `https://api.abliteratedllm.dev/v1` | | OpenGateway | `https://apis.opengateway.ai/v1` | @@ -223,6 +224,16 @@ output tokens, which hold for any model the router picks. The router accepts tex routing mode or pinned model at the preset destination the proxy hands images to the vision sidecar instead of sending them. Its Anthropic Messages endpoint is a passthrough to Anthropic without routing, so the preset does not use it. +**AI/ML API**, operated by Boiler Labs FZ-LLC under its [Terms of Service](https://aimlapi.com/terms-and-conditions), +is an OpenAI-compatible gateway at `https://api.aimlapi.com/v1`. Create an [API key](https://aimlapi.com/app/keys), +then select **AI/ML API** in `ocx init` or the dashboard's **Add provider** picker, or run +`ocx provider add aimlapi`. Provide the key directly or as `${AIMLAPI_API_KEY}`. +The preset uses Chat Completions and preserves vendor-prefixed model IDs, such as +`openai/gpt-5.6-terra` (the default). Live discovery filters the public `GET /v1/models` catalog +to Chat Completions entries. The public catalog cannot validate API keys. +Requests to the preset destination carry the `X-AIMLAPI-Source` attribution header. It is removed +when the preset is configured with another origin. + **cheapaimodel** is a pay-per-token API gateway for open-weight models (DeepSeek, GLM, Kimi) and Grok, operated by LINKOVA PTE. LTD. Create an [API key](https://console.cheapaimodel.ai/keys) on a prepaid USD balance, then select **cheapaimodel** in `ocx init` or the dashboard's **Add provider** diff --git a/docs-site/src/content/docs/ja/getting-started/quickstart.md b/docs-site/src/content/docs/ja/getting-started/quickstart.md index 0664f063d62..84f7da28caf 100644 --- a/docs-site/src/content/docs/ja/getting-started/quickstart.md +++ b/docs-site/src/content/docs/ja/getting-started/quickstart.md @@ -18,7 +18,7 @@ ocx init `ocx init` では次の手順を説明します。 -1. **プロバイダーを選択してください** — 112 個の組み込みレジストリプリセットのいずれか、または `custom` を選択してベース URL とアダプターを入力します。 +1. **プロバイダーを選択してください** — 113 個の組み込みレジストリプリセットのいずれか、または `custom` を選択してベース URL とアダプターを入力します。 2. **API キー** — キーを貼り付けるか、`${ANTHROPIC_API_KEY}` のような環境変数を参照します。 3. **デフォルト モデル** — キー、ローカル、カスタム プロバイダーの場合は、プリセットを受け入れるか、モデル ID を入力します。 4. **プロキシ ポート** — デフォルトは `10100` です。 diff --git a/docs-site/src/content/docs/ja/guides/providers.md b/docs-site/src/content/docs/ja/guides/providers.md index e587a01d379..e0e46c7c6ea 100644 --- a/docs-site/src/content/docs/ja/guides/providers.md +++ b/docs-site/src/content/docs/ja/guides/providers.md @@ -210,7 +210,7 @@ Kiro のログインには Kiro CLI が必要です。Unix では `curl -fsSL ht ## 3. API キーカタログ -opencodex には組み込みプリセットが 112 個含まれています。キー方式 90、OAuth 18、ローカル 3、 +opencodex には組み込みプリセットが 113 個含まれています。キー方式 91、OAuth 18、ローカル 3、 デフォルト ChatGPT 転送プリセット 1 です。ダッシュボードの **Add provider** ピッカーはキー発行ページを開き、 入力したキーを検証した後保存します(検証はプロバイダー固有です)。主な項目は以下のとおりです: diff --git a/docs-site/src/content/docs/ko/getting-started/quickstart.md b/docs-site/src/content/docs/ko/getting-started/quickstart.md index 54a0229caf7..00b7a092bce 100644 --- a/docs-site/src/content/docs/ko/getting-started/quickstart.md +++ b/docs-site/src/content/docs/ko/getting-started/quickstart.md @@ -18,7 +18,7 @@ ocx init `ocx init`은 다음 과정을 안내합니다: -1. **프로바이더 선택** — 내장 레지스트리 프리셋 112개 중 하나를 고르거나 `custom`을 선택해 base URL과 adapter를 직접 입력합니다. +1. **프로바이더 선택** — 내장 레지스트리 프리셋 113개 중 하나를 고르거나 `custom`을 선택해 base URL과 adapter를 직접 입력합니다. 2. **API 키** — 키를 붙여넣거나 `${ANTHROPIC_API_KEY}` 같은 환경 변수를 참조합니다. 3. **기본 모델** — 키, 로컬, custom 프로바이더에서는 프리셋을 그대로 쓰거나 모델 ID를 직접 입력합니다. 4. **프록시 포트** — 기본값은 `10100`입니다. diff --git a/docs-site/src/content/docs/ko/guides/providers.md b/docs-site/src/content/docs/ko/guides/providers.md index 0ec689e1835..f4b027c5b17 100644 --- a/docs-site/src/content/docs/ko/guides/providers.md +++ b/docs-site/src/content/docs/ko/guides/providers.md @@ -212,7 +212,7 @@ Kiro 로그인에는 Kiro CLI가 필요합니다. Unix에서는 `curl -fsSL http ## 3. API 키 카탈로그 -opencodex에는 빌트인 프리셋이 112개 들어 있습니다. 키 방식 90개, OAuth 18개, 로컬 3개, +opencodex에는 빌트인 프리셋이 113개 들어 있습니다. 키 방식 91개, OAuth 18개, 로컬 3개, 기본 ChatGPT 포워드 프리셋 1개입니다. 대시보드의 **Add provider** 선택기는 키 발급 페이지를 열고, 입력한 키를 검증한 뒤 저장합니다(검증은 프로바이더별로 다릅니다). 주요 항목은 다음과 같습니다: diff --git a/docs-site/src/content/docs/ru/getting-started/quickstart.md b/docs-site/src/content/docs/ru/getting-started/quickstart.md index 3c7a9f180b2..b435866488b 100644 --- a/docs-site/src/content/docs/ru/getting-started/quickstart.md +++ b/docs-site/src/content/docs/ru/getting-started/quickstart.md @@ -18,7 +18,7 @@ ocx init `ocx init` проведёт вас по следующим шагам: -1. **Выбор провайдера** — выберите один из 112 встроенных пресетов реестра или `custom`, чтобы +1. **Выбор провайдера** — выберите один из 113 встроенных пресетов реестра или `custom`, чтобы ввести базовый URL и адаптер вручную. 2. **API-ключ** — вставьте ключ или сошлитесь на переменную окружения вида `${ANTHROPIC_API_KEY}`. 3. **Модель по умолчанию** — для провайдеров с ключом, локальных и `custom` примите значение из diff --git a/docs-site/src/content/docs/ru/guides/providers.md b/docs-site/src/content/docs/ru/guides/providers.md index 1bf3f7a7145..6a4c65a89e3 100644 --- a/docs-site/src/content/docs/ru/guides/providers.md +++ b/docs-site/src/content/docs/ru/guides/providers.md @@ -222,7 +222,7 @@ Inline JSON и лишние позиционные аргументы откло ## 3. Каталог API-ключей -opencodex поставляется с 112 встроенными пресетами: 90 на основе ключей, 18 OAuth, три локальных и +opencodex поставляется с 113 встроенными пресетами: 91 на основе ключей, 18 OAuth, три локальных и один пресет ChatGPT-форварда по умолчанию. Селектор **Add provider** в дашборде открывает страницу выдачи ключей провайдера, проверяет ключ и сохраняет его; проверка зависит от провайдера. Наиболее заметные записи: diff --git a/docs-site/src/content/docs/tr/getting-started/quickstart.md b/docs-site/src/content/docs/tr/getting-started/quickstart.md index c10f65b30ea..674db589571 100644 --- a/docs-site/src/content/docs/tr/getting-started/quickstart.md +++ b/docs-site/src/content/docs/tr/getting-started/quickstart.md @@ -13,7 +13,7 @@ ocx init `ocx init` adım adım size rehberlik eder: -1. **Bir sağlayıcı seçin** — yerleşik kayıt defterindeki 112 önayardan birini +1. **Bir sağlayıcı seçin** — yerleşik kayıt defterindeki 113 önayardan birini veya bir temel URL ile adaptör yazmak için `custom` seçeneğini belirleyin. 2. **API anahtarı** — bir anahtar yapıştırın veya `${ANTHROPIC_API_KEY}` gibi bir ortam değişkenine başvurun. diff --git a/docs-site/src/content/docs/tr/guides/providers.md b/docs-site/src/content/docs/tr/guides/providers.md index 03317bed745..5e41868ee1d 100644 --- a/docs-site/src/content/docs/tr/guides/providers.md +++ b/docs-site/src/content/docs/tr/guides/providers.md @@ -342,7 +342,7 @@ olmayan bir makineden oturum açmak bundan etkilenmez. ## 3. API anahtarı kataloğu -opencodex 112 yerleşik önayar ile birlikte gelir: 90 anahtar tabanlı, 18 +opencodex 113 yerleşik önayar ile birlikte gelir: 91 anahtar tabanlı, 18 OAuth, üç yerel ve bir varsayılan ChatGPT iletme önayarı. Kontrol panelinin **Sağlayıcı ekle** seçicisi bir anahtar sağlayıcısının kontrol panelini açar, anahtarı doğrular ve saklar; doğrulama sağlayıcıya özgüdür. Dikkate değer diff --git a/docs-site/src/content/docs/zh-cn/getting-started/quickstart.md b/docs-site/src/content/docs/zh-cn/getting-started/quickstart.md index 4d93d4dd8ff..4d85a88a4d3 100644 --- a/docs-site/src/content/docs/zh-cn/getting-started/quickstart.md +++ b/docs-site/src/content/docs/zh-cn/getting-started/quickstart.md @@ -18,7 +18,7 @@ ocx init `ocx init` 会引导你完成: -1. **选择 provider** — 从内置 registry 的 112 个预设中选择一个,或选择 `custom` 手动输入 base URL 和 adapter。 +1. **选择 provider** — 从内置 registry 的 113 个预设中选择一个,或选择 `custom` 手动输入 base URL 和 adapter。 2. **API key** — 粘贴一个 key,或引用一个环境变量,例如 `${ANTHROPIC_API_KEY}`。 3. **默认模型** — 对于 key、本地和 custom provider,接受预设值或输入模型 id。 4. **代理端口** — 默认为 `10100`。 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 ffbe65d2206..8292d0fa675 100644 --- a/docs-site/src/content/docs/zh-cn/guides/providers.md +++ b/docs-site/src/content/docs/zh-cn/guides/providers.md @@ -222,7 +222,7 @@ API Key 提供商,也不负责让 WorkBuddy 桌面客户端使用 OpenCodex ## 3. API 密钥目录 -opencodex 内置 112 个预设:90 个密钥预设、18 个 OAuth 预设、3 个本地预设,以及 1 个默认的 +opencodex 内置 113 个预设:91 个密钥预设、18 个 OAuth 预设、3 个本地预设,以及 1 个默认的 ChatGPT 转发预设。仪表盘的 **Add provider** 选择器会打开密钥提供商的控制台,验证并保存密钥。 验证因提供商而异。主要条目包括: diff --git a/docs-site/src/content/docs/zh-tw/getting-started/quickstart.md b/docs-site/src/content/docs/zh-tw/getting-started/quickstart.md index 0c163353f4d..1dd6c8bde30 100644 --- a/docs-site/src/content/docs/zh-tw/getting-started/quickstart.md +++ b/docs-site/src/content/docs/zh-tw/getting-started/quickstart.md @@ -13,7 +13,7 @@ ocx init `ocx init` 會引導你完成: -1. **選擇 provider** —— 從內建 registry 的 112 個預設中選擇一個,或選擇 `custom` 手動輸入 +1. **選擇 provider** —— 從內建 registry 的 113 個預設中選擇一個,或選擇 `custom` 手動輸入 base URL 和 adapter。 2. **API key** —— 貼上一個 key,或引用一個環境變數,例如 `${ANTHROPIC_API_KEY}`。 3. **預設模型** —— 對於 API key、本機和 custom provider,可接受預設值或輸入模型 id。 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 a33b7a71825..41811a72da6 100644 --- a/docs-site/src/content/docs/zh-tw/guides/providers.md +++ b/docs-site/src/content/docs/zh-tw/guides/providers.md @@ -264,7 +264,7 @@ database 並移除目前的 WAL、SHM 與 journal sidecar,再發布先前的 s ## 3. API 金鑰目錄 -opencodex 內建 112 個 preset:90 個 key-based、18 個 OAuth、3 個 local,以及 1 個預設 ChatGPT-forward +opencodex 內建 113 個 preset:91 個 key-based、18 個 OAuth、3 個 local,以及 1 個預設 ChatGPT-forward preset。儀表板的 **Add provider** picker 會開啟 key provider 的 dashboard、驗證金鑰並儲存;驗證方式 依 provider 而異。主要條目如下。 diff --git a/scripts/test-layout/layout-providers.json b/scripts/test-layout/layout-providers.json index 93337dba685..a64f325f9c0 100644 --- a/scripts/test-layout/layout-providers.json +++ b/scripts/test-layout/layout-providers.json @@ -17,6 +17,7 @@ "abliteratedllm-provider.test.ts": "providers", "free-directory-llmtr.test.ts": "providers", "free-directory-runcrate.test.ts": "providers", + "aimlapi-provider.test.ts": "providers", "cc-switch-import.test.ts": "providers", "kiro-completion-with-real-tools.test.ts": "providers/kiro", "mistral-image-limit.test.ts": "providers", diff --git a/src/oauth/index.ts b/src/oauth/index.ts index f1519ba2ac4..60915e61189 100644 --- a/src/oauth/index.ts +++ b/src/oauth/index.ts @@ -62,7 +62,7 @@ import { deriveOAuthDefaultModel, deriveOAuthProviderConfig } from "../providers import { isOAuthCredentialSiblingOf, oauthCredentialSlot } from "./credential-siblings"; import { apiKeyPoolEntryId, sanitizeApiKeyValue } from "../providers/api-keys"; import { preservableApiKeyPool } from "./api-key-pool-preserve"; -import { effectiveGoogleMode, getProviderRegistryEntry, mergeRegistryStaticHeaders, providerMatchesRegistryTransport } from "../providers/registry"; +import { effectiveGoogleMode, getProviderRegistryEntry, mergeRegistryStaticHeaders, providerMatchesRegistryTransport, withoutRegistryStaticHeaderCopies } from "../providers/registry"; import { providerModelsUrl, resolveProviderModelDiscoveryUrl } from "../providers/model-discovery"; import { resolveProviderTransport } from "../providers/xai-transport"; import { detectGrokCliToken, hasComparableGrokIdentity, isSameGrokIdentity, shouldAdoptGrokGeneration } from "./local-token-detect"; @@ -1229,12 +1229,13 @@ export function buildModelsRequest( // Model discovery is an upstream request like any other, so it carries the same registry // static headers the inference path does. Without this a provider is identified correctly // when it answers a completion but anonymously when it lists its own models, which is the - // kind of split fingerprint an upstream rate limiter reads as two different clients. - const registryStaticHeaders = providerMatchesRegistryTransport(providerName, effectiveProvider) - ? getProviderRegistryEntry(providerName)?.staticHeaders - : undefined; + // kind of split fingerprint an upstream rate limiter reads as two different clients. A row + // retargeted to another host keeps its own headers, not the preset's ones. + const registryEntry = getProviderRegistryEntry(providerName); const headers: Record = { - ...(mergeRegistryStaticHeaders(registryStaticHeaders, effectiveProvider.headers) ?? {}), + ...((providerMatchesRegistryTransport(providerName, effectiveProvider) + ? mergeRegistryStaticHeaders(registryEntry?.staticHeaders, effectiveProvider.headers) + : withoutRegistryStaticHeaderCopies(registryEntry, effectiveProvider)) ?? {}), }; const discoveryUrl = (defaultUrl: string): string => resolveProviderModelDiscoveryUrl( providerName, diff --git a/src/providers/registry-static-headers.ts b/src/providers/registry-static-headers.ts new file mode 100644 index 00000000000..462ed51708a --- /dev/null +++ b/src/providers/registry-static-headers.ts @@ -0,0 +1,39 @@ +import type { OcxProviderConfig } from "../types"; +import type { ProviderRegistryEntry } from "./registry/types"; + +/** + * A row's headers without its registry `staticHeaders`, for a row whose transport no longer + * matches the registry entry. + * + * `providerConfigSeed` writes the registry headers into the saved row, and a + * `preserveCustomDestination` preset keeps a row whose `baseUrl` was changed afterwards + * (`ocx provider add --base-url`, a config edit). Without this, headers meant for the + * preset's host would follow the row to the new one. While the row still targets the registry + * host (same scheme and hostname; only the path or adapter changed) its headers are kept as + * they are. Otherwise every header named like a registry static header is dropped, whatever its + * value, so a copy seeded by an older release with a different value does not follow the row + * either; headers with other names are kept. + */ +export function withoutRegistryStaticHeaderCopies( + entry: Readonly> | undefined, + row: Readonly>, +): Record | undefined { + const headers = row.headers; + if (!entry?.staticHeaders || !headers) return headers; + if (sameOrigin(entry.baseUrl, row.baseUrl || entry.baseUrl)) return headers; + const owned = new Set(Object.keys(entry.staticHeaders).map(name => name.toLowerCase())); + const kept = Object.entries(headers).filter(([name]) => !owned.has(name.toLowerCase())); + if (kept.length === Object.keys(headers).length) return headers; + return kept.length > 0 ? Object.fromEntries(kept) : undefined; +} + +function sameOrigin(a: string | undefined, b: string | undefined): boolean { + if (!a || !b) return false; + try { + const left = new URL(a); + const right = new URL(b); + return left.protocol === right.protocol && left.hostname === right.hostname && left.port === right.port; + } catch { + return false; + } +} diff --git a/src/providers/registry.ts b/src/providers/registry.ts index d419bef2bd2..b6e57e7ce12 100644 --- a/src/providers/registry.ts +++ b/src/providers/registry.ts @@ -8,6 +8,7 @@ import type { import { PROVIDER_REGISTRY_CORE } from "./registry/entries-core"; import { PROVIDER_REGISTRY_EXTENDED } from "./registry/entries-extended"; import { anthropicInstanceRowShapeMatches } from "./anthropic-instance-id"; +export { withoutRegistryStaticHeaderCopies } from "./registry-static-headers"; export type { ProviderAuthKind, MetadataModelIdNormalize, diff --git a/src/providers/registry/entries-extended.ts b/src/providers/registry/entries-extended.ts index 9b05e5af16c..1a25dc2045b 100644 --- a/src/providers/registry/entries-extended.ts +++ b/src/providers/registry/entries-extended.ts @@ -1398,6 +1398,71 @@ export const PROVIDER_REGISTRY_EXTENDED: readonly ProviderRegistryEntry[] = [ inputModalities: ["text"], note: "Smart Router that sends each request to a model chosen from AI Stupid Level's benchmarks, using the provider keys saved on your AI Stupid Level account (OpenAI, Anthropic, Google, DeepSeek, Kimi, GLM), so each provider bills you directly with no markup. Routing modes: auto-coding (the default), auto-tooling, auto-reasoning, auto-best, plus value and speed modes. A real model id from the live list, such as claude-opus-5-5, pins one model. The X-AISM-Model response header names the model that answered. Text only.", }, + { + // AI/ML API: OpenAI-compatible gateway at https://api.aimlapi.com/v1. Contract checked + // 2026-10-27: https://docs.aimlapi.com/api-references/model-database. GET /v1/models is + // public and answers 200 for any Bearer value, so it cannot validate a key. It lists ~950 + // rows, and only the row `type` separates chat models from image, video, audio, embedding + // and Anthropic-batch rows; one id can appear in several rows. Discovery admits only + // `openai/chat-completions` rows. The seven seeds answered chat, streaming and tool calls + // through the proxy on 2026-10-27; context and output limits are the /v1/models `info` + // values. The env reference derived from the id is ${AIMLAPI_API_KEY}. + id: "aimlapi", + label: "AI/ML API", + adapter: "openai-chat", + baseUrl: "https://api.aimlapi.com/v1", + authKind: "key", + dashboardUrl: "https://aimlapi.com/app/keys", + // Client attribution requested by AI/ML API. Registry static headers reach the upstream only + // while the row still targets this host (withoutRegistryStaticHeaderCopies). The partner id + // AI/ML API asked for is deliberately absent: a default third-party partner identifier in an + // MIT client needs a commercial arrangement behind it, and there is none (owner decision, + // 2026-11-19). + staticHeaders: { + "X-AIMLAPI-Source": "agent/opencodex", + }, + liveModels: true, + apiKeyValidation: "unknown", + preserveCustomDestination: true, + defaultModel: "openai/gpt-5.6-terra", + models: [ + "openai/gpt-5.6-terra", "openai/gpt-6.1-terra", "anthropic/claude-sonnet-5-5", "google/gemini-3.5-flash", + "deepseek/deepseek-v4-flash", "z-ai/glm-5.3-flash", "moonshot/kimi-k3", + ], + modelContextWindows: { + "openai/gpt-5.6-terra": 1_050_000, + "openai/gpt-6.1-terra": 1_050_000, + "anthropic/claude-sonnet-5-5": 1_000_000, + "google/gemini-3.5-flash": 1_048_576, + "deepseek/deepseek-v4-flash": 1_000_000, + "z-ai/glm-5.3-flash": 1_048_576, + "moonshot/kimi-k3": 1_048_576, + }, + // moonshot/kimi-k3 has no output cap here: /v1/models gives it no `outputMax` and its + // docs-json sets no maximum for max_tokens, so there is no published value to seed. + modelMaxOutputTokens: { + "openai/gpt-5.6-terra": 128_000, + "openai/gpt-6.1-terra": 128_000, + "anthropic/claude-sonnet-5-5": 128_000, + "google/gemini-3.5-flash": 65_536, + "deepseek/deepseek-v4-flash": 384_000, + "z-ai/glm-5.3-flash": 131_072, + }, + modelInputModalities: { + "openai/gpt-5.6-terra": ["text", "image"], + "openai/gpt-6.1-terra": ["text", "image"], + "anthropic/claude-sonnet-5-5": ["text", "image"], + "google/gemini-3.5-flash": ["text", "image"], + "deepseek/deepseek-v4-flash": ["text"], + "z-ai/glm-5.3-flash": ["text", "image"], + "moonshot/kimi-k3": ["text", "image"], + }, + modelDiscovery: { + path: "models", + filter: { allOf: [{ path: ["type"], equalsAny: ["openai/chat-completions"] }] }, + }, + note: "OpenAI-compatible gateway with one key for OpenAI, Anthropic, Google, DeepSeek, GLM, Kimi and other chat models. Model ids carry the vendor prefix (openai/gpt-5.6-terra). Live discovery lists only the Chat Completions models from the public catalog; image, video, audio and embedding models are left out. The public catalog cannot validate keys. Requests to api.aimlapi.com carry an X-AIMLAPI-Source attribution header.", + }, { // cheapaimodel, operated by LINKOVA PTE. LTD. (Singapore). Contract checked 2026-10-28: // https://cheapaimodel.ai/docs/api/create-chat-completion and diff --git a/src/providers/routed-config.ts b/src/providers/routed-config.ts index 42069637d22..a6c76905d8c 100644 --- a/src/providers/routed-config.ts +++ b/src/providers/routed-config.ts @@ -13,7 +13,7 @@ import { captureProviderApiKeySelection } from "./api-key-selection-capture"; import { captureVertexEnvironmentKey } from "./vertex-environment-authority"; import { assertProviderDestinationAllowed } from "../lib/destination-policy"; import { redactSecretString, redactUrlForLog } from "../lib/redact"; -import { PROVIDER_REGISTRY, registryEntryForProviderDestination } from "./registry"; +import { PROVIDER_REGISTRY, registryEntryForProviderDestination, withoutRegistryStaticHeaderCopies } from "./registry"; import { applyDirectReasoningEffortContracts, hasLegacyClinePassReasoningEfforts, registryInputModalitiesForDestination } from "./derive"; import { cloneFastWire } from "./fastwire"; import { fastSwitchOff } from "./fast-opt-in"; @@ -153,8 +153,11 @@ export function routedProviderConfig(providerName: string, provider: OcxProvider const destination = registryEntryForProviderDestination(provider); const inputModalities = provider.inputModalities === undefined ? registryInputModalitiesForDestination(providerName, provider) : undefined; + const headers = withoutRegistryStaticHeaderCopies(registryEntry, provider); + const { headers: _savedHeaders, ...rest } = provider; return withAnthropicModelOutputCaps(snapshotVertexEnvironment({ - ...provider, + ...rest, + ...(headers ? { headers } : {}), ...(inputModalities ? { inputModalities } : {}), apiKey: usableResolvedApiKey(provider.apiKey), ...(destination?.modelReasoningEfforts ? { diff --git a/structure/INDEX.md b/structure/INDEX.md index b8cf4a04fda..d6241de20d3 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -104,6 +104,7 @@ Per-vendor contracts and the adapter authority that constructs them. | [`providers-and-adapters.md`](providers-and-adapters.md) | Provider and adapter selection, the adapter inventory, live model discovery, and the hosted-search continuation bridge. | | [`providers/step-cli-transport.md`](providers/step-cli-transport.md) | StepCode as a Step Plan transport: its own framed stdio wire, one process per conversation, inline SDK tools instead of an MCP catalog, and the bounded tool-result window. | | [`providers/opengateway.md`](providers/opengateway.md) | Preset discovery, paired Responses tool-result projection and bounded empty-completion recovery. | +| [`providers/aimlapi.md`](providers/aimlapi.md) | Type-filtered Chat discovery, seeded models and attribution headers bound to the preset destination. | | [`providers/jev-decision.md`](providers/jev-decision.md) | JEV Combo decision methods (TypeSafe, self-hosted System One rows, opencodex models), the decision request path, dashboard surfaces, and the content-free statistics projection. | | [`providers/anthropic-output-caps.md`](providers/anthropic-output-caps.md) | Routed omitted-output caps for adapter:anthropic rows keyed by Claude model id, precedence and unknown-id fallback. | | [`providers/anthropic-cache-lifecycle.md`](providers/anthropic-cache-lifecycle.md) | Default-off one-shot image-413 recovery and its physical credential, destination, and budget fences. | @@ -427,6 +428,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/oauth/api-key-pool-preserve.ts` | [`account-auto-pause.md`](account-auto-pause.md) | | `src/oauth/dsh.ts` | [`providers/dsh-account.md`](providers/dsh-account.md) | | `src/oauth/generic-account-failover.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | +| `src/oauth/index.ts` | [`providers/aimlapi.md`](providers/aimlapi.md) | | `src/oauth/login-cli.ts` | [`providers/meta-muse.md`](providers/meta-muse.md) | | `src/oauth/m365-copilot-browser.ts` | [`providers/m365-copilot.md`](providers/m365-copilot.md) | | `src/oauth/m365-copilot-web-session.ts` | [`providers/m365-copilot.md`](providers/m365-copilot.md) | @@ -469,7 +471,11 @@ A source area can be described by more than one doc, because these docs are orga | `src/providers/quota/dsh-account.ts` | [`providers/dsh-account.md`](providers/dsh-account.md) | | `src/providers/quota/workbuddy.ts` | [`providers/workbuddy.md`](providers/workbuddy.md) | | `src/providers/reasoning-metadata.ts` | [`transports/responses-combo-boundaries.md`](transports/responses-combo-boundaries.md) | +| `src/providers/registry-static-headers.ts` | [`providers/aimlapi.md`](providers/aimlapi.md) | +| `src/providers/registry.ts` | [`providers/aimlapi.md`](providers/aimlapi.md) | +| `src/providers/registry/entries-extended.ts` | [`providers/aimlapi.md`](providers/aimlapi.md) | | `src/providers/request-pacing.ts` | [`providers/anthropic-key-billing.md`](providers/anthropic-key-billing.md) | +| `src/providers/routed-config.ts` | [`providers/aimlapi.md`](providers/aimlapi.md) | | `src/providers/workbuddy-credit-balance.ts` | [`providers/workbuddy.md`](providers/workbuddy.md) | | `src/providers/workbuddy-models.ts` | [`providers/workbuddy.md`](providers/workbuddy.md) | | `src/providers/workbuddy.ts` | [`providers/workbuddy.md`](providers/workbuddy.md) | diff --git a/structure/manifest.json b/structure/manifest.json index 92dbe82542d..2c0569847e1 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -751,6 +751,19 @@ "src/codex/catalog/routed-gather.ts" ] }, + { + "path": "providers/aimlapi.md", + "tier": 4, + "title": "AI/ML API", + "scope": "Type-filtered Chat discovery, seeded models and attribution headers bound to the preset destination.", + "documents": [ + "src/providers/registry/entries-extended.ts", + "src/providers/registry.ts", + "src/providers/registry-static-headers.ts", + "src/providers/routed-config.ts", + "src/oauth/index.ts" + ] + }, { "path": "providers/jev-decision.md", "tier": 4, diff --git a/structure/ops/docs-and-release.md b/structure/ops/docs-and-release.md index 2cd82aaf9cb..f975b62d4d2 100644 --- a/structure/ops/docs-and-release.md +++ b/structure/ops/docs-and-release.md @@ -86,7 +86,7 @@ Manual navigation is defined in `docs-site/astro.config.mjs`. When adding a publ sidebar and either add localized copies or intentionally accept Starlight fallback behavior. Use slugs for local pages, including Platform Support and OS Keychain, so navigation preserves the selected locale. `tests/ci-workflows/docs-spanish-localization.test.ts` guards canonical Spanish coverage, literal provider-key references, protected remote examples, foreground quickstart alternatives, separate-terminal and Bash/stdin pairing recipes, Pi reasoning metadata, and the data/management credential and admission-header distinctions across shipped locale copies, including empty-header bearer fallback. `tests/ci-workflows/docs-remote-hub-claims.test.ts` validates Docker initialization against the image seed and configuration schema; `tests/ci-workflows/docs-bun-source-requirement.test.ts` checks current bundle claims against the package pin. Provider preset totals are recounted from the current registry when a preset lands. The -documented split is 112 total: 90 key-based, 18 OAuth, three local, and one default +documented split is 113 total: 91 key-based, 18 OAuth, three local, and one default ChatGPT-forward preset. The English and Spanish API-key catalog pages, every other locale's provider guide, and every locale's quickstart carry the same counts. Section 3 of the provider guide lives on its own page, `docs-site/src/content/docs/guides/api-key-catalog.md` (with its Spanish copy), so the guide stays under the file-size ratchet's 2,000-line default; the guide keeps a section 3 stub that links every moved heading anchor, and other locales keep section 3 in their provider guide until they add a translated catalog page. diff --git a/structure/providers/aimlapi.md b/structure/providers/aimlapi.md new file mode 100644 index 00000000000..aa3499723c2 --- /dev/null +++ b/structure/providers/aimlapi.md @@ -0,0 +1,19 @@ +# AI/ML API + +The `aimlapi` key preset in `src/providers/registry/entries-extended.ts` uses the existing OpenAI Chat adapter at `https://api.aimlapi.com/v1`. +Its public `GET /v1/models` mixes chat, image, video, audio, embedding and Anthropic-batch rows, +and only the row `type` tells them apart, so registry-owned discovery admits rows whose `type` is +`openai/chat-completions`. The catalog answers 200 for any Bearer value, so key validation is +`unknown`. Seven vendor-prefixed chat ids are seeded with their catalog context and output limits. +The preset's `staticHeaders` carry the `X-AIMLAPI-Source` attribution header only; the partner id AI/ML API requested is left out because no commercial arrangement backs it. +Registry static headers are merged only while the row matches the registry transport. For a +same-named row that no longer matches, `withoutRegistryStaticHeaderCopies` in +`src/providers/registry-static-headers.ts` (re-exported from `src/providers/registry.ts`) decides +on inference (`src/providers/routed-config.ts`) and model discovery (`src/oauth/index.ts`): if the row still targets the registry origin (same scheme, host +and port; only the path or adapter changed) its headers are sent as saved; if it targets another +origin, every header named like a preset static header is dropped, whatever its value (so an older +seeded copy, or one the operator edited, does not follow the row), and headers with other names +are kept. +`tests/providers/aimlapi-provider.test.ts` covers derived entry points, type-filtered discovery, +key validation, routing, and the headers on the wire for the preset, a row retargeted to another +host, and a row that stays on the registry host with another path or adapter. diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index ce0b98ebb76..f91b3cd8849 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1273,6 +1273,7 @@ "aistupidlevel-provider.test.ts": "providers", "cheapaimodel-provider.test.ts": "providers", "abliteratedllm-provider.test.ts": "providers", + "aimlapi-provider.test.ts": "providers", "tokenlab-provider.test.ts": "providers", "optional-shutdown-hooks.test.ts": "lib", "orca-import.test.ts": "codex-integration", "orcarouter-provider.test.ts": "providers", "cc-switch-import.test.ts": "providers", "outbound-body-guard.test.ts": "server", "owned-service-home.test.ts": "server", diff --git a/tests/providers/aimlapi-provider.test.ts b/tests/providers/aimlapi-provider.test.ts new file mode 100644 index 00000000000..42e80e54414 --- /dev/null +++ b/tests/providers/aimlapi-provider.test.ts @@ -0,0 +1,233 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { saveConfig } from "../../src/config"; +import { gatherRoutedModels } from "../../src/codex/catalog"; +import { clearModelCache } from "../../src/codex/model-cache"; +import { buildModelsRequest } from "../../src/oauth"; +import { KEY_LOGIN_PROVIDERS, validateApiKey } from "../../src/oauth/key-providers"; +import { deriveInitProviders, deriveKeyLoginMap, deriveProviderPresets, providerConfigSeed } from "../../src/providers/derive"; +import { extractProviderModelItems, providerModelDiscoverySpecError, resolveProviderModelDiscovery } from "../../src/providers/model-discovery"; +import { PROVIDER_REGISTRY, withoutRegistryStaticHeaderCopies } from "../../src/providers/registry"; +import { routeModel } from "../../src/router"; +import { startServer } from "../../src/server"; +import { resolveWireProtocolOverride } from "../../src/server/adapter-resolve"; +import type { OcxConfig, OcxProviderConfig } from "../../src/types"; +import { isModelVisionSidecarConsumer } from "../../src/vision/eligibility"; +import { withStubbedProviderFetch } from "../helpers/catalog-provider-fetch"; +import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const originalFetch = globalThis.fetch; +const baseUrl = "https://api.aimlapi.com/v1"; +const RELAY = "https://relay.example.test/v1"; +// Chat Completions rows of the public GET /v1/models, each answering chat, streaming and a tool +// call on 2026-10-27. +const SEEDS = [ + "openai/gpt-5.6-terra", "openai/gpt-6.1-terra", "anthropic/claude-sonnet-5-5", "google/gemini-3.5-flash", + "deepseek/deepseek-v4-flash", "z-ai/glm-5.3-flash", "moonshot/kimi-k3", +] as const; +// Row shapes of the public GET /v1/models: only `type` tells a chat row from the rest, and one id +// can appear once per type it is served on. +const CATALOG = { object: "list", data: [ + { id: "openai/gpt-5.6-terra", type: "openai/chat-completions", aliases: ["gpt-5.6-terra"], info: {} }, + { id: "openai/gpt-5.6-terra", type: "openai/responses/submit", aliases: [], info: {} }, + { id: "anthropic/claude-sonnet-5-5", type: "anthropic/messages", aliases: [], info: {} }, + { id: "anthropic/claude-sonnet-5-5", type: "anthropic/batches", aliases: [], info: {} }, + { id: "anthropic/claude-sonnet-5-5", type: "openai/chat-completions", aliases: [], info: {} }, + { id: "flux/schnell", type: "openai/image-generations", aliases: [], info: {} }, + { id: "google/veo-3.1", type: "internal/video-generations/submit", aliases: [], info: {} }, + { id: "openai/text-embedding-3-small", type: "openai/embeddings", aliases: [], info: {} }, + { id: "elevenlabs/eleven_v3", type: "internal/text-to-speech", aliases: [], info: {} }, + { id: "untyped/row", aliases: [], info: {} }, +] }; + +afterEach(() => { + globalThis.fetch = originalFetch; + clearModelCache("aimlapi"); +}); + +function entry() { + const row = PROVIDER_REGISTRY.find(candidate => candidate.id === "aimlapi"); + if (!row) throw new Error("missing AI/ML API preset"); + return row; +} + +function config(overrides: Partial = {}): OcxConfig { + return withStubbedProviderFetch({ + port: 10100, + defaultProvider: "aimlapi", + providers: { aimlapi: { ...providerConfigSeed(entry()), apiKey: "test-key", ...overrides } }, + }); +} + +describe("AI/ML API provider", () => { + test("is offered by ocx provider add, ocx init and the dashboard picker", () => { + expect(deriveInitProviders().find(row => row.id === "aimlapi")).toMatchObject({ + label: "AI/ML API", kind: "key", adapter: "openai-chat", baseUrl, + }); + const preset = deriveProviderPresets().find(row => row.id === "aimlapi"); + expect(preset).toMatchObject({ auth: "key", dashboardUrl: "https://aimlapi.com/app/keys" }); + expect(preset?.sponsor).toBeUndefined(); + expect(KEY_LOGIN_PROVIDERS.aimlapi?.defaultModel).toBe("openai/gpt-5.6-terra"); + }); + + test("seeds the verified chat models with their catalog limits and live discovery on", () => { + const seeded = config().providers.aimlapi!; + expect(seeded).toMatchObject({ adapter: "openai-chat", baseUrl, defaultModel: "openai/gpt-5.6-terra", liveModels: true }); + expect(entry().models).toEqual([...SEEDS]); + for (const model of SEEDS) expect(seeded.modelContextWindows?.[model]).toBeGreaterThanOrEqual(1_000_000); + // DeepSeek V4 Flash is the one text-only seed: an image goes to the vision sidecar first. + expect(isModelVisionSidecarConsumer(seeded, "deepseek/deepseek-v4-flash")).toBe(true); + expect(isModelVisionSidecarConsumer(seeded, "openai/gpt-5.6-terra")).toBe(false); + }); + + test.each(SEEDS)("%s routes over Chat with its vendor-prefixed upstream id unchanged", model => { + const route = routeModel(config(), `aimlapi/${model}`); + expect(route.modelId).toBe(model); + expect(route.provider).toMatchObject({ adapter: "openai-chat", baseUrl }); + for (const inbound of ["responses", "chat", "anthropic"] as const) { + expect(resolveWireProtocolOverride("aimlapi", model, config().providers.aimlapi!, inbound).adapter) + .toBe("openai-chat"); + } + }); + + test("keeps a same-named custom destination instead of retargeting it", () => { + expect(routeModel(config({ baseUrl: RELAY }), "aimlapi/custom-model").provider.baseUrl).toBe(RELAY); + }); + + test("live discovery admits only Chat Completions rows, so image, video and audio models stay out", () => { + const discovery = resolveProviderModelDiscovery("aimlapi", config().providers.aimlapi!); + expect(providerModelDiscoverySpecError(entry().modelDiscovery!)).toBeNull(); + expect(buildModelsRequest(config().providers.aimlapi!, "test-key", "aimlapi").url).toBe(`${baseUrl}/models`); + const result = extractProviderModelItems(CATALOG, discovery); + if (!result.ok) throw new Error(result.reason); + expect(result.items.map(row => row.id)).toEqual(["openai/gpt-5.6-terra", "anthropic/claude-sonnet-5-5"]); + }); + + test("the routed model list carries the chat rows only", async () => { + globalThis.fetch = (async input => { + expect(String(input)).toBe(`${baseUrl}/models`); + return Response.json(CATALOG); + }) as typeof fetch; + const models = (await gatherRoutedModels(config())).filter(row => row.provider === "aimlapi"); + expect(models.map(row => row.id).sort()).toEqual(["anthropic/claude-sonnet-5-5", "openai/gpt-5.6-terra"]); + }); + + test("the public catalog is never probed to validate a key", async () => { + expect(deriveKeyLoginMap().aimlapi?.apiKeyValidation).toBe("unknown"); + let calls = 0; + globalThis.fetch = (async () => { calls++; return Response.json({ object: "list", data: [] }); }) as unknown as typeof fetch; + expect(await validateApiKey("aimlapi", KEY_LOGIN_PROVIDERS.aimlapi!, "any-key")).toBe("unknown"); + expect(calls).toBe(0); + }); +}); + +describe("AI/ML API attribution headers", () => { + const MODEL = "openai/gpt-5.6-terra"; + let previousHome: string | undefined; + let home = ""; + let codexHome: IsolatedCodexHome; + let upstream: Array<{ url: string; headers: Headers }>; + + const attribution = () => Object.entries(entry().staticHeaders ?? {}); + + beforeEach(() => { + previousHome = process.env.OPENCODEX_HOME; + codexHome = installIsolatedCodexHome("ocx-aimlapi-attribution-codex-"); + home = mkdtempSync(join(tmpdir(), "ocx-aimlapi-attribution-")); + process.env.OPENCODEX_HOME = home; + clearModelCache(); + upstream = []; + globalThis.fetch = (async (input, init) => { + const url = new URL(input instanceof Request ? input.url : String(input)); + if (url.hostname === "127.0.0.1") return originalFetch(input, init); + if (url.origin !== "https://api.aimlapi.com" && url.origin !== "https://relay.example.test") { + throw new Error(`Unexpected network destination in AI/ML API fixture: ${url.origin}`); + } + upstream.push({ url: url.toString(), headers: new Headers(input instanceof Request ? input.headers : init?.headers) }); + if (url.pathname === "/v1/models") return Response.json({ object: "list", data: [{ id: MODEL, type: "openai/chat-completions" }] }); + return Response.json({ + id: "chatcmpl-aimlapi", object: "chat.completion", model: MODEL, + choices: [{ index: 0, message: { role: "assistant", content: "pong" }, finish_reason: "stop" }], + usage: { prompt_tokens: 5, completion_tokens: 1, total_tokens: 6 }, + }); + }) as typeof fetch; + }); + + afterEach(() => { + clearModelCache(); + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousHome; + codexHome.restore(); + removeTreeWithRetry(home); + }); + + async function send(provider: OcxProviderConfig): Promise { + saveConfig({ port: 0, hostname: "127.0.0.1", defaultProvider: "aimlapi", providers: { aimlapi: provider } }); + const server = startServer(0); + try { + const response = await fetch(new URL("/v1/chat/completions", server.url), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: `aimlapi/${MODEL}`, stream: false, messages: [{ role: "user", content: "ping" }] }), + }); + expect(response.status).toBe(200); + await response.text(); + } finally { + await server.stop(true); + } + } + + test("declares only the source header on the preset", () => { + expect(entry().staticHeaders?.["X-AIMLAPI-Source"]).toBe("agent/opencodex"); + // The partner id is a commercial arrangement, not a preset default: an MIT client must not + // ship a third-party identifier to every user's upstream (owner decision, 2026-11-19). + expect(Object.keys(entry().staticHeaders ?? {})).toEqual(["X-AIMLAPI-Source"]); + }); + + test("inference and model discovery at api.aimlapi.com carry the source header", async () => { + await send({ ...providerConfigSeed(entry()), apiKey: "fixture-aimlapi-key" }); + const chat = upstream.filter(call => call.url === `${baseUrl}/chat/completions`); + expect(chat).toHaveLength(1); + for (const [name, value] of attribution()) expect(chat[0]!.headers.get(name)).toBe(value); + + upstream = []; + await gatherRoutedModels(config()); + expect(upstream.map(call => call.url)).toEqual([`${baseUrl}/models`]); + for (const [name, value] of attribution()) expect(upstream[0]!.headers.get(name)).toBe(value); + }); + + test("a preset row pointed at another host loses the preset headers there", async () => { + // `ocx provider add aimlapi --base-url ...` seeds the row (static headers included) and then + // replaces the URL, so the copies in the saved row must not follow it to the new host. + await send({ ...providerConfigSeed(entry()), baseUrl: RELAY, apiKey: "fixture-relay-key" }); + const chat = upstream.filter(call => call.url === `${RELAY}/chat/completions`); + expect(chat).toHaveLength(1); + for (const [name] of attribution()) expect(chat[0]!.headers.has(name)).toBe(false); + + upstream = []; + await gatherRoutedModels(config({ baseUrl: RELAY })); + expect(upstream.map(call => call.url)).toEqual([`${RELAY}/models`]); + for (const [name] of attribution()) expect(upstream[0]!.headers.has(name)).toBe(false); + }); + + test("on a retargeted row, headers named like the preset's are dropped and others are sent", async () => { + // A copy seeded by an older release carries a different value; it must not follow the row either. + await send({ ...providerConfigSeed(entry()), baseUrl: RELAY, apiKey: "fixture-relay-key", + headers: { "X-AIMLAPI-Source": "agent/seededByAnOlderRelease", "X-Relay-Tenant": "team-a" } }); + const chat = upstream.filter(call => call.url === `${RELAY}/chat/completions`); + expect(chat).toHaveLength(1); + expect(chat[0]!.headers.get("X-Relay-Tenant")).toBe("team-a"); + for (const [name] of attribution()) expect(chat[0]!.headers.has(name)).toBe(false); + }); + + test("a row still on api.aimlapi.com keeps its headers when its transport differs from the preset", () => { + const seeded = providerConfigSeed(entry()); + const sameHost = { ...seeded, baseUrl: "https://api.aimlapi.com/v1beta", adapter: "openai-responses" as const }; + expect(withoutRegistryStaticHeaderCopies(entry(), sameHost)).toEqual(seeded.headers); + const otherHost = { ...seeded, baseUrl: "https://api.aimlapi.com.relay.example.test/v1" }; + expect(withoutRegistryStaticHeaderCopies(entry(), otherHost)).toBeUndefined(); + }); +}); From 00ddbb3ddfe163274e8b2999e1b1eab24aeb9791 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Wed, 25 Nov 2026 12:38:52 +0900 Subject: [PATCH 08/60] fix(windows): check the stop deadline after reading the idle task state (#9058) * fix(windows): check the idle task state within the stop deadline A slow final Task Scheduler state read could outlast stop-before and report the task idle. Check the deadline after sampling the state. Cover the cutoff with a simulated getter and a zero-stop assertion. * test(windows): group the idle-state deadline with the other timeout cases --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- src/service/windows-task-instance-stop.ts | 4 +++- structure/ops/windows-checked-stop.md | 7 ++++--- tests/windows/windows-checked-stop-live.test.ts | 9 ++++++++- 3 files changed, 15 insertions(+), 5 deletions(-) diff --git a/src/service/windows-task-instance-stop.ts b/src/service/windows-task-instance-stop.ts index 446c4f46da6..0e057b8a21a 100644 --- a/src/service/windows-task-instance-stop.ts +++ b/src/service/windows-task-instance-stop.ts @@ -63,7 +63,9 @@ try { if (![string]::Equals($xml, [string]$current.Xml, [StringComparison]::Ordinal)) { 'unverified-registration'; return } if ($count -eq 0) { # Ready or disabled; an empty collection can also mean instances were hidden by ACLs. - if ($current.State -in @(1, 3)) { 'not-running' } else { 'unverified-registration' } + $state = $current.State + if ($stopClock.ElapsedMilliseconds -ge $stopBeforeMs) { 'failed'; return } + if ($state -in @(1, 3)) { 'not-running' } else { 'unverified-registration' } return } foreach ($target in $verified) { diff --git a/structure/ops/windows-checked-stop.md b/structure/ops/windows-checked-stop.md index 48906174f73..ff899608b7c 100644 --- a/structure/ops/windows-checked-stop.md +++ b/structure/ops/windows-checked-stop.md @@ -156,9 +156,10 @@ The helper requires a successful same-account SID check for every `EnginePID`, w creation time re-read after the owner lookup. After approval it re-reads the registration XML and refreshes every captured instance to verify that its GUID, engine PID and running state still agree. It stops each captured `IRunningTask` by instance GUID. An empty collection counts as idle only if -the task is ready or disabled. Failed proof returns `evidence-unreadable` with instructions to -verify the task in Task Scheduler and repair an owned registration or contact its owner or -administrator. Ending a running instance alone does not repair an unverifiable registration. +the final task state shows ready or disabled before the stop deadline. Failed proof returns +`evidence-unreadable` with instructions to verify the task in Task Scheduler and repair an owned +registration or contact its owner or administrator. Ending a running instance alone does not repair +an unverifiable registration. The Scheduler exposes current registration XML separately from instance identity. An instance already running under the same account from an earlier definition can still be visible under that diff --git a/tests/windows/windows-checked-stop-live.test.ts b/tests/windows/windows-checked-stop-live.test.ts index c0fca700b7f..c01b352ff17 100644 --- a/tests/windows/windows-checked-stop-live.test.ts +++ b/tests/windows/windows-checked-stop-live.test.ts @@ -403,8 +403,14 @@ $instances = [pscustomobject]@{ Rows = @((New-Instance 42), (New-Instance 43)) } $instances | Add-Member ScriptProperty Count { $this.Rows.Count } $instances | Add-Member ScriptMethod Item { param($index) $this.Rows[$index - 1] } $script:task = [pscustomobject]@{ Xml = 'original'; State = 4; Instances = $instances } -if ($script:scenario -in @('hidden', 'idle')) { $instances.Rows = @() } +if ($script:scenario -in @('hidden', 'idle', 'idle-state-deadline')) { $instances.Rows = @() } if ($script:scenario -eq 'idle') { $script:task.State = 3 } +if ($script:scenario -eq 'idle-state-deadline') { + $script:task | Add-Member -Force ScriptProperty State { + if ($script:taskReads -eq 2) { $script:elapsed = 2000 } + 3 + } +} $script:task | Add-Member ScriptMethod GetInstances { param($flags) $this.Instances } $script:folder = [pscustomobject]@{} $script:folder | Add-Member ScriptMethod GetTask { @@ -464,6 +470,7 @@ function Invoke-CimMethod { ["late-approval", "failed", ""], ["deadline-before-first", "failed", ""], ["deadline-between-stops", "failed", "42"], + ["idle-state-deadline", "failed", ""], ]) { // Production runs the helper alone, which silences progress before its first module use. The fixture // runs first here and its Add-Member/[pscustomobject] calls autoload Microsoft.PowerShell.Utility, which From d8b28be56e34824348be7d02f0ab47349b1a5d0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EB=B0=95=ED=98=84=EC=A4=80?= Date: Wed, 25 Nov 2026 12:39:45 +0900 Subject: [PATCH 09/60] fix(link): give the post-restart relay check room for SSH setup (#9095) * fix(link): give the post-restart relay check room for SSH setup (#8947) The health and catalog probes after a Child restart shared a flat 15s deadline. On Windows each probe is a fresh SSH + PowerShell start, so a slow health check left the catalog probe a few seconds and enrollment failed with child_relay_timeout. The relay deadline now adds the measured SSH setup cost for both probes, capped at 60s like other link commands. * test(link): run the relay timing case on Windows too, document the relay budget --------- Co-authored-by: JUN --- src/link/remote-probe.ts | 6 ++++++ src/server/management/link-enrollment.ts | 4 ++-- structure/remote-link.md | 2 +- tests/server/link-enrollment.test.ts | 17 +++++++++++++---- 4 files changed, 22 insertions(+), 7 deletions(-) diff --git a/src/link/remote-probe.ts b/src/link/remote-probe.ts index e18ab97b9c0..b94c4aa9b14 100644 --- a/src/link/remote-probe.ts +++ b/src/link/remote-probe.ts @@ -13,6 +13,12 @@ export function linkCommandBudget(latencyMs = 0): number { return Math.min(LINK_COMMAND_MAX_MS, LINK_COMMAND_WORK_MS + Math.ceil(latency * 4)); } +/** Post-restart relay check: the health and catalog probes are two SSH commands, so each pays SSH setup. */ +export function linkRelayBudget(latencyMs = 0): number { + const latency = Number.isFinite(latencyMs) ? Math.max(0, latencyMs) : 0; + return Math.min(LINK_COMMAND_MAX_MS, LINK_RELAY_VERIFY_MS + 2 * Math.ceil(latency * 4)); +} + export function linkRestartBudget(latencyMs = 0): number { return MEMORY_DRAIN_RESTART_MS + REPLACEMENT_READY_TIMEOUT_MS + linkCommandBudget(latencyMs); } diff --git a/src/server/management/link-enrollment.ts b/src/server/management/link-enrollment.ts index f2c5327a110..3d63c498429 100644 --- a/src/server/management/link-enrollment.ts +++ b/src/server/management/link-enrollment.ts @@ -9,7 +9,7 @@ import { confirmedLineTrust as confirmedLineTrustIn, type ConfirmedLineTrust } f import { isDetachedEphemeralChildConfig } from "../../link/ephemeral-child"; import { classifyChildAttachConflict, classifyPlantFailure, inspectRemoteChildRuntime, parseFullInstallCensus, remoteFullInstallCensusArgv, remotePlantChildArgv, remotePurgePlantedChildArgv } from "../../link/remote-plant"; import { requireRemotePlatform } from "../../link/remote-platform"; -import { LINK_CATALOG_MAX_BYTES, LINK_RELAY_VERIFY_MS, isChildHealth, linkCommandBudget, linkRestartBudget, parseChildHttp, remoteChildHttpArgv, REMOTE_CURL_PREFLIGHT } from "../../link/remote-probe"; +import { LINK_CATALOG_MAX_BYTES, LINK_RELAY_VERIFY_MS, isChildHealth, linkCommandBudget, linkRelayBudget, linkRestartBudget, parseChildHttp, remoteChildHttpArgv, REMOTE_CURL_PREFLIGHT } from "../../link/remote-probe"; import { newLinkId, type LinkStore } from "../../link/store"; import { residualRecovery } from "../../link/residual-recovery"; import { SshRunnerError, boundHint, sshFailureHint, sshRunnerErrorHint, type SshRunResult } from "../../link/ssh-runner"; @@ -490,7 +490,7 @@ export async function apply(ctx: ManagementContext, state: LinkRouteState): Prom const restarted = await run(ocx(["restart"]), linkRestartBudget(confirmed.sshLatencyMs)); if (restarted.code !== 0) return await failed(fail("child_restart_failed", "The Child restart could not be verified.", 502, sshFailureHint(restarted.stderr))); phase = "child_relay"; - const deadline = now() + LINK_RELAY_VERIFY_MS, remaining = () => Math.max(1, deadline - now()); + const deadline = now() + linkRelayBudget(confirmed.sshLatencyMs), remaining = () => Math.max(1, deadline - now()); const health = await run(remoteChildHttpArgv(childPort, "healthz", remaining(), remotePlatform), remaining()); if (!isChildHealth(health.code === 0 ? parseChildHttp(health.stdout) : null, "client", childPort)) return await failed(fail("child_runtime_not_client", "The Child is not serving the client runtime after restart.", 502)); let admitted = false; diff --git a/structure/remote-link.md b/structure/remote-link.md index 4ac8ca66958..5bba97f4799 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -303,7 +303,7 @@ The link retirement record module stores a private, atomically published record `src/server/management/link-enrollment.ts` owns probe, host confirmation and Home apply; `src/server/management/link-route-state.ts` supplies shared authorization and lifecycle compensation. The three routes accept the existing dashboard authority or trusted loopback admin authority; Tailscale identity sessions remain refused. Join remains operator-paired only. CLI `ocx link probe ` requests the optional `includeVersion: true` offer; legacy dashboard offers retain their three fields. Version probing executes against the temporary learned key and persists no trust. Confirm rechecks the pending generation and five-minute expiry after its SSH await, then updates the latest known_hosts atomically under the config lock. Same-alias operations fail fast on overlap; apply pins a private immutable host file and consumes confirmation before issuing a key. -`src/link/remote-probe.ts` separates command budget (15 seconds plus four times measured SSH setup, capped at 60 seconds) from a fresh 15-second relay deadline. Restart adds the existing 60-second drain and 70-second replacement windows. The runner's one deadline covers stdin writes, process exit and output drains; failure cancels readers and kills the local SSH child without an unbounded cleanup wait. Ordinary stdout and stderr cap at 64 KiB. The catalog command and the Child `config show --json` preflight in `src/server/management/link-child-preflight.ts` permit 4 MiB stdout, because no smaller command reports `port`, `runtimeRole` and `ephemeralChild` on every supported Child: full `ocx` has `config get`, the lightweight `ocx-child` binary answers only `config show --json`. A Child exceeding even that cap answers `502 child_preflight_output_limit` instead of a generic preflight failure. Coverage: `tests/clients/link-ssh-runner.test.ts`, `tests/server/link-enrollment.test.ts`. A `config show` that exits non-zero answers `child_preflight_failed` with the Child's own validation reason as the hint: a full `ocx` Child then runs `config validate --json` (16 KiB cap), and only its `error` string, which names fields and expected types and never configured values, is read through `boundHint`. A Child without that command, or one whose validate fails or times out, keeps the last `config show` stderr line (`sshFailureHint`), or names the exit code when stderr is empty; a `config show` that exits 0 without a usable port names the command. The CLI (`src/cli/link.ts` `errorCodeBody`) keeps exactly that hint, bounded and redacted again with `boundHint`, beside the error code, and still never echoes the rest of an error body (#8357). +`src/link/remote-probe.ts` separates command budget (15 seconds plus four times measured SSH setup, capped at 60 seconds) from a fresh relay deadline (`linkRelayBudget`): 15 seconds plus four times measured SSH setup for each of the health and catalog probes, capped at 60 seconds, so a slow SSH start (PowerShell on a Windows Child) does not leave the catalog probe too little time (#8947). Each probe's request on the Child (curl, or PowerShell on Windows) stays capped at 15 seconds. Restart adds the existing 60-second drain and 70-second replacement windows. The runner's one deadline covers stdin writes, process exit and output drains; failure cancels readers and kills the local SSH child without an unbounded cleanup wait. Ordinary stdout and stderr cap at 64 KiB. The catalog command and the Child `config show --json` preflight in `src/server/management/link-child-preflight.ts` permit 4 MiB stdout, because no smaller command reports `port`, `runtimeRole` and `ephemeralChild` on every supported Child: full `ocx` has `config get`, the lightweight `ocx-child` binary answers only `config show --json`. A Child exceeding even that cap answers `502 child_preflight_output_limit` instead of a generic preflight failure. Coverage: `tests/clients/link-ssh-runner.test.ts`, `tests/server/link-enrollment.test.ts`. A `config show` that exits non-zero answers `child_preflight_failed` with the Child's own validation reason as the hint: a full `ocx` Child then runs `config validate --json` (16 KiB cap), and only its `error` string, which names fields and expected types and never configured values, is read through `boundHint`. A Child without that command, or one whose validate fails or times out, keeps the last `config show` stderr line (`sshFailureHint`), or names the exit code when stderr is empty; a `config show` that exits 0 without a usable port names the command. The CLI (`src/cli/link.ts` `errorCodeBody`) keeps exactly that hint, bounded and redacted again with `boundHint`, beside the error code, and still never echoes the rest of an error body (#8357). Before issuance, apply requires curl and effective standalone Child configuration plus a native Child health response on its configured port with `restartCapability: v1`. Already-client, mismatched-port and pre-capability runtimes are refused without enrollment. Thus a capable older standalone Child can be linked by a newer Home. Home calls existing `ocx restart` exactly once after `connect --key-stdin`; no raw stop/start or timeout replay. After client-role health, Home registers a fresh expected-key observer and asks Child's credential-free loopback `/v1/catalog`. Both a complete HTTP 200 JSON catalog and matching authenticated Home callback must occur within the relay window. Enrollment admission cannot satisfy this check. Curl ignores curlrc, proxies and redirects. Phase-specific failures compensate Home state; after possible remote commit, `residual: true` and fixed Child disconnect/restart guidance remain even if compensation fails. This is not remote rollback. diff --git a/tests/server/link-enrollment.test.ts b/tests/server/link-enrollment.test.ts index c561ba1518d..068dbd9a896 100644 --- a/tests/server/link-enrollment.test.ts +++ b/tests/server/link-enrollment.test.ts @@ -351,8 +351,17 @@ describe("Home enrollment of a standalone Child", () => { const timeouts = new Map(h.calls.map(call => [call.step, call.options?.timeoutMs])); for (const step of ["port", "config", "curl", "connect"] as const) expect(timeouts.get(step)).toBe(28_600); expect(timeouts.get("restart")).toBe(158_600); - expect(h.calls.at(-2)?.options?.timeoutMs).toBe(15_000); - expect(timeouts.get("catalog")).toBe(15_000); + expect(h.calls.at(-2)?.options?.timeoutMs).toBe(42_200); + expect(timeouts.get("catalog")).toBe(42_200); + }); + + test.each(["posix", "windows"] as const)("relay deadline pays SSH setup for both probes, so a slow health check leaves time for the catalog (%s)", async platform => { + const h = harness(platform); h.confirmed("child", 3600); + h.overrides.health = () => { h.advance(10_800); return health("client"); }; + h.overrides.catalog = () => { h.emit("catalog"); h.advance(4500); return http({ models: [] }); }; + expect((await h.call("apply", { alias: "child" })).status).toBe(202); + expect(h.calls.find(call => call.step === "health")?.options?.timeoutMs).toBe(43_800); + expect(h.calls.find(call => call.step === "catalog")?.options?.timeoutMs).toBe(33_000); }); test("a Child whose config show exceeds the ordinary SSH output cap still passes preflight", async () => { @@ -406,12 +415,12 @@ describe("Home enrollment of a standalone Child", () => { expect(payload.residual).toBeUndefined(); noEnrollmentEffects(h); }); - test("huge measured latency caps ordinary work at 60s and restart at 190s", async () => { + test("huge measured latency caps ordinary work and the relay check at 60s, and restart at 190s", async () => { const h = harness(); h.confirmed("child", Number.MAX_VALUE); expect((await h.call("apply", { alias: "child" })).status).toBe(202); expect(h.calls.find(call => call.step === "connect")?.options?.timeoutMs).toBe(60_000); expect(h.calls.find(call => call.step === "restart")?.options?.timeoutMs).toBe(190_000); - expect(h.calls.find(call => call.step === "catalog")?.options?.timeoutMs).toBe(15_000); + expect(h.calls.find(call => call.step === "catalog")?.options?.timeoutMs).toBe(60_000); }); test("health and catalog share a fresh relay deadline after restart", async () => { From 5ab63b3a0d1594009306484188c79253d0dfba15 Mon Sep 17 00:00:00 2001 From: Fred Amartey <43480311+FredAmartey@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:40:18 -0500 Subject: [PATCH 10/60] fix(codex): retire a carried monthly window when Plus reports its 5-hour window (#9097) * fix(codex): retire a carried monthly window when Plus reports its 5-hour window * fix(codex): require an allowed verdict for the 5-hour monthly proof --------- Co-authored-by: JUN Co-authored-by: lidge-jun --- src/codex/quota.ts | 12 ++++++++- structure/providers/openai-tiers.md | 2 +- .../pool-monthly-window-retirement.test.ts | 25 +++++++++++++++++++ 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/src/codex/quota.ts b/src/codex/quota.ts index 94d03cf41da..b2fbb3693c0 100644 --- a/src/codex/quota.ts +++ b/src/codex/quota.ts @@ -1166,14 +1166,20 @@ function hasMalformedWhamReading(data: WhamUsageResponse): boolean { * #8067/#8596: the complete topology that proves short-window absence also proves there is no * monthly window when no window declares a monthly duration and no tertiary window is present, * so a plan change away from a monthly primary (Free to Pro Lite) retires the carried tuple. + * A complete, allowed 5-hour and weekly read supplies the same proof. * An explicit denial and invalid or unparseable readings never supply that proof. */ function withWhamMonthlyWindowAbsence( data: WhamUsageResponse, observation: MainPolicyQuotaObservation, ): MainPolicyQuotaObservation { - if (observation.shortWindowAbsent !== true || data.rate_limit?.allowed === false) return observation; + if (data.rate_limit?.allowed === false) return observation; if (!isValidWhamHistoryObservation(data) || hasMalformedWhamReading(data)) return observation; const [primary, secondary, tertiary] = [data.rate_limit?.primary_window, data.rate_limit?.secondary_window, data.rate_limit?.tertiary_window]; + // Plus reports a 5-hour primary beside the weekly secondary, which the short-absence + // proof never covers; the same complete, allowed topology proves no monthly window either. + const completeWithShort = data.rate_limit?.allowed === true && isMeasuredWindow(primary) + && (secondary === null || isMeasuredWindow(secondary)) && tertiary == null; + if (observation.shortWindowAbsent !== true && !completeWithShort) return observation; return !isExplicitMonthlyWindow(primary) && !isExplicitMonthlyWindow(secondary) && tertiary == null ? { ...observation, monthlyWindowAbsent: true } : observation; @@ -1183,6 +1189,10 @@ function isMeasuredLongWindow(window: WhamUsageWindow | null | undefined): boole return isExplicitLongWindow(window) && normalizeUsagePercent(window?.used_percent) !== undefined; } +function isMeasuredWindow(window: WhamUsageWindow | null | undefined): boolean { + return (isExplicitShortWindow(window) || isExplicitLongWindow(window)) && normalizeUsagePercent(window?.used_percent) !== undefined; +} + /** Absent/null controls impose no veto; a present control requires reached:false. */ function spendControlAllowsCredits(control: unknown): boolean | undefined { if (control === undefined || control === null) return undefined; diff --git a/structure/providers/openai-tiers.md b/structure/providers/openai-tiers.md index 0479e8a5ad5..d67a6b69e8c 100644 --- a/structure/providers/openai-tiers.md +++ b/structure/providers/openai-tiers.md @@ -435,7 +435,7 @@ cannot prove that the short window disappeared. All-null credits-only and tertia the resulting weekly/monthly window still blocks at its long threshold (98% by default). This prevents old short-window exhaustion from surviving indefinitely on a now weekly/monthly account. A live main writer applies that same retirement proof to the display/rotation cache, so account selection cannot keep refusing the -recovered main account on its old short tuple. Pool accounts get the same proof from a valid complete WHAM probe (#7961): `poolWhamPolicyObservation` marks the observation from its window topology only, so a Plus to Pro upgrade cannot keep a stored pool account on the old plan's 5-hour tuple, while partial WHAM, invalid or unparseable readings, an explicit `allowed: false` verdict and response headers keep carrying it. A pool probe retires the tuple only with a live captured pool writer for that account and credential generation, the same proof its history write needs; a missing, stale or other-account writer keeps the tuple. The login usage read marks its observation the same way, but reauthentication clears the row before writing and creation refuses existing ids, so it has nothing to retire. The same complete topology, when no window declares a monthly duration and no tertiary window is present, also retires a carried monthly tuple under the same writer proof (#8067), so a Free to Pro Lite change cannot keep a pool account on the old plan's exhausted monthly reading. A complete main WHAM read with a live main writer carries the same monthly proof into both the display cache and the identity-bound policy snapshot (#8596), so a stale monthly tuple with no upstream window cannot refuse every main request; an explicit `allowed: false`, invalid or unparseable readings (additional windows included), partial topology and response headers keep it. Main-only monthly filtering is not applied to pool observations, and a main observation without a live main writer still carries its tuple. Coverage lives in `tests/codex-integration/codex-credits-probes.test.ts` (pool), +recovered main account on its old short tuple. Pool accounts get the same proof from a valid complete WHAM probe (#7961): `poolWhamPolicyObservation` marks the observation from its window topology only, so a Plus to Pro upgrade cannot keep a stored pool account on the old plan's 5-hour tuple, while partial WHAM, invalid or unparseable readings, an explicit `allowed: false` verdict and response headers keep carrying it. A pool probe retires the tuple only with a live captured pool writer for that account and credential generation, the same proof its history write needs; a missing, stale or other-account writer keeps the tuple. The login usage read marks its observation the same way, but reauthentication clears the row before writing and creation refuses existing ids, so it has nothing to retire. The same complete topology, when no window declares a monthly duration and no tertiary window is present, also retires a carried monthly tuple under the same writer proof (#8067), so a Free to Pro Lite change cannot keep a pool account on the old plan's exhausted monthly reading. A complete main WHAM read with a live main writer carries the same monthly proof into both the display cache and the identity-bound policy snapshot (#8596), so a stale monthly tuple with no upstream window cannot refuse every main request. A complete, allowed read with a 5-hour primary and a weekly or null secondary carries the same monthly proof for main and pool accounts, since Plus reports that shape; an explicit `allowed: false`, invalid or unparseable readings (additional windows included), partial topology and response headers keep it. Main-only monthly filtering is not applied to pool observations, and a main observation without a live main writer still carries its tuple. Coverage lives in `tests/codex-integration/codex-credits-probes.test.ts` (pool), `tests/codex-integration/main-quota-evidence-validation.test.ts`, `tests/codex-integration/main-account-hard-lock-retirement.test.ts`, `tests/codex-integration/main-quota-provenance.test.ts`, and diff --git a/tests/codex-integration/pool-monthly-window-retirement.test.ts b/tests/codex-integration/pool-monthly-window-retirement.test.ts index 96fd9840d74..f6110813283 100644 --- a/tests/codex-integration/pool-monthly-window-retirement.test.ts +++ b/tests/codex-integration/pool-monthly-window-retirement.test.ts @@ -42,6 +42,7 @@ function poolContext() { const now = () => Math.floor(Date.now() / 1000); const monthly = (used_percent = 100) => ({ used_percent, limit_window_seconds: 2_592_000, reset_at: now() + 2_592_000 }); const weekly = (used_percent = 0) => ({ used_percent, limit_window_seconds: 604_800, reset_at: now() + 604_800 }); +const fiveHour = (used_percent = 0) => ({ used_percent, limit_window_seconds: 18_000, reset_at: now() + 18_000 }); const observe = (plan_type: string, rate_limit: Record) => Response.json({ plan_type, rate_limit }); const freeExhausted = () => observe("free", { allowed: false, primary_window: monthly(), secondary_window: null }); const proLite = (extra: Record = {}) => @@ -128,6 +129,9 @@ describe("pool WHAM monthly-window retirement (#8067)", () => { expect(evidence({ ...weeklyOnly, rate_limit: { ...weeklyOnly.rate_limit, tertiary_window: monthly(5) } })?.monthlyWindowAbsent).toBeUndefined(); expect(evidence({ plan_type: "team", rate_limit: { allowed: true, primary_window: monthly(5), secondary_window: weekly() } })?.monthlyWindowAbsent).toBeUndefined(); expect(evidence({ plan_type: "prolite", rate_limit: { primary_window: weekly() } })?.monthlyWindowAbsent).toBeUndefined(); + expect(evidence({ plan_type: "plus", rate_limit: { allowed: true, primary_window: fiveHour(), secondary_window: weekly() } })?.monthlyWindowAbsent).toBe(true); + expect(evidence({ plan_type: "plus", rate_limit: { allowed: true, primary_window: fiveHour() } })?.monthlyWindowAbsent).toBeUndefined(); + expect(evidence({ plan_type: "plus", rate_limit: { primary_window: fiveHour(), secondary_window: weekly(), tertiary_window: null } })?.monthlyWindowAbsent).toBeUndefined(); }); }); @@ -189,6 +193,27 @@ describe("main WHAM monthly-window retirement (#8596)", () => { for (const quota of caches()) expect(quota?.monthlyPercent).toBeUndefined(); }); + // Plus restored its 5-hour window, so its complete read is a short primary with a weekly secondary. + const plusShortAndWeekly = (rate: Record = {}) => ({ plan_type: "plus", + rate_limit: { allowed: true, limit_reached: false, primary_window: fiveHour(5), secondary_window: weekly(1), ...rate } }); + + test("a complete allowed 5-hour and weekly read retires the carried monthly tuple in both caches", () => { + observeMainQuotaIdentity(mainIdentity); + exhaustMonthly(); + publish(plusShortAndWeekly({ secondary_window: undefined })); + publish(plusShortAndWeekly({ allowed: false })); + for (const quota of caches()) expect(quota?.monthlyPercent).toBe(100); + expect(isCodexQuotaExhausted(getAccountQuota(MAIN), "plus")).toBe(true); + publish(plusShortAndWeekly()); + for (const quota of caches()) { + expect(quota?.weeklyPercent).toBe(1); + expect(quota?.monthlyPercent).toBeUndefined(); + expect(quota?.monthlyResetAt).toBeUndefined(); + expect(quota?.monthlyIsPrimaryWindow).toBeUndefined(); + } + expect(isCodexQuotaExhausted(getAccountQuota(MAIN), "plus")).toBe(false); + }); + test("a present monthly window replaces the reading instead of retiring it", () => { observeMainQuotaIdentity(mainIdentity); exhaustMonthly(); From af11c5879784514a5ada3eac36602ff7758f87e4 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 12:46:20 +0900 Subject: [PATCH 11/60] feat(connections): read-only client connection view and Claude first-party preview (#9108) * feat(connections): read-only client connection view and Claude first-party preview Adds GET /api/connections, a read-only projection of where Codex, Claude Code (per registered home) and Claude Desktop route, who owns their files, why that differs from the switch, and which keys switching back would change. Adds GET /api/claude-code/first-party/preview, a dry run of the CLI first-party switch that the dashboard shows before the PUT. New config leaf claudeCode.extraConfigDirs. Catch-up 010 (G-001, G-002). * fix(connections): mask identity-bearing config keys; refuse a symlinked profile in the restore preview * fix(connections): show restore-preview keys through an allowlist * fix(connections): mask arbitrary path segments, bound status reads, document the Connections view in Spanish and the CLI parity map * test(layout): register the client-connection tests in their own explicit shard * fix(gui): check the preview response status before reading it; group masked restore rows; drop unused exports --- .../010_client_connection.md | 12 + .../src/content/docs/es/guides/claude-code.md | 8 + .../src/content/docs/guides/claude-code.md | 8 + gui/src/i18n/connections-copy.ts | 63 ++++ gui/src/i18n/de.ts | 2 + gui/src/i18n/en.ts | 2 + gui/src/i18n/fr.ts | 2 + gui/src/i18n/ja.ts | 2 + gui/src/i18n/ko.ts | 2 + gui/src/i18n/pt.ts | 2 + gui/src/i18n/ru.ts | 2 + gui/src/i18n/tr.ts | 2 + gui/src/i18n/vi.ts | 2 + gui/src/i18n/zh-TW.ts | 2 + gui/src/i18n/zh.ts | 2 + gui/src/pages/ClaudeCode.tsx | 46 ++- gui/src/pages/ClaudeHomesStatus.tsx | 47 +++ gui/src/pages/FirstPartyPreviewDialog.tsx | 67 ++++ gui/src/pages/claude-first-party-preview.ts | 44 +++ .../pages/integrations/ConnectionsPanel.tsx | 162 +++++++++ .../integrations/IntegrationsOverview.tsx | 4 + gui/src/pages/integrations/connections-api.ts | 38 ++ gui/tests/claude-toggle-race.test.tsx | 85 ++++- gui/tests/claudecode-save-bar.test.tsx | 7 + .../layout-client-connections.json | 4 + scripts/test-layout/layout.json | 2 +- src/claude/auth-detect.ts | 40 +- src/claude/connection-projection.ts | 135 +++++++ src/claude/first-party-preview.ts | 139 +++++++ src/claude/first-party-transition.ts | 51 +++ src/claude/intercept/settings.ts | 31 +- src/codex/connection-projection.ts | 102 ++++++ src/codex/inject/remove.ts | 97 +++-- src/codex/journal.ts | 43 +++ src/codex/provider-routing.ts | 32 +- src/codex/restore-preview.ts | 208 +++++++++++ src/config/load-degrade.ts | 9 + src/integrations/connection-view.ts | 53 +++ .../native/ownership-preflight.ts | 54 ++- src/lib/display-path.ts | 38 ++ src/server/management-api.ts | 8 + .../management/agent-settings-routes.ts | 24 +- .../claude-first-party-preview-routes.ts | 39 ++ .../management/connection-status-routes.ts | 46 +++ .../management/native-integration-routes.ts | 10 +- src/server/management/route-registry.ts | 4 + src/types/config.ts | 7 + structure/INDEX.md | 13 +- structure/clients/connections.md | 95 +++++ structure/config.md | 2 +- structure/gui-and-management-api.md | 2 +- structure/manifest.json | 14 + .../claude-first-party-preview.test.ts | 200 ++++++++++ tests/cli/cli-headless-parity.test.ts | 2 + .../connection-restore-preview-runner.ts | 82 +++++ tests/fixtures/test-layout-expected.json | 1 + tests/server/connection-status-routes.test.ts | 341 ++++++++++++++++++ 57 files changed, 2448 insertions(+), 93 deletions(-) create mode 100644 gui/src/i18n/connections-copy.ts create mode 100644 gui/src/pages/ClaudeHomesStatus.tsx create mode 100644 gui/src/pages/FirstPartyPreviewDialog.tsx create mode 100644 gui/src/pages/claude-first-party-preview.ts create mode 100644 gui/src/pages/integrations/ConnectionsPanel.tsx create mode 100644 gui/src/pages/integrations/connections-api.ts create mode 100644 scripts/test-layout/layout-client-connections.json create mode 100644 src/claude/connection-projection.ts create mode 100644 src/claude/first-party-preview.ts create mode 100644 src/claude/first-party-transition.ts create mode 100644 src/codex/connection-projection.ts create mode 100644 src/codex/restore-preview.ts create mode 100644 src/integrations/connection-view.ts create mode 100644 src/lib/display-path.ts create mode 100644 src/server/management/claude-first-party-preview-routes.ts create mode 100644 src/server/management/connection-status-routes.ts create mode 100644 structure/clients/connections.md create mode 100644 tests/claude-integration/claude-first-party-preview.test.ts create mode 100644 tests/fixtures/connection-restore-preview-runner.ts create mode 100644 tests/server/connection-status-routes.test.ts diff --git a/devlog/_plan/261123_proxy_upstream_catchup/010_client_connection.md b/devlog/_plan/261123_proxy_upstream_catchup/010_client_connection.md index 70ba5b2d387..e5063bed820 100644 --- a/devlog/_plan/261123_proxy_upstream_catchup/010_client_connection.md +++ b/devlog/_plan/261123_proxy_upstream_catchup/010_client_connection.md @@ -113,3 +113,15 @@ const toggleFirstParty = async () => { - magpie식 자동 provider 전환. - 다른 클라이언트(Gemini CLI, Zed)는 030. 계정 자격 증명 이동은 020(G-004). + +## Implementation (lane R1, 2026-11-25) + +Delivered in one PR. Departures from the sketch, each with its reason: + +- Drift reasons are `external_owner | account_mode | hub_gated | intercept_disabled | file_edited | pending_restart`. `hub_gated` and `intercept_disabled` were added because those gates are the real cause of drift there; `quota_block` is not produced because no read-only signal exists for the desktop quota gate (#6196 is still a design proposal). `observed` and `owner` also carry `unknown` for unreadable evidence. +- The Codex `restorePreview` follows `restoreNativeCodexAsync` through shared read-only halves (journal comparison, removal transform, provider-table retention, approved-provider URLs) and is checked against the real restore; it reports refusals (`refused_owner`, `refused_history`, …) as outcomes. +- The first-party preview shares `claudeFirstPartyTransition`, extracted from `PUT /api/claude-code`, and runs it on the persisted config like the PUT does. The dashboard skips the confirmation when no key would change. +- Every returned path goes through `displayPath` (home to `~`, `@` segments elided). +- `GET /api/connections` has no CLI verb yet; it is a `deferred-verb` owned by 020. + +Contract record: `structure/clients/connections.md`. diff --git a/docs-site/src/content/docs/es/guides/claude-code.md b/docs-site/src/content/docs/es/guides/claude-code.md index b496eece20b..70f1e17d6af 100644 --- a/docs-site/src/content/docs/es/guides/claude-code.md +++ b/docs-site/src/content/docs/es/guides/claude-code.md @@ -281,6 +281,14 @@ Encienda el interruptor CLI en Conecte → Claude, o ejecute `ocx claude config +#### Vista previa antes de activarlo y homes de Claude + +Al activar el interruptor en el panel, OpenCodex primero muestra las claves que añadiría o cambiaría en el `settings.json` del home predeterminado (por ejemplo `env.HTTPS_PROXY`, `env.NODE_EXTRA_CA_CERTS`, `env.NO_PROXY`) y espera tu confirmación. Nunca muestra valores y la vista previa no escribe nada; si cancelas o la vista previa falla, el interruptor queda apagado y no se envía ningún cambio. El interruptor aún puede rechazar el cambio después, al iniciar la intercepción o preparar su certificado y su token. Los scripts pueden leer la misma vista previa con `GET /api/claude-code/first-party/preview?enabled=true`. + +El interruptor solo escribe en el home predeterminado de Claude (`CLAUDE_CONFIG_DIR`, o si no `~/.claude`). Si usas otros homes de Claude, añádelos en `claudeCode.extraConfigDirs` (por ejemplo `ocx config set claudeCode.extraConfigDirs '["~/.claude-work"]' --json`) y la página de Claude Code y **Connect → Client connections** mostrarán adónde se dirige cada uno. OpenCodex solo lee esos homes y nunca busca otros en el disco. + +**Client connections** en la vista general de Connect muestra, para Codex, Claude Code (por home) y Claude Desktop, adónde debería ir el cliente, adónde apuntan ahora sus archivos, quién los controla, por qué difieren y qué claves cambiaría volver atrás. + #### Selector de modelos en el CLI Con el interruptor de primera parte CLI encendido y el enrutamiento Claude habilitado, inicie un nuevo `claude` y abra `/model`. Sus modelos opencodex aparecen junto a los modelos Claude de su cuenta, etiquetados como " Grok 4.7 (xai)" y descritos con su ruta ( `opencodex · xai/grok-4.7` ). Escoger uno dirige esa sesión al modelo, al igual que un enlace. diff --git a/docs-site/src/content/docs/guides/claude-code.md b/docs-site/src/content/docs/guides/claude-code.md index fefedb9ff54..6fccdf4f2fe 100644 --- a/docs-site/src/content/docs/guides/claude-code.md +++ b/docs-site/src/content/docs/guides/claude-code.md @@ -541,6 +541,14 @@ The UI distinguishes uncertainty about whether settings still point at its proxy - Claude Code honours `HTTPS_PROXY`/`NODE_EXTRA_CA_CERTS` as documented for corporate proxies; a CLI release that stops doing so would stop routing, not break login. +#### Preview before turning it on, and Claude homes + +When you turn the dashboard switch on, OpenCodex first lists the keys it would add or change in the default home's `settings.json` (for example `env.HTTPS_PROXY`, `env.NODE_EXTRA_CA_CERTS`, `env.NO_PROXY`) and waits for you to confirm. Values are never shown, and the preview writes nothing; cancelling, or a preview that fails, leaves the switch off and sends no change. The switch can still refuse afterwards while it starts the intercept or prepares its certificate and token. Scripts can read the same preview from `GET /api/claude-code/first-party/preview?enabled=true`. + +The switch only ever writes the default Claude home (`CLAUDE_CONFIG_DIR`, else `~/.claude`). If you keep other Claude homes, list them under `claudeCode.extraConfigDirs` (for example `ocx config set claudeCode.extraConfigDirs '["~/.claude-work"]' --json`) and the Claude Code page and **Connect → Client connections** show where each one routes. OpenCodex only reads those homes and never searches the disk for others. + +**Client connections** on the Connect overview shows, for Codex, Claude Code (per home) and Claude Desktop, where the client is wanted to go, where its files point now, who owns them, why the two differ, and which keys switching it back would change. + #### Model picker in the CLI With the CLI first-party switch on and Claude routing enabled, start a new `claude` and open diff --git a/gui/src/i18n/connections-copy.ts b/gui/src/i18n/connections-copy.ts new file mode 100644 index 00000000000..eed3965d872 --- /dev/null +++ b/gui/src/i18n/connections-copy.ts @@ -0,0 +1,63 @@ +/* + * Copy for the read-only Connections view and the Claude Code first-party preview (catch-up 010). + * One row per key, columns in the order of `locales`, kept apart from the per-locale files like + * gateway-clients-copy.ts. Paths and setting keys are shown as sent. + */ +type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; +type Row = readonly [string, string, string, string, string, string, string, string, string, string, string]; + +const rows = { + "title": ["Client connections","클라이언트 연결","Client-Verbindungen","Connexions des clients","客户端连接","用戶端連線","Подключения клиентов","クライアント接続","İstemci bağlantıları","Kết nối máy khách","Conexões dos clientes"], + "intro": ["Where each client goes now, who owns its settings, and what switching it back would change. Read-only: nothing here writes.","각 클라이언트가 지금 어디로 가는지, 설정을 누가 소유하는지, 되돌리면 무엇이 바뀌는지 보여 줘요. 읽기 전용이라 여기서는 아무것도 쓰지 않아요.","Wohin jeder Client gerade geht, wem seine Einstellungen gehören und was ein Zurückschalten ändern würde. Nur lesend: hier wird nichts geschrieben.","Où va chaque client maintenant, à qui appartiennent ses réglages et ce que le retour en arrière changerait. Lecture seule : rien n’est écrit ici.","每个客户端现在去往哪里、谁拥有它的设置、切回会改变什么。只读:这里不会写入任何内容。","每個用戶端現在前往哪裡、誰擁有它的設定、切回會改變什麼。唯讀:這裡不會寫入任何內容。","Куда сейчас идёт каждый клиент, кому принадлежат его настройки и что изменит возврат. Только чтение: здесь ничего не записывается.","各クライアントが今どこへ向かっているか、設定の所有者、元に戻すと何が変わるかを表示します。読み取り専用で、ここでは何も書き込みません。","Her istemcinin şu an nereye gittiği, ayarlarının kime ait olduğu ve geri almanın neyi değiştireceği. Salt okunur: burada hiçbir şey yazılmaz.","Mỗi máy khách hiện đi đâu, ai sở hữu cài đặt của nó và chuyển về sẽ thay đổi gì. Chỉ đọc: không ghi gì ở đây.","Para onde cada cliente vai agora, quem é dono das configurações e o que voltar atrás mudaria. Somente leitura: nada é gravado aqui."], + "loading": ["Reading connection status…","연결 상태를 읽는 중…","Verbindungsstatus wird gelesen…","Lecture de l’état des connexions…","正在读取连接状态…","正在讀取連線狀態…","Чтение состояния подключений…","接続状態を読み込み中…","Bağlantı durumu okunuyor…","Đang đọc trạng thái kết nối…","Lendo o status das conexões…"], + "loadFail": ["Could not read the connection status.","연결 상태를 읽지 못했어요.","Der Verbindungsstatus konnte nicht gelesen werden.","Impossible de lire l’état des connexions.","无法读取连接状态。","無法讀取連線狀態。","Не удалось прочитать состояние подключений.","接続状態を読み取れませんでした。","Bağlantı durumu okunamadı.","Không đọc được trạng thái kết nối.","Não foi possível ler o status das conexões."], + "refresh": ["Refresh","새로고침","Aktualisieren","Actualiser","刷新","重新整理","Обновить","更新","Yenile","Làm mới","Atualizar"], + "homeDefault": ["Default home","기본 home","Standard-Home","Dossier par défaut","默认主目录","預設主目錄","Домашний каталог по умолчанию","既定のホーム","Varsayılan ana dizin","Thư mục mặc định","Pasta padrão"], + "homeExtra": ["Registered home {n}","등록한 home {n}","Registriertes Home {n}","Dossier enregistré {n}","已登记的主目录 {n}","已登記的主目錄 {n}","Зарегистрированный каталог {n}","登録したホーム {n}","Kayıtlı ana dizin {n}","Thư mục đã đăng ký {n}","Pasta registrada {n}"], + "desired": ["Wanted","원하는 상태","Gewünscht","Souhaité","期望","期望","Нужно","希望","İstenen","Mong muốn","Desejado"], + "observed": ["Now","현재","Aktuell","Actuel","当前","目前","Сейчас","現在","Şu an","Hiện tại","Agora"], + "owner": ["Owner","소유자","Eigentümer","Propriétaire","所有者","擁有者","Владелец","所有者","Sahip","Chủ sở hữu","Dono"], + "state.proxy": ["Through OpenCodex","OpenCodex 경유","Über OpenCodex","Via OpenCodex","经由 OpenCodex","經由 OpenCodex","Через OpenCodex","OpenCodex 経由","OpenCodex üzerinden","Qua OpenCodex","Via OpenCodex"], + "state.native": ["Native","기본 경로","Nativ","Natif","原生","原生","Напрямую","ネイティブ","Yerel","Gốc","Nativo"], + "state.remote-home": ["Through the Remote Link Home","Remote Link Home 경유","Über das Remote-Link-Home","Via le Remote Link Home","经由 Remote Link Home","經由 Remote Link Home","Через Remote Link Home","Remote Link Home 経由","Remote Link Home üzerinden","Qua Remote Link Home","Via o Remote Link Home"], + "state.unset": ["Not managed by OpenCodex","OpenCodex가 관리하지 않음","Nicht von OpenCodex verwaltet","Non géré par OpenCodex","不由 OpenCodex 管理","不由 OpenCodex 管理","Не управляется OpenCodex","OpenCodex の管理外","OpenCodex tarafından yönetilmiyor","OpenCodex không quản lý","Não gerenciado pelo OpenCodex"], + "state.foreign": ["Another proxy or provider","다른 프록시 또는 공급자","Anderer Proxy oder Anbieter","Autre proxy ou fournisseur","其他代理或提供商","其他代理或供應商","Другой прокси или провайдер","別のプロキシまたはプロバイダー","Başka bir proxy veya sağlayıcı","Proxy hoặc nhà cung cấp khác","Outro proxy ou provedor"], + "state.missing": ["Not set up","설정 없음","Nicht eingerichtet","Non configuré","未设置","未設定","Не настроено","未設定","Kurulmamış","Chưa thiết lập","Não configurado"], + "state.unknown": ["Unknown","알 수 없음","Unbekannt","Inconnu","未知","未知","Неизвестно","不明","Bilinmiyor","Không rõ","Desconhecido"], + "owner.opencodex": ["Managed by OpenCodex","OpenCodex가 관리","Von OpenCodex verwaltet","Géré par OpenCodex","由 OpenCodex 管理","由 OpenCodex 管理","Управляется OpenCodex","OpenCodex が管理","OpenCodex tarafından yönetiliyor","Do OpenCodex quản lý","Gerenciado pelo OpenCodex"], + "owner.external": ["Someone else","다른 소유자","Jemand anderes","Quelqu’un d’autre","其他所有者","其他擁有者","Кто-то другой","他の所有者","Başka biri","Bên khác","Outra parte"], + "owner.hub": ["Hub mode","Hub 모드","Hub-Modus","Mode hub","Hub 模式","Hub 模式","Режим хаба","Hub モード","Hub modu","Chế độ Hub","Modo hub"], + "owner.none": ["Nobody","없음","Niemand","Personne","无","無","Никто","なし","Yok","Không có","Ninguém"], + "owner.unknown": ["Unknown","알 수 없음","Unbekannt","Inconnu","未知","未知","Неизвестно","不明","Bilinmiyor","Không rõ","Desconhecido"], + "ownerPath": ["Owned by {path}","소유 파일: {path}","Gehört zu {path}","Appartient à {path}","所属文件:{path}","所屬檔案:{path}","Принадлежит {path}","所有ファイル: {path}","Sahibi: {path}","Thuộc về {path}","Pertence a {path}"], + "reason.external_owner": ["Another program, OpenCodex home or service owns these files, so OpenCodex leaves them alone.","다른 프로그램, OpenCodex home 또는 서비스가 이 파일을 소유하고 있어서 OpenCodex가 건드리지 않아요.","Ein anderes Programm, OpenCodex-Home oder ein Dienst besitzt diese Dateien, daher lässt OpenCodex sie unverändert.","Un autre programme, dossier OpenCodex ou service possède ces fichiers ; OpenCodex n’y touche donc pas.","这些文件属于其他程序、OpenCodex 主目录或服务,因此 OpenCodex 不会改动它们。","這些檔案屬於其他程式、OpenCodex 主目錄或服務,因此 OpenCodex 不會變動它們。","Этими файлами владеет другая программа, каталог OpenCodex или служба, поэтому OpenCodex их не трогает.","別のプログラム、OpenCodex ホーム、またはサービスがこれらのファイルを所有しているため、OpenCodex は変更しません。","Bu dosyalar başka bir programa, OpenCodex ana dizinine veya hizmete ait; bu yüzden OpenCodex onlara dokunmaz.","Một chương trình, thư mục OpenCodex hoặc dịch vụ khác sở hữu các tệp này, nên OpenCodex không động vào.","Outro programa, pasta do OpenCodex ou serviço é dono destes arquivos, então o OpenCodex não mexe neles."], + "reason.account_mode": ["Claude Desktop is pinned to one account mode but runs the other.","Claude Desktop이 한 계정 모드로 고정되어 있지만 다른 모드로 실행 중이에요.","Claude Desktop ist auf einen Kontomodus festgelegt, läuft aber im anderen.","Claude Desktop est fixé sur un mode de compte mais fonctionne dans l’autre.","Claude Desktop 固定为一种账户模式,却在以另一种模式运行。","Claude Desktop 固定為一種帳戶模式,卻以另一種模式執行。","Claude Desktop закреплён за одним режимом учётной записи, но работает в другом.","Claude Desktop は一方のアカウントモードに固定されていますが、もう一方で動いています。","Claude Desktop bir hesap moduna sabitlenmiş ama diğerinde çalışıyor.","Claude Desktop được ghim vào một chế độ tài khoản nhưng đang chạy chế độ kia.","O Claude Desktop está fixado em um modo de conta, mas roda no outro."], + "reason.hub_gated": ["This machine is a hub, so it does not rewrite its own clients unless the loopback listener is enabled.","이 기기는 hub라서 loopback listener를 켜지 않으면 자기 클라이언트 설정을 다시 쓰지 않아요.","Dieser Rechner ist ein Hub und schreibt seine eigenen Clients nur mit aktiviertem Loopback-Listener um.","Cette machine est un hub : elle ne réécrit ses propres clients que si l’écoute loopback est activée.","这台机器是 hub,除非启用 loopback 监听,否则不会改写自己的客户端。","這台機器是 hub,除非啟用 loopback 監聽,否則不會改寫自己的用戶端。","Эта машина — хаб и не перезаписывает свои клиенты, пока не включён loopback-слушатель.","このマシンは hub なので、loopback リスナーを有効にしない限り自身のクライアントを書き換えません。","Bu makine bir hub; loopback dinleyicisi açık olmadıkça kendi istemcilerini yeniden yazmaz.","Máy này là hub nên không ghi lại máy khách của chính nó trừ khi bật loopback listener.","Esta máquina é um hub e não reescreve os próprios clientes, a menos que o listener de loopback esteja ativado."], + "reason.intercept_disabled": ["First-party is on, but the interception proxy is disabled here.","first-party가 켜져 있지만 이 기기에서는 가로채기 프록시가 꺼져 있어요.","First-Party ist an, aber der Abfang-Proxy ist hier deaktiviert.","Le mode first-party est actif, mais le proxy d’interception est désactivé ici.","first-party 已开启,但这里的拦截代理已禁用。","first-party 已開啟,但這裡的攔截代理已停用。","Режим first-party включён, но перехватывающий прокси здесь отключён.","first-party はオンですが、ここではインターセプトプロキシが無効です。","First-party açık ama burada yakalama proxy'si devre dışı.","First-party đang bật nhưng proxy chặn đã bị tắt ở đây.","O first-party está ligado, mas o proxy de interceptação está desativado aqui."], + "reason.file_edited": ["The file no longer matches the switch: it was edited, rewritten by the app, or left over from an earlier change.","파일이 스위치와 맞지 않아요. 직접 수정됐거나, 앱이 다시 썼거나, 이전 변경에서 남은 거예요.","Die Datei passt nicht mehr zum Schalter: bearbeitet, von der App neu geschrieben oder von einer früheren Änderung übrig.","Le fichier ne correspond plus à l’interrupteur : modifié, réécrit par l’application ou resté d’un changement précédent.","文件已与开关不一致:被编辑过、被应用改写,或是之前更改的残留。","檔案已與開關不一致:被編輯過、被應用程式改寫,或是先前變更的殘留。","Файл больше не соответствует переключателю: его изменили, перезаписало приложение или он остался от прошлого изменения.","ファイルがスイッチと一致しません。編集されたか、アプリが書き換えたか、以前の変更の残りです。","Dosya artık anahtarla eşleşmiyor: düzenlenmiş, uygulama tarafından yeniden yazılmış ya da önceki bir değişiklikten kalmış.","Tệp không còn khớp với công tắc: đã bị sửa, bị ứng dụng ghi lại hoặc còn sót từ thay đổi trước.","O arquivo não corresponde mais ao interruptor: foi editado, reescrito pelo app ou sobrou de uma mudança anterior."], + "reason.pending_restart": ["The settings are written, but the listener they point at is stopped or on another port. Start OpenCodex or run ocx ensure.","설정은 써 있지만 가리키는 listener가 멈췄거나 다른 포트에 있어요. OpenCodex를 시작하거나 ocx ensure를 실행하세요.","Die Einstellungen sind geschrieben, aber der Listener ist gestoppt oder auf einem anderen Port. Starten Sie OpenCodex oder führen Sie ocx ensure aus.","Les réglages sont écrits, mais l’écouteur visé est arrêté ou sur un autre port. Démarrez OpenCodex ou lancez ocx ensure.","设置已写入,但指向的监听器已停止或在其他端口。请启动 OpenCodex 或运行 ocx ensure。","設定已寫入,但指向的監聽器已停止或在其他連接埠。請啟動 OpenCodex 或執行 ocx ensure。","Настройки записаны, но указанный слушатель остановлен или на другом порту. Запустите OpenCodex или выполните ocx ensure.","設定は書き込まれていますが、指す先のリスナーが停止しているか別のポートです。OpenCodex を起動するか ocx ensure を実行してください。","Ayarlar yazıldı ama gösterdikleri dinleyici durmuş ya da başka bir portta. OpenCodex'i başlatın veya ocx ensure çalıştırın.","Cài đặt đã được ghi nhưng listener mà nó trỏ tới đã dừng hoặc ở cổng khác. Hãy khởi động OpenCodex hoặc chạy ocx ensure.","As configurações estão gravadas, mas o listener indicado está parado ou em outra porta. Inicie o OpenCodex ou rode ocx ensure."], + "restoreTitle": ["Switching it back would change","되돌리면 바뀌는 항목","Zurückschalten würde ändern","Le retour en arrière changerait","切回将会改变","切回將會改變","Возврат изменит","元に戻すと変わる項目","Geri almak şunları değiştirir","Chuyển về sẽ thay đổi","Voltar atrás mudaria"], + "restoreNone": ["No settings keys would change.","바뀌는 설정 키가 없어요.","Keine Einstellungsschlüssel würden sich ändern.","Aucune clé de réglage ne changerait.","没有设置键会改变。","沒有設定鍵會改變。","Ни один ключ настроек не изменится.","変わる設定キーはありません。","Hiçbir ayar anahtarı değişmez.","Không có khóa cài đặt nào thay đổi.","Nenhuma chave de configuração mudaria."], + "change.add": ["added","추가","hinzugefügt","ajoutée","新增","新增","добавится","追加","eklenir","thêm","adicionada"], + "change.update": ["changed","변경","geändert","modifiée","更改","變更","изменится","変更","değişir","thay đổi","alterada"], + "change.remove": ["removed","삭제","entfernt","supprimée","移除","移除","удалится","削除","kaldırılır","xóa","removida"], + "outcome.refused": ["Switching back would be refused first: {reason}","되돌리기가 먼저 거절돼요: {reason}","Das Zurückschalten würde zuerst abgelehnt: {reason}","Le retour en arrière serait d’abord refusé : {reason}","切回会先被拒绝:{reason}","切回會先被拒絕:{reason}","Возврат будет сначала отклонён: {reason}","元に戻す操作は先に拒否されます: {reason}","Geri alma önce reddedilir: {reason}","Chuyển về sẽ bị từ chối trước: {reason}","Voltar atrás seria recusado primeiro: {reason}"], + "homesTitle": ["Claude homes","Claude home 목록","Claude-Homes","Dossiers Claude","Claude 主目录","Claude 主目錄","Каталоги Claude","Claude ホーム","Claude ana dizinleri","Thư mục Claude","Pastas do Claude"], + "homesHint": ["The switch acts on the default home. Add more under claudeCode.extraConfigDirs to see them here.","스위치는 기본 home에만 적용돼요. claudeCode.extraConfigDirs에 추가하면 여기에 함께 보여요.","Der Schalter wirkt auf das Standard-Home. Weitere unter claudeCode.extraConfigDirs eintragen, um sie hier zu sehen.","L’interrupteur agit sur le dossier par défaut. Ajoutez-en d’autres dans claudeCode.extraConfigDirs pour les voir ici.","开关只作用于默认主目录。把其他目录加到 claudeCode.extraConfigDirs 即可在此看到。","開關只作用於預設主目錄。把其他目錄加到 claudeCode.extraConfigDirs 即可在此看到。","Переключатель действует на каталог по умолчанию. Добавьте другие в claudeCode.extraConfigDirs, чтобы видеть их здесь.","スイッチは既定のホームに作用します。claudeCode.extraConfigDirs に追加するとここに表示されます。","Anahtar varsayılan ana dizine uygulanır. Diğerlerini burada görmek için claudeCode.extraConfigDirs'e ekleyin.","Công tắc tác động lên thư mục mặc định. Thêm thư mục khác vào claudeCode.extraConfigDirs để xem ở đây.","O interruptor age na pasta padrão. Adicione outras em claudeCode.extraConfigDirs para vê-las aqui."], + "preview.title": ["Turn on first-party for Claude Code?","Claude Code first-party를 켤까요?","First-Party für Claude Code einschalten?","Activer le mode first-party pour Claude Code ?","为 Claude Code 开启 first-party?","為 Claude Code 開啟 first-party?","Включить first-party для Claude Code?","Claude Code の first-party をオンにしますか?","Claude Code için first-party açılsın mı?","Bật first-party cho Claude Code?","Ligar o first-party para o Claude Code?"], + "preview.intro": ["These keys in {path} would change. Values are not shown.","{path}에서 아래 키가 바뀌어요. 값은 보여 주지 않아요.","Diese Schlüssel in {path} würden sich ändern. Werte werden nicht angezeigt.","Ces clés de {path} changeraient. Les valeurs ne sont pas affichées.","{path} 中的以下键会改变。不显示值。","{path} 中的以下鍵會改變。不顯示值。","Эти ключи в {path} изменятся. Значения не показываются.","{path} の次のキーが変わります。値は表示しません。","{path} içindeki şu anahtarlar değişir. Değerler gösterilmez.","Các khóa sau trong {path} sẽ thay đổi. Không hiển thị giá trị.","Estas chaves em {path} mudariam. Os valores não são mostrados."], + "preview.checks": ["The switch can still refuse while it starts the intercept or prepares its certificate and token.","가로채기를 시작하거나 인증서와 토큰을 준비하는 중에 스위치가 거절될 수도 있어요.","Der Schalter kann noch ablehnen, während er den Abfang startet oder Zertifikat und Token vorbereitet.","L’interrupteur peut encore refuser en démarrant l’interception ou en préparant son certificat et son jeton.","在启动拦截或准备证书和令牌时,开关仍可能拒绝。","在啟動攔截或準備憑證和權杖時,開關仍可能拒絕。","Переключатель ещё может отказать при запуске перехвата или подготовке сертификата и токена.","インターセプトの開始や証明書・トークンの準備中に、スイッチが拒否することもあります。","Anahtar, yakalamayı başlatırken veya sertifika ve belirtecini hazırlarken yine de reddedebilir.","Công tắc vẫn có thể từ chối khi khởi động chặn hoặc chuẩn bị chứng chỉ và token.","O interruptor ainda pode recusar ao iniciar a interceptação ou preparar o certificado e o token."], + "preview.confirm": ["Turn on","켜기","Einschalten","Activer","开启","開啟","Включить","オンにする","Aç","Bật","Ligar"], + "preview.cancel": ["Cancel","취소","Abbrechen","Annuler","取消","取消","Отмена","キャンセル","İptal","Hủy","Cancelar"], + "preview.loadFail": ["Could not preview the change, so nothing was changed.","변경 내용을 미리 보지 못해서 아무것도 바꾸지 않았어요.","Die Änderung konnte nicht vorab angezeigt werden; nichts wurde geändert.","Impossible de prévisualiser le changement ; rien n’a été modifié.","无法预览更改,因此没有做任何改动。","無法預覽變更,因此沒有做任何變動。","Не удалось показать изменение заранее, поэтому ничего не изменено.","変更をプレビューできなかったため、何も変更していません。","Değişiklik önizlenemedi, bu yüzden hiçbir şey değiştirilmedi.","Không xem trước được thay đổi nên chưa thay đổi gì.","Não foi possível pré-visualizar a mudança, então nada foi alterado."], +} satisfies Record; + +export type ConnectionsCopyKey = `connections.${keyof typeof rows}`; + +export function connectionsCopy(locale: Locale): Record { + const column = locales.indexOf(locale); + return Object.fromEntries( + Object.entries(rows).map(([key, row]) => [`connections.${key}`, row[column]!]), + ) as Record; +} diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 662085a28aa..d7c539d6f9a 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -5,6 +5,7 @@ import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { remoteLinkChildCopy } from "./remote-link-child-copy"; import { gatewayClientsCopy } from "./gateway-clients-copy"; +import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -144,6 +145,7 @@ export const de: Record = { ...remoteLinkDiagnosticsCopy("de"), ...remoteLinkChildCopy("de"), ...gatewayClientsCopy("de"), + ...connectionsCopy("de"), ...modelsV2Copy("de"), ...modelsOverallCopy("de"), ...accountsV2Copy("de"), diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index bf5b4e3a9e6..6325f2eaf0e 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -5,6 +5,7 @@ import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { remoteLinkChildCopy } from "./remote-link-child-copy"; import { gatewayClientsCopy } from "./gateway-clients-copy"; +import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -145,6 +146,7 @@ export const en = { ...remoteLinkDiagnosticsCopy("en"), ...remoteLinkChildCopy("en"), ...gatewayClientsCopy("en"), + ...connectionsCopy("en"), ...modelsV2Copy("en"), ...modelsOverallCopy("en"), ...accountsV2Copy("en"), diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index df72570ea96..43b0a829483 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -5,6 +5,7 @@ import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { remoteLinkChildCopy } from "./remote-link-child-copy"; import { gatewayClientsCopy } from "./gateway-clients-copy"; +import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -143,6 +144,7 @@ export const fr: Record = { ...remoteLinkDiagnosticsCopy("fr"), ...remoteLinkChildCopy("fr"), ...gatewayClientsCopy("fr"), + ...connectionsCopy("fr"), ...modelsV2Copy("fr"), ...modelsOverallCopy("fr"), ...accountsV2Copy("fr"), diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index 26d520cd9c5..1e16e633be6 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -5,6 +5,7 @@ import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { remoteLinkChildCopy } from "./remote-link-child-copy"; import { gatewayClientsCopy } from "./gateway-clients-copy"; +import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -143,6 +144,7 @@ export const ja: Record = { ...remoteLinkDiagnosticsCopy("ja"), ...remoteLinkChildCopy("ja"), ...gatewayClientsCopy("ja"), + ...connectionsCopy("ja"), ...modelsV2Copy("ja"), ...modelsOverallCopy("ja"), ...accountsV2Copy("ja"), diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index cce54f54592..1be02045cf4 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -5,6 +5,7 @@ import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { remoteLinkChildCopy } from "./remote-link-child-copy"; import { gatewayClientsCopy } from "./gateway-clients-copy"; +import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -143,6 +144,7 @@ export const ko: Record = { ...remoteLinkDiagnosticsCopy("ko"), ...remoteLinkChildCopy("ko"), ...gatewayClientsCopy("ko"), + ...connectionsCopy("ko"), ...modelsV2Copy("ko"), ...modelsOverallCopy("ko"), ...accountsV2Copy("ko"), diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index cc4981d49da..fd8bac76cb3 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -5,6 +5,7 @@ import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { remoteLinkChildCopy } from "./remote-link-child-copy"; import { gatewayClientsCopy } from "./gateway-clients-copy"; +import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -145,6 +146,7 @@ export const pt: Record = { ...remoteLinkDiagnosticsCopy("pt"), ...remoteLinkChildCopy("pt"), ...gatewayClientsCopy("pt"), + ...connectionsCopy("pt"), ...modelsV2Copy("pt"), ...modelsOverallCopy("pt"), ...accountsV2Copy("pt"), diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index ed6c4ac314e..053767f475a 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -5,6 +5,7 @@ import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { remoteLinkChildCopy } from "./remote-link-child-copy"; import { gatewayClientsCopy } from "./gateway-clients-copy"; +import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -143,6 +144,7 @@ export const ru: Record = { ...remoteLinkDiagnosticsCopy("ru"), ...remoteLinkChildCopy("ru"), ...gatewayClientsCopy("ru"), + ...connectionsCopy("ru"), ...modelsV2Copy("ru"), ...modelsOverallCopy("ru"), ...accountsV2Copy("ru"), diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 0760d99bf57..8f8ac6ea527 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -5,6 +5,7 @@ import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { remoteLinkChildCopy } from "./remote-link-child-copy"; import { gatewayClientsCopy } from "./gateway-clients-copy"; +import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -144,6 +145,7 @@ export const tr: Record = { ...remoteLinkDiagnosticsCopy("tr"), ...remoteLinkChildCopy("tr"), ...gatewayClientsCopy("tr"), + ...connectionsCopy("tr"), ...modelsV2Copy("tr"), ...modelsOverallCopy("tr"), ...accountsV2Copy("tr"), diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index b078b1c61f9..467fa61a16c 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -5,6 +5,7 @@ import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { remoteLinkChildCopy } from "./remote-link-child-copy"; import { gatewayClientsCopy } from "./gateway-clients-copy"; +import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -145,6 +146,7 @@ export const vi: Record = { ...remoteLinkDiagnosticsCopy("vi"), ...remoteLinkChildCopy("vi"), ...gatewayClientsCopy("vi"), + ...connectionsCopy("vi"), ...modelsV2Copy("vi"), ...modelsOverallCopy("vi"), ...accountsV2Copy("vi"), diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 6a334a868c8..de636a22df7 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -5,6 +5,7 @@ import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { remoteLinkChildCopy } from "./remote-link-child-copy"; import { gatewayClientsCopy } from "./gateway-clients-copy"; +import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -141,6 +142,7 @@ export const zhTW: Record = { ...remoteLinkDiagnosticsCopy("zh-TW"), ...remoteLinkChildCopy("zh-TW"), ...gatewayClientsCopy("zh-TW"), + ...connectionsCopy("zh-TW"), ...modelsV2Copy("zh-TW"), ...modelsOverallCopy("zh-TW"), ...accountsV2Copy("zh-TW"), diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 9ee4e59b4c4..976add704d5 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -5,6 +5,7 @@ import { codexCliUpdateCopy } from "./codex-cli-update-copy"; import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; import { remoteLinkChildCopy } from "./remote-link-child-copy"; import { gatewayClientsCopy } from "./gateway-clients-copy"; +import { connectionsCopy } from "./connections-copy"; import { modelsV2Copy } from "./v2-pages/models-copy"; import { modelsOverallCopy } from "./models-overall-copy"; import { accountsV2Copy } from "./v2-pages/accounts-copy"; @@ -143,6 +144,7 @@ export const zh: Record = { ...remoteLinkDiagnosticsCopy("zh"), ...remoteLinkChildCopy("zh"), ...gatewayClientsCopy("zh"), + ...connectionsCopy("zh"), ...modelsV2Copy("zh"), ...modelsOverallCopy("zh"), ...accountsV2Copy("zh"), diff --git a/gui/src/pages/ClaudeCode.tsx b/gui/src/pages/ClaudeCode.tsx index 1fba60db1ba..541d8a74344 100644 --- a/gui/src/pages/ClaudeCode.tsx +++ b/gui/src/pages/ClaudeCode.tsx @@ -20,6 +20,19 @@ import { AUTO_COMPACT_WINDOW_DEFAULT, formatCompactWindow, newClientId, normaliz import { SmallFastModelSetting } from "./claude-code-settings"; import { ClaudeCodeTierDefaults } from "./claude-code-tier-defaults"; import { interceptReasonKey, normalizeSharedProxy, selectFirstPartyNotice, type FirstPartyNotice } from "./claude-code-first-party"; +import FirstPartyPreviewDialog from "./FirstPartyPreviewDialog"; +import ClaudeHomesStatus from "./ClaudeHomesStatus"; +import { fetchFirstPartyPreview, FirstPartyPreviewRefusal, type FirstPartyPreview } from "./claude-first-party-preview"; + +/** Refusal codes the first-party switch (and its preview) answer with, and their copy. */ +const FIRST_PARTY_REFUSAL_KEYS = { + intercept_disabled: "claude.firstParty.refusal.interceptDisabled", + intercept_unavailable: "claude.firstParty.refusal.interceptUnavailable", + foreign_env: "claude.firstParty.refusal.foreignEnv", + ca_unavailable: "claude.firstParty.refusal.caUnavailable", + unreadable: "claude.firstParty.refusal.unreadable", + write_failed: "claude.firstParty.refusal.writeFailed", +} as const satisfies Record; import { acknowledgeSave, applyServerRead, @@ -148,6 +161,8 @@ export default function ClaudeCode({ apiBase, active = true }: { apiBase: string const { pending: connectionPending, change: changeConnection } = useClaudeConnection(apiBase); const [firstPartyPending, setFirstPartyPending] = useState(false); const firstPartyInFlight = useRef(false); + /* The open preview confirmation and the answer the switch is waiting for. */ + const [previewPrompt, setPreviewPrompt] = useState<{ preview: FirstPartyPreview; answer: (confirmed: boolean) => void } | null>(null); const fetchCode = useCallback(async (signal: AbortSignal): Promise => { const epoch = writeEpoch(cacheKey); @@ -297,6 +312,26 @@ export default function ClaudeCode({ apiBase, active = true }: { apiBase: string setStatus(""); const requested = !state.cliFirstParty; try { + if (requested) { + // Preview before writing: the dry run reports the settings.json keys and change kinds. + // A failed or refused preview throws here, so the PUT is never sent and the finally + // below releases the switch. + let preview: FirstPartyPreview; + try { + preview = await fetchFirstPartyPreview(apiBase, true); + } catch (error) { + const refusalKey = error instanceof FirstPartyPreviewRefusal && error.code in FIRST_PARTY_REFUSAL_KEYS + ? FIRST_PARTY_REFUSAL_KEYS[error.code as keyof typeof FIRST_PARTY_REFUSAL_KEYS] + : "connections.preview.loadFail"; + throw new Error(t(refusalKey), { cause: error }); + } + // Nothing to confirm when no settings.json key would change. + if (preview.changes.length > 0) { + const confirmed = await new Promise(answer => setPreviewPrompt({ preview, answer })); + setPreviewPrompt(null); + if (!confirmed) return; + } + } const response = await fetch(`${apiBase}/api/claude-code`, { method: "PUT", headers: { "Content-Type": "application/json" }, @@ -304,14 +339,7 @@ export default function ClaudeCode({ apiBase, active = true }: { apiBase: string }); if (!response.ok) { const payload = await response.json().catch(() => null) as { code?: string; port?: number; bound?: number; configured?: number } | null; - const refusalKeys = { - intercept_disabled: "claude.firstParty.refusal.interceptDisabled", - intercept_unavailable: "claude.firstParty.refusal.interceptUnavailable", - foreign_env: "claude.firstParty.refusal.foreignEnv", - ca_unavailable: "claude.firstParty.refusal.caUnavailable", - unreadable: "claude.firstParty.refusal.unreadable", - write_failed: "claude.firstParty.refusal.writeFailed", - } as const; + const refusalKeys = FIRST_PARTY_REFUSAL_KEYS; const key = payload?.code && payload.code in refusalKeys ? refusalKeys[payload.code as keyof typeof refusalKeys] : "claude.saveFailed"; @@ -442,7 +470,9 @@ export default function ClaudeCode({ apiBase, active = true }: { apiBase: string label={t("claude.firstParty.aria")} /> + + {previewPrompt && } {!state.interceptRunning && codeResource.refresh()} />} {state.cliFirstParty && ( {t("claude.firstParty.risk")} diff --git a/gui/src/pages/ClaudeHomesStatus.tsx b/gui/src/pages/ClaudeHomesStatus.tsx new file mode 100644 index 00000000000..509e5a96bd7 --- /dev/null +++ b/gui/src/pages/ClaudeHomesStatus.tsx @@ -0,0 +1,47 @@ +import { useCallback } from "react"; +import { useDataSurface } from "../data-surface"; +import { useT, type TKey } from "../i18n/shared"; +import { loadConnections, type ConnectionObserved, type ConnectionView } from "./integrations/connections-api"; + +const OBSERVED_KEYS: Record = { + proxy: "connections.state.proxy", + native: "connections.state.native", + "remote-home": "connections.state.remote-home", + foreign: "connections.state.foreign", + missing: "connections.state.missing", + unknown: "connections.state.unknown", +}; + +/** + * Per-home first-party status (catch-up 010, G-002): the default Claude home the switch acts on + * and every home registered in `claudeCode.extraConfigDirs`, read from the shared Connections + * projection. Renders nothing until that read succeeds; the switch does not depend on it. + */ +export default function ClaudeHomesStatus({ apiBase }: { apiBase: string }) { + const t = useT(); + const load = useCallback((signal: AbortSignal) => loadConnections(apiBase, signal), [apiBase]); + const resource = useDataSurface(`connections-view:${apiBase}`, [apiBase], load, { isEmpty: rows => rows.length === 0 }); + const homes = (resource.state.data ?? []).filter(view => view.client === "claude-code"); + if (homes.length === 0) return null; + return ( +
+
+ {t("connections.homesTitle")} + {t("connections.homesHint")} +
    + {homes.map(view => ( +
  • + {view.home}{" "} + {view.homeSource === "extra" + ? t("connections.homeExtra", { n: String(view.homeOrdinal ?? "") }) + : t("connections.homeDefault")}{" "} + 0 ? "badge badge-amber" : "badge badge-green"} data-claude-home-observed={view.observed}> + {t(OBSERVED_KEYS[view.observed])} + +
  • + ))} +
+
+
+ ); +} diff --git a/gui/src/pages/FirstPartyPreviewDialog.tsx b/gui/src/pages/FirstPartyPreviewDialog.tsx new file mode 100644 index 00000000000..72702a5ba8d --- /dev/null +++ b/gui/src/pages/FirstPartyPreviewDialog.tsx @@ -0,0 +1,67 @@ +import { useEffect, useRef } from "react"; +import { useT, type TKey } from "../i18n/shared"; +import type { FirstPartyPreview } from "./claude-first-party-preview"; + +const CHANGE_KEYS: Record = { + add: "connections.change.add", + update: "connections.change.update", + remove: "connections.change.remove", +}; + +/** + * The confirmation step before the CLI first-party switch writes settings.json (catch-up 010, + * G-002): the keys and change kinds the server's dry run reported, never their values. A modal + * `` like ConsequenceDialog, so the page behind it is inert while it is open. + */ +export default function FirstPartyPreviewDialog({ + preview, + onAnswer, +}: { + preview: FirstPartyPreview; + onAnswer: (confirmed: boolean) => void; +}) { + const t = useT(); + const dialogRef = useRef(null); + const cancelRef = useRef(null); + + useEffect(() => { + const dialog = dialogRef.current; + if (dialog && !dialog.open && typeof dialog.showModal === "function") dialog.showModal(); + cancelRef.current?.focus(); + return () => { if (dialog?.open) dialog.close(); }; + }, []); + + return ( + { event.preventDefault(); onAnswer(false); }} + > +
+
+

{t("connections.preview.title")}

+
+
+

{t("connections.preview.intro", { path: preview.path })}

+
    + {preview.changes.map(change => ( +
  • + {change.key} {t(CHANGE_KEYS[change.change])} +
  • + ))} +
+ {preview.applyChecks.length > 0 &&

{t("connections.preview.checks")}

} +
+
+ + +
+
+
+ ); +} diff --git a/gui/src/pages/claude-first-party-preview.ts b/gui/src/pages/claude-first-party-preview.ts new file mode 100644 index 00000000000..864766726ae --- /dev/null +++ b/gui/src/pages/claude-first-party-preview.ts @@ -0,0 +1,44 @@ +import { readJsonIfOk } from "../fetch-json"; + +/** Client for GET /api/claude-code/first-party/preview (catch-up 010, G-002). */ +export interface FirstPartyPreview { + enabled: boolean; + path: string; + changes: Array<{ file: "settings.json"; key: string; change: "add" | "update" | "remove" }>; + applyChecks: string[]; +} + +/** A refusal the switch itself would answer with; `code` matches the PUT's refusal codes. */ +export class FirstPartyPreviewRefusal extends Error { + readonly code: string; + constructor(code: string) { + super(code); + this.code = code; + this.name = "FirstPartyPreviewRefusal"; + } +} + +/** + * Fetch the dry run for turning CLI first-party on. Throws FirstPartyPreviewRefusal for a coded + * refusal and a plain Error for anything else (network, 5xx, malformed body); the caller then + * releases the switch and never sends the PUT. + */ +export async function fetchFirstPartyPreview(apiBase: string, enabled: boolean): Promise { + const response = await fetch(`${apiBase}/api/claude-code/first-party/preview?enabled=${enabled ? "true" : "false"}`); + if (!response.ok) { + // Only a 409 carries a refusal code the switch itself would answer with. + const refusal = response.status === 409 + ? await response.json().catch(() => null) as { code?: unknown } | null + : null; + if (refusal && typeof refusal.code === "string") throw new FirstPartyPreviewRefusal(refusal.code); + throw new Error("preview_failed"); + } + const body = await readJsonIfOk>(response); + if (!body || typeof body.path !== "string" || !Array.isArray(body.changes)) throw new Error("preview_failed"); + return { + enabled: body.enabled === true, + path: body.path, + changes: body.changes, + applyChecks: Array.isArray(body.applyChecks) ? body.applyChecks : [], + }; +} diff --git a/gui/src/pages/integrations/ConnectionsPanel.tsx b/gui/src/pages/integrations/ConnectionsPanel.tsx new file mode 100644 index 00000000000..6cf8cca8da9 --- /dev/null +++ b/gui/src/pages/integrations/ConnectionsPanel.tsx @@ -0,0 +1,162 @@ +import { useCallback } from "react"; +import { useDataSurface } from "../../data-surface"; +import { useT, type TKey } from "../../i18n/shared"; +import { Notice } from "../../ui"; +import { + loadConnections, + type ConnectionDriftReason, + type ConnectionKeyChange, + type ConnectionObserved, + type ConnectionOwner, + type ConnectionView, + type ConnectionDesired, +} from "./connections-api"; + +const CLIENT_LABEL: Record = { + codex: "integrations.tab.codex", + "claude-code": "claude.pageTitle", + "claude-desktop": "claudeDesktop.title", +}; + +const STATE_KEYS: Record = { + proxy: "connections.state.proxy", + native: "connections.state.native", + "remote-home": "connections.state.remote-home", + unset: "connections.state.unset", + foreign: "connections.state.foreign", + missing: "connections.state.missing", + unknown: "connections.state.unknown", +}; + +const OWNER_KEYS: Record = { + opencodex: "connections.owner.opencodex", + external: "connections.owner.external", + hub: "connections.owner.hub", + none: "connections.owner.none", + unknown: "connections.owner.unknown", +}; + +const REASON_KEYS: Record = { + external_owner: "connections.reason.external_owner", + account_mode: "connections.reason.account_mode", + hub_gated: "connections.reason.hub_gated", + intercept_disabled: "connections.reason.intercept_disabled", + file_edited: "connections.reason.file_edited", + pending_restart: "connections.reason.pending_restart", +}; + +const CHANGE_KEYS: Record = { + add: "connections.change.add", + update: "connections.change.update", + remove: "connections.change.remove", +}; + +function stateClass(desired: ConnectionDesired, observed: ConnectionObserved): string { + if (observed === "unknown") return "badge badge-muted"; + const matches = (desired === observed) || (desired === "unset"); + return matches ? "badge badge-green" : "badge badge-amber"; +} + +/** Masked keys can repeat (two user tables become `projects.….trust_level`); show each once with a count. */ +function groupedChanges(changes: readonly ConnectionKeyChange[]): Array { + const groups = new Map(); + for (const change of changes) { + const id = `${change.file}:${change.key}:${change.change}`; + const existing = groups.get(id); + if (existing) existing.count += 1; + else groups.set(id, { ...change, id, count: 1 }); + } + return [...groups.values()]; +} + +function ConnectionCard({ view }: { view: ConnectionView }) { + const t = useT(); + const drift = view.driftReasons.length > 0; + const preview = view.restorePreview; + return ( +
  • +
    +

    {t(CLIENT_LABEL[view.client])}

    + {view.homeSource && ( + {view.homeSource === "default" + ? t("connections.homeDefault") + : t("connections.homeExtra", { n: String(view.homeOrdinal ?? "") })} + )} +
    + {view.home &&

    {view.home}

    } +

    + {t("connections.desired")} {t(STATE_KEYS[view.desired])} + {" · "} + {t("connections.observed")} {t(STATE_KEYS[view.observed])} + {" · "} + {t("connections.owner")} {t(OWNER_KEYS[view.owner])} +

    +

    {view.configPath}

    + {view.driftReasons.map(reason => ( + + {t(REASON_KEYS[reason])} + {reason === "external_owner" && view.ownerPath && ( + <> {t("connections.ownerPath", { path: view.ownerPath })} + )} + + ))} + {preview && ( +
    + {t("connections.restoreTitle")} + {preview.outcome !== "restore" && ( +

    + {t("connections.outcome.refused", { reason: preview.outcome })} +

    + )} + {preview.outcome === "restore" && preview.changes.length === 0 && ( +

    {t("connections.restoreNone")}

    + )} + {preview.changes.length > 0 && ( +
      + {groupedChanges(preview.changes).map(change => ( +
    • + {change.file} {change.key} {t(CHANGE_KEYS[change.change])} + {change.count > 1 && <> ×{change.count}} +
    • + ))} +
    + )} +
    + )} +
  • + ); +} + +/** + * The read-only Connections panel (catch-up 010, G-001): one card per client and Claude home, + * read once per visit and on Refresh — no timer, the projection reads several files. + */ +export default function ConnectionsPanel({ apiBase, active = true }: { apiBase: string; active?: boolean }) { + const t = useT(); + const load = useCallback((signal: AbortSignal) => loadConnections(apiBase, signal), [apiBase]); + const resource = useDataSurface( + `connections-view:${apiBase}`, + [apiBase], + load, + { isEmpty: rows => rows.length === 0, enabled: active }, + ); + const rows = resource.state.data; + return ( +
    +
    +

    {t("connections.title")}

    + +
    +

    {t("connections.intro")}

    + {resource.state.showError && {t("connections.loadFail")}} + {!rows && !resource.state.showError &&

    {t("connections.loading")}

    } + {rows && ( +
      + {rows.map(view => )} +
    + )} +
    + ); +} diff --git a/gui/src/pages/integrations/IntegrationsOverview.tsx b/gui/src/pages/integrations/IntegrationsOverview.tsx index 88ac713e035..0b2ec495b1d 100644 --- a/gui/src/pages/integrations/IntegrationsOverview.tsx +++ b/gui/src/pages/integrations/IntegrationsOverview.tsx @@ -11,6 +11,7 @@ import IntegrationStateBadge from "./IntegrationStateBadge"; import ConsequenceDialog, { type ConsequenceCopy } from "./ConsequenceDialog"; import RestoreDialog from "./RestoreDialog"; import { RollbackHistory } from "./RollbackHistory"; +import ConnectionsPanel from "./ConnectionsPanel"; import { describeRefusal } from "./refusal-copy"; import { previewRecoveryFor, type PreviewRecovery } from "./preview-recovery"; import { loadCursorIntegrationStatus } from "./cursor-api"; @@ -898,6 +899,9 @@ export default function IntegrationsOverview({ )} + {/* Read-only: where Codex and Claude go now, who owns their files, what switching back changes. */} + +

    {t("integrations.rollback.title")}

    {/* The newest operation stays visible and the rest collapse. This page diff --git a/gui/src/pages/integrations/connections-api.ts b/gui/src/pages/integrations/connections-api.ts new file mode 100644 index 00000000000..dc70876c9c3 --- /dev/null +++ b/gui/src/pages/integrations/connections-api.ts @@ -0,0 +1,38 @@ +import { readJsonIfOk } from "../../fetch-json"; + +/** Kept in step with src/integrations/connection-view.ts (GET /api/connections). */ +export type ConnectionClient = "codex" | "claude-code" | "claude-desktop"; +export type ConnectionDesired = "proxy" | "native" | "remote-home" | "unset"; +export type ConnectionObserved = "proxy" | "native" | "remote-home" | "foreign" | "missing" | "unknown"; +export type ConnectionOwner = "opencodex" | "external" | "hub" | "none" | "unknown"; +const CONNECTION_DRIFT_REASONS = [ + "external_owner", "account_mode", "hub_gated", "intercept_disabled", "file_edited", "pending_restart", +] as const; +export type ConnectionDriftReason = (typeof CONNECTION_DRIFT_REASONS)[number]; + +export interface ConnectionKeyChange { + file: string; + key: string; + change: "add" | "update" | "remove"; +} + +export interface ConnectionView { + client: ConnectionClient; + home?: string; + homeSource?: "default" | "extra"; + homeOrdinal?: number; + configPath: string; + desired: ConnectionDesired; + observed: ConnectionObserved; + owner: ConnectionOwner; + ownerPath?: string; + driftReasons: ConnectionDriftReason[]; + restorePreview?: { outcome: string; changes: ConnectionKeyChange[] }; +} + +export async function loadConnections(apiBase: string, signal?: AbortSignal): Promise { + const response = await fetch(`${apiBase}/api/connections`, { signal }); + const body = await readJsonIfOk<{ connections?: unknown }>(response); + if (!body || !Array.isArray(body.connections)) throw new Error("connections_unavailable"); + return body.connections as ConnectionView[]; +} diff --git a/gui/tests/claude-toggle-race.test.tsx b/gui/tests/claude-toggle-race.test.tsx index d2668b880b9..35e811a28c2 100644 --- a/gui/tests/claude-toggle-race.test.tsx +++ b/gui/tests/claude-toggle-race.test.tsx @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { Window } from "happy-dom"; import { act } from "react"; import type { Root } from "react-dom/client"; @@ -32,6 +32,11 @@ let putBodies: unknown[] = []; let claudeEnabled = false; let cliFirstParty = false; let firstPartyPutResponse: { body: unknown; status?: number } | null = null; +/** The first-party preview answer: a body and status, or "network" for a rejected fetch. */ +let previewResponse: { body: unknown; status?: number } | "network" = { + body: { enabled: true, path: "~/.claude/settings.json", changes: [{ file: "settings.json", key: "env.HTTPS_PROXY", change: "add" }], applyChecks: ["intercept_start"] }, +}; +let previewRequests = 0; let releasePut: (() => void) | null = null; let putGate: Promise | null = null; @@ -88,6 +93,10 @@ beforeEach(() => { claudeEnabled = false; cliFirstParty = false; firstPartyPutResponse = null; + previewResponse = { + body: { enabled: true, path: "~/.claude/settings.json", changes: [{ file: "settings.json", key: "env.HTTPS_PROXY", change: "add" }], applyChecks: ["intercept_start"] }, + }; + previewRequests = 0; putGate = new Promise((resolve) => { releasePut = resolve; }); @@ -97,6 +106,11 @@ beforeEach(() => { const method = (init?.method ?? (input instanceof Request ? input.method : "GET")).toUpperCase(); if (url.includes("/api/machine/status")) return jsonResponse({}, 404); + if (url.includes("/api/claude-code/first-party/preview")) { + previewRequests++; + if (previewResponse === "network") throw new TypeError("Failed to fetch"); + return jsonResponse(previewResponse.body, previewResponse.status ?? 200); + } if (url.endsWith("/api/native-integrations/claude") && method === "PUT") { const body = JSON.parse(String(init?.body ?? "{}")) as { enabled: boolean }; putBodies.push(body); @@ -211,6 +225,15 @@ function firstPartySwitch(): HTMLButtonElement { return button as HTMLButtonElement; } + +function previewButton(label: "Turn on" | "Cancel"): HTMLButtonElement | null { + return (Array.from(container.querySelectorAll("button")).find(button => button.textContent === label) as HTMLButtonElement | undefined) ?? null; +} + +async function answerPreview(label: "Turn on" | "Cancel"): Promise { + await waitFor(() => previewButton(label) !== null); + await act(async () => { previewButton(label)!.click(); }); +} function claudeSwitch(): HTMLButtonElement { const btn = Array.from(container.querySelectorAll("button")).find( (b) => b.getAttribute("aria-label") === "Toggle Claude connection", @@ -297,6 +320,9 @@ test("CLI first-party waits for one PUT and a confirmed GET", async () => { firstPartySwitch().click(); firstPartySwitch().click(); }); + // Enabling previews first: one preview request, one confirmation, then exactly one PUT. + await answerPreview("Turn on"); + expect(previewRequests).toBe(1); expect(putBodies).toEqual([{ cliFirstParty: true }]); expect(firstPartySwitch().disabled).toBe(true); expect(firstPartySwitch().getAttribute("aria-checked")).toBe("false"); @@ -324,6 +350,7 @@ for (const [code, message] of refusalCases) { await mountApp(); await waitFor(() => { try { return !!firstPartySwitch(); } catch { return false; } }); await act(async () => { firstPartySwitch().click(); }); + await answerPreview("Turn on"); await waitFor(() => (container.textContent ?? "").includes(message)); expect(firstPartySwitch().getAttribute("aria-checked")).toBe("false"); }); @@ -334,6 +361,7 @@ test("CLI first-party success trusts the divergent GET state", async () => { await mountApp(); await waitFor(() => { try { return !!firstPartySwitch(); } catch { return false; } }); await act(async () => { firstPartySwitch().click(); }); + await answerPreview("Turn on"); await waitFor(() => !firstPartySwitch().disabled); expect(firstPartySwitch().getAttribute("aria-checked")).toBe("false"); }); @@ -367,3 +395,58 @@ test("the Save payload does not overwrite CLI first-party intent", async () => { await waitFor(() => putBodies.length === 1); expect(putBodies[0]).not.toHaveProperty("cliFirstParty"); }); + +describe("CLI first-party preview", () => { + const PREVIEW_FAILED = "Could not preview the change, so nothing was changed."; + + for (const [name, answer] of [ + ["a network error", "network"], + ["a server error", { status: 500, body: { error: "first-party preview could not be computed", code: "preview_failed" } }], + ] as const) { + test(`${name} releases the switch, shows the error and never sends the PUT`, async () => { + previewResponse = answer; + await mountApp(); + await waitFor(() => { try { return !!firstPartySwitch(); } catch { return false; } }); + await act(async () => { firstPartySwitch().click(); }); + await waitFor(() => (container.textContent ?? "").includes(PREVIEW_FAILED)); + await waitFor(() => !firstPartySwitch().disabled); + expect(putBodies).toEqual([]); + expect(firstPartySwitch().getAttribute("aria-checked")).toBe("false"); + }); + } + + test("a refusal the switch would give is shown before anything is written", async () => { + previewResponse = { status: 409, body: { error: "refused", code: "foreign_env" } }; + await mountApp(); + await waitFor(() => { try { return !!firstPartySwitch(); } catch { return false; } }); + await act(async () => { firstPartySwitch().click(); }); + await waitFor(() => (container.textContent ?? "").includes("Another program owns the Claude proxy settings.")); + await waitFor(() => !firstPartySwitch().disabled); + expect(putBodies).toEqual([]); + }); + + test("the dialog lists keys and change kinds; Cancel sends nothing and releases the switch", async () => { + await mountApp(); + await waitFor(() => { try { return !!firstPartySwitch(); } catch { return false; } }); + await act(async () => { firstPartySwitch().click(); }); + await waitFor(() => previewButton("Cancel") !== null); + const list = container.querySelector("[data-first-party-preview]"); + expect(list?.textContent).toContain("env.HTTPS_PROXY"); + expect(list?.querySelector("li")?.getAttribute("data-change")).toBe("add"); + expect(firstPartySwitch().disabled).toBe(true); + await answerPreview("Cancel"); + await waitFor(() => !firstPartySwitch().disabled); + expect(putBodies).toEqual([]); + expect(previewButton("Turn on")).toBeNull(); + }); + + test("turning first-party off needs no preview", async () => { + cliFirstParty = true; + claudeEnabled = true; + await mountApp(); + await waitFor(() => firstPartySwitch().getAttribute("aria-checked") === "true"); + await act(async () => { firstPartySwitch().click(); releasePut?.(); releasePut = null; }); + await waitFor(() => putBodies.length === 1); + expect(previewRequests).toBe(0); + }); +}); diff --git a/gui/tests/claudecode-save-bar.test.tsx b/gui/tests/claudecode-save-bar.test.tsx index 4c6173af2fa..75b357376a9 100644 --- a/gui/tests/claudecode-save-bar.test.tsx +++ b/gui/tests/claudecode-save-bar.test.tsx @@ -583,6 +583,13 @@ async function settle(testWindow: Window) { } async function mount() { + // The first-party switch previews before its PUT; an empty preview has nothing to confirm, so + // these Save-race tests keep exercising the PUT and its reread (the dialog is covered in + // claude-toggle-race.test.tsx). + const served = globalThis.fetch; + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => String(input).includes("/api/claude-code/first-party/preview") + ? Response.json({ enabled: true, path: "~/.claude/settings.json", changes: [], applyChecks: [] }) + : served(input, init)) as typeof fetch; const testWindow = new Window({ url: "http://localhost/" }); const container = testWindow.document.createElement("div"); testWindow.document.body.appendChild(container); diff --git a/scripts/test-layout/layout-client-connections.json b/scripts/test-layout/layout-client-connections.json new file mode 100644 index 00000000000..bf613e3a115 --- /dev/null +++ b/scripts/test-layout/layout-client-connections.json @@ -0,0 +1,4 @@ +{ + "claude-first-party-preview.test.ts": "claude-integration", + "connection-status-routes.test.ts": "server" +} diff --git a/scripts/test-layout/layout.json b/scripts/test-layout/layout.json index 9560e77348e..6c60cd343d1 100644 --- a/scripts/test-layout/layout.json +++ b/scripts/test-layout/layout.json @@ -1,7 +1,7 @@ { "version": 1, "root": "tests", - "explicitShards": ["layout-route-intent.json", "layout-release-signing.json", "layout-file-identity.json", "layout-clients.json", "layout-codex-collision.json", "layout-native-profiles.json", "layout-agent-assertion.json", "layout-chat.json", "layout-replay.json", "layout-adapters.json", "layout-jev.json", "layout-workbuddy.json", "layout-combos.json", "layout-credit-renewal.json", "layout-server-inbound.json", "layout-providers.json", "layout-responses.json", "layout-exec-boundary.json", "layout-persistent-dashboard.json", "layout-start-ownership.json", "layout-config.json", "layout-kiro-usage.json", "layout-usage.json", "layout-docs-guides.json", "layout-docs.json", "layout-claude-keychain.json", "layout-test-hygiene.json", "layout-codex-journal.json", "layout-upload-reduction.json", "layout-step-cli.json"], + "explicitShards": ["layout-route-intent.json", "layout-client-connections.json", "layout-release-signing.json", "layout-file-identity.json", "layout-clients.json", "layout-codex-collision.json", "layout-native-profiles.json", "layout-agent-assertion.json", "layout-chat.json", "layout-replay.json", "layout-adapters.json", "layout-jev.json", "layout-workbuddy.json", "layout-combos.json", "layout-credit-renewal.json", "layout-server-inbound.json", "layout-providers.json", "layout-responses.json", "layout-exec-boundary.json", "layout-persistent-dashboard.json", "layout-start-ownership.json", "layout-config.json", "layout-kiro-usage.json", "layout-usage.json", "layout-docs-guides.json", "layout-docs.json", "layout-claude-keychain.json", "layout-test-hygiene.json", "layout-codex-journal.json", "layout-upload-reduction.json", "layout-step-cli.json"], "explicit": { "gui-account-quota-table.test.ts": "gui", "account-probe-routes.test.ts": "server", "web-search-local-deadline-provenance.test.ts": "web-search", "kimi-monthly-quota.test.ts": "providers", "vertex-adc-verified.test.ts": "adapters/google", "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "catalog-omit-disabled-native.test.ts": "codex-integration", "provider-input-modalities.test.ts": "providers", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "codex-provider-routing.test.ts": "codex-integration", "config-native-reasoning-retention.test.ts": "config", "server-native-reasoning-retention-merge.test.ts": "server", "server-native-reasoning-retention.test.ts": "server", "config-workflow-budget.test.ts": "config", "server-workflow-budget-settings.test.ts": "server", "responses-retained-reasoning-stream-recovery.test.ts": "responses", "openai-native-hosted-search-history.test.ts": "adapters/openai", "responses-native-compact-search-history.test.ts": "responses", "config-hosted-search-projection.test.ts": "config", "gcp-credential-boundary.test.ts": "adapters/google", "gcp-sa-marker.test.ts": "adapters/google", "gcp-sa-adapter.test.ts": "adapters/google", "management-gcp-credential-input.test.ts": "server", "codex-preserve-signed-in.test.ts": "codex-integration", "cli-account-preservation.test.ts": "cli", "cli-provider-list-active.test.ts": "cli", "service-state-isolation.test.ts": "service", "compaction-history-framing.test.ts": "responses", "catalog-native-max-context.test.ts": "codex-integration", "protocol-argon-thought-boundary.test.ts": "responses", "service-log.test.ts": "service", "messages-native-empty-inline.test.ts": "claude-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "bridge-terminal-refusal.test.ts": "adapters", "loop-terminal-refusal.test.ts": "images", "web-search-terminal-refusal.test.ts": "web-search", "combo-terminal-refusal.test.ts": "routing", "server-terminal-refusal-wiring.test.ts": "server", "incomplete-reason-normalization.test.ts": "responses", "advisor-retention.test.ts": "advisor", "responses-native-key-cooldown.test.ts": "responses", "responses-run-turn-key-readmission.test.ts": "responses", "qoder-spawn-readmission.test.ts": "adapters", "api-key-selection-cooldown.test.ts": "providers", "api-key-auto-pause-distribution.test.ts": "providers", "explicit-key-pause-oauth-boundary.test.ts": "providers", "server-chat-native-key-selection.test.ts": "server", "compact-key-selection.test.ts": "responses", "messages-native-key-selection.test.ts": "claude-integration", "coding-agent-windows-dispatch.test.ts": "adapters", "coding-agent-native-empty-argv.test.ts": "windows", "cli-message-mcp-resume.test.ts": "cli", "messaging-mcp-resume.test.ts": "codex-integration", "pr-gates-workflow.test.ts": "ci-workflows", "stop-restore-history-ownership.test.ts": "service", "cli-stop-refusal-transport.test.ts": "cli", diff --git a/src/claude/auth-detect.ts b/src/claude/auth-detect.ts index 877bd2b85f9..e5bf463b5a6 100644 --- a/src/claude/auth-detect.ts +++ b/src/claude/auth-detect.ts @@ -12,8 +12,9 @@ */ import { existsSync, readFileSync } from "node:fs"; import { homedir } from "node:os"; -import { join } from "node:path"; +import { isAbsolute, join, resolve } from "node:path"; import { claudeKeychainReader } from "../oauth/claude-keychain-read"; +import type { OcxConfig } from "../types"; export type AuthPresence = "present" | "absent" | "unknown"; @@ -102,6 +103,43 @@ export function claudeConfigDir(env: NodeJS.ProcessEnv = process.env): string { return explicit ? explicit : join(homeDir(env), ".claude"); } +export interface RegisteredClaudeConfigDir { + dir: string; + source: "default" | "extra"; +} + +/** Read-only status work is bounded: at most this many extra homes are reported. */ +export const MAX_EXTRA_CLAUDE_CONFIG_DIRS = 16; + +/** + * The default Claude home followed by the extra homes the operator listed in + * `claudeCode.extraConfigDirs`. Nothing is discovered on disk: an unregistered home never + * appears. A leading `~` expands against the same home `claudeConfigDir` uses; entries that are + * still relative after that are skipped, and duplicates (including the default) collapse. + */ +export function registeredClaudeConfigDirs( + config: Pick, + env: NodeJS.ProcessEnv = process.env, +): RegisteredClaudeConfigDir[] { + const homes: RegisteredClaudeConfigDir[] = [{ dir: resolve(claudeConfigDir(env)), source: "default" }]; + const seen = new Set(homes.map(home => home.dir)); + const extras = config.claudeCode?.extraConfigDirs; + if (!Array.isArray(extras)) return homes; + for (const entry of extras) { + if (homes.length > MAX_EXTRA_CLAUDE_CONFIG_DIRS) break; + if (typeof entry !== "string") continue; + const trimmed = entry.trim(); + const expanded = trimmed === "~" ? homeDir(env) + : /^~[\\/]/.test(trimmed) ? join(homeDir(env), trimmed.slice(2)) : trimmed; + if (!expanded || !isAbsolute(expanded)) continue; + const dir = resolve(expanded); + if (seen.has(dir)) continue; + seen.add(dir); + homes.push({ dir, source: "extra" }); + } + return homes; +} + /** * `os.homedir()` reads the OS user database and ignores a reassigned `HOME`, which * makes an isolated-profile probe silently read the real user's files. Prefer the diff --git a/src/claude/connection-projection.ts b/src/claude/connection-projection.ts new file mode 100644 index 00000000000..1d23955dc93 --- /dev/null +++ b/src/claude/connection-projection.ts @@ -0,0 +1,135 @@ +/** + * Read-only Claude rows of the Connections view (catch-up 010, G-001/G-002). + * + * One Claude Code row per registered home (the default `claudeConfigDir` plus the explicit + * `claudeCode.extraConfigDirs`; nothing is discovered on disk) and one Claude Desktop row. The + * first-party switch acts on the default home only, so only that row carries an intent, drift + * and a switch-off preview; extra homes report what their settings.json routes to. + */ +import { join } from "node:path"; +import { claudeDesktopIntegrationEnabled } from "../codex/desired-state"; +import type { ConnectionDriftReason, ConnectionObserved, ConnectionOwner, ConnectionView } from "../integrations/connection-view"; +import { displayPath } from "../lib/display-path"; +import type { OcxConfig } from "../types"; +import { registeredClaudeConfigDirs } from "./auth-detect"; +import { inspectDesktop3pConfigLibrary } from "./desktop-3p"; +import { inspectDesktopFirstParty, observeClaudeDesktopMode, resolveClaudeDesktopMode } from "./desktop-first-party"; +import { previewClaudeFirstPartySettings } from "./first-party-preview"; +import { firstPartyDesired, firstPartyProxyStatus } from "./first-party-settings"; +import { claudeInterceptEnabled } from "./intercept/runtime"; +import { claudeSettingsFileState } from "./intercept/settings"; + +export interface ClaudeConnectionInput { + live: OcxConfig; + /** The persisted config the first-party switch transitions (for the switch-off preview). */ + persisted: OcxConfig; + /** The intercept listener this process has bound, or null. */ + boundProxyPort: number | null; + env?: NodeJS.ProcessEnv; + opencodexConfigDir?: string; +} + +function claudeCodeRow(input: ClaudeConnectionInput, dir: string, source: "default" | "extra", ordinal?: number): ConnectionView { + const { live } = input; + const options = { claudeConfigDir: dir, ...(input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}) }; + const settingsPath = join(dir, "settings.json"); + const fileState = claudeSettingsFileState(dir); + if (fileState === "unsafe") { + // A FIFO, device or oversized file is not read at all; its state is unknown. + return { + client: "claude-code", home: displayPath(dir), homeSource: source, ...(ordinal ? { homeOrdinal: ordinal } : {}), + configPath: displayPath(settingsPath), desired: source === "extra" ? "unset" : live.claudeCode?.cliFirstParty === true ? "proxy" : "native", + observed: "unknown", owner: "unknown", driftReasons: [], + }; + } + const settings = inspectDesktopFirstParty(live, options).settings; + const observed: ConnectionObserved = settings.kind === "unreadable" ? "unknown" + : settings.kind === "foreign" ? "foreign" + : settings.kind === "applied" || settings.kind === "stale" ? "proxy" + : fileState === "regular" ? "native" : "missing"; + const owner: ConnectionOwner = observed === "foreign" ? "external" + : observed === "proxy" ? "opencodex" : observed === "unknown" ? "unknown" : "none"; + const base = { + client: "claude-code" as const, + home: displayPath(dir), + homeSource: source, + ...(ordinal ? { homeOrdinal: ordinal } : {}), + configPath: displayPath(settingsPath), + observed, + owner, + ...(owner === "external" ? { ownerPath: displayPath(settingsPath) } : {}), + }; + if (source === "extra") return { ...base, desired: "unset", driftReasons: [] }; + + const cli = live.claudeCode?.cliFirstParty === true; + const wanted = firstPartyDesired(live, observeClaudeDesktopMode(live, options)); + const eligible = claudeInterceptEnabled(live); + const status = firstPartyProxyStatus({ settings, boundProxyPort: input.boundProxyPort, eligible }); + const driftReasons: ConnectionDriftReason[] = []; + if (owner === "external") driftReasons.push("external_owner"); + if (cli && !eligible) driftReasons.push("intercept_disabled"); + if ((cli || wanted.desktop) && (status === "stopped" || status === "broken")) driftReasons.push("pending_restart"); + if (owner !== "external" && ((cli && (observed === "native" || observed === "missing")) + || (!wanted.cli && !wanted.desktop && observed === "proxy"))) driftReasons.push("file_edited"); + + const view: ConnectionView = { ...base, desired: cli ? "proxy" : "native", driftReasons }; + if (cli) { + const preview = previewClaudeFirstPartySettings({ live, persisted: input.persisted, enabled: false, options }); + view.restorePreview = preview.ok + ? { outcome: "restore", changes: preview.changes } + : { outcome: preview.reason, changes: [] }; + } + return view; +} + +function claudeDesktopRow(input: ClaudeConnectionInput): ConnectionView { + const { live } = input; + const options = input.opencodexConfigDir ? { opencodexConfigDir: input.opencodexConfigDir } : {}; + const wanted = claudeDesktopIntegrationEnabled(live); + const observation = observeClaudeDesktopMode(live, options); + const mode = resolveClaudeDesktopMode(live, observation); + const library = inspectDesktop3pConfigLibrary({ appliedFingerprint: live.claudeCode?.desktopProfile?.appliedFingerprint ?? null }); + let observed: ConnectionObserved; + switch (library.kind) { + case "not_installed": observed = "missing"; break; + case "gateway_ours": case "gateway_drifted": observed = "proxy"; break; + case "foreign": observed = "foreign"; break; + case "broken": case "unsafe": observed = "unknown"; break; + case "standard": case "no_owned_state": { + const settings = mode === "first-party" ? inspectDesktopFirstParty(live, options).settings : null; + observed = settings && (settings.kind === "applied" || settings.kind === "stale") ? "proxy" : "native"; + break; + } + default: { + const exhaustive: never = library.kind; + throw new Error(`unhandled Claude Desktop library kind: ${String(exhaustive)}`); + } + } + const owner: ConnectionOwner = observed === "foreign" ? "external" + : observed === "proxy" ? "opencodex" : observed === "unknown" ? "unknown" : "none"; + const driftReasons: ConnectionDriftReason[] = []; + if (owner === "external") driftReasons.push("external_owner"); + const pinned = live.claudeCode?.desktopMode; + if ((pinned === "first-party" && observation.ownedGatewaySelected) + || (pinned === "gateway" && observation.ownedFirstPartySettings)) driftReasons.push("account_mode"); + if (library.kind === "gateway_drifted" || library.kind === "broken" + || (wanted && observed === "native")) driftReasons.push("file_edited"); + return { + client: "claude-desktop", + configPath: displayPath(library.libraryPath), + desired: wanted ? "proxy" : "native", + observed, + owner, + ...(owner === "external" ? { ownerPath: displayPath(library.libraryPath) } : {}), + driftReasons, + }; +} + +export function projectClaudeConnections(input: ClaudeConnectionInput): ConnectionView[] { + const homes = registeredClaudeConfigDirs(input.live, input.env); + let extra = 0; + return [ + ...homes.map(home => claudeCodeRow(input, home.dir, home.source, home.source === "extra" ? ++extra : undefined)), + claudeDesktopRow(input), + ]; +} diff --git a/src/claude/first-party-preview.ts b/src/claude/first-party-preview.ts new file mode 100644 index 00000000000..607d242f8a3 --- /dev/null +++ b/src/claude/first-party-preview.ts @@ -0,0 +1,139 @@ +/** + * Dry run of the Claude Code CLI first-party switch (catch-up 010, G-002). + * + * `PUT /api/claude-code { cliFirstParty }` rewrites the env block of the default Claude home's + * settings.json. This module answers which keys that switch would add, update or remove, with the + * same inputs the switch uses: the persisted-config transition (`claudeFirstPartyTransition`), + * the live config the route reconciles with, and the same settings inspection. It reports key + * names and change kinds only, never a value, and it never writes, mints a proxy token or + * creates the local CA: the token is read if it exists, and a missing one only means the apply + * would write a new HTTPS_PROXY value. + * + * Read-only predictions stop where the switch does runtime work: starting the intercept, + * creating secrets and dropping the NO_PROXY receipt can still refuse at apply time. + * `applyChecks` names those steps so a caller does not present the preview as a guarantee. + */ +import { join } from "node:path"; +import { getConfigDir } from "../config/paths"; +import type { OcxConfig } from "../types"; +import { claudeConfigDir } from "./auth-detect"; +import { inspectDesktopFirstParty, observeClaudeDesktopMode, type DesktopFirstPartyOptions } from "./desktop-first-party"; +import { firstPartyDesired } from "./first-party-settings"; +import { claudeFirstPartyTransition } from "./first-party-transition"; +import { claudeInterceptCaCertPath } from "./intercept/local-ca"; +import { readClaudeInterceptProxyToken } from "./intercept/proxy-auth"; +import { claudeInterceptEnabled } from "./intercept/runtime"; +import { claudeInterceptProxyUrl, claudeSettingsFileState, isClaudeInterceptProxyUrl, readClaudeSettingsEnv } from "./intercept/settings"; +import { mergeClaudeInterceptNoProxy, noProxyMergeable, readNoProxyReceipt } from "./intercept/settings-no-proxy"; + +export type SettingsChangeKind = "add" | "update" | "remove"; +export interface FirstPartySettingsChange { + file: "settings.json"; + /** Dotted key inside settings.json, e.g. `env.HTTPS_PROXY`. */ + key: string; + change: SettingsChangeKind; +} + +/** Apply steps a read cannot predict; the switch can still refuse at one of them. */ +export const FIRST_PARTY_APPLY_CHECKS = ["intercept_start", "secrets", "receipt"] as const; + +export type FirstPartyPreviewRefusal = "intercept_disabled" | "foreign_env" | "unreadable"; + +export type FirstPartyPreview = + | { + ok: true; + enabled: boolean; + path: string; + changes: FirstPartySettingsChange[]; + applyChecks: readonly (typeof FIRST_PARTY_APPLY_CHECKS)[number][]; + } + | { ok: false; enabled: boolean; reason: FirstPartyPreviewRefusal; path: string }; + +export interface FirstPartyPreviewInput { + /** The server's live config: the switch reconciles with it. */ + live: OcxConfig; + /** The persisted config the switch's locked mutation transitions. */ + persisted: OcxConfig; + /** The CLI first-party value the switch would be sent. */ + enabled: boolean; + options?: DesktopFirstPartyOptions; +} + +const MANAGED_KEYS = ["HTTPS_PROXY", "NODE_EXTRA_CA_CERTS"] as const; + +function change(key: string, kind: SettingsChangeKind): FirstPartySettingsChange { + return { file: "settings.json", key: `env.${key}`, change: kind }; +} + +export function previewClaudeFirstPartySettings(input: FirstPartyPreviewInput): FirstPartyPreview { + const { live, persisted, enabled } = input; + const options = input.options ?? {}; + const dir = options.claudeConfigDir ?? claudeConfigDir(); + const path = join(dir, "settings.json"); + const refuse = (reason: FirstPartyPreviewRefusal): FirstPartyPreview => ({ ok: false, enabled, reason, path }); + const accept = (changes: FirstPartySettingsChange[]): FirstPartyPreview => ({ + ok: true, enabled, path, changes, applyChecks: enabled ? FIRST_PARTY_APPLY_CHECKS : [], + }); + // A special or oversized settings.json would block or balloon the reads below. + if (claudeSettingsFileState(dir) === "unsafe") return refuse("unreadable"); + + // The switch's own pre-checks for turning CLI first-party on, in its order. + if (enabled) { + if (!claudeInterceptEnabled(live) || !claudeInterceptEnabled(persisted)) return refuse("intercept_disabled"); + const inspected = inspectDesktopFirstParty(live, options).settings; + if (inspected.kind === "foreign") return refuse("foreign_env"); + if (inspected.kind === "unreadable") return refuse("unreadable"); + } + + // The route adopts the transitioned block into its live config and reconciles with that. + const { nextBlock } = claudeFirstPartyTransition(persisted, enabled, options); + const reconciled: OcxConfig = { ...live, claudeCode: nextBlock }; + const desired = firstPartyDesired(reconciled, observeClaudeDesktopMode(reconciled, options)); + + const read = readClaudeSettingsEnv(dir); + if (read.kind === "unreadable") return refuse("unreadable"); + const env = read.kind === "env" ? read.env : {}; + + if (!desired.desktop && !desired.cli) { + // Mirrors removeClaudeInterceptSettings: only our CA marks the block as ours. + const ownedCa = claudeInterceptCaCertPath(options.opencodexConfigDir ?? getConfigDir()); + const ca = env.NODE_EXTRA_CA_CERTS; + if (typeof ca !== "string" || ca.trim() !== ownedCa) return accept([]); + const changes = [change("NODE_EXTRA_CA_CERTS", "remove")]; + if (isClaudeInterceptProxyUrl(env.HTTPS_PROXY)) changes.push(change("HTTPS_PROXY", "remove")); + const receipt = readNoProxyReceipt(dir); + if (receipt && env.NO_PROXY === receipt.written) { + const restored = receipt.hadKey ? receipt.previous : undefined; + if (restored === undefined) changes.push(change("NO_PROXY", "remove")); + else if (restored !== env.NO_PROXY) changes.push(change("NO_PROXY", "update")); + } + return accept(changes); + } + + // A wanted env with the intercept ineligible is left exactly as it is. + if (!claudeInterceptEnabled(reconciled)) return accept([]); + + // Mirrors applyClaudeInterceptSettings against the env the apply would write. + const inspection = inspectDesktopFirstParty(reconciled, options); + const state = inspection.settings; + if (state.kind === "unreadable") return refuse("unreadable"); + if (state.kind === "foreign") return refuse("foreign_env"); + if (state.kind === "applied") return accept([]); + if (!noProxyMergeable(env.NO_PROXY)) return refuse("foreign_env"); + // The expected HTTPS_PROXY carries the stored token; without one the apply mints a new token, + // so any existing value is replaced. The token is read, never created. + const token = readClaudeInterceptProxyToken(options.opencodexConfigDir ?? getConfigDir()); + const expected: Record<(typeof MANAGED_KEYS)[number], string | null> = { + HTTPS_PROXY: token === null ? null : claudeInterceptProxyUrl(inspection.proxyPort, token), + NODE_EXTRA_CA_CERTS: inspection.caCertPath, + }; + const changes: FirstPartySettingsChange[] = []; + for (const key of MANAGED_KEYS) { + const current = env[key]; + if (current === undefined) { changes.push(change(key, "add")); continue; } + if (current !== expected[key]) changes.push(change(key, "update")); + } + const noProxy = mergeClaudeInterceptNoProxy(env.NO_PROXY); + if (noProxy !== null) changes.push(change("NO_PROXY", Object.hasOwn(env, "NO_PROXY") ? "update" : "add")); + return accept(changes); +} diff --git a/src/claude/first-party-transition.ts b/src/claude/first-party-transition.ts new file mode 100644 index 00000000000..d7b2a050d5e --- /dev/null +++ b/src/claude/first-party-transition.ts @@ -0,0 +1,51 @@ +import type { OcxConfig } from "../types"; +import { + observeClaudeDesktopMode, + resolveClaudeDesktopMode, + type DesktopFirstPartyOptions, +} from "./desktop-first-party"; + +export interface ClaudeFirstPartyTransition { + /** The whole `claudeCode` block the switch writes. */ + nextBlock: NonNullable; + /** The stored CLI flag before the switch, for a conditional rollback. */ + previous: { present: boolean; value: boolean }; + /** The Desktop mode pinned by this switch when none was stored. */ + pinnedMode: "first-party" | "gateway" | undefined; + /** An opt-out that keeps a shared env whose owner it cannot tell apart. */ + retainedAmbiguous: boolean; +} + +/** + * The persisted-config transition of `PUT /api/claude-code { cliFirstParty }`. + * + * One function so the switch and its preview cannot disagree about what the switch does: the + * route runs it inside the locked persisted mutation, and the first-party preview runs it on + * the same persisted snapshot before reconciling nothing. It reads Desktop evidence through + * `observeClaudeDesktopMode` and never writes. + */ +export function claudeFirstPartyTransition( + persisted: OcxConfig, + requested: boolean, + options: DesktopFirstPartyOptions = {}, +): ClaudeFirstPartyTransition { + const before = structuredClone(persisted); + const previous = { present: Object.hasOwn(persisted.claudeCode ?? {}, "cliFirstParty"), + value: persisted.claudeCode?.cliFirstParty === true }; + // Pin the mode Desktop resolves to *after* this mutation: while cliFirstParty is set the + // shared env is suppressed as Desktop evidence, so an opt-out observed with the flag still + // on would pin gateway and disconnect a Desktop install that predates the marker. + const observedBefore = structuredClone(before); + if (!requested) delete observedBefore.claudeCode?.cliFirstParty; + const pinnedMode = persisted.claudeCode?.desktopMode === undefined + ? resolveClaudeDesktopMode(before, observeClaudeDesktopMode(observedBefore, options)) : undefined; + const nextBlock = { ...(persisted.claudeCode ?? {}) }; + if (requested) nextBlock.cliFirstParty = true; + else delete nextBlock.cliFirstParty; + if (pinnedMode) nextBlock.desktopMode = pinnedMode; + // An opt-out that pins first-party from the shared env cannot tell whether that env was + // Desktop's or a hand-configured CLI-only one; the env is retained (Desktop keeps its + // route) and the caller is warned so it can pin gateway explicitly to release it. + const retainedAmbiguous = !requested && previous.value && pinnedMode === "first-party"; + return { nextBlock, previous, pinnedMode, retainedAmbiguous }; +} diff --git a/src/claude/intercept/settings.ts b/src/claude/intercept/settings.ts index bb4371bcf3c..0b44b6e091d 100644 --- a/src/claude/intercept/settings.ts +++ b/src/claude/intercept/settings.ts @@ -1,4 +1,4 @@ -import { mkdirSync, readFileSync } from "node:fs"; +import { mkdirSync, readFileSync, statSync } from "node:fs"; import { dirname, join } from "node:path"; import { atomicWriteFile } from "../../config/atomic-write"; import { assertNotRealClaudeConfigUnderTest } from "../../lib/test-home-guard"; @@ -95,6 +95,35 @@ function envRecord(doc: SettingsDoc): Record { return doc.env && typeof doc.env === "object" && !Array.isArray(doc.env) ? doc.env : {}; } +export type ClaudeSettingsEnvRead = + | { kind: "missing" } + | { kind: "unreadable" } + | { kind: "env"; env: Readonly> }; + +const MAX_STATUS_SETTINGS_BYTES = 1024 * 1024; + +/** + * Read-only status guard for a settings.json a status GET is about to read: `unsafe` for a + * FIFO, device, directory or oversized file, which the synchronous read would block on or + * buffer without bound. `stat` follows a symlink, as Claude Code does, and never opens the file. + */ +export function claudeSettingsFileState(configDir = claudeConfigDir()): "missing" | "regular" | "unsafe" { + try { + const stats = statSync(settingsPath(configDir)); + return stats.isFile() && stats.size <= MAX_STATUS_SETTINGS_BYTES ? "regular" : "unsafe"; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + return code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unsafe"; + } +} + +/** Read-only: the settings.json env block the writers below start from. Never writes. */ +export function readClaudeSettingsEnv(configDir = claudeConfigDir()): ClaudeSettingsEnvRead { + const read = readSettings(settingsPath(configDir)); + if ("error" in read) return { kind: read.error }; + return { kind: "env", env: { ...envRecord(read.doc) } }; +} + /** Loopback proxy URLs are the only shape opencodex ever writes. */ export function isClaudeInterceptProxyUrl(value: unknown): value is string { return typeof value === "string" && /^http:\/\/(?:opencodex:[^@/]+@)?127\.0\.0\.1:\d{1,5}\/?$/.test(value.trim()); diff --git a/src/codex/connection-projection.ts b/src/codex/connection-projection.ts new file mode 100644 index 00000000000..6444ef57609 --- /dev/null +++ b/src/codex/connection-projection.ts @@ -0,0 +1,102 @@ +/** + * Read-only Codex row of the Connections view (catch-up 010, G-001). + * + * Reads the same evidence the toggle and restore act on: the durable intent + * (`codexIntegrationEnabled`), the routing classifier over a bounded read of config.toml, the + * Codex-home journal binding, the recorded service state (file reads only; the service-manager + * probe spawns processes and stays on the write paths), the external-provider rule, the hub + * gate and the sibling mark. Nothing here writes, locks, or deletes recovery evidence. + */ +import { join } from "node:path"; +import type { OcxConfig } from "../types"; +import type { ConnectionDriftReason, ConnectionObserved, ConnectionOwner, ConnectionView } from "../integrations/connection-view"; +import { inspectRecordedServiceOwnership, type OwnershipDeps } from "../integrations/native/ownership-preflight"; +import { displayPath } from "../lib/display-path"; +import { CODEX_HOME_JOURNAL_FILE, inspectCodexHomeOwner } from "./codex-home-owner"; +import { codexIntegrationEnabled, localClientSkipReason } from "./desired-state"; +import { readBoundedCodexConfig } from "./inject/bounded-config-reader"; +import { externalCodexModelProvider } from "./inject/config-toml"; +import { classifyCodexRouting } from "./inject/routing-classify"; +import { CODEX_CONFIG_PATH, getCodexHome } from "./paths"; +import { isApprovedCodexProviderUrl } from "./provider-routing"; +import { previewCodexNativeRestore, type CodexRestorePreviewDeps } from "./restore-preview"; +import { siblingOfLivePort } from "./sibling-start"; + +export interface CodexConnectionDeps { + ownership?: OwnershipDeps; + restore?: CodexRestorePreviewDeps; +} + +function approvedUrl(id: string, url: string): boolean { + // Invalid consent evidence is no consent: the URL is then not ours. + try { return isApprovedCodexProviderUrl(id, url); } catch { return false; } +} + +export function projectCodexConnection( + config: Pick, + deps: CodexConnectionDeps = {}, +): ConnectionView { + const child = config.runtimeRole === "client"; + const wanted = codexIntegrationEnabled(config); + const desired = wanted ? (child ? "remote-home" : "proxy") : "native"; + + let content: string | null = null; + let observed: ConnectionObserved; + try { + content = readBoundedCodexConfig(CODEX_CONFIG_PATH); + if (content === null) observed = "missing"; + else { + const kind = classifyCodexRouting(content, approvedUrl); + observed = kind === "opencodex-local" ? (child ? "remote-home" : "proxy") + : kind === "native" ? "native" + : kind === "unknown" ? "unknown" : "foreign"; + } + } catch { + observed = "unknown"; + } + + const home = getCodexHome(); + const homeOwner = inspectCodexHomeOwner(home); + const recorded = homeOwner.kind === "foreign" ? null : inspectRecordedServiceOwnership(deps.ownership); + let owner: ConnectionOwner; + let ownerPath: string | undefined; + if (homeOwner.kind === "foreign") { + owner = "external"; + ownerPath = join(home, CODEX_HOME_JOURNAL_FILE); + } else if (recorded?.ownership === "foreign") { + owner = "external"; + ownerPath = recorded.path; + } else if (content !== null && externalCodexModelProvider(content)) { + owner = "external"; + ownerPath = CODEX_CONFIG_PATH; + } else if (siblingOfLivePort() !== null) { + owner = "external"; + } else if (wanted && localClientSkipReason(config) === "hub-gated") { + owner = "hub"; + } else if (homeOwner.kind === "unknown" || recorded?.ownership === "unknown") { + owner = "unknown"; + } else { + owner = observed === "proxy" || observed === "remote-home" ? "opencodex" : "none"; + } + + const driftReasons: ConnectionDriftReason[] = []; + if (owner === "external") driftReasons.push("external_owner"); + if (owner === "hub") driftReasons.push("hub_gated"); + const routed = observed === "proxy" || observed === "remote-home"; + if (owner !== "external" && owner !== "hub" + && ((wanted && observed === "native") || (!wanted && routed))) { + driftReasons.push("file_edited"); + } + + const preview = previewCodexNativeRestore(deps.restore); + return { + client: "codex", + configPath: displayPath(CODEX_CONFIG_PATH), + desired, + observed, + owner, + ...(ownerPath ? { ownerPath: displayPath(ownerPath) } : {}), + driftReasons, + restorePreview: { outcome: preview.outcome, changes: preview.changes }, + }; +} diff --git a/src/codex/inject/remove.ts b/src/codex/inject/remove.ts index 6dcc40f1232..c39cea281de 100644 --- a/src/codex/inject/remove.ts +++ b/src/codex/inject/remove.ts @@ -234,36 +234,7 @@ export function removeCodexConfig( // The unchanged fast path compares in LF space so an untouched file is never rewritten. const eol = dominantEol(rawContent); const content = applyEol(rawContent, "\n"); - // Read the recorded injection once: the strip below consumes it, and so does the - // ownership verdict, which must agree with what was actually removed. - const journaledBaseUrls = journaledInjectedRootValues("openai_base_url"); - const journaledRealtimeWsBaseUrls = journaledInjectedRootValues(REALTIME_WS_BASE_URL_KEY); - const journaledRootWebSearch = journaledInjectedRootWebSearch(); - const journaledReplaced = journaledReplacedRootWebSearch(); - const ownedRoot = (key: string, owned: readonly string[]) => { - const value = rootTomlString(content, key); - return value !== null && owned.includes(value); - }; - const had = hasOpencodexRouting(content) - || ownedRoot("openai_base_url", journaledBaseUrls) - || ownedRoot(REALTIME_WS_BASE_URL_KEY, journaledRealtimeWsBaseUrls); - const stripped = stripOpencodexConfigResult( - content, - journaledBaseUrls, - journaledRealtimeWsBaseUrls, - journaledRootWebSearch, - journaledReplaced, - journaledInjectedSubagentDefaults(), - journaledOwnedCatalogBinding(), - ); - // Captured from the pre-strip bytes: the strip is what removes the table, so reading it - // afterwards would find nothing. - const retainedBlock = historyDisposition === "stand-down-retain" - ? extractOcxProviderTableBlock(content) - : null; - const finalContent = retainedBlock === null - ? stripped.content - : appendOcxProviderTableBlock(stripped.content, retainedBlock); + const { had, stripped, retainedBlock, finalContent } = planCodexConfigRemoval(content, historyDisposition); if (had || finalContent !== content) { publishCodexConfigIfUnchanged(held, "remove", rawContent, applyEol(finalContent, eol)); } @@ -297,3 +268,69 @@ export function removeCodexConfig( if (!locked.ok) return { success: false, retryable: locked.error === "locked", message: configWriteLockFailureMessage(locked) }; return locked.value; } + +interface CodexConfigRemovalPlan { + had: boolean; + stripped: StripOpencodexConfigResult; + retainedBlock: string | null; + finalContent: string; +} + +/** + * The removal transform for one LF-normalized config.toml text. Shared by the write path below + * and by the read-only Connections restore preview, so the preview shows what restore writes. + */ +function planCodexConfigRemoval( + content: string, + historyDisposition: RemoveCodexConfigHistoryDisposition, +): CodexConfigRemovalPlan { + // Read the recorded injection once: the strip below consumes it, and so does the + // ownership verdict, which must agree with what was actually removed. + const journaledBaseUrls = journaledInjectedRootValues("openai_base_url"); + const journaledRealtimeWsBaseUrls = journaledInjectedRootValues(REALTIME_WS_BASE_URL_KEY); + const journaledRootWebSearch = journaledInjectedRootWebSearch(); + const journaledReplaced = journaledReplacedRootWebSearch(); + const ownedRoot = (key: string, owned: readonly string[]) => { + const value = rootTomlString(content, key); + return value !== null && owned.includes(value); + }; + const had = hasOpencodexRouting(content) + || ownedRoot("openai_base_url", journaledBaseUrls) + || ownedRoot(REALTIME_WS_BASE_URL_KEY, journaledRealtimeWsBaseUrls); + const stripped = stripOpencodexConfigResult( + content, + journaledBaseUrls, + journaledRealtimeWsBaseUrls, + journaledRootWebSearch, + journaledReplaced, + journaledInjectedSubagentDefaults(), + journaledOwnedCatalogBinding(), + ); + // Captured from the pre-strip bytes: the strip is what removes the table, so reading it + // afterwards would find nothing. + const retainedBlock = historyDisposition === "stand-down-retain" + ? extractOcxProviderTableBlock(content) + : null; + const finalContent = retainedBlock === null + ? stripped.content + : appendOcxProviderTableBlock(stripped.content, retainedBlock); + return { had, stripped, retainedBlock, finalContent }; +} + +/** + * Read-only: the config.toml text `removeCodexConfig` would publish for `rawContent`, or the + * managed-defaults error that makes it fail. No lock, no write. + */ +export function previewRemovedCodexConfig( + rawContent: string, + historyDisposition: RemoveCodexConfigHistoryDisposition, +): { content: string; managedDefaultsError: string | null } { + const eol = dominantEol(rawContent); + const content = applyEol(rawContent, "\n"); + const plan = planCodexConfigRemoval(content, historyDisposition); + const published = plan.had || plan.finalContent !== content; + return { + content: published ? applyEol(plan.finalContent, eol) : rawContent, + managedDefaultsError: plan.stripped.managedDefaultsError, + }; +} diff --git a/src/codex/journal.ts b/src/codex/journal.ts index 58664ecede7..b2f5e9ab500 100644 --- a/src/codex/journal.ts +++ b/src/codex/journal.ts @@ -171,6 +171,49 @@ export function hasUnverifiedJournalBaseline(config: string | null, profile: str return journal !== null && compareJournalState(journal, config, profile).unverified; } +/** What a plain native restore's journal step would do to config.toml and the profile. */ +export type JournalRestorePreview = + | { kind: "none" } + | { kind: "unverified" } + | { kind: "profile-symlink" } + | { + kind: "planned"; + /** Bytes the journal replay writes to config.toml, or null when it writes none. */ + configWrite: string | null; + configRestored: boolean; + profileRestored: boolean; + profileChanged: boolean; + /** Profile after the step: bytes, null for removed, undefined for untouched. */ + profileAfter: string | null | undefined; + }; + +/** + * Read-only twin of {@link restoreJournalState} for the plain restore path (no field-level + * recovery, no client disconnect recovery): the same journal read and the same comparison, + * and no lock, write or journal cleanup. Used by the Connections restore preview. + */ +export function previewJournalRestore(currentConfig: string | null, currentProfile: string | null): JournalRestorePreview { + const journal = readJournal(false); + if (!journal) return { kind: "none" }; + const comparison = compareJournalState(journal, currentConfig, currentProfile); + if (comparison.unverified) return { kind: "unverified" }; + const { configUnchanged, profileUnchanged } = comparison; + if (profileUnchanged && (!comparison.profileAlreadyOriginal || comparison.originalProfile === null)) { + try { if (lstatSync(CODEX_PROFILE_PATH).isSymbolicLink()) return { kind: "profile-symlink" }; } + catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") return { kind: "profile-symlink" }; } + } + const replay = configUnchanged && !comparison.configAlreadyOriginal; + const profileReplay = profileUnchanged && !comparison.profileAlreadyOriginal; + return { + kind: "planned", + configWrite: replay && comparison.originalConfig !== currentConfig ? comparison.originalConfig : null, + configRestored: comparison.configAlreadyOriginal || configUnchanged, + profileRestored: comparison.profileAlreadyOriginal || profileUnchanged, + profileChanged: !profileUnchanged, + profileAfter: profileReplay ? comparison.originalProfile : undefined, + }; +} + export interface WriteJournalOptions { /** * The caller's verdict on the config it is about to transform: false when diff --git a/src/codex/provider-routing.ts b/src/codex/provider-routing.ts index c6b171ce3b5..ad158a3bbea 100644 --- a/src/codex/provider-routing.ts +++ b/src/codex/provider-routing.ts @@ -158,17 +158,31 @@ export function restoreApprovedCodexProviders(revokeId?: string): boolean { if (revokeId !== undefined && !ids.includes(revokeId)) throw new Error("Provider has no routing consent to revoke."); if (!ids.length) return false; return inWriteSection((held, content, record) => { - let next = content; - for (const id of revokeId === undefined ? Object.keys(record.providers) : [revokeId]) { - const saved = record.providers[id]!; - const parsed = Bun.TOML.parse(next) as Record; - const table = (parsed.model_providers as Record> | undefined)?.[id]; - if (!table || !saved.managedUrls.includes(table.base_url as string)) continue; - const field = providerUrl(next, id, false); - if (saved.managedUrls.includes(field.url)) next = field.replace(saved.original); - } + const next = restoredApprovedProviderContent(content, record, revokeId); if (next !== content) publish(CODEX_CONFIG_PATH, next, held); if (revokeId !== undefined) { delete record.providers[revokeId]; save(record, held); } return next !== content; }); } + +function restoredApprovedProviderContent(content: string, record: RoutingRecord, revokeId?: string): string { + let next = content; + for (const id of revokeId === undefined ? Object.keys(record.providers) : [revokeId]) { + const saved = record.providers[id]!; + const parsed = Bun.TOML.parse(next) as Record; + const table = (parsed.model_providers as Record> | undefined)?.[id]; + if (!table || !saved.managedUrls.includes(table.base_url as string)) continue; + const field = providerUrl(next, id, false); + if (saved.managedUrls.includes(field.url)) next = field.replace(saved.original); + } + return next; +} + +/** + * Read-only: `content` after the approved-provider URL restore a native restore finishes with. + * Throws exactly where that restore would fail (invalid or foreign recovery evidence). + */ +export function previewApprovedCodexProviderRestore(content: string): string { + const record = readRecord(); + return Object.keys(record.providers).length === 0 ? content : restoredApprovedProviderContent(content, record); +} diff --git a/src/codex/restore-preview.ts b/src/codex/restore-preview.ts new file mode 100644 index 00000000000..253d6998556 --- /dev/null +++ b/src/codex/restore-preview.ts @@ -0,0 +1,208 @@ +/** + * Read-only preview of the native Codex restore (catch-up 010, G-001). + * + * Answers "if Codex were switched back to its native path now, which config.toml keys would + * change, and would the restore refuse first?" by walking `restoreNativeCodexAsync` in its own + * order with the read-only halves of the same decisions: the home owner check, the external + * provider courtesy, the recorded service ownership, the history disposition, the journal + * comparison (`previewJournalRestore`), the removal transform (`previewRemovedCodexConfig`), + * the provider-table retention and the approved-provider URL restore + * (`previewApprovedCodexProviderRestore`). It takes no lock and writes nothing. Values never + * leave this module: a change is a file, a key and add/update/remove. + * + * The catalog rows and conversation-history relabel a restore also performs are not config + * keys and are not listed. + */ +import { lstatSync } from "node:fs"; +import { basename } from "node:path"; +import { inspectRecordedServiceOwnership, type OwnershipDeps } from "../integrations/native/ownership-preflight"; +import { codexHomeIsAbsent, inspectCodexHomeOwner } from "./codex-home-owner"; +import { readBoundedCodexConfig } from "./inject/bounded-config-reader"; +import { applyEol, externalCodexModelProvider } from "./inject/config-toml"; +import { appendOcxProviderTableBlock, extractOcxProviderTableBlock } from "./inject/provider-table"; +import { previewRemovedCodexConfig } from "./inject/remove"; +import { resolveRestoreHistoryDisposition } from "./inject/restore"; +import { previewJournalRestore } from "./journal"; +import { CODEX_CONFIG_PATH, CODEX_PROFILE_PATH, getCodexHome } from "./paths"; +import { parseTomlDocument } from "./project-config-warnings"; +import { previewApprovedCodexProviderRestore } from "./provider-routing"; +import { siblingOfLivePort } from "./sibling-start"; + +export type CodexRestoreOutcome = + /** The restore would run; `changes` lists what it rewrites (possibly nothing). */ + | "restore" + | "skipped_sibling" + | "refused_owner" + | "refused_history" + | "refused_journal" + | "refused_profile" + | "refused_managed_defaults" + /** Config would be restored, then the approved-provider URL restore fails on its evidence. */ + | "provider_evidence_invalid" + | "unreadable"; + +export interface CodexRestoreChange { + file: "config.toml" | "opencodex.config.toml"; + /** Root key, `section.key`, or `*` for the whole file. */ + key: string; + change: "add" | "update" | "remove"; +} + +export interface CodexRestorePreview { + outcome: CodexRestoreOutcome; + changes: CodexRestoreChange[]; + /** Kept `[model_providers.opencodex]` because tagged conversations still need it. */ + providerTableRetained: boolean; +} + +export interface CodexRestorePreviewDeps { + ownership?: OwnershipDeps; + historyDisposition?: () => ReturnType; +} + +/** Bounded like config.toml: a special or oversized profile throws instead of blocking. */ +function readProfile(): string | null { + return readBoundedCodexConfig(CODEX_PROFILE_PATH); +} + +function flatten(content: string | null): Map { + const keys = new Map(); + if (content === null) return keys; + const { root, sections } = parseTomlDocument(applyEol(content, "\n")); + for (const [key, value] of Object.entries(root)) keys.set(key, value); + for (const [section, entries] of sections) { + for (const [key, value] of Object.entries(entries)) keys.set(`${section}.${key}`, value); + } + return keys; +} + +/** Root keys OpenCodex writes or restores; any other root key is shown as `…`. */ +const SHOWN_ROOT_KEYS = new Set([ + "model_provider", "model", "openai_base_url", "experimental_realtime_ws_base_url", "chatgpt_base_url", + "model_catalog_json", "web_search", "profile", "model_reasoning_effort", +]); +/** Codex's own top-level tables. A user-named table is shown as `…`. */ +const SHOWN_TABLES = new Set([ + "model_providers", "profiles", "projects", "hooks", "plugins", "agents", "mcp_servers", "features", + "tools", "tui", "notice", "sandbox_workspace_write", "shell_environment_policy", "history", "otel", +]); +/** Table ids OpenCodex owns; every other id (a provider, profile, project or server name) is masked. */ +const SHOWN_TABLE_IDS = new Set(["opencodex", "openai", "state"]); +/** Leaf keys of Codex's fixed vocabulary inside any table. */ +const SHOWN_LEAF_KEYS = new Set([ + "base_url", "name", "wire_api", "env_key", "requires_openai_auth", "query_params", "http_headers", + "trust_level", "enabled", "trusted_hash", "model", "model_provider", "model_reasoning_effort", + "default_subagent_model", "default_subagent_reasoning_effort", "stream_idle_timeout_ms", + "request_max_retries", "stream_max_retries", "supports_websockets", +]); + +/** + * A config key as a response may show it. Allowlist only: OpenCodex-managed root keys, Codex's + * own table names, the table ids OpenCodex owns and Codex's fixed leaf vocabulary are shown; + * every other segment — a provider, profile, project, hook or server name, which can be a user + * name, an email or a secret of any length — becomes `…`. + */ +export function displayCodexConfigKey(key: string): string { + const segments = key.match(/"(?:[^"\\]|\\.)*"|'[^']*'|[^.]+/g) ?? [key]; + if (segments.length === 1) return SHOWN_ROOT_KEYS.has(segments[0]!) ? segments[0]! : "…"; + const last = segments.length - 1; + return segments.map((segment, index) => { + if (index === 0) return SHOWN_TABLES.has(segment) ? segment : "…"; + if (index === last) return SHOWN_LEAF_KEYS.has(segment) ? segment : "…"; + return SHOWN_TABLE_IDS.has(segment) ? segment : "…"; + }).join("."); +} + +function profileIsSymlink(): boolean { + try { return lstatSync(CODEX_PROFILE_PATH).isSymbolicLink(); } + catch (error) { return (error as NodeJS.ErrnoException).code !== "ENOENT"; } +} + +/** Key-level difference between two config.toml texts; values are compared, never returned. */ +export function codexConfigKeyChanges(before: string | null, after: string | null): CodexRestoreChange[] { + const a = flatten(before); + const b = flatten(after); + const changes: CodexRestoreChange[] = []; + for (const [key, value] of a) { + if (!b.has(key)) changes.push({ file: "config.toml", key, change: "remove" }); + else if (b.get(key) !== value) changes.push({ file: "config.toml", key, change: "update" }); + } + for (const key of b.keys()) if (!a.has(key)) changes.push({ file: "config.toml", key, change: "add" }); + return changes + .map(change => ({ ...change, key: displayCodexConfigKey(change.key) })) + .sort((x, y) => x.key.localeCompare(y.key) || x.change.localeCompare(y.change)); +} + +function profileChange(before: string | null, after: string | null): CodexRestoreChange[] { + if (before === after) return []; + const file = basename(CODEX_PROFILE_PATH) as CodexRestoreChange["file"]; + const change = before === null ? "add" : after === null ? "remove" : "update"; + return [{ file, key: "*", change }]; +} + +export function previewCodexNativeRestore(deps: CodexRestorePreviewDeps = {}): CodexRestorePreview { + const none = (outcome: CodexRestoreOutcome): CodexRestorePreview => ({ outcome, changes: [], providerTableRetained: false }); + const home = getCodexHome(); + if (codexHomeIsAbsent(home)) return none("restore"); + if (siblingOfLivePort() !== null) return none("skipped_sibling"); + const owner = inspectCodexHomeOwner(home); + if (owner.kind === "foreign" || owner.kind === "unknown") return none("refused_owner"); + + let config: string | null; + let profile: string | null; + try { + config = readBoundedCodexConfig(CODEX_CONFIG_PATH); + profile = readProfile(); + } catch { return none("unreadable"); } + const finish = (afterConfig: string | null, afterProfile: string | null, retained: boolean): CodexRestorePreview => { + let restored = afterConfig; + let outcome: CodexRestoreOutcome = "restore"; + if (afterConfig !== null) { + try { restored = previewApprovedCodexProviderRestore(afterConfig); } + catch { outcome = "provider_evidence_invalid"; } + } + return { + outcome, + changes: [...codexConfigKeyChanges(config, restored), ...profileChange(profile, afterProfile)], + providerTableRetained: retained, + }; + }; + + // External-provider courtesy: config.toml is the other provider's; only approved URLs revert. + if (config !== null && externalCodexModelProvider(config)) return finish(config, profile, false); + if (inspectRecordedServiceOwnership(deps.ownership)?.ownership === "foreign") return none("refused_owner"); + const disposition = (deps.historyDisposition ?? (() => resolveRestoreHistoryDisposition(undefined)))(); + if (disposition.kind === "refuse") return none("refused_history"); + const retain = disposition.kind === "stand-down" && disposition.retainProviderTable; + const capturedBlock = retain && config !== null ? extractOcxProviderTableBlock(applyEol(config, "\n")) : null; + + const journal = previewJournalRestore(config, profile); + if (journal.kind === "unverified") return none("refused_journal"); + if (journal.kind === "profile-symlink") return none("refused_profile"); + const planned = journal.kind === "planned" ? journal : null; + let afterProfile = planned && planned.profileAfter !== undefined ? planned.profileAfter : profile; + + let afterConfig: string | null; + if (planned?.configRestored) { + afterConfig = planned.configWrite ?? config; + } else { + // removeCodexConfig: the profile goes unless the journal step restored or kept it. + const preserveProfile = planned !== null && (planned.profileRestored || planned.profileChanged); + // ...and it refuses a profile that is a symbolic link before touching config.toml. + if (!preserveProfile && profileIsSymlink()) return none("refused_profile"); + if (config === null) { + afterConfig = null; + } else { + const removed = previewRemovedCodexConfig(config, retain ? "stand-down-retain" : disposition.kind === "stand-down" ? "stand-down-remove" : "refuse-on-any"); + if (removed.managedDefaultsError) return none("refused_managed_defaults"); + afterConfig = removed.content; + } + if (!preserveProfile) afterProfile = null; + } + // The settled re-attach after a journal replay (idempotent on the strip path). + if (capturedBlock !== null && afterConfig !== null) { + try { afterConfig = appendOcxProviderTableBlock(applyEol(afterConfig, "\n"), capturedBlock); } + catch { return none("refused_history"); } + } + return finish(afterConfig, afterProfile, capturedBlock !== null); +} diff --git a/src/config/load-degrade.ts b/src/config/load-degrade.ts index 2f68d675f09..0c74aecbc9e 100644 --- a/src/config/load-degrade.ts +++ b/src/config/load-degrade.ts @@ -771,6 +771,15 @@ export function normalizePersistedClaudeCode(claudeCode: unknown): OcxConfig["cl if (Object.hasOwn(normalized, "cliFirstParty") && typeof normalized.cliFirstParty !== "boolean") { delete normalized.cliFirstParty; } + // A read-only list of extra Claude homes: keep trimmed non-empty strings, drop anything else. + if (Object.hasOwn(normalized, "extraConfigDirs")) { + const raw = normalized.extraConfigDirs; + const kept = Array.isArray(raw) + ? raw.filter((entry): entry is string => typeof entry === "string" && entry.trim().length > 0).map(entry => entry.trim()) + : []; + if (kept.length > 0) normalized.extraConfigDirs = kept; + else delete normalized.extraConfigDirs; + } if (Object.hasOwn(normalized, "subagentEffort") && !isClaudeSubagentEffort(normalized.subagentEffort)) { delete normalized.subagentEffort; } diff --git a/src/integrations/connection-view.ts b/src/integrations/connection-view.ts new file mode 100644 index 00000000000..1e584f691be --- /dev/null +++ b/src/integrations/connection-view.ts @@ -0,0 +1,53 @@ +/** + * One client connection as the Connections view reports it (catch-up 010, G-001). + * + * Read-only projection: where a client is wanted to go (`desired`), where its files point now + * (`observed`), who controls those files (`owner`) and why the two differ. Paths are display + * paths (see src/lib/display-path.ts); no value, token or email is ever carried. + */ +export type ConnectionClient = "codex" | "claude-code" | "claude-desktop"; +export type ConnectionDesired = "proxy" | "native" | "remote-home" | "unset"; +export type ConnectionObserved = "proxy" | "native" | "remote-home" | "foreign" | "missing" | "unknown"; +export type ConnectionOwner = "opencodex" | "external" | "hub" | "none" | "unknown"; + +/** + * Why observed differs (or cannot follow) desired. Every member is produced by a projection: + * - external_owner: another program, OpenCodex home or service owns the files (`ownerPath`). + * - account_mode: Claude Desktop's pinned account mode contradicts what it runs. + * - hub_gated: this machine is a hub and does not rewrite its own clients. + * - intercept_disabled: Claude first-party is wanted while the intercept cannot run. + * - file_edited: the file no longer matches the switch (edited, rewritten, or a restore remainder). + * - pending_restart: the file is right but the listener it names is stopped or another port. + */ +export const CONNECTION_DRIFT_REASONS = [ + "external_owner", "account_mode", "hub_gated", "intercept_disabled", "file_edited", "pending_restart", +] as const; +export type ConnectionDriftReason = (typeof CONNECTION_DRIFT_REASONS)[number]; + +export interface ConnectionKeyChange { + file: string; + key: string; + change: "add" | "update" | "remove"; +} + +export interface ConnectionRestorePreview { + /** `restore` when the switch-off would run; otherwise the refusal or skip it would hit. */ + outcome: string; + changes: ConnectionKeyChange[]; +} + +export interface ConnectionView { + client: ConnectionClient; + /** Claude Code only: the config dir this row describes. */ + home?: string; + homeSource?: "default" | "extra"; + /** Extra homes only: 1-based position in `claudeCode.extraConfigDirs`, since the path is masked. */ + homeOrdinal?: number; + configPath: string; + desired: ConnectionDesired; + observed: ConnectionObserved; + owner: ConnectionOwner; + ownerPath?: string; + driftReasons: ConnectionDriftReason[]; + restorePreview?: ConnectionRestorePreview; +} diff --git a/src/integrations/native/ownership-preflight.ts b/src/integrations/native/ownership-preflight.ts index 065870127d2..3867a4d1708 100644 --- a/src/integrations/native/ownership-preflight.ts +++ b/src/integrations/native/ownership-preflight.ts @@ -125,54 +125,86 @@ export interface OwnershipDeps extends ProbeDeps { readonly realpathSync?: (path: string) => string; } -export function inspectNativeCodexOwnership(deps: OwnershipDeps = {}): OwnershipInspection { +/** The verdict the recorded service state alone decides, with the state file it came from. */ +export interface RecordedServiceOwnership extends OwnershipInspection { + readonly ownership: "foreign" | "unknown"; + /** The service state file that decided the verdict, when one file did. */ + readonly path?: string; +} + +type ValidStateEvidence = Extract; + +function recordedStateVerdict(deps: OwnershipDeps): { + verdict: RecordedServiceOwnership | null; + valid: ValidStateEvidence[]; + current: { codexHome: string; opencodexHome: string }; +} { const current = deps.currentHomes ?? currentServiceHomes(); const evidence = deps.statePaths ? inspectServiceStateEvidence(deps.statePaths) : inspectServiceStateEvidence(); + const decide = (verdict: RecordedServiceOwnership) => ({ verdict, valid: [] as ValidStateEvidence[], current }); const unreadable = evidence.find((e): e is Extract => e.kind === "unreadable"); if (unreadable) { - return { ownership: "unknown", reason: `service state at ${unreadable.path} could not be read (${unreadable.reason})` }; + return decide({ ownership: "unknown", reason: `service state at ${unreadable.path} could not be read (${unreadable.reason})`, path: unreadable.path }); } const invalid = evidence.find(e => e.kind === "invalid"); if (invalid) { - return { ownership: "unknown", reason: `service state at ${invalid.path} is malformed` }; + return decide({ ownership: "unknown", reason: `service state at ${invalid.path} is malformed`, path: invalid.path }); } - const valid = evidence.filter((e): e is Extract => e.kind === "valid"); + const valid = evidence.filter((e): e is ValidStateEvidence => e.kind === "valid"); // Mirrors that disagree with each other are not a majority vote. for (const one of valid) { for (const other of valid) { if (compareServicePathToInstall(one.state.codexHome, other.state.codexHome, deps) !== "same" || compareServicePathToInstall(one.state.opencodexHome, other.state.opencodexHome, deps) !== "same") { - return { ownership: "unknown", reason: "two service state files disagree about which homes are installed" }; + return decide({ ownership: "unknown", reason: "two service state files disagree about which homes are installed" }); } } } - const evidenceComparesDifferent = (e: Extract): boolean => + const evidenceComparesDifferent = (e: ValidStateEvidence): boolean => compareServicePathToInstall(e.state.codexHome, current.codexHome, deps) === "different" || compareServicePathToInstall(e.state.opencodexHome, current.opencodexHome, deps) === "different"; - const evidenceComparesIndeterminate = (e: Extract): boolean => + const evidenceComparesIndeterminate = (e: ValidStateEvidence): boolean => compareServicePathToInstall(e.state.codexHome, current.codexHome, deps) === "unknown" || compareServicePathToInstall(e.state.opencodexHome, current.opencodexHome, deps) === "unknown"; const foreign = valid.find(evidenceComparesDifferent); if (foreign) { - return { + return decide({ ownership: "foreign", reason: `a service is installed for CODEX_HOME=${foreign.state.codexHome} / OPENCODEX_HOME=${foreign.state.opencodexHome}`, - }; + path: foreign.path, + }); } // A resolution that could not run (EACCES, EPERM, a vanished directory, transient I/O) // proves neither same nor different — report it as unknown, never as foreign. const indeterminateEvidence = valid.find(evidenceComparesIndeterminate); if (indeterminateEvidence) { - return { + return decide({ ownership: "unknown", reason: `a recorded home in ${indeterminateEvidence.path} could not be resolved for comparison`, - }; + path: indeterminateEvidence.path, + }); } + return { verdict: null, valid, current }; +} + +/** + * The service-state half of {@link inspectNativeCodexOwnership}: file reads only, no + * service-manager probe (no `spawnSync`), so a status GET can ask it. `null` means the state + * files do not decide; the full inspection then consults the service manager. A `foreign` + * verdict here is the same verdict the full inspection returns, because it returns first. + */ +export function inspectRecordedServiceOwnership(deps: OwnershipDeps = {}): RecordedServiceOwnership | null { + return recordedStateVerdict(deps).verdict; +} + +export function inspectNativeCodexOwnership(deps: OwnershipDeps = {}): OwnershipInspection { + const { verdict, valid, current } = recordedStateVerdict(deps); + if (verdict) return { ownership: verdict.ownership, reason: verdict.reason }; // The manager assets live under the effective OPENCODEX_HOME. Production // callers do not inject ProbeDeps.configDir, so derive it from the same diff --git a/src/lib/display-path.ts b/src/lib/display-path.ts new file mode 100644 index 00000000000..cb8a638b722 --- /dev/null +++ b/src/lib/display-path.ts @@ -0,0 +1,38 @@ +import { homedir } from "node:os"; + +/** + * Path segments a management response may show as they are. Everything else is `…`. + * + * The Connections view has to name files (the acceptance asks for the owning file), but any + * segment the operator chose — a user name, an account id, a per-account directory, a token + * someone used as a folder name — can identify them. Policy: the user's home prefix becomes + * `~`, a drive letter stays, and only the fixed directory and file names OpenCodex, Codex and + * Claude use are shown; consecutive masked segments collapse into one `…`. + */ +const SHOWN_SEGMENTS = new Set([ + "~", ".claude", ".codex", ".opencodex", ".config", "opencodex", + "settings.json", "config.toml", "opencodex.config.toml", "opencodex-journal.json", "service-state.json", + "Library", "Application Support", "Claude", "Claude-3p", "configLibrary", "AppData", "Roaming", "Local", +]); + +export function displayPath(path: string, home: string = process.env.HOME?.trim() || homedir()): string { + let shown = path; + const trimmedHome = home.replace(/[\\/]+$/, ""); + if (trimmedHome && (path === trimmedHome || path.startsWith(`${trimmedHome}/`) || path.startsWith(`${trimmedHome}\\`))) { + shown = `~${path.slice(trimmedHome.length)}`; + } + const parts = shown.split(/([\\/])/); + const out: string[] = []; + for (const part of parts) { + if (part === "/" || part === "\\" || part === "") { out.push(part); continue; } + const kept = SHOWN_SEGMENTS.has(part) || /^[A-Za-z]:$/.test(part); + if (kept) { out.push(part); continue; } + // Collapse "…/…" runs: the separator before this segment follows a previous mask. + if (out.length >= 2 && out[out.length - 2] === "…" && (out[out.length - 1] === "/" || out[out.length - 1] === "\\")) { + out.pop(); + continue; + } + out.push("…"); + } + return out.join(""); +} diff --git a/src/server/management-api.ts b/src/server/management-api.ts index 2c77513135b..8490fe20b0d 100644 --- a/src/server/management-api.ts +++ b/src/server/management-api.ts @@ -250,6 +250,13 @@ async function handleTelemetryRoutesOnDemand(ctx: ManagementContext): Promise { + if (!pathInManagementNamespace(ctx.url.pathname, "/api/connections", false)) return null; + const { handleConnectionStatusRoutes } = await import("./management/connection-status-routes"); + return handleConnectionStatusRoutes(ctx); +} + export async function handleManagementAPI( req: Request, url: URL, @@ -395,6 +402,7 @@ export async function handleManagementAPI( ?? (await handleModelRoutes(ctx)) ?? (await handleIntegrationRoutes(ctx)) ?? (await handleNativeIntegrationRoutes(ctx)) + ?? (await handleConnectionStatusRoutesOnDemand(ctx)) ?? (await handleCursorIntegrationRoutes(ctx)) ?? (await handleClaudeDesktopPickerRoutes(ctx)) ?? (await handleDesktopCompatibilityRoutes(ctx)) diff --git a/src/server/management/agent-settings-routes.ts b/src/server/management/agent-settings-routes.ts index 57417b49e89..f07d6c6dc03 100644 --- a/src/server/management/agent-settings-routes.ts +++ b/src/server/management/agent-settings-routes.ts @@ -1535,6 +1535,7 @@ async function handleAgentSettingsRoutesImpl(ctx: ManagementContext): Promise { + if (ctx.url.pathname === "/api/claude-code/first-party/preview" && ctx.req.method === "GET") return previewResponse(ctx); + return null; +} + +async function previewResponse(ctx: ManagementContext): Promise { + const { req, url, config } = ctx; + const raw = url.searchParams.get("enabled"); + if (raw !== null && raw !== "true" && raw !== "false") { + return jsonResponse({ error: "enabled must be true or false", code: "invalid_enabled" }, 400, req, config); + } + const enabled = raw === null ? config.claudeCode?.cliFirstParty !== true : raw === "true"; + try { + const { previewClaudeFirstPartySettings } = await import("../../claude/first-party-preview"); + const preview = previewClaudeFirstPartySettings({ live: config, persisted: persistedConfigOr(config), enabled }); + if (!preview.ok) { + return jsonResponse({ + error: "Claude first-party switch would be refused", code: preview.reason, enabled, path: displayPath(preview.path), + }, preview.reason === "unreadable" ? 500 : 409, req, config); + } + return jsonResponse({ + enabled, path: displayPath(preview.path), changes: preview.changes, applyChecks: preview.applyChecks, + }, 200, req, config); + } catch { + // A fixed body: an error message can carry a path or a settings value. + return jsonResponse({ error: "first-party preview could not be computed", code: "preview_failed" }, 500, req, config); + } +} diff --git a/src/server/management/connection-status-routes.ts b/src/server/management/connection-status-routes.ts new file mode 100644 index 00000000000..6450a855652 --- /dev/null +++ b/src/server/management/connection-status-routes.ts @@ -0,0 +1,46 @@ +/** + * `GET /api/connections` — the read-only Connections view (catch-up 010, G-001). + * + * Lazy-loaded by namespace from management-api.ts, like the other optional surfaces, so the + * projections' imports stay off every other dashboard request. Nothing here writes: every + * projection is a read of the files the switches act on. + */ +import { readConfigDiagnostics } from "../../config/diagnostics"; +import type { OcxConfig } from "../../types"; +import { jsonResponse } from "../auth-cors"; +import type { ManagementContext } from "./context"; + +/** The persisted config a switch would transition; the live snapshot when there is no readable file. */ +export function persistedConfigOr(live: OcxConfig): OcxConfig { + try { + const latest = readConfigDiagnostics({ passive: true }); + return latest.source === "file" && !latest.error ? latest.config : live; + } catch { + return live; + } +} + +export async function handleConnectionStatusRoutes(ctx: ManagementContext): Promise { + if (ctx.url.pathname === "/api/connections" && ctx.req.method === "GET") return connectionsResponse(ctx); + return null; +} + +async function connectionsResponse(ctx: ManagementContext): Promise { + const { req, config, deps } = ctx; + try { + const [{ projectCodexConnection }, { projectClaudeConnections }, { getClaudeInterceptState }] = await Promise.all([ + import("../../codex/connection-projection"), + import("../../claude/connection-projection"), + import("../../claude/intercept/runtime"), + ]); + const bound = (deps.getClaudeInterceptState ?? getClaudeInterceptState)(); + const connections = [ + projectCodexConnection(persistedConfigOr(config)), + ...projectClaudeConnections({ live: config, persisted: persistedConfigOr(config), boundProxyPort: bound?.proxyPort ?? null }), + ]; + return jsonResponse({ connections }, 200, req, config); + } catch { + // A fixed body: an error message can carry a path or a settings value. + return jsonResponse({ error: "connection status could not be read", code: "connections_failed" }, 500, req, config); + } +} diff --git a/src/server/management/native-integration-routes.ts b/src/server/management/native-integration-routes.ts index 6dd26a34bde..a193ad87f8e 100644 --- a/src/server/management/native-integration-routes.ts +++ b/src/server/management/native-integration-routes.ts @@ -112,6 +112,8 @@ export interface NativeToggleEnvelope { reason?: string; interceptReason?: string | null; artifacts?: CodexNativeRestoreResult["artifacts"]; + /** Where the read-only Connections view explains this client's state (Codex only). */ + connections?: "/api/connections"; } export interface NativeRefusalEnvelope { @@ -454,7 +456,7 @@ async function handleCodexToggle(ctx: NativeDecisionContext): Promise const applied = await syncModelsToCodex(port); if (applied.status === "skipped") { return jsonResponse({ - ok: true, clientId: "codex", changed: durable && persisted.status === "committed", + ok: true, clientId: "codex", connections: "/api/connections", changed: durable && persisted.status === "committed", state: rememberCodexToggle(true, "absent"), desiredEnabled: enabled, message: "Codex integration is OFF; enable did not change Codex.", @@ -462,7 +464,7 @@ async function handleCodexToggle(ctx: NativeDecisionContext): Promise } satisfies NativeToggleEnvelope); } return jsonResponse({ - ok: true, clientId: "codex", changed: durable && persisted.status === "committed", + ok: true, clientId: "codex", connections: "/api/connections", changed: durable && persisted.status === "committed", state: rememberCodexToggle(true, applied.ok ? "current" : "absent"), desiredEnabled: enabled, message: applied.ok @@ -480,7 +482,7 @@ async function handleCodexToggle(ctx: NativeDecisionContext): Promise if (classifyNativeRoutedResidue().kind === "clean") { rememberCodexToggle(false, "absent"); return jsonResponse({ - ok: true, clientId: "codex", changed: false, state: "absent", desiredEnabled: false, + ok: true, clientId: "codex", connections: "/api/connections", changed: false, state: "absent", desiredEnabled: false, message: "Codex integration is already OFF and native; no Codex files changed.", } satisfies NativeToggleEnvelope); } @@ -489,7 +491,7 @@ async function handleCodexToggle(ctx: NativeDecisionContext): Promise const { OCX_NATIVE_REPLAY_RECOVERY_NOTE } = await import("../../responses/compaction"); const restored = await restoreNativeCodexAsync({ revalidateDesiredState: true }); return jsonResponse({ - ok: true, clientId: "codex", changed: durable && persisted.status === "committed", + ok: true, clientId: "codex", connections: "/api/connections", changed: durable && persisted.status === "committed", state: rememberCodexToggle(false, restored.success ? "absent" : "unsafe"), desiredEnabled: enabled, message: restored.success diff --git a/src/server/management/route-registry.ts b/src/server/management/route-registry.ts index 06a8de36db4..c7ebbef4264 100644 --- a/src/server/management/route-registry.ts +++ b/src/server/management/route-registry.ts @@ -147,6 +147,10 @@ export const MANAGEMENT_ROUTES: readonly ManagementRoute[] = [ { method: "POST", path: "/api/native-main-profiles/switch", module: "codex/native-profile-api", mutates: true }, // server/management/agent-settings-routes { method: "GET", path: "/api/claude-code", module: "server/management/agent-settings-routes", mutates: false }, + // server/management/claude-first-party-preview-routes (catch-up 010, G-002) + { method: "GET", path: "/api/claude-code/first-party/preview", module: "server/management/claude-first-party-preview-routes", mutates: false, exempt: { reason: "interactive-preview", why: "Preview half of the dashboard's CLI first-party switch: the dashboard shows the settings.json keys and asks before the PUT. ocx claude config set --first-party has no confirmation step to attach it to." } }, + // server/management/connection-status-routes (catch-up 010, G-001) + { method: "GET", path: "/api/connections", module: "server/management/connection-status-routes", mutates: false, exempt: { reason: "deferred-verb", why: "The read-only Connections view is dashboard-only for now; a CLI verb that prints the same projection is owed by the client-connection follow-up.", owner: "proxy catch-up 020 (client connections CLI)", ownerDoc: "structure/clients/connections.md" } }, { method: "GET", path: "/api/claude-code/model-defaults", module: "server/management/agent-settings-routes", mutates: false, exempt: { reason: "interactive-preview", why: "Preview half of the GUI-only Claude Code tier-default apply; the fingerprint it returns is the only input POST accepts, and no terminal confirmation workflow exists yet." } }, { method: "POST", path: "/api/claude-code/model-defaults", module: "server/management/agent-settings-routes", mutates: true, exempt: { reason: "interactive-preview", why: "Apply half of the GUI-only Claude Code tier-default preview; it writes the shared Claude settings only for a fingerprint the dashboard preview produced." } }, { method: "GET", path: "/api/claude-desktop", module: "server/management/agent-settings-routes", mutates: false }, diff --git a/src/types/config.ts b/src/types/config.ts index ffe135d0836..6098edb96ea 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -66,6 +66,13 @@ export interface OcxClaudeCodeConfig extends OcxClaudeCodeToolLoadingConfig { /** Route the standalone Claude Code CLI through the first-party intercept (settings.json env). * Independent of Desktop's first-party mode. Absent/false = off. */ cliFirstParty?: boolean; + /** + * Extra Claude Code config directories (`CLAUDE_CONFIG_DIR` homes) the operator registered so + * the Connections view reports each one. Read-only: OpenCodex never writes them and never + * discovers homes on disk; the first-party toggle keeps acting on the default home only. + * Absolute paths or `~/`-relative paths; anything else is ignored. + */ + extraConfigDirs?: string[]; /** * Opt-in relocation of supported trailing Claude harness notices from system instructions * to a user input message on translated routes. Changes the Desktop cache-key prefix. diff --git a/structure/INDEX.md b/structure/INDEX.md index d6241de20d3..9ac2f198c92 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -154,6 +154,7 @@ The dashboard, the management API, and third-party client config ownership. | [`clients/codex-desktop.md`](clients/codex-desktop.md) | Windows package activation, restart context, and protected compatibility authority persistence. | | [`clients/chatgpt-desktop.md`](clients/chatgpt-desktop.md) | Experimental macOS app-server stdout shim, opt-in launch, restore and failure boundaries. | | [`clients/claude-desktop.md`](clients/claude-desktop.md) | Claude Desktop profile ownership and config-library resolution. | +| [`clients/connections.md`](clients/connections.md) | Read-only Connections view (desired, observed, owner, drift, restore preview) and the Claude Code first-party preview. | | [`clients/claude-desktop-config-reads.md`](clients/claude-desktop-config-reads.md) | Verified regular-file reads of Claude Desktop config-library metadata, profiles and snapshots. | | [`clients/claude-desktop-model-visibility.md`](clients/claude-desktop-model-visibility.md) | Per-client selection of the rows the Claude Desktop 3P model list carries. | | [`clients/antigravity-gateway.md`](clients/antigravity-gateway.md) | One-click connect and disconnect of the Antigravity app and agy CLI to the OpenCodex gateway: files written, stash and restore, override precedence, refusal rules. | @@ -220,7 +221,7 @@ A source area can be described by more than one doc, because these docs are orga | `desktop/ui/cli.html` | [`desktop-terminal-command.md`](desktop-terminal-command.md) | | `desktop/ui/cli.js` | [`desktop-terminal-command.md`](desktop-terminal-command.md) | | `docs-site/` | [`clients/client-support-matrix.md`](clients/client-support-matrix.md)
    [`ops/docs-and-release.md`](ops/docs-and-release.md) | -| `gui/` | [`overview.md`](overview.md)
    [`transports/native-reasoning-retention.md`](transports/native-reasoning-retention.md)
    [`gui-and-management-api.md`](gui-and-management-api.md)
    [`provider-completion-diagnostic.md`](provider-completion-diagnostic.md)
    [`dashboard-and-usage.md`](dashboard-and-usage.md)
    [`fallback-policy.md`](fallback-policy.md)
    [`design-methodology.md`](design-methodology.md)
    [`companion.md`](companion.md) | +| `gui/` | [`overview.md`](overview.md)
    [`transports/native-reasoning-retention.md`](transports/native-reasoning-retention.md)
    [`gui-and-management-api.md`](gui-and-management-api.md)
    [`provider-completion-diagnostic.md`](provider-completion-diagnostic.md)
    [`dashboard-and-usage.md`](dashboard-and-usage.md)
    [`fallback-policy.md`](fallback-policy.md)
    [`clients/connections.md`](clients/connections.md)
    [`design-methodology.md`](design-methodology.md)
    [`companion.md`](companion.md) | | `gui/src/account-pause-display.ts` | [`account-auto-pause.md`](account-auto-pause.md) | | `gui/src/components/ModelPriceDialog.tsx` | [`pricing.md`](pricing.md) | | `gui/src/hooks/useProviderAccountPools.ts` | [`account-auto-pause.md`](account-auto-pause.md) | @@ -269,7 +270,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/chat/failure-verdict.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | | `src/chat/reasoning-details.ts` | [`data-planes/chat-reasoning-details.md`](data-planes/chat-reasoning-details.md) | | `src/chatgpt/` | [`clients/chatgpt-desktop.md`](clients/chatgpt-desktop.md) | -| `src/claude/` | [`runtime.md`](runtime.md)
    [`data-planes/claude-tool-loading.md`](data-planes/claude-tool-loading.md)
    [`providers/anthropic-progress.md`](providers/anthropic-progress.md)
    [`clients/claude-desktop.md`](clients/claude-desktop.md)
    [`clients/claude-desktop-config-reads.md`](clients/claude-desktop-config-reads.md)
    [`clients/claude-desktop-model-visibility.md`](clients/claude-desktop-model-visibility.md) | +| `src/claude/` | [`runtime.md`](runtime.md)
    [`data-planes/claude-tool-loading.md`](data-planes/claude-tool-loading.md)
    [`providers/anthropic-progress.md`](providers/anthropic-progress.md)
    [`clients/claude-desktop.md`](clients/claude-desktop.md)
    [`clients/connections.md`](clients/connections.md)
    [`clients/claude-desktop-config-reads.md`](clients/claude-desktop-config-reads.md)
    [`clients/claude-desktop-model-visibility.md`](clients/claude-desktop-model-visibility.md) | | `src/claude/failure-verdict.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | | `src/claude/outbound.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | | `src/cli.ts` | [`runtime.md`](runtime.md)
    [`ops/docs-and-release.md`](ops/docs-and-release.md) | @@ -305,7 +306,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/clients/` | [`clients/integrations.md`](clients/integrations.md)
    [`clients/qoder.md`](clients/qoder.md)
    [`clients/client-support-matrix.md`](clients/client-support-matrix.md)
    [`clients/t3code.md`](clients/t3code.md) | | `src/clients/config-export.ts` | [`transports/timeouts.md`](transports/timeouts.md)
    [`clients/export-model-names.md`](clients/export-model-names.md)
    [`clients/omo-export-dialect.md`](clients/omo-export-dialect.md) | | `src/clients/config-export/` | [`clients/export-model-names.md`](clients/export-model-names.md) | -| `src/codex/` | [`runtime.md`](runtime.md)
    [`config.md`](config.md)
    [`codex-home.md`](codex-home.md)
    [`codex-prompts.md`](codex-prompts.md)
    [`catalog.md`](catalog.md)
    [`subagents.md`](subagents.md)
    [`subagent-capacity.md`](subagent-capacity.md)
    [`transports/responses-failover.md`](transports/responses-failover.md)
    [`providers/openai-tiers.md`](providers/openai-tiers.md)
    [`providers/openai-accounts.md`](providers/openai-accounts.md)
    [`gui-and-management-api.md`](gui-and-management-api.md)
    [`dashboard-and-usage.md`](dashboard-and-usage.md)
    [`fallback-policy.md`](fallback-policy.md)
    [`clients/codex-desktop.md`](clients/codex-desktop.md)
    [`clients/chatgpt-desktop.md`](clients/chatgpt-desktop.md)
    [`ops/docs-and-release.md`](ops/docs-and-release.md) | +| `src/codex/` | [`runtime.md`](runtime.md)
    [`config.md`](config.md)
    [`codex-home.md`](codex-home.md)
    [`codex-prompts.md`](codex-prompts.md)
    [`catalog.md`](catalog.md)
    [`subagents.md`](subagents.md)
    [`subagent-capacity.md`](subagent-capacity.md)
    [`transports/responses-failover.md`](transports/responses-failover.md)
    [`providers/openai-tiers.md`](providers/openai-tiers.md)
    [`providers/openai-accounts.md`](providers/openai-accounts.md)
    [`gui-and-management-api.md`](gui-and-management-api.md)
    [`dashboard-and-usage.md`](dashboard-and-usage.md)
    [`fallback-policy.md`](fallback-policy.md)
    [`clients/codex-desktop.md`](clients/codex-desktop.md)
    [`clients/chatgpt-desktop.md`](clients/chatgpt-desktop.md)
    [`clients/connections.md`](clients/connections.md)
    [`ops/docs-and-release.md`](ops/docs-and-release.md) | | `src/codex/account-pause.ts` | [`account-auto-pause.md`](account-auto-pause.md) | | `src/codex/account-preservation.ts` | [`providers/openai-signed-in-preservation.md`](providers/openai-signed-in-preservation.md) | | `src/codex/account-resume-health.ts` | [`account-auto-pause.md`](account-auto-pause.md) | @@ -389,10 +390,10 @@ A source area can be described by more than one doc, because these docs are orga | `src/images/` | [`runtime.md`](runtime.md)
    [`transports/inventory.md`](transports/inventory.md)
    [`providers/anthropic-progress.md`](providers/anthropic-progress.md) | | `src/images/loop.ts` | [`providers/anthropic-cache-lifecycle.md`](providers/anthropic-cache-lifecycle.md) | | `src/index.ts` | [`runtime.md`](runtime.md) | -| `src/integrations/` | [`clients/export-model-names.md`](clients/export-model-names.md)
    [`clients/integrations.md`](clients/integrations.md)
    [`clients/hermes.md`](clients/hermes.md)
    [`clients/qoder.md`](clients/qoder.md)
    [`clients/client-support-matrix.md`](clients/client-support-matrix.md)
    [`clients/t3code.md`](clients/t3code.md) | +| `src/integrations/` | [`clients/export-model-names.md`](clients/export-model-names.md)
    [`clients/integrations.md`](clients/integrations.md)
    [`clients/connections.md`](clients/connections.md)
    [`clients/hermes.md`](clients/hermes.md)
    [`clients/qoder.md`](clients/qoder.md)
    [`clients/client-support-matrix.md`](clients/client-support-matrix.md)
    [`clients/t3code.md`](clients/t3code.md) | | `src/integrations/gateway-clients/` | [`clients/antigravity-gateway.md`](clients/antigravity-gateway.md) | | `src/lab/` | [`runtime.md`](runtime.md)
    [`adapters/compatibility-lab.md`](adapters/compatibility-lab.md) | -| `src/lib/` | [`overview.md`](overview.md)
    [`runtime.md`](runtime.md)
    [`transports/byte-accounting.md`](transports/byte-accounting.md)
    [`transports/responses-wire-shapes.md`](transports/responses-wire-shapes.md)
    [`transports/responses-failover.md`](transports/responses-failover.md)
    [`transports/responses-spend.md`](transports/responses-spend.md)
    [`transports/inventory.md`](transports/inventory.md)
    [`gui-and-management-api.md`](gui-and-management-api.md)
    [`dashboard-and-usage.md`](dashboard-and-usage.md)
    [`clients/integrations.md`](clients/integrations.md)
    [`ops/service-and-sidecars.md`](ops/service-and-sidecars.md)
    [`ops/docs-and-release.md`](ops/docs-and-release.md) | +| `src/lib/` | [`overview.md`](overview.md)
    [`runtime.md`](runtime.md)
    [`transports/byte-accounting.md`](transports/byte-accounting.md)
    [`transports/responses-wire-shapes.md`](transports/responses-wire-shapes.md)
    [`transports/responses-failover.md`](transports/responses-failover.md)
    [`transports/responses-spend.md`](transports/responses-spend.md)
    [`transports/inventory.md`](transports/inventory.md)
    [`gui-and-management-api.md`](gui-and-management-api.md)
    [`dashboard-and-usage.md`](dashboard-and-usage.md)
    [`clients/integrations.md`](clients/integrations.md)
    [`clients/connections.md`](clients/connections.md)
    [`ops/service-and-sidecars.md`](ops/service-and-sidecars.md)
    [`ops/docs-and-release.md`](ops/docs-and-release.md) | | `src/lib/abort.ts` | [`transports/timeouts.md`](transports/timeouts.md) | | `src/lib/account-auto-pause-response.ts` | [`account-auto-pause.md`](account-auto-pause.md) | | `src/lib/advisor-activation.ts` | [`advisor.md`](advisor.md) | @@ -494,7 +495,7 @@ A source area can be described by more than one doc, because these docs are orga | `src/routing/` | [`catalog.md`](catalog.md)
    [`fallback-policy.md`](fallback-policy.md) | | `src/routing/history/` | [`dashboard-and-usage.md`](dashboard-and-usage.md) | | `src/routing/machine-weighted-routing.ts` | [`providers/reset-near-weighted.md`](providers/reset-near-weighted.md) | -| `src/server/` | [`transports/timeouts.md`](transports/timeouts.md)
    [`providers/generic-account-pool.md`](providers/generic-account-pool.md)
    [`runtime.md`](runtime.md)
    [`codex-prompts.md`](codex-prompts.md)
    [`catalog.md`](catalog.md)
    [`subagents.md`](subagents.md)
    [`transports/byte-accounting.md`](transports/byte-accounting.md)
    [`transports/responses.md`](transports/responses.md)
    [`transports/native-reasoning-retention.md`](transports/native-reasoning-retention.md)
    [`transports/responses-wire-shapes.md`](transports/responses-wire-shapes.md)
    [`transports/responses-failover.md`](transports/responses-failover.md)
    [`transports/responses-combo-boundaries.md`](transports/responses-combo-boundaries.md)
    [`transports/policy-fallback.md`](transports/policy-fallback.md)
    [`transports/streaming-health.md`](transports/streaming-health.md)
    [`transports/inventory.md`](transports/inventory.md)
    [`data-planes/images.md`](data-planes/images.md)
    [`data-planes/inbound-compat.md`](data-planes/inbound-compat.md)
    [`providers/anthropic-progress.md`](providers/anthropic-progress.md)
    [`providers/anthropic-per-message-effort.md`](providers/anthropic-per-message-effort.md)
    [`providers-and-adapters.md`](providers-and-adapters.md)
    [`providers/jev-decision.md`](providers/jev-decision.md)
    [`providers/xai-grok.md`](providers/xai-grok.md)
    [`adapters/registry.md`](adapters/registry.md)
    [`gui-and-management-api.md`](gui-and-management-api.md)
    [`provider-completion-diagnostic.md`](provider-completion-diagnostic.md)
    [`dashboard-and-usage.md`](dashboard-and-usage.md)
    [`fallback-policy.md`](fallback-policy.md)
    [`clients/claude-desktop.md`](clients/claude-desktop.md)
    [`clients/claude-desktop-model-visibility.md`](clients/claude-desktop-model-visibility.md)
    [`clients/hermes.md`](clients/hermes.md)
    [`ops/service-and-sidecars.md`](ops/service-and-sidecars.md) | +| `src/server/` | [`transports/timeouts.md`](transports/timeouts.md)
    [`providers/generic-account-pool.md`](providers/generic-account-pool.md)
    [`runtime.md`](runtime.md)
    [`codex-prompts.md`](codex-prompts.md)
    [`catalog.md`](catalog.md)
    [`subagents.md`](subagents.md)
    [`transports/byte-accounting.md`](transports/byte-accounting.md)
    [`transports/responses.md`](transports/responses.md)
    [`transports/native-reasoning-retention.md`](transports/native-reasoning-retention.md)
    [`transports/responses-wire-shapes.md`](transports/responses-wire-shapes.md)
    [`transports/responses-failover.md`](transports/responses-failover.md)
    [`transports/responses-combo-boundaries.md`](transports/responses-combo-boundaries.md)
    [`transports/policy-fallback.md`](transports/policy-fallback.md)
    [`transports/streaming-health.md`](transports/streaming-health.md)
    [`transports/inventory.md`](transports/inventory.md)
    [`data-planes/images.md`](data-planes/images.md)
    [`data-planes/inbound-compat.md`](data-planes/inbound-compat.md)
    [`providers/anthropic-progress.md`](providers/anthropic-progress.md)
    [`providers/anthropic-per-message-effort.md`](providers/anthropic-per-message-effort.md)
    [`providers-and-adapters.md`](providers-and-adapters.md)
    [`providers/jev-decision.md`](providers/jev-decision.md)
    [`providers/xai-grok.md`](providers/xai-grok.md)
    [`adapters/registry.md`](adapters/registry.md)
    [`gui-and-management-api.md`](gui-and-management-api.md)
    [`provider-completion-diagnostic.md`](provider-completion-diagnostic.md)
    [`dashboard-and-usage.md`](dashboard-and-usage.md)
    [`fallback-policy.md`](fallback-policy.md)
    [`clients/claude-desktop.md`](clients/claude-desktop.md)
    [`clients/connections.md`](clients/connections.md)
    [`clients/claude-desktop-model-visibility.md`](clients/claude-desktop-model-visibility.md)
    [`clients/hermes.md`](clients/hermes.md)
    [`ops/service-and-sidecars.md`](ops/service-and-sidecars.md) | | `src/server/admission-model-scope.ts` | [`data-planes/error-detail.md`](data-planes/error-detail.md) | | `src/server/admitted-http-turn.ts` | [`data-planes/ollama-inbound.md`](data-planes/ollama-inbound.md) | | `src/server/advisor-admission-scope.ts` | [`advisor.md`](advisor.md) | diff --git a/structure/clients/connections.md b/structure/clients/connections.md new file mode 100644 index 00000000000..5cde8d43e37 --- /dev/null +++ b/structure/clients/connections.md @@ -0,0 +1,95 @@ +# Client Connections + +The read-only Connections view and the Claude Code first-party preview (proxy catch-up 010, gaps +G-001 and G-002; roadmap `devlog/_plan/261123_proxy_upstream_catchup/010_client_connection.md`). +Neither surface writes: they project the files the existing switches act on, and the switches keep +their own apply and rollback paths unchanged. + +## `GET /api/connections` + +`src/server/management/connection-status-routes.ts` serves it, lazily loaded by namespace from +`src/server/management-api.ts` so its imports stay off every other dashboard request and no +`src/lab/` edge appears. The response is `{ connections: ConnectionView[] }`, typed in +`src/integrations/connection-view.ts`: per row `client` (`codex`, `claude-code`, +`claude-desktop`), `desired`, `observed`, `owner`, an optional `ownerPath`, `driftReasons` and +an optional `restorePreview` of `{ outcome, changes: [{ file, key, change }] }`. + +Drift reasons, each produced by a projection: `external_owner` (another program, OpenCodex home or +service owns the files; `ownerPath` names the file), `account_mode` (Claude Desktop's pinned +`desktopMode` contradicts the artifact it runs), `hub_gated` (a hub without the loopback listener +does not rewrite its own clients), `intercept_disabled` (CLI first-party wanted while the intercept +cannot run), `file_edited` (the file no longer matches the switch) and `pending_restart` (settings +point at a stopped or mismatched listener). The roadmap's `quota_block` has no read-only signal — +the desktop quota gate (#6196) is still a design proposal — and is not produced. + +**Codex** (`src/codex/connection-projection.ts`): `desired` from `codexIntegrationEnabled` +(`remote-home` on a Link Child), `observed` from `classifyCodexRouting` over a bounded read of +config.toml. Ownership precedence: a Codex-home journal bound to another OpenCodex home (owner +file: the journal), a recorded service state naming other homes (`inspectRecordedServiceOwnership` +in `src/integrations/native/ownership-preflight.ts`, the state-file half of +`inspectNativeCodexOwnership`, file reads only — the service-manager probe spawns processes and +stays on write paths), an external model provider (owner file: config.toml), the sibling mark, the +hub gate, unknown evidence. `restorePreview` comes from `src/codex/restore-preview.ts`, which walks +`restoreNativeCodexAsync` in its own order with the read-only halves of the same decisions: +`previewJournalRestore` (`src/codex/journal.ts`), `previewRemovedCodexConfig` (sharing +`planCodexConfigRemoval` with `removeCodexConfig` in `src/codex/inject/remove.ts`), the provider +table retention, and `previewApprovedCodexProviderRestore` (sharing the URL transform with +`restoreApprovedCodexProviders`). Changes are root keys or `section.key` in config.toml plus a +whole-file entry for `opencodex.config.toml`; catalog rows and the history relabel are not keys and +are not listed. Keys are shown through an allowlist (`displayCodexConfigKey`): OpenCodex-managed root +keys, Codex's own table names, the table ids OpenCodex owns (`opencodex`, `openai`) and Codex's fixed +leaf vocabulary; any other segment — a provider, profile, project, hook or server name, which can be a +user name, an email or a secret of any length — is shown as `…`. A profile +that is a symbolic link is refused before config.toml is touched, as `removeCodexConfig` does. The +service manager is not probed: restore refuses only a `foreign` verdict, which only the recorded +service state yields (a manager definition naming other homes reads `unknown`), so the recorded state +alone decides the preview's refusal. `tests/server/connection-status-routes.test.ts` runs +`tests/fixtures/connection-restore-preview-runner.ts` in temporary homes and compares the preview +with the real restore for injected, edited, native, external-provider and foreign-owner homes. + +**Claude** (`src/claude/connection-projection.ts`): one Claude Code row per registered home — +`registeredClaudeConfigDirs` (`src/claude/auth-detect.ts`) returns the default `claudeConfigDir` +and then `claudeCode.extraConfigDirs`; nothing is discovered on disk. Only the default home carries +intent, drift and the switch-off preview, because the switch writes only that home; an extra home +reports `desired: "unset"` and what its settings.json routes to. One Claude Desktop row maps the +config-library inspection the native status row uses. + +Privacy: every returned path goes through `displayPath` (`src/lib/display-path.ts`): the user's home +prefix becomes `~`, a drive letter stays, and only the fixed directory and file names OpenCodex, Codex +and Claude use are shown; any other segment (a user name, account id or token used as a folder name) +becomes `…`, and an extra home is identified by `homeOrdinal` instead of its path. No setting value, +token or email is returned; an unexpected failure answers a fixed `connections_failed` body. Reads are +bounded: at most 16 extra homes (`MAX_EXTRA_CLAUDE_CONFIG_DIRS`), a `settings.json` that is not a +regular file of at most 1 MiB is never opened (`claudeSettingsFileState`; the row reads `unknown` and +the preview refuses `unreadable`), and the Codex profile goes through the same bounded reader as +config.toml. The Codex +toggle envelopes in `native-integration-routes.ts` carry `connections: "/api/connections"`. + +CLI verb: owed. The route registry declares it `deferred-verb` with owner "proxy catch-up 020 +(client connections CLI)"; this document is its owner doc. + +## `GET /api/claude-code/first-party/preview` + +`src/server/management/claude-first-party-preview-routes.ts`, delegated by one line from +`agent-settings-routes.ts`. `?enabled=true|false` names the switch value (absent: the flip of the +current value; anything else is `400 invalid_enabled`). The answer is +`{ enabled, path, changes: [{ file: "settings.json", key: "env.X", change }], applyChecks }`. +`src/claude/first-party-preview.ts` uses the switch's inputs: the persisted-config transition +`claudeFirstPartyTransition` (`src/claude/first-party-transition.ts`, which `PUT /api/claude-code` +calls inside its locked mutation), the live config the route reconciles with, the settings +inspection, and the NO_PROXY merge and receipt rules (a removal restores NO_PROXY only when the +current value is the one the receipt records). Enabling repeats the PUT's pre-checks and answers +their codes: `409 intercept_disabled`, `409 foreign_env`, `500 unreadable`. The token is read, +never minted, and the CA is never created; `applyChecks` names the runtime steps a read cannot +predict. `tests/claude-integration/claude-first-party-preview.test.ts` compares each preview with +the real transition and reconcile, including a persisted snapshot that differs from the live one. +The registry exempts the route as `interactive-preview`: `ocx claude config set --first-party` +has no confirmation step. + +The dashboard switch (`gui/src/pages/ClaudeCode.tsx`) fetches the preview before the PUT and, +when keys would change, waits on `FirstPartyPreviewDialog`. A failed, refused or cancelled +preview releases the switch through the existing `finally` and sends no PUT +(`gui/tests/claude-toggle-race.test.tsx`). Turning first-party off sends the PUT directly. The page +lists registered homes (`ClaudeHomesStatus`) and the Integrations overview mounts +`ConnectionsPanel`, both reading `GET /api/connections`; copy lives in +`gui/src/i18n/connections-copy.ts` for every locale. diff --git a/structure/config.md b/structure/config.md index 2868b014795..a6b924fd154 100644 --- a/structure/config.md +++ b/structure/config.md @@ -120,7 +120,7 @@ Its client annotation compares only the bounded service-token fingerprint with t Generic config writers follow the [CLI plaintext-entry contract](cli-management.md); all config publication continues through the existing required ACL-hardened writers above. `claudeCode.desktopProfile` follows the same preserve-the-rest rule. JSON `null` (or any non-string) `appliedFingerprint` / `appliedAt` is treated as unset. A profile that is still invalid after that is dropped as a whole — `src/config/salvage.ts` already does this for independent `routingProfiles` / `combos` entries — so one bad Desktop marker cannot replace the operator's providers with `getDefaultConfig()`. A `claudeCode` value that is not an object still fails the document, because there is no safe subtree to keep. -`claudeCode.cliFirstParty` is an optional boolean in `src/types/config.ts`. The schema passes it through; the load normalizer (`src/config/load-degrade.ts`) drops a non-boolean hand edit, every reader treats only `true` as on, and `PUT /api/claude-code` accepts only a boolean. Absence means off. It is independent of `claudeCode.desktopMode`; changing CLI first-party pins an absent Desktop mode from the observation that will apply after the flag flips — an opt-out observes with `cliFirstParty` already cleared, so a shared env that predates the marker stays attributed to Desktop instead of being pinned `gateway` and removed from under it, and an owned env cannot be mistaken for CLI-only intent. The flag is written by a standalone `PUT /api/claude-code { cliFirstParty }`, including `ocx claude config set --first-party`; the mutation pins an absent `desktopMode` at the same time. The shared settings proxy status follows the ordered classifier in `src/claude/first-party-settings.ts`: unreadable settings are `unknown`; absent or unrecognized proxy URLs are `none`; a token-bearing opencodex URL beside a foreign CA is `foreign`, while a tokenless loopback URL beside that CA is `local` with unconfirmed ownership. An attributed proxy with no bound listener is `stopped`; a usable applied pair on a bound listener is `disabled` when Claude routing is ineligible and `live` when eligible; remaining mismatches are `broken` regardless of eligibility. Inspection never mints a token. A separate `ocx ensure` may write a config-derived port while this server remains bound elsewhere; status is then `broken` until the server restarts or ensure runs after restart. `claudeCode.contextAccounting` in `src/types/config.ts` stores only `"200k"`; absence is the 1m default and `"1m"` deletes the key. `ocx claude config set --context-accounting` writes it. The surface contract is [Claude Desktop picker mode](clients/claude-desktop.md#picker-mode-the-desktop-egress-proxy). `claudeCode.nativePassthrough` is default-on: only a stored `false` sends bare Claude ids to the routed lane instead of forwarding the caller's own `sk-ant-*` credential (`wantsNativePassthrough` in `src/server/claude-messages.ts`). `PUT /api/claude-code` stores `false` or deletes the key. `ocx claude config set --native-passthrough` requires a boolean capability read from the [management API](gui-and-management-api.md#api-ownership) before sending the whole settings patch to the same resolved runtime. The PUT response must confirm the requested effective boolean. +`claudeCode.cliFirstParty` is an optional boolean in `src/types/config.ts`. The schema passes it through; the load normalizer (`src/config/load-degrade.ts`) drops a non-boolean hand edit, every reader treats only `true` as on, and `PUT /api/claude-code` accepts only a boolean. Absence means off. It is independent of `claudeCode.desktopMode`; changing CLI first-party pins an absent Desktop mode from the observation that will apply after the flag flips — an opt-out observes with `cliFirstParty` already cleared, so a shared env that predates the marker stays attributed to Desktop instead of being pinned `gateway` and removed from under it, and an owned env cannot be mistaken for CLI-only intent. The flag is written by a standalone `PUT /api/claude-code { cliFirstParty }`, including `ocx claude config set --first-party`; the mutation pins an absent `desktopMode` at the same time. The shared settings proxy status follows the ordered classifier in `src/claude/first-party-settings.ts`: unreadable settings are `unknown`; absent or unrecognized proxy URLs are `none`; a token-bearing opencodex URL beside a foreign CA is `foreign`, while a tokenless loopback URL beside that CA is `local` with unconfirmed ownership. An attributed proxy with no bound listener is `stopped`; a usable applied pair on a bound listener is `disabled` when Claude routing is ineligible and `live` when eligible; remaining mismatches are `broken` regardless of eligibility. Inspection never mints a token. A separate `ocx ensure` may write a config-derived port while this server remains bound elsewhere; status is then `broken` until the server restarts or ensure runs after restart. `claudeCode.contextAccounting` in `src/types/config.ts` stores only `"200k"`; absence is the 1m default and `"1m"` deletes the key. `ocx claude config set --context-accounting` writes it. The surface contract is [Claude Desktop picker mode](clients/claude-desktop.md#picker-mode-the-desktop-egress-proxy). `claudeCode.nativePassthrough` is default-on: only a stored `false` sends bare Claude ids to the routed lane instead of forwarding the caller's own `sk-ant-*` credential (`wantsNativePassthrough` in `src/server/claude-messages.ts`). `PUT /api/claude-code` stores `false` or deletes the key. `ocx claude config set --native-passthrough` requires a boolean capability read from the [management API](gui-and-management-api.md#api-ownership) before sending the whole settings patch to the same resolved runtime. The PUT response must confirm the requested effective boolean. `claudeCode.extraConfigDirs` (catch-up 010) is an optional list of extra Claude Code config directories in `src/types/config.ts`. The load normalizer keeps trimmed non-empty strings and drops the key otherwise; the schema passes it through. `registeredClaudeConfigDirs` in `src/claude/auth-detect.ts` returns the default `claudeConfigDir(env)` first and then each listed entry, expanding a leading `~`, skipping entries that stay relative, collapsing duplicates and reporting at most 16 extras. It is read-only evidence for `GET /api/connections`: OpenCodex never writes those homes or discovers others on disk, and the CLI first-party switch and its preview keep acting on the default home only. The key is edited by hand (or `ocx config set`). `claudeCode.appendOnlyToolLoadingModels` follows the [append-only discovery contract](data-planes/claude-tool-loading.md): at most 128 provider-qualified selectors of 512 characters, optional trailing prefix wildcard, absent/off by default. `src/claude/inbound-tool-loading.ts` shares fail-closed validation with the schema; writes reject malformed lists and `src/config/salvage.ts` drops only that optional field on load, preserving providers and other Claude settings. Provider-ID rewrites carry exact and wildcard selectors without changing their model suffixes. `claudeCode.chatToolDispatchModels` is the Chat-wire counterpart with the identical selector contract, validation, salvage and provider-ID rewrite. Both lists and `claudeCode.toolSearch` are typed in `src/types/claude-tool-loading.ts`, which `OcxClaudeCodeConfig` extends; its runtime behavior is the [Chat-wire dispatcher](data-planes/claude-tool-loading.md#chat-wire-dispatcher). Absent or empty is off and byte-identical to an unset key. `showCodexCredits` is an optional, display-only boolean in `src/types/config.ts`, default off. The load schema degrades malformed values to false; `src/config/diagnostics.ts` rejects malformed write candidates. `GET /api/settings`, its successful PUT response, and the safe `/api/config` DTO always project a boolean. PUT accepts a partial boolean update, persists it, and restores both the previous value and key presence if saving fails. The switch gates account DTO exposure without changing probes or routing; [credits identity binding](providers/openai-accounts.md#display-only-codex-credits) owns the observation contract. The former `showCodexSparkQuota` key is inert passthrough data when loading an old config. It is absent from the typed settings contract and cannot re-enable Spark quota through the management API. Retirement does not migrate user-selected model ids or erase usage history. diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index c0105777f4e..f040f5d4a86 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -306,7 +306,7 @@ effective window when absent, and offers a read-only Reload after an unknown sav confirmed save whose list reload failed; a failed or retryable Codex catalog refresh is a warning after the save, and a non-retryable skip (no managed catalog) is a clean save. Close returns focus to the opening row control. -`GET /api/claude-code` reports `cliFirstParty`, `desktopFirstParty`, `cliFirstPartyApplied`, `interceptEligible`, `interceptRunning`, and the eight-value `sharedProxy: FirstPartyProxyStatus` from observed settings and the bound listener. `interceptEligible = claudeInterceptEnabled(config)` uses the same GET snapshot as `sharedProxy` and `interceptRunning`; the latter remains bound listener present AND eligible. The ordered classifier gives unreadable → `unknown`, absent or non-loopback URL → `none`, foreign CA with an opencodex token → `foreign`, foreign CA with a tokenless loopback URL → `local`, no bound listener → `stopped`, ineligible applied settings at the bound port → `disabled`, other ineligible or stale/mismatched settings → `broken`, and eligible applied settings at the bound port → `live`. `cliFirstPartyApplied` requires CLI intent and `live`. `PUT /api/claude-code` accepts standalone `cliFirstParty`; CLI-on repeats eligibility and port checks inside the locked persisted mutation, reconciles, and conditionally rolls back its own fields on failure. CLI-off deletes intent, pins an absent `desktopMode` from the post-clear observation, and retains an env Desktop still desires; when that retained env's ownership was ambiguous (an owned shared proxy suppressed by the flag), the success response warns `shared_proxy_retained` so the operator can pin `gateway` explicitly to release it. A successful nothing-desired reconcile returns `settings_residual` for every status except `none`, including `local`; unreadable cleanup returns the coded 500. Native Claude routing enable persists its setting and reports `interceptReason` when local start authority is absent; disable and no-op paths never attempt a start. `enabled:false` alone leaves the env untouched, and a mixed body returns 400 before save. GUI normalization maps only missing `sharedProxy:undefined` to `none`, invalid statuses including `null` to `unknown`; `interceptEligible:undefined` from an older cache maps to `true`, while present values use `=== true`. The source coverage map checks all eight statuses. Notice order is unknown, foreign, local, residual when undesired, disabled, routingOff for stopped/broken with ineligible routing, stopped, broken, notApplied, shared, null. Unknown copy states uncertainty, local copy names the unconfirmed 127.0.0.1 proxy and manual HTTPS_PROXY removal, disabled copy retains the first-party-off remedy, foreign copy directs manual CA/proxy repair, routingOff says to restore Claude routing or turn first-party off, stopped says to start opencodex, and eligible broken advises `ocx ensure` or restart. `GET /api/claude-code` reports `contextAccounting` as `"200k"` or `"1m"`; `PUT` accepts only those two, stores `"200k"`, deletes the key for `"1m"`, and reconciles system env with the other levers. The marking contract is [Claude Desktop picker mode](clients/claude-desktop.md#picker-mode-the-desktop-egress-proxy). `GET /api/claude-code` and successful `PUT /api/claude-code` responses report the effective `nativePassthrough` boolean. The patch stores `false` and deletes the key for `true`. A save failure before publication restores the previous live Claude Code block and any submitted `fastMode`. A failure after publication retains the published values in memory. The dashboard edits this field through `ClaudeNativePassthroughSetting` (Providers → Anthropic → Accounts on the `anthropic` row in either auth mode, under the account pool card for OAuth), independently of the Claude Code page's full-form Save. A missing or invalid GET value disables the switch and shows a load error. An unsuccessful or unconfirmed PUT clears the displayed value, shows a save error, and reloads the live value with a fresh GET. The switch stays disabled while the value is unknown, and Retry repeats a failed read. For `--native-passthrough`, the CLI requires a boolean from GET on the resolved runtime before sending the patch, then requires a matching boolean from PUT. Changing only this switch skips system-env reconciliation. `wantsNativePassthrough` in `src/server/claude-messages.ts` reads the live config per request, PUT re-syncs generated agents, and launch context windows update on the next `ocx claude` launch. The dashboard manual launch snippet uses the Fable slot from the same read as `effectiveModelEnv`. It exports an explicit slot and leaves an automatic fill to the CLI in the pasted shell. `GET /api/claude-code?view=launch` returns the authenticated launcher fields `enabled`, `forceAvailable`, and `contextWindows`. The daemon resolves auth for context windows and skips the dashboard's available-model and alias previews and CLI version probe for this view. The dashboard uses the full GET, which probes the daemon's Claude Code version when it can affect `effectiveModelEnv`. +`GET /api/claude-code` reports `cliFirstParty`, `desktopFirstParty`, `cliFirstPartyApplied`, `interceptEligible`, `interceptRunning`, and the eight-value `sharedProxy: FirstPartyProxyStatus` from observed settings and the bound listener. `interceptEligible = claudeInterceptEnabled(config)` uses the same GET snapshot as `sharedProxy` and `interceptRunning`; the latter remains bound listener present AND eligible. The ordered classifier gives unreadable → `unknown`, absent or non-loopback URL → `none`, foreign CA with an opencodex token → `foreign`, foreign CA with a tokenless loopback URL → `local`, no bound listener → `stopped`, ineligible applied settings at the bound port → `disabled`, other ineligible or stale/mismatched settings → `broken`, and eligible applied settings at the bound port → `live`. `cliFirstPartyApplied` requires CLI intent and `live`. `PUT /api/claude-code` accepts standalone `cliFirstParty`; CLI-on repeats eligibility and port checks inside the locked persisted mutation, reconciles, and conditionally rolls back its own fields on failure. CLI-off deletes intent, pins an absent `desktopMode` from the post-clear observation, and retains an env Desktop still desires; when that retained env's ownership was ambiguous (an owned shared proxy suppressed by the flag), the success response warns `shared_proxy_retained` so the operator can pin `gateway` explicitly to release it. A successful nothing-desired reconcile returns `settings_residual` for every status except `none`, including `local`; unreadable cleanup returns the coded 500. Native Claude routing enable persists its setting and reports `interceptReason` when local start authority is absent; disable and no-op paths never attempt a start. `enabled:false` alone leaves the env untouched, and a mixed body returns 400 before save. GUI normalization maps only missing `sharedProxy:undefined` to `none`, invalid statuses including `null` to `unknown`; `interceptEligible:undefined` from an older cache maps to `true`, while present values use `=== true`. The source coverage map checks all eight statuses. Notice order is unknown, foreign, local, residual when undesired, disabled, routingOff for stopped/broken with ineligible routing, stopped, broken, notApplied, shared, null. Unknown copy states uncertainty, local copy names the unconfirmed 127.0.0.1 proxy and manual HTTPS_PROXY removal, disabled copy retains the first-party-off remedy, foreign copy directs manual CA/proxy repair, routingOff says to restore Claude routing or turn first-party off, stopped says to start opencodex, and eligible broken advises `ocx ensure` or restart. `GET /api/claude-code` reports `contextAccounting` as `"200k"` or `"1m"`; `PUT` accepts only those two, stores `"200k"`, deletes the key for `"1m"`, and reconciles system env with the other levers. The marking contract is [Claude Desktop picker mode](clients/claude-desktop.md#picker-mode-the-desktop-egress-proxy). `GET /api/claude-code` and successful `PUT /api/claude-code` responses report the effective `nativePassthrough` boolean. The patch stores `false` and deletes the key for `true`. A save failure before publication restores the previous live Claude Code block and any submitted `fastMode`. A failure after publication retains the published values in memory. The dashboard edits this field through `ClaudeNativePassthroughSetting` (Providers → Anthropic → Accounts on the `anthropic` row in either auth mode, under the account pool card for OAuth), independently of the Claude Code page's full-form Save. A missing or invalid GET value disables the switch and shows a load error. An unsuccessful or unconfirmed PUT clears the displayed value, shows a save error, and reloads the live value with a fresh GET. The switch stays disabled while the value is unknown, and Retry repeats a failed read. For `--native-passthrough`, the CLI requires a boolean from GET on the resolved runtime before sending the patch, then requires a matching boolean from PUT. Changing only this switch skips system-env reconciliation. `wantsNativePassthrough` in `src/server/claude-messages.ts` reads the live config per request, PUT re-syncs generated agents, and launch context windows update on the next `ocx claude` launch. The dashboard manual launch snippet uses the Fable slot from the same read as `effectiveModelEnv`. It exports an explicit slot and leaves an automatic fill to the CLI in the pasted shell. `GET /api/claude-code?view=launch` returns the authenticated launcher fields `enabled`, `forceAvailable`, and `contextWindows`. The daemon resolves auth for context windows and skips the dashboard's available-model and alias previews and CLI version probe for this view. The dashboard uses the full GET, which probes the daemon's Claude Code version when it can affect `effectiveModelEnv`. The first-party preview route (`GET /api/claude-code/first-party/preview`) and the read-only `GET /api/connections` view are owned by [Client connections](clients/connections.md). | File-integration plans | `src/server/management/integration-routes.ts` and `aside-profile-routes.ts` — `POST /api/client-integrations/preview`, `POST /api/client-integrations/restore/preview`, and `POST /api/client-integrations/aside/profiles/{profileId}/preview`. Management-authenticated, declared non-mutating, and they write nothing: no snapshot, no lock, no maintenance, no recovery. They answer `409 integration_preview_unavailable` rather than gathering a model roster, because discovery refreshes credentials and writes the provider cache. Responses carry only declared managed schema paths, closed change kinds and an opaque fingerprint; no value, filesystem location or selected member identity appears. Mutation routes accept `operation` and `planFingerprint` together or not at all, reject a half-bound request and an operation that disagrees with the change, and answer `409 integration_preview_stale` with a freshly computed plan. Binding is an optimistic token, never authorization. [The integration contract](clients/integrations.md) owns the ordering. | | Grok reset coupons | `src/server/management/grok-coupon-routes.ts` — `GET /api/grok/reset-coupons`, `POST /api/grok/reset-coupons/consume`. The dashboard owner is `gui/src/hooks/useGrokResetCoupons.ts` with `gui/src/components/provider-workspace/GrokResetCoupons.tsx`, wired into the xAI OAuth rows of `ProviderAuthPanel`. Redemption truth is the settled ledger `code`, not the HTTP status: a replayed failure returns 200 with `replayed: true`. See [`providers/xai-grok.md`](providers/xai-grok.md). The route returns `ledger_unavailable` before dispatch when the shared ledger cannot be read or locked; stale uncertain attempts are inspected without another redemption or inferred success. A late inspection refusal or a lost claim replays an identity-matching definitive winner; otherwise it returns `operation_state_changed` (late refusal) or `attempt_in_progress` (lost claim) and never replaces an attempted or terminal record. Unknown-outcome responses include the effective operation ID; the CLI mints it before dispatch. Uncertain and pending attempts live in a module-level hold store shared by all hook instances and mirrored to `sessionStorage` (`ocx.grok-coupon-holds.v1`), so they survive modal close/reopen, remount, and reload for the tab session; the pending hold is written before the POST, only a definitive response for the same `operationId` clears it, and only GET refreshes are allowed after uncertainty. Every response that cannot prove settlement under a supplied operation ID, including pre-open refusals, carries that `operationId`. A definitive failure releases the matching speculative pending hold. Supplied token IDs must be non-empty strings before journal admission, and omitted account/token retries recover the operation’s durable identity within retention. Legacy version-one opens are quarantined rather than dispatched. After confirmed redemption, local settlement has five attempts and four 20 ms waits only for a `ConfigMutationLockError` caused by `SQLITE_BUSY`; any other error or changed claim stops without another redemption. | diff --git a/structure/manifest.json b/structure/manifest.json index 2c0569847e1..71cffd1094e 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -1252,6 +1252,20 @@ "src/server/" ] }, + { + "path": "clients/connections.md", + "tier": 5, + "title": "Client Connections", + "scope": "Read-only Connections view (desired, observed, owner, drift, restore preview) and the Claude Code first-party preview.", + "documents": [ + "gui/", + "src/claude/", + "src/codex/", + "src/integrations/", + "src/lib/", + "src/server/" + ] + }, { "path": "clients/claude-desktop-config-reads.md", "tier": 5, diff --git a/tests/claude-integration/claude-first-party-preview.test.ts b/tests/claude-integration/claude-first-party-preview.test.ts new file mode 100644 index 00000000000..9b55c2cf4e3 --- /dev/null +++ b/tests/claude-integration/claude-first-party-preview.test.ts @@ -0,0 +1,200 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { registeredClaudeConfigDirs } from "../../src/claude/auth-detect"; +import { observeClaudeDesktopMode } from "../../src/claude/desktop-first-party"; +import { previewClaudeFirstPartySettings, type FirstPartySettingsChange } from "../../src/claude/first-party-preview"; +import { firstPartyDesired, reconcileClaudeFirstPartySettings } from "../../src/claude/first-party-settings"; +import { claudeFirstPartyTransition } from "../../src/claude/first-party-transition"; +import { claudeInterceptCaCertPath } from "../../src/claude/intercept/local-ca"; +import { claudeInterceptProxyTokenPath } from "../../src/claude/intercept/proxy-auth"; +import type { OcxConfig } from "../../src/types"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +/** + * Catch-up 010, G-002: the first-party preview must report exactly the settings.json keys the + * switch changes. Every case runs the preview, checks it wrote nothing, then runs the switch's + * own path (the shared persisted transition, then reconcile with the adopted block) in the same + * temporary homes and compares the key-level diff. Values never appear in a preview. + */ +let root = ""; +let claudeHome = ""; +let oldLibrary: string | undefined; +const options = () => ({ opencodexConfigDir: root, claudeConfigDir: claudeHome }); +const settingsPath = () => join(claudeHome, "settings.json"); + +function cfg(extra: { desktop?: boolean; cli?: boolean; desktopMode?: "first-party" | "gateway" | null; intercept?: boolean; port?: number } = {}): OcxConfig { + const claudeCode: Record = {}; + if (extra.desktopMode !== null) claudeCode.desktopMode = extra.desktopMode ?? "first-party"; + if (extra.cli) claudeCode.cliFirstParty = true; + if (extra.intercept === false) claudeCode.intercept = { enabled: false }; + return { port: extra.port ?? 10100, defaultProvider: "openai", providers: {}, + clientIntegrations: { "claude-desktop": extra.desktop === true }, claudeCode } as unknown as OcxConfig; +} + +function env(): Record { + if (!existsSync(settingsPath())) return {}; + return (JSON.parse(readFileSync(settingsPath(), "utf8")) as { env?: Record }).env ?? {}; +} + +function writeEnv(value: Record): void { + mkdirSync(claudeHome, { recursive: true }); + writeFileSync(settingsPath(), JSON.stringify({ theme: "dark", env: value }, null, 2)); +} + +function diff(before: Record, after: Record): FirstPartySettingsChange[] { + const keys = [...new Set([...Object.keys(before), ...Object.keys(after)])].sort(); + const changes: FirstPartySettingsChange[] = []; + for (const key of keys) { + const had = Object.hasOwn(before, key); + const has = Object.hasOwn(after, key); + if (!had && has) changes.push({ file: "settings.json", key: `env.${key}`, change: "add" }); + else if (had && !has) changes.push({ file: "settings.json", key: `env.${key}`, change: "remove" }); + else if (before[key] !== after[key]) changes.push({ file: "settings.json", key: `env.${key}`, change: "update" }); + } + return changes; +} + +const sorted = (changes: FirstPartySettingsChange[]) => [...changes].sort((a, b) => a.key.localeCompare(b.key)); + +/** Every file under root with its bytes, to prove a preview wrote, minted and deleted nothing. */ +function snapshot(dir = root): Record { + const out: Record = {}; + if (!existsSync(dir)) return out; + for (const name of readdirSync(dir)) { + const path = join(dir, name); + if (statSync(path).isDirectory()) Object.assign(out, snapshot(path)); + else out[path] = readFileSync(path, "base64"); + } + return out; +} + +/** The switch's path: shared transition on the persisted config, reconcile with the adopted block. */ +function realSwitch(live: OcxConfig, persisted: OcxConfig, requested: boolean) { + const { nextBlock } = claudeFirstPartyTransition(persisted, requested, options()); + const reconciled = { ...live, claudeCode: nextBlock } as OcxConfig; + return reconcileClaudeFirstPartySettings(reconciled, firstPartyDesired(reconciled, observeClaudeDesktopMode(reconciled, options())), options()); +} + +function expectPreviewMatchesSwitch(live: OcxConfig, requested: boolean, persisted: OcxConfig = live): FirstPartySettingsChange[] { + const before = snapshot(); + const preview = previewClaudeFirstPartySettings({ live, persisted, enabled: requested, options: options() }); + expect(snapshot()).toEqual(before); + if (!preview.ok) throw new Error(`preview refused: ${preview.reason}`); + expect(JSON.stringify(preview)).not.toContain("127.0.0.1"); + // Values never leave the preview: not the CA path, not the proxy token. + expect(JSON.stringify(preview)).not.toContain(claudeInterceptCaCertPath(root)); + const token = existsSync(claudeInterceptProxyTokenPath(root)) ? readFileSync(claudeInterceptProxyTokenPath(root), "utf8").trim() : ""; + if (token) expect(JSON.stringify(preview)).not.toContain(token); + const envBefore = env(); + const result = realSwitch(live, persisted, requested); + expect(result.ok).toBe(true); + expect(sorted(preview.changes)).toEqual(sorted(diff(envBefore, env()))); + return preview.changes; +} + +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), "ocx-first-party-preview-")); + claudeHome = join(root, "claude"); + oldLibrary = process.env.OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR; + process.env.OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR = join(root, "library"); +}); +afterEach(() => { + if (oldLibrary === undefined) delete process.env.OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR; + else process.env.OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR = oldLibrary; + removeTreeWithRetry(root); +}); + +describe("enabling CLI first-party", () => { + test("a fresh home adds the proxy, the CA and the loopback bypass; nothing is minted by the preview", () => { + const changes = expectPreviewMatchesSwitch(cfg(), true); + expect(changes.map(c => `${c.key}:${c.change}`).sort()).toEqual(["env.HTTPS_PROXY:add", "env.NODE_EXTRA_CA_CERTS:add", "env.NO_PROXY:add"]); + }); + + test("a user NO_PROXY without loopback is extended (update), one covering everything is left alone", () => { + writeEnv({ NO_PROXY: "corp.example" }); + expect(expectPreviewMatchesSwitch(cfg(), true).find(c => c.key === "env.NO_PROXY")?.change).toBe("update"); + removeTreeWithRetry(root); + mkdirSync(root, { recursive: true }); + writeEnv({ NO_PROXY: "*" }); + expect(expectPreviewMatchesSwitch(cfg(), true).some(c => c.key === "env.NO_PROXY")).toBe(false); + }); + + test("an applied env previews no change, and a moved port previews the proxy update", () => { + expect(realSwitch(cfg(), cfg(), true).ok).toBe(true); + expect(expectPreviewMatchesSwitch(cfg({ cli: true }), true)).toEqual([]); + const moved = expectPreviewMatchesSwitch(cfg({ cli: true, port: 10300 }), true); + expect(moved).toEqual([{ file: "settings.json", key: "env.HTTPS_PROXY", change: "update" }]); + }); + + test("the switch's refusals are previewed: foreign env, unreadable settings, disabled intercept", () => { + writeEnv({ HTTPS_PROXY: "http://proxy.corp:8080", NODE_EXTRA_CA_CERTS: "/corp/ca.pem" }); + const foreign = previewClaudeFirstPartySettings({ live: cfg(), persisted: cfg(), enabled: true, options: options() }); + expect(foreign).toMatchObject({ ok: false, reason: "foreign_env" }); + expect(realSwitch(cfg(), cfg(), true)).toMatchObject({ ok: false, reason: "foreign_env" }); + + writeFileSync(settingsPath(), "{broken"); + expect(previewClaudeFirstPartySettings({ live: cfg(), persisted: cfg(), enabled: true, options: options() })) + .toMatchObject({ ok: false, reason: "unreadable" }); + + const disabled = cfg({ intercept: false }); + expect(previewClaudeFirstPartySettings({ live: disabled, persisted: disabled, enabled: true, options: options() })) + .toMatchObject({ ok: false, reason: "intercept_disabled" }); + }); + + test("the preview never creates the proxy token or the local CA", () => { + previewClaudeFirstPartySettings({ live: cfg(), persisted: cfg(), enabled: true, options: options() }); + expect(existsSync(claudeInterceptProxyTokenPath(root))).toBe(false); + expect(existsSync(claudeInterceptCaCertPath(root))).toBe(false); + }); +}); + +describe("turning CLI first-party off", () => { + test("a CLI-only env is removed, restoring NO_PROXY from its receipt", () => { + expect(realSwitch(cfg({ desktopMode: "gateway" }), cfg({ desktopMode: "gateway" }), true).ok).toBe(true); + const on = cfg({ cli: true, desktopMode: "gateway" }); + const changes = expectPreviewMatchesSwitch(on, false); + expect(changes.map(c => `${c.key}:${c.change}`).sort()).toEqual(["env.HTTPS_PROXY:remove", "env.NODE_EXTRA_CA_CERTS:remove", "env.NO_PROXY:remove"]); + }); + + test("a NO_PROXY the user edited after the apply is kept", () => { + expect(realSwitch(cfg({ desktopMode: "gateway" }), cfg({ desktopMode: "gateway" }), true).ok).toBe(true); + writeEnv({ ...env(), NO_PROXY: "edited.example" }); + const changes = expectPreviewMatchesSwitch(cfg({ cli: true, desktopMode: "gateway" }), false); + expect(changes.some(c => c.key === "env.NO_PROXY")).toBe(false); + }); + + test("an env Desktop still wants is retained, pinned or inferred", () => { + expect(realSwitch(cfg({ desktop: true }), cfg({ desktop: true }), true).ok).toBe(true); + expect(expectPreviewMatchesSwitch(cfg({ desktop: true, cli: true }), false)).toEqual([]); + // Unpinned: the transition pins the mode it observes after the flag clears. + const unpinned = cfg({ desktop: true, cli: true, desktopMode: null }); + expect(expectPreviewMatchesSwitch(unpinned, false)).toEqual([]); + }); + + test("the transition runs on the persisted config, not the live snapshot", () => { + expect(realSwitch(cfg({ desktop: true }), cfg({ desktop: true }), true).ok).toBe(true); + const live = cfg({ desktop: true, cli: true, desktopMode: null }); + const persisted = cfg({ desktop: true, cli: true, desktopMode: "gateway" }); + // Live alone would infer Desktop first-party and retain the env; the persisted pin releases it. + expect(previewClaudeFirstPartySettings({ live, persisted: live, enabled: false, options: options() })).toMatchObject({ ok: true, changes: [] }); + const changes = expectPreviewMatchesSwitch(live, false, persisted); + expect(changes.some(c => c.key === "env.NODE_EXTRA_CA_CERTS" && c.change === "remove")).toBe(true); + }); +}); + +describe("registered Claude homes", () => { + test("the default home comes first; extras are expanded, deduplicated, and only what is listed", () => { + const fakeHome = join(root, "user"); + const homes = registeredClaudeConfigDirs({ claudeCode: { extraConfigDirs: [ + "~/work-claude", join(root, "abs"), "relative/skip", join(fakeHome, ".claude"), "~/work-claude", + ] } } as OcxConfig, { HOME: fakeHome }); + expect(homes).toEqual([ + { dir: join(fakeHome, ".claude"), source: "default" }, + { dir: join(fakeHome, "work-claude"), source: "extra" }, + { dir: join(root, "abs"), source: "extra" }, + ]); + expect(registeredClaudeConfigDirs({ claudeCode: {} } as OcxConfig, { HOME: fakeHome })).toHaveLength(1); + }); +}); diff --git a/tests/cli/cli-headless-parity.test.ts b/tests/cli/cli-headless-parity.test.ts index b069b49a78c..2560b9056e6 100644 --- a/tests/cli/cli-headless-parity.test.ts +++ b/tests/cli/cli-headless-parity.test.ts @@ -646,6 +646,8 @@ describe("headless GUI parity CLI", () => { ["/api/routing-profiles", "ocx route policy"], ["/api/fallback", "ocx fallback"], ["/api/routing-analytics", "(none — GUI analytics surface; history via ocx observe/logs)"], + // Catch-up 010: the read-only Connections view; its CLI verb is a deferred-verb owned by 020. + ["/api/connections", "(none — read-only Connections view; CLI verb deferred in clients/connections.md)"], // Remote Workspace is one product family in both surfaces. The current CLI owns // executor pairing, presence, and local status; Hub/device/session inspection is // intentionally dashboard-only until the deferred Hub-status verbs documented in diff --git a/tests/fixtures/connection-restore-preview-runner.ts b/tests/fixtures/connection-restore-preview-runner.ts new file mode 100644 index 00000000000..fbdbabfa005 --- /dev/null +++ b/tests/fixtures/connection-restore-preview-runner.ts @@ -0,0 +1,82 @@ +/** + * Child process for tests/server/connection-status-routes.test.ts: the Codex restore preview + * oracle. The parent points CODEX_HOME, OPENCODEX_HOME and HOME at fresh temporary directories + * and this child refuses to start otherwise. Each scenario takes the read-only preview, then runs + * the real native restore on the same home and prints one JSON line with both key-level diffs. + * Config values never appear in the output. + */ +import { existsSync, mkdirSync, readFileSync, realpathSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, sep } from "node:path"; + +const temp = realpathSync.native(tmpdir()) + sep; +for (const name of ["CODEX_HOME", "OPENCODEX_HOME", "HOME"] as const) { + const value = process.env[name]; + if (!value || !realpathSync.native(value).startsWith(temp)) { + throw new Error("fixture requires " + name + " under the temporary directory"); + } +} +const home = process.env.CODEX_HOME!; +const { injectCodexConfig, restoreNativeCodexAsync } = await import("../../src/codex/inject"); +const { previewCodexNativeRestore, codexConfigKeyChanges } = await import("../../src/codex/restore-preview"); +const configPath = join(home, "config.toml"); +const profilePath = join(home, "opencodex.config.toml"); +const journalPath = join(home, "opencodex-journal.json"); +const [scenario = ""] = process.argv.slice(2); + +type InjectSettings = Parameters[1]; +async function inject(): Promise { + const settings = { port: 10100, providers: {}, defaultProvider: "openai", injectionModel: "gpt-5.6-sol", injectionEffort: "high" }; + const result = await injectCodexConfig(10100, settings as unknown as InjectSettings, { catalogPath: null }); + if (!result.success) throw new Error("fixture injection failed: " + result.message); +} +const readOrNull = (path: string): string | null => existsSync(path) ? readFileSync(path, "utf8") : null; + +switch (scenario) { + case "injected": await inject(); break; + case "edited": { + await inject(); + const text = readFileSync(configPath, "utf8"); + const firstTable = text.search(/^\[/m); + writeFileSync(configPath, text.slice(0, firstTable) + 'approval_policy = "never"\n' + text.slice(firstTable)); + break; + } + case "native": break; + case "profile-symlink": { + writeFileSync(configPath, 'model_provider = "opencodex"\n\n[model_providers.opencodex]\nname = "opencodex"\nbase_url = "http://127.0.0.1:10100/v1"\n'); + const target = join(process.env.HOME!, "profile-target.toml"); + writeFileSync(target, "# not ours\n"); + symlinkSync(target, profilePath); + break; + } + case "external-provider": + writeFileSync(configPath, 'model_provider = "corp"\n\n[model_providers.corp]\nname = "corp"\nbase_url = "https://gateway.example.test/v1"\n'); + break; + case "foreign-owner": { + await inject(); + const other = join(process.env.HOME!, "other-opencodex-home"); + mkdirSync(other, { recursive: true }); + const journal = JSON.parse(readFileSync(journalPath, "utf8")) as Record; + writeFileSync(journalPath, JSON.stringify({ ...journal, opencodexHome: other })); + break; + } + default: throw new Error("unknown scenario " + scenario); +} + +const beforeConfig = readOrNull(configPath); +const beforeProfile = readOrNull(profilePath); +const beforeJournal = readOrNull(journalPath); +const preview = previewCodexNativeRestore({ historyDisposition: () => ({ kind: "proceed" }) }); +const untouched = readOrNull(configPath) === beforeConfig && readOrNull(profilePath) === beforeProfile + && readOrNull(journalPath) === beforeJournal; +const restored = await restoreNativeCodexAsync(); +const afterConfig = readOrNull(configPath); +const afterProfile = readOrNull(profilePath); +const actual = [ + ...codexConfigKeyChanges(beforeConfig, afterConfig), + ...(beforeProfile === afterProfile ? [] : [{ + file: "opencodex.config.toml", key: "*", + change: beforeProfile === null ? "add" : afterProfile === null ? "remove" : "update", + }]), +]; +console.log(JSON.stringify({ preview, actual, success: restored.success, untouched })); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index f91b3cd8849..0330e14613e 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -555,6 +555,7 @@ "claude-estimate-projection.test.ts": "claude-integration", "claude-first-party-agent-sync.test.ts": "claude-integration", "claude-first-party-union.test.ts": "claude-integration", "claude-desktop-system-proxy.test.ts": "claude-integration", + "claude-first-party-preview.test.ts": "claude-integration", "connection-status-routes.test.ts": "server", "claude-gateway-cache.test.ts": "claude-integration", "claude-config-home-isolation.test.ts": "claude-integration", "claude-inbound-cache-stabilize.test.ts": "claude-integration", "claude-inbound-token-footer.test.ts": "claude-integration", "claude-inbound-debug.test.ts": "claude-integration", "claude-inbound.test.ts": "claude-integration", "claude-inbound-tool-loading.test.ts": "claude-integration", "claude-chat-tool-dispatch.test.ts": "claude-integration", diff --git a/tests/server/connection-status-routes.test.ts b/tests/server/connection-status-routes.test.ts new file mode 100644 index 00000000000..a5fc13c12be --- /dev/null +++ b/tests/server/connection-status-routes.test.ts @@ -0,0 +1,341 @@ +/** + * Catch-up 010 (G-001, G-002): the read-only Connections view and the Claude first-party + * preview route. Proves the acceptance list: an external owner is named with its file, a refused + * Codex switch points at this view, extra Claude homes appear only when registered, the preview + * names keys and change kinds without values, and neither GET writes a byte. The Codex restore + * preview is checked against the real restore in a child process with temporary homes. + */ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { handleManagementAPI } from "../../src/server/management-api"; +import type { ManagementApiDeps } from "../../src/server/management/context"; +import type { ConnectionView } from "../../src/integrations/connection-view"; +import { displayPath } from "../../src/lib/display-path"; +import { codexConfigKeyChanges, displayCodexConfigKey, previewCodexNativeRestore } from "../../src/codex/restore-preview"; +import { inspectNativeCodexOwnership, inspectRecordedServiceOwnership } from "../../src/integrations/native/ownership-preflight"; +import { CODEX_CONFIG_PATH, CODEX_PROFILE_PATH } from "../../src/codex/paths"; +import * as serviceManagerProbe from "../../src/service-manager-probe"; +import type { OcxConfig } from "../../src/types"; +import { fixturePath, repoRoot } from "../helpers/repo-root"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { SPAWN_BUDGET_MS } from "../helpers/test-budget"; + +let root = ""; +let codexHome = ""; +let claudeHome = ""; +const saved: Record = {}; +const ENV_KEYS = ["OPENCODEX_HOME", "CODEX_HOME", "CLAUDE_CONFIG_DIR", "OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR"] as const; +let restoreProbe = () => {}; + +function baseConfig(extra: Partial = {}): OcxConfig { + return { port: 10100, providers: {}, defaultProvider: "openai", ...extra } as OcxConfig; +} + +function dispatch(config: OcxConfig, path: string, init?: RequestInit) { + const url = new URL(`http://127.0.0.1:10100${path}`); + return handleManagementAPI( + new Request(url, { ...init, headers: { Host: url.host, ...(init?.headers ?? {}) } }), + url, + config, + { fetchAllModels: async () => [] as never, getClaudeInterceptState: () => null } as unknown as ManagementApiDeps, + ); +} + +async function connections(config: OcxConfig = baseConfig()): Promise { + const response = await dispatch(config, "/api/connections"); + expect(response!.status).toBe(200); + return ((await response!.json()) as { connections: ConnectionView[] }).connections; +} + +function snapshot(dir = root): Record { + const out: Record = {}; + if (!existsSync(dir)) return out; + for (const name of readdirSync(dir)) { + const path = join(dir, name); + if (statSync(path).isDirectory()) Object.assign(out, snapshot(path)); + else out[path] = readFileSync(path, "base64"); + } + return out; +} + +function writeServiceState(codexHomeInState: string): void { + writeFileSync(join(root, "service-state.json"), JSON.stringify({ + version: 2, codexHome: codexHomeInState, opencodexHome: root, backend: "scheduler", + })); +} + +beforeEach(() => { + for (const key of ENV_KEYS) saved[key] = process.env[key]; + root = realpathSync.native(mkdtempSync(join(tmpdir(), "ocx-connections-"))); + codexHome = join(root, "codex"); + claudeHome = join(root, "claude"); + mkdirSync(codexHome); + process.env.OPENCODEX_HOME = root; + process.env.CODEX_HOME = codexHome; + process.env.CLAUDE_CONFIG_DIR = claudeHome; + process.env.OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR = join(root, "library"); + writeFileSync(join(root, "config.json"), JSON.stringify(baseConfig(), null, 2)); + writeServiceState(codexHome); + // The GET must not consult the service manager (it spawns processes); fail loudly if it does. + const probe = spyOn(serviceManagerProbe, "inspectServiceManagerInstallation").mockImplementation(() => { + throw new Error("the connections view must not probe the service manager"); + }); + restoreProbe = () => probe.mockRestore(); +}); + +afterEach(() => { + restoreProbe(); + for (const key of ENV_KEYS) { + if (saved[key] === undefined) delete process.env[key]; + else process.env[key] = saved[key]; + } + removeTreeWithRetry(root); +}); + +describe("Codex row", () => { + test("a recorded service for another home is external_owner with its state file", async () => { + writeServiceState(join(root, "someone-elses-codex")); + const codex = (await connections()).find(row => row.client === "codex")!; + expect(codex.owner).toBe("external"); + expect(codex.driftReasons).toContain("external_owner"); + expect(codex.ownerPath).toBe(displayPath(join(root, "service-state.json"))); + }); + + test("the refused Codex switch-off points at the view, which names the owner", async () => { + writeServiceState(join(root, "someone-elses-codex")); + restoreProbe(); + const probe = spyOn(serviceManagerProbe, "inspectServiceManagerInstallation").mockReturnValue({ kind: "absent" }); + const response = await dispatch(baseConfig(), "/api/native-integrations/codex", { + method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ enabled: false }), + }); + probe.mockRestore(); + const body = await response!.json() as Record; + expect(body.connections).toBe("/api/connections"); + expect(body.reason).toBe("restore_incomplete"); + const codex = (await connections()).find(row => row.client === "codex")!; + expect(codex).toMatchObject({ owner: "external", restorePreview: { outcome: "refused_owner" } }); + }); + + // config.toml is the process-lifetime path restore writes through (the preload's sandbox home). + const withCodexConfig = async (content: string, run: () => Promise) => { + mkdirSync(dirname(CODEX_CONFIG_PATH), { recursive: true }); + writeFileSync(CODEX_CONFIG_PATH, content); + try { await run(); } finally { removeTreeWithRetry(CODEX_CONFIG_PATH); } + }; + + test("an external provider in config.toml is foreign and owned by that file", () => withCodexConfig( + 'model_provider = "corp"\n\n[model_providers.corp]\nname = "corp"\nbase_url = "https://gateway.example.test/v1"\n', + async () => { + const codex = (await connections()).find(row => row.client === "codex")!; + expect(codex).toMatchObject({ observed: "foreign", owner: "external", ownerPath: displayPath(CODEX_CONFIG_PATH) }); + }, + )); + + test("wanted but native is file_edited; switched off and native has no drift", () => withCodexConfig('model = "gpt-5.5"\n', async () => { + expect((await connections()).find(row => row.client === "codex")).toMatchObject({ + desired: "proxy", observed: "native", owner: "none", driftReasons: ["file_edited"], + }); + const off = baseConfig({ clientIntegrations: { codex: false } }); + writeFileSync(join(root, "config.json"), JSON.stringify(off, null, 2)); + expect((await connections(off)).find(row => row.client === "codex")).toMatchObject({ desired: "native", driftReasons: [] }); + })); + + test("a hub without the loopback listener is hub_gated", async () => { + const hub = baseConfig({ runtimeRole: "hub" } as Partial); + writeFileSync(join(root, "config.json"), JSON.stringify(hub, null, 2)); + expect((await connections(hub)).find(row => row.client === "codex")).toMatchObject({ owner: "hub", driftReasons: ["hub_gated"] }); + }); +}); + +describe("Claude rows", () => { + test("extra homes appear only when registered, separately, with masked identity segments", async () => { + const extra = join(root, "person@example.com", "claude-work"); + const unregistered = join(root, "claude-unregistered"); + mkdirSync(extra, { recursive: true }); + mkdirSync(unregistered, { recursive: true }); + writeFileSync(join(extra, "settings.json"), JSON.stringify({ env: { HTTPS_PROXY: "http://proxy.corp:8080", NODE_EXTRA_CA_CERTS: "/corp/ca.pem" } })); + const config = baseConfig({ claudeCode: { extraConfigDirs: [extra] } } as Partial); + const rows = (await connections(config)).filter(row => row.client === "claude-code"); + expect(rows.map(row => row.homeSource)).toEqual(["default", "extra"]); + expect(rows[1]).toMatchObject({ desired: "unset", observed: "foreign", owner: "external", driftReasons: [] }); + const serialized = JSON.stringify(rows); + expect(serialized).not.toContain("person@example.com"); + expect(serialized).not.toContain("claude-unregistered"); + expect(serialized).not.toContain("proxy.corp"); + expect(rows[1]!.home).toContain("…"); + expect((await connections()).filter(row => row.client === "claude-code")).toHaveLength(1); + }); + + test("CLI first-party wanted with no settings is file_edited and carries a switch-off preview", async () => { + const config = baseConfig({ claudeCode: { cliFirstParty: true } } as Partial); + const row = (await connections(config)).find(view => view.client === "claude-code" && view.homeSource === "default")!; + expect(row).toMatchObject({ desired: "proxy", observed: "missing", driftReasons: ["file_edited"] }); + expect(row.restorePreview).toEqual({ outcome: "restore", changes: [] }); + }); +}); + +describe("GET /api/claude-code/first-party/preview", () => { + test("names keys and change kinds, never values, and writes nothing", async () => { + const before = snapshot(); + const response = await dispatch(baseConfig(), "/api/claude-code/first-party/preview?enabled=true"); + expect(response!.status).toBe(200); + const body = await response!.json() as { path: string; changes: Array<{ key: string; change: string }> }; + expect(body.changes.map(c => `${c.key}:${c.change}`).sort()).toEqual(["env.HTTPS_PROXY:add", "env.NODE_EXTRA_CA_CERTS:add", "env.NO_PROXY:add"]); + expect(body.path).toBe(displayPath(join(claudeHome, "settings.json"))); + expect(JSON.stringify(body)).not.toContain("127.0.0.1"); + expect(snapshot()).toEqual(before); + }); + + test("refusals use the switch's codes; a malformed enabled is a 400", async () => { + mkdirSync(claudeHome, { recursive: true }); + writeFileSync(join(claudeHome, "settings.json"), JSON.stringify({ env: { HTTPS_PROXY: "http://proxy.corp:8080", NODE_EXTRA_CA_CERTS: "/corp/ca.pem" } })); + const refused = await dispatch(baseConfig(), "/api/claude-code/first-party/preview?enabled=true"); + expect(refused!.status).toBe(409); + expect(await refused!.json()).toMatchObject({ code: "foreign_env" }); + const bad = await dispatch(baseConfig(), "/api/claude-code/first-party/preview?enabled=maybe"); + expect(bad!.status).toBe(400); + }); +}); + +test("GET /api/connections leaves every byte alone, including a corrupt Codex journal", async () => { + writeFileSync(join(codexHome, "opencodex-journal.json"), "{corrupt"); + writeFileSync(join(codexHome, "config.toml"), 'model = "gpt-5.5"\n'); + const before = snapshot(); + const rows = await connections(); + expect(rows.find(row => row.client === "codex")?.owner).toBe("unknown"); + expect(snapshot()).toEqual(before); +}); + +describe("Codex restore preview matches the real restore", () => { + for (const [scenario, outcome] of [ + ["injected", "restore"], ["edited", "restore"], ["native", "restore"], + ["external-provider", "restore"], ["foreign-owner", "refused_owner"], + ["profile-symlink", "refused_profile"], + ] as const) { + test(scenario, () => { + const homes = realpathSync.native(mkdtempSync(join(tmpdir(), "ocx-restore-preview-"))); + try { + for (const dir of ["codex", "ocx", "home"]) mkdirSync(join(homes, dir), { recursive: true }); + writeFileSync(join(homes, "codex", "config.toml"), 'model = "gpt-5.5"\n\n[projects."/fixture/existing"]\ntrust_level = "trusted"\n'); + const result = spawnSync(process.execPath, [fixturePath("connection-restore-preview-runner.ts"), scenario], { + cwd: repoRoot(), + env: { ...process.env, CODEX_HOME: join(homes, "codex"), OPENCODEX_HOME: join(homes, "ocx"), HOME: join(homes, "home") }, + encoding: "utf8", timeout: SPAWN_BUDGET_MS - 5_000, killSignal: "SIGKILL", + }); + if (result.status !== 0) throw new Error(`runner failed: ${result.stderr.slice(-3000)}`); + const report = JSON.parse(result.stdout.trim().split("\n").at(-1)!) as { + preview: { outcome: string; changes: unknown[] }; actual: unknown[]; success: boolean; untouched: boolean; + }; + expect(report.untouched).toBe(true); + expect(report.preview.outcome).toBe(outcome); + expect(report.success).toBe(outcome === "restore"); + expect(report.preview.changes).toEqual(report.actual); + if (scenario === "injected" || scenario === "edited") expect(report.actual.length).toBeGreaterThan(0); + } finally { + removeTreeWithRetry(homes); + } + }, SPAWN_BUDGET_MS); + } +}); + +// Built at runtime so the source carries no token-looking literal (privacy:scan). +const LONG_TOKEN = ["tok", "x".repeat(48)].join("-"); + +describe("restore preview privacy and ownership evidence", () => { + test("table names that can carry identity are masked; managed keys stay readable", () => { + const before = [ + 'sk_token = "x"', + 'openai_base_url = "http://127.0.0.1:10100/v1"', + '[projects."/Users/person@example.com/repo"]', 'trust_level = "trusted"', + `[model_providers.${LONG_TOKEN}]`, 'base_url = "https://x.test"', + "[model_providers.sk-secret-123]", 'base_url = "https://y.test"', + "[profiles.alice]", 'model = "gpt-5.5"', + "[mcp_servers.tools.env]", 'sk_live_abc = "x"', + "[model_providers.opencodex]", 'name = "opencodex"', + ].join("\n"); + const changes = codexConfigKeyChanges(before, ""); + const serialized = JSON.stringify(changes); + for (const planted of ["person@example.com", LONG_TOKEN, "/Users/", "sk-secret-123", "alice", "sk_live_abc", "sk_token"]) { + expect(serialized).not.toContain(planted); + } + expect(changes.map(change => change.key)).toEqual(expect.arrayContaining([ + "openai_base_url", "model_providers.opencodex.name", "projects.….trust_level", "model_providers.….base_url", + "profiles.….model", "mcp_servers.….….…", "…", + ])); + expect(displayCodexConfigKey('hooks.state."plugin:demo:hook".trusted_hash')).toBe("hooks.state.….trusted_hash"); + expect(displayCodexConfigKey("model_providers.sk-secret-123.base_url")).toBe("model_providers.….base_url"); + }); + + test("a service manager claim alone never makes restore refuse, so the GET need not probe it", () => { + // Restore refuses only on ownership "foreign" (restore.ts), and only the recorded service + // state yields it; a manager definition naming other homes is "unknown". The preview reads + // the recorded state and therefore agrees with restore without spawning the probe. + const stateFile = join(root, "service-state.json"); + restoreProbe(); + const probe = spyOn(serviceManagerProbe, "inspectServiceManagerInstallation").mockReturnValue({ + kind: "present", + claims: [{ backend: "launchd", definitionPath: join(root, "agent.plist"), homes: { codexHome: join(root, "elsewhere"), opencodexHome: join(root, "elsewhere-ocx") } }], + } as never); + try { + const full = inspectNativeCodexOwnership({ statePaths: [stateFile], currentHomes: { codexHome, opencodexHome: root } }); + expect(full.ownership).not.toBe("foreign"); + expect(inspectRecordedServiceOwnership({ statePaths: [stateFile], currentHomes: { codexHome, opencodexHome: root } })).toBeNull(); + } finally { + probe.mockRestore(); + } + }); +}); + +describe("security bounds", () => { + test("arbitrary path segments are masked; only fixed names and the home prefix show", async () => { + const extra = join(root, "profiles", "account-123", "token-value"); + mkdirSync(extra, { recursive: true }); + const config = baseConfig({ claudeCode: { extraConfigDirs: [extra] } } as Partial); + const rows = (await connections(config)).filter(row => row.client === "claude-code"); + const serialized = JSON.stringify(rows); + expect(serialized).not.toContain("account-123"); + expect(serialized).not.toContain("token-value"); + expect(rows[1]).toMatchObject({ homeSource: "extra", homeOrdinal: 1 }); + expect(displayPath("/home-fixture/someone/.claude/settings.json", "/home-fixture/someone")).toBe("~/.claude/settings.json"); + expect(displayPath("/srv/acct-9/secret/config.toml", "/home-fixture/someone")).toBe("/…/config.toml"); + }); + + test.skipIf(process.platform === "win32")("a FIFO settings.json in a registered home is not read and does not block", async () => { + const extra = join(root, "fifo-home"); + mkdirSync(extra, { recursive: true }); + const made = spawnSync("mkfifo", [join(extra, "settings.json")]); + expect(made.status).toBe(0); + const config = baseConfig({ claudeCode: { extraConfigDirs: [extra] } } as Partial); + const row = (await connections(config)).find(view => view.homeSource === "extra")!; + expect(row).toMatchObject({ observed: "unknown", owner: "unknown", driftReasons: [] }); + }); + + test("an oversized default settings.json makes the preview refuse instead of reading it", async () => { + mkdirSync(claudeHome, { recursive: true }); + writeFileSync(join(claudeHome, "settings.json"), `{"pad":"${"x".repeat(1024 * 1024 + 16)}"}`); + const response = await dispatch(baseConfig(), "/api/claude-code/first-party/preview?enabled=true"); + expect(response!.status).toBe(500); + expect(await response!.json()).toMatchObject({ code: "unreadable" }); + }); + + test("registered homes are capped", async () => { + const extras = Array.from({ length: 20 }, (_, index) => join(root, `home-${index}`)); + const config = baseConfig({ claudeCode: { extraConfigDirs: extras } } as Partial); + const rows = (await connections(config)).filter(row => row.homeSource === "extra"); + expect(rows).toHaveLength(16); + expect(rows.at(-1)?.homeOrdinal).toBe(16); + }); + + test("an oversized Codex profile makes the restore preview unreadable instead of reading it", () => { + mkdirSync(dirname(CODEX_PROFILE_PATH), { recursive: true }); + writeFileSync(CODEX_PROFILE_PATH, "#".repeat(1024 * 1024 + 16)); + try { + expect(previewCodexNativeRestore({ historyDisposition: () => ({ kind: "proceed" }) }).outcome).toBe("unreadable"); + } finally { + removeTreeWithRetry(CODEX_PROFILE_PATH); + } + }); +}); From 85a35eafb085ae3ce5ef577b6c2ea8b5bf250178 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Wed, 25 Nov 2026 12:50:50 +0900 Subject: [PATCH 12/60] docs: point security support and reproduction to dev (#9059) Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- SECURITY.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index ec415e969e0..74f3ea65514 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -6,11 +6,11 @@ opencodex accepts security fixes on a best-effort basis for these lines: | Version | Supported | | --- | --- | -| `main` | ✅ | +| `dev` | ✅ | | Latest published npm release | ✅ | | Older releases | ❌ | -If you report an issue against an older release, maintainers may ask you to reproduce it on `main` +If you report an issue against an older release, maintainers may ask you to reproduce it on `dev` or the latest published package before triage continues. ## Reporting a Vulnerability From 89614765bdd8206b6285df57c6b0ecae5c9d6346 Mon Sep 17 00:00:00 2001 From: Enes Kartal <43950508+EnesKartal@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:52:24 +0300 Subject: [PATCH 13/60] fix(providers): send x-opencode-session in opencode-go completion test (#9079) * fix(providers): send x-opencode-session in opencode-go completion test * Fix OpenCode Go Responses diagnostic session header --------- Co-authored-by: JUN Co-authored-by: lidge-jun --- .../management/provider-completion-test.ts | 7 +++-- structure/provider-completion-diagnostic.md | 2 +- .../provider-completion-test.test.ts | 26 +++++++++++++++++++ 3 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/server/management/provider-completion-test.ts b/src/server/management/provider-completion-test.ts index fbb559e08c0..63cfcc144c7 100644 --- a/src/server/management/provider-completion-test.ts +++ b/src/server/management/provider-completion-test.ts @@ -12,6 +12,7 @@ import { resolveWireProtocolOverride } from "../adapter-resolve"; import { openAIChatTransport, stripBracketedModelSuffix } from "../../adapters/openai-chat/wire"; import { buildResponsesTransport } from "../../adapters/openai-responses/transport"; import { openRouterProviderPayload, resolveOpenRouterRouting } from "../../providers/openrouter-routing"; +import { resolveOpenCodeGoTransport } from "../../providers/opencode-go-transport"; import { resolveVercelGatewayRouting, vercelGatewayProviderPayload } from "../../providers/vercel-gateway-routing"; import { assertProviderDestinationAllowed, providerAllowsPrivateNetwork } from "../../lib/destination-policy"; import { providerOutboundPost, ProviderOutboundPolicyError, ProviderOutboundSendCancelledError, @@ -79,9 +80,11 @@ function nativeModel(config: OcxConfig, name: string, row: OcxProviderConfig, mo function derive(config: OcxConfig, name: string, row: OcxProviderConfig, model: string) { const resolved = routedProviderConfig(name, row); const native = nativeModel(config, name, resolved, model); - const routed = resolveWireProtocolOverride(name, native, resolved); - const wire = routed.adapter; + const wireProvider = resolveWireProtocolOverride(name, native, resolved); + const wire = wireProvider.adapter; if (wire !== "openai-chat" && wire !== "openai-responses") throw new Error("unsupported adapter"); + const destination = resolved.adapter === "openai-responses" ? { ...resolved, adapter: "openai-chat" as const } : resolved; + const routed = resolveOpenCodeGoTransport(wireProvider, `provider-completion-test:${name}:${model}`, destination); const transport = wire === "openai-chat" ? openAIChatTransport(routed) : buildResponsesTransport(routed, { headers: new Headers() }); const headers = new Headers(transport.headers); diff --git a/structure/provider-completion-diagnostic.md b/structure/provider-completion-diagnostic.md index 133671184ca..102c512a7df 100644 --- a/structure/provider-completion-diagnostic.md +++ b/structure/provider-completion-diagnostic.md @@ -6,7 +6,7 @@ Provider routes lazily dispatch `POST /api/providers/test-completion?name=...` t Applicability checks disabled state, forwarded/OAuth auth, unsupported transports and effective per-model wire before credentials. TLS profiles, HTTP-version pins, enabled pacing and custom executors with provider proxy overrides are unsupported. Metadata routing removes stored keys/pools; destination policy precedes real key resolution. Only OpenAI Chat and Responses execute, through existing transport builders and `providerOutboundPost`, without redirects, retries or failover. Both applicability and authority derivation resolve aliases to native model ids before selecting per-model wires, then apply wire-model suffix stripping through existing helpers. -Local HTTP probes materialize the existing effective private-network policy (operator opt-in or a registry-local default) and enable `providerOutboundPost`'s local-cleartext safeguard. Its narrow host/address allowlist, DNS-answer checks and proxy refusal still apply; public HTTP and private destinations without admission are refused. Chat probes resolve OpenRouter and Vercel AI Gateway routing with the same helpers as the chat adapter, keyed by the native model before suffix stripping, and serialize the resulting `provider` field. Responses does not synthesize that chat-only field. +Local HTTP probes materialize the existing effective private-network policy (operator opt-in or a registry-local default) and enable `providerOutboundPost`'s local-cleartext safeguard. Its narrow host/address allowlist, DNS-answer checks and proxy refusal still apply; public HTTP and private destinations without admission are refused. Chat probes resolve OpenRouter and Vercel AI Gateway routing with the same helpers as the chat adapter, keyed by the native model before suffix stripping, and serialize the resulting `provider` field. Responses does not synthesize that chat-only field. Canonical OpenCode Go Chat and Responses probes derive a stable provider/model and wire-scoped `x-opencode-session` value; an explicitly configured header takes precedence, and other destinations receive no generated Go header. A memory-only fingerprint captures wire, URL, wire model, computed gateway routing, local-cleartext admission, sorted headers, auth, key selection/resolved key, destination policy, egress and disabled state. Before physical send the same live row must reproduce it, with current key-selection authority for credentialed rows; changes return `credential_changed` with no send. diff --git a/tests/providers/provider-completion-test.test.ts b/tests/providers/provider-completion-test.test.ts index ee77a4e1114..c6963b4c098 100644 --- a/tests/providers/provider-completion-test.test.ts +++ b/tests/providers/provider-completion-test.test.ts @@ -310,4 +310,30 @@ describe("failure classification and cleanup", () => { expect(await f.run("test-model", {}, AbortSignal.abort())).toMatchObject({ error: { code: "aborted" } }); expect(f.calls).toHaveLength(0); }); + test("opencode-go completion test sends deterministic x-opencode-session header", async () => { + const f = fixture({ baseUrl: "https://opencode.ai/zen/go/v1" }); + f.config.providers["opencode-go"] = f.row; + const res = await runProviderCompletionTest({ config: f.config, name: "opencode-go", model: "glm-5" }); + expect(res).toMatchObject({ ok: true, wire: "openai-chat" }); + expect(f.calls).toHaveLength(1); + expect(new Headers(f.calls[0]?.init?.headers).get("x-opencode-session")).toBeTruthy(); + }); + for (const wire of ["openai-chat", "openai-responses"] as const) test(`Go ${wire} session is stable and respects explicit headers`, async () => { + const payload = wire === "openai-chat" ? chat() : frame({ type: "response.output_text.delta", delta: "OK" }) + frame({ type: "response.completed" }); + const f = fixture({ adapter: wire, baseUrl: "https://opencode.ai/zen/go/v1" }, () => new Response(payload)); + expect(await f.run()).toMatchObject({ ok: true, wire }); + expect(await f.run()).toMatchObject({ ok: true, wire }); + const header = (i: number) => new Headers(f.calls[i]!.init!.headers).get("x-opencode-session"); + expect(header(0)).toMatch(/^ocx_[a-f0-9]{32}$/); + expect(header(1)).toBe(header(0)); + f.row.headers = { "X-OpenCode-Session": "explicit-session" }; + expect(await f.run()).toMatchObject({ ok: true }); + expect(header(2)).toBe("explicit-session"); + }); + for (const baseUrl of ["https://provider.example/v1", "https://opencode.ai/zen/go/v1/other"]) test(`no Go session for ${baseUrl}`, async () => { + const f = fixture({ adapter: "openai-responses", baseUrl }, () => new Response(frame({ type: "response.output_text.delta", delta: "OK" }) + frame({ type: "response.completed" }))); + expect(await f.run()).toMatchObject({ ok: true }); + expect(new Headers(f.calls[0]!.init!.headers).has("x-opencode-session")).toBe(false); + }); + }); From 8d43c92f840bcb57cbf7b5eea8c485e8aa89dc7e Mon Sep 17 00:00:00 2001 From: bokjk <32791704+bokjk@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:54:18 +0900 Subject: [PATCH 14/60] fix(service): stop an update wedging on its own teardown receipts (#8960) (#9062) * fix(service): stop an update wedging on its own teardown receipts (#8960) A Windows `ocx update` claims its handover receipt before the checked stop's Part A admission. When admission refused `unverified-budget` (nothing changed), the receipt stayed on disk. The next stop inherited it and budgeted another 3 s probe on a ~53.5 s baseline against a 60 s deadline, so each refused retry needed more time than the last and the update wedged permanently. - A held snapshotless Part A that changed nothing removes the receipt this run claimed (`windowsPartAHeldUnchanged`): it describes a stop that never happened. - Admission budgets one probe per distinct exact endpoint among inherited receipts (`inheritedTeardownProbeCount`), and the recovery pass asks each endpoint once (`abandonedTeardownProbeOncePerEndpoint`). Invalid, unscannable and guessed-endpoint receipts block without probing, so they cost nothing. Co-Authored-By: Claude Opus 5.5 * test(service): an inherited receipt survives an unchanged refused handover --------- Co-authored-by: Claude Opus 5.5 Co-authored-by: JUN --- src/cli/index.ts | 14 ++-- src/cli/stop-restore.ts | 38 +++++++++++ src/cli/stop-windows-checked.ts | 11 ++++ structure/ops/windows-checked-stop.md | 13 +++- tests/windows/windows-stop-ocx-stop.test.ts | 72 ++++++++++++++++++++- 5 files changed, 140 insertions(+), 8 deletions(-) diff --git a/src/cli/index.ts b/src/cli/index.ts index dbb8978c7fb..9d97024f7b8 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -72,6 +72,7 @@ import { import { describeTrackedRuntimeTarget } from "../config/tracked-runtime-inspection"; import { claimPendingTeardown, + clearPendingTeardown, isPendingTeardownAbandoned, listPendingTeardowns, pendingTeardownPathFor, @@ -126,7 +127,7 @@ import { type StopApproval, } from "./stop-approval"; import { summarizeStopRun, type StopOutcome, type StopRunRecord } from "./stop-report"; -import { confirmGuardedFreed, inspectGuardedTarget, noServiceStop, observeGuardedStopped, orphanDiscoveryCap, stopGuardedManager, stopServiceForOcxStop, stopServiceForUninstall, stopWindowFailed, verifyUninstallStopWindow, windowsChildStopHeld, windowsPartAHolds, windowsPartAReceiptRecord, windowsPartBDue, windowsPartBOwnsPortWait, windowsStopRequiresReceipt } from "./stop-windows-checked"; +import { confirmGuardedFreed, inspectGuardedTarget, noServiceStop, observeGuardedStopped, orphanDiscoveryCap, stopGuardedManager, stopServiceForOcxStop, stopServiceForUninstall, stopWindowFailed, verifyUninstallStopWindow, windowsChildStopHeld, windowsPartAHeldUnchanged, windowsPartAHolds, windowsPartAReceiptRecord, windowsPartBDue, windowsPartBOwnsPortWait, windowsStopRequiresReceipt } from "./stop-windows-checked"; import { runCli } from "./root"; import { isProcessAlive, ProxyOwnershipRefusedError, refusalNextStep, stopProxy } from "../lib/process-control"; import { startupDataPlaneToken } from "../lib/service-secrets"; @@ -166,7 +167,7 @@ import { uninstallPrivilegeRefusal } from "../lib/config-ownership"; import { withProcessRuntimeProvenance } from "../lib/bun-runtime"; import { startArgv } from "../lib/self-launch-argv"; import { initializeNodeLauncherContext } from "./launcher-context"; -import { abandonedTeardownIsSafeToFinish, assertConnectedClientStopSupported, classifyStopRole, clearRestoredStopReceipts, configuredStopEndpoint, connectedClientStopSkipLine, isRegisteredServiceStopTarget, notOwnedTeardownIsAcceptable, preflightConnectedClientStop, preserveConnectedClientRoutingOnExit, proveStandaloneStopRecord, restoreBoundaryOwnership, restoreSharedClientStateAfterStop, settleUnrestoredStopBoundary, stopOwnershipRefused, unclassifiedStopTarget, unsupportedConnectedStop, verifyConnectedStopTarget, type LinkStopPreflight, type StopTargetProof } from "./stop-restore"; +import { abandonedTeardownProbeOncePerEndpoint, assertConnectedClientStopSupported, classifyStopRole, clearRestoredStopReceipts, configuredStopEndpoint, connectedClientStopSkipLine, inheritedTeardownProbeCount, isRegisteredServiceStopTarget, notOwnedTeardownIsAcceptable, preflightConnectedClientStop, preserveConnectedClientRoutingOnExit, proveStandaloneStopRecord, restoreBoundaryOwnership, restoreSharedClientStateAfterStop, settleUnrestoredStopBoundary, stopOwnershipRefused, unclassifiedStopTarget, unsupportedConnectedStop, verifyConnectedStopTarget, type LinkStopPreflight, type StopTargetProof } from "./stop-restore"; import { stopRestoreWriteGuard } from "./stop-restore-guard"; import { startConnectedClientWithOwnershipFence } from "./client-start-fence"; import { recoverStartJournalAfterOwnerRecheck, recoverStartStateUnderOwnershipLease } from "./start-owner-fence"; @@ -1198,7 +1199,7 @@ async function handleStopUnlocked(snapshot: GuardedStopSnapshot | undefined, onF stopManager: () => { verifyStopTarget(); if (approvedEndpoint) claimTeardown(approvedEndpoint, "exact"); - return stopGuardedManager({ approvedPort: snapshot.approval.port, receiptNonce: () => teardownNonce, inheritedReceipts: inheritedTeardowns.length }); + return stopGuardedManager({ approvedPort: snapshot.approval.port, receiptNonce: () => teardownNonce, inheritedReceipts: inheritedTeardownProbeCount(inheritedTeardowns) }); }, signalApproved: () => stopWithDeferral(snapshot.approval.pid, approvedEndpoint), settle: () => settleApprovedTarget(snapshot.approval), @@ -1213,7 +1214,7 @@ async function handleStopUnlocked(snapshot: GuardedStopSnapshot | undefined, onF const linkEndpoint = linkStop && endpointOf(linkStop.target); if (linkEndpoint) claimTeardown(linkEndpoint, "exact"); else claimHandoverBeforeManager(); - return stopServiceForOcxStop({ receiptNonce: () => teardownNonce, inheritedReceipts: inheritedTeardowns.length }); + return stopServiceForOcxStop({ receiptNonce: () => teardownNonce, inheritedReceipts: inheritedTeardownProbeCount(inheritedTeardowns) }); })(); record.service = serviceStop; stoppedService = serviceStop === "stopped" || serviceStop === "stopped-respawnable"; @@ -1236,6 +1237,10 @@ async function handleStopUnlocked(snapshot: GuardedStopSnapshot | undefined, onF console.error(" Run 'ocx service status' to see the query error, repair Task Scheduler access, then retry."); } ownershipBlocked = windowsPartAHolds(record) || ownershipBlocked; // #7771: no POST and no shared teardown. + // #8960: a held Part A that changed nothing owes no teardown, so the receipt this run claimed + // before it goes too. Kept, the next stop inherits it and budgets one more probe, so each + // refused retry needed more time than the last and an update could wedge for good. + if (teardownNonce && windowsPartAHeldUnchanged() && clearPendingTeardown(teardownNonce)) teardownNonce = undefined; } catch (err) { record.service = "error"; if (err instanceof ProxyOwnershipRefusedError || isServiceOwnershipError(err) || windowsChildStopHeld()) { @@ -1395,6 +1400,7 @@ async function handleStopUnlocked(snapshot: GuardedStopSnapshot | undefined, onF const unreadable: { nonce: string }[] = []; let inheritedBlocks = false; if (inheritedTeardowns.length > 0 && !ownershipBlocked) { + const abandonedTeardownIsSafeToFinish = abandonedTeardownProbeOncePerEndpoint(); for (const read of inheritedTeardowns) { if (read.state === "unscannable") { // No file, no nonce: nothing to quarantine and nothing to remove. The home itself diff --git a/src/cli/stop-restore.ts b/src/cli/stop-restore.ts index d0ec6c18945..91bd22f7f37 100644 --- a/src/cli/stop-restore.ts +++ b/src/cli/stop-restore.ts @@ -217,6 +217,44 @@ export async function abandonedTeardownIsSafeToFinish( } } +function teardownEndpointKey(endpoint: { hostname: string; port: number }): string { + return JSON.stringify([endpoint.hostname, endpoint.port]); +} + +/** + * The liveness probes an inherited-receipt recovery will run: one per distinct exact endpoint + * (#8960). An unscannable, invalid or guessed-endpoint receipt blocks without probing, and + * receipts naming the same endpoint ask the same question, so they share one probe. Counting + * receipts instead let repeated failed stops against one proxy grow the admission budget + * without bound. + */ +export function inheritedTeardownProbeCount(reads: readonly OutstandingTeardown[]): number { + const endpoints = new Set(); + for (const read of reads) { + if (read.state === "valid" && read.receipt.endpointSource !== "guessed") endpoints.add(teardownEndpointKey(read.receipt.endpoint)); + } + return endpoints.size; +} + +/** + * `abandonedTeardownIsSafeToFinish`, asked once per endpoint within one recovery pass, so the + * pass runs exactly the probes `inheritedTeardownProbeCount` budgeted (#8960). + */ +export function abandonedTeardownProbeOncePerEndpoint( + probe: (endpoint: { hostname: string; port: number }) => Promise = abandonedTeardownIsSafeToFinish, +): (endpoint: { hostname: string; port: number }) => Promise { + const answers = new Map>(); + return endpoint => { + const key = teardownEndpointKey(endpoint); + let answer = answers.get(key); + if (!answer) { + answer = probe(endpoint); + answers.set(key, answer); + } + return answer; + }; +} + /** Require the pinned runtime's proof before accepting its shutdown contract. */ export async function assertConnectedClientStopSupported( target: ConnectedStopTarget | null, options: { requireLinkStopFence?: boolean; healthOnly?: boolean } = {}, diff --git a/src/cli/stop-windows-checked.ts b/src/cli/stop-windows-checked.ts index 35299e01a11..95cb46e0657 100644 --- a/src/cli/stop-windows-checked.ts +++ b/src/cli/stop-windows-checked.ts @@ -189,6 +189,17 @@ export function windowsPartAHolds(record: StopRunRecord): boolean { return true; } +/** + * A held snapshotless Part A that changed nothing (#8960): no manager stop, no terminate, and, + * because the hold skips it, no POST. A receipt this run claimed before Part A (an update + * handover claims first) then describes a stop that never happened and owes no teardown. + */ +export function windowsPartAHeldUnchanged(): boolean { + const result = state.result; + return windows() && state.snapshotless && result !== null + && result.outcome !== "stopped" && result.outcome !== "absent" && !result.changed; +} + /** Orphan discovery after a checked Windows stop is capped at 3 s (030 "Time budget"). */ export function orphanDiscoveryCap(): { deadlineAt?: number } { return windowsPartBDue() ? { deadlineAt: Date.now() + ORPHAN_DISCOVERY_CAP_MS } : {}; diff --git a/structure/ops/windows-checked-stop.md b/structure/ops/windows-checked-stop.md index ff899608b7c..de6897f0bdc 100644 --- a/structure/ops/windows-checked-stop.md +++ b/structure/ops/windows-checked-stop.md @@ -211,9 +211,16 @@ stop instead of sliding forward. - `stopServiceIfInstalledReport` / `stopServiceIfInstalledDetailed` (`src/service/orchestration.ts`) are async and run Part A on Windows. On Windows Task Scheduler never yields `stopped-respawnable`. - Plain `ocx stop` (`src/cli/stop-windows-checked.ts`) admits against the deadline with orphan - discovery and the inherited receipts counted. A Part A other than stopped or absent holds the - child: no `/api/stop` POST, the shared teardown skipped, `service` failed or state-unknown, - `proxy` unknown. A thrown Part A also holds the child and reports a service error. After a stopped Part A, the POST skips `stopProxy`'s legacy 15 s + discovery and the inherited receipts counted as the probes their recovery runs: one per + distinct exact endpoint (`inheritedTeardownProbeCount`, `src/cli/stop-restore.ts`), since an + invalid, unscannable or guessed-endpoint receipt blocks without probing and the recovery pass + asks each endpoint once (`abandonedTeardownProbeOncePerEndpoint`). Counting receipts let + repeated failed stops against one proxy raise the budget past any deadline (#8960). A Part A + other than stopped or absent holds the child: no `/api/stop` POST, the shared teardown + skipped, `service` failed or state-unknown, `proxy` unknown. When that held Part A changed + nothing (`windowsPartAHeldUnchanged`: no manager stop, no terminate), the receipt this run + claimed before it (an update handover claims first) is removed: it describes a stop that never + happened, and kept it would be inherited by the next stop's admission. A thrown Part A also holds the child and reports a service error. After a stopped Part A, the POST skips `stopProxy`'s legacy 15 s `waitForStoppedPort`, orphan discovery is capped at 3 s, and Part B replaces the respawn re-poll: our identity back on the port is `proxy: respawned`, an unconfirmed port is `evidence-unreadable`, and another program on the port sets `portHeldByForeign` without failing diff --git a/tests/windows/windows-stop-ocx-stop.test.ts b/tests/windows/windows-stop-ocx-stop.test.ts index 5d8eaf29d15..bd4e135b133 100644 --- a/tests/windows/windows-stop-ocx-stop.test.ts +++ b/tests/windows/windows-stop-ocx-stop.test.ts @@ -10,11 +10,14 @@ */ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { spawnSync } from "node:child_process"; -import { existsSync, mkdtempSync, readFileSync } from "node:fs"; +import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { removeTreeWithRetry } from "../helpers/remove-tree"; import { fixturePath, repoPath } from "../helpers/repo-root"; +import { abandonedTeardownProbeOncePerEndpoint, inheritedTeardownProbeCount } from "../../src/cli/stop-restore"; +import type { OutstandingTeardown } from "../../src/config/pending-teardown"; +import { PENDING_TEARDOWN_PREFIX, PENDING_TEARDOWN_SUFFIX } from "../../src/config/pending-teardown-names.mjs"; let home: string; beforeEach(() => { home = mkdtempSync(join(tmpdir(), "ocx-windows-plain-stop-")); }); @@ -179,3 +182,70 @@ describe("plain ocx stop on Windows: Part B after a stopped Part A", () => { expect("portHeldByForeign" in run.summary).toBe(false); }); }); + +describe("an update handover refused by Part A (#8960)", () => { + test("unverified-budget changed nothing: the receipt this run claimed is removed", () => { + // The handover claims before Part A. Kept after a refusal that changed nothing, the receipt + // was inherited by the next stop and raised its admission budget, so every retry needed more. + const run = runStop("unverified-budget", undefined, { handover: true }); + expect(run.calls.service, run.stderr).toBe(1); + expect(run.urls, run.stderr).toEqual([]); + expect(run.nonce, run.stderr).toBeDefined(); + expect(run.receiptExists, run.stderr).toBe(false); + expect(run.exitCode).toBe(1); + expect(run.summary).toMatchObject({ outcome: "failed", service: "failed", serviceStopReason: "unverified-budget", sharedTeardown: "skipped" }); + }); + + test("a Part A that changed something keeps the receipt", () => { + const run = runStop("survived", undefined, { handover: true }); + expect(run.urls, run.stderr).toEqual([]); + expect(run.nonce, run.stderr).toBeDefined(); + expect(run.receiptExists, run.stderr).toBe(true); + expect(run.exitCode).toBe(1); + }); + + test("another run's receipt survives while this run removes only its own unchanged claim", () => { + const inherited = "0123456789abcdef0123456789abcdef"; + const inheritedPath = join(home, PENDING_TEARDOWN_PREFIX + inherited + PENDING_TEARDOWN_SUFFIX); + const body = JSON.stringify({ ownerPid: 4242, nonce: inherited, createdAt: "2026-11-23T00:00:00.000Z", + endpoint: { hostname: "127.0.0.1", port: 10100 }, endpointSource: "exact" }); + writeFileSync(inheritedPath, body); + const run = runStop("unverified-budget", undefined, { handover: true }); + expect(run.calls.service, run.stderr).toBe(1); + expect(run.urls, run.stderr).toEqual([]); + expect(run.nonce, run.stderr).toBeDefined(); + expect(run.nonce).not.toBe(inherited); + expect(run.receiptExists, run.stderr).toBe(false); + expect(readFileSync(inheritedPath, "utf8")).toBe(body); + expect(run.summary).toMatchObject({ outcome: "failed", serviceStopReason: "unverified-budget", sharedTeardown: "skipped" }); + }); +}); + +describe("inherited receipts are budgeted and probed per endpoint (#8960)", () => { + const receipt = (nonce: string, port: number, endpointSource: "exact" | "guessed" = "exact"): OutstandingTeardown => ({ + state: "valid", + receipt: { ownerPid: 1, nonce, createdAt: "2026-11-23T00:00:00.000Z", endpoint: { hostname: "127.0.0.1", port }, endpointSource }, + }); + + test("receipts naming one endpoint count once; unprobed receipts count zero", () => { + expect(inheritedTeardownProbeCount([])).toBe(0); + expect(inheritedTeardownProbeCount([receipt("a", 10100), receipt("b", 10100), receipt("c", 10100)])).toBe(1); + expect(inheritedTeardownProbeCount([receipt("a", 10100), receipt("b", 10200)])).toBe(2); + expect(inheritedTeardownProbeCount([ + receipt("a", 10100, "guessed"), + { state: "invalid", nonce: "b", detail: "unreadable" }, + { state: "unscannable", detail: "home unreadable" }, + ])).toBe(0); + }); + + test("one recovery pass asks each endpoint once", async () => { + const asked: number[] = []; + const probe = abandonedTeardownProbeOncePerEndpoint(async endpoint => { asked.push(endpoint.port); return endpoint.port === 10100; }); + const endpoint = (port: number) => ({ hostname: "127.0.0.1", port }); + expect(await probe(endpoint(10100))).toBe(true); + expect(await probe(endpoint(10100))).toBe(true); + expect(await probe(endpoint(10200))).toBe(false); + expect(await probe(endpoint(10200))).toBe(false); + expect(asked).toEqual([10100, 10200]); + }); +}); From 66367b7c5bee4cc1509597efe5e4ca64900db604 Mon Sep 17 00:00:00 2001 From: ingwannu Date: Wed, 25 Nov 2026 13:04:35 +0900 Subject: [PATCH 15/60] fix(service): explain a missing Windows scheduled task on start (#9043) * fix(service): explain a missing Windows scheduled task on start * fix(service): test the Scheduler start path that gives install advice Move the try/catch around the Scheduler start into startWindowsSchedulerService so the advice-or-rethrow decision is exercised directly: one start attempt, advice only for a confirmed missing registration, the original error otherwise. Supersedes #9085, which reported the same missing-task start failure (#9038). Co-authored-by: EnesKartal <43950508+EnesKartal@users.noreply.github.com> * fix(service): keep the start call literal for the environment-guard order check --------- Co-authored-by: Ingwannu <186453546+Ingwannu@users.noreply.github.com> Co-authored-by: JUN Co-authored-by: EnesKartal <43950508+EnesKartal@users.noreply.github.com> --- .../content/docs/reference/cli/lifecycle.md | 3 ++ src/service/cli.ts | 11 +++++- src/service/windows-scheduler.ts | 32 ++++++++++++++- structure/ops/service-and-sidecars.md | 2 +- .../windows/windows-scheduler-errors.test.ts | 39 ++++++++++++++++++- 5 files changed, 82 insertions(+), 5 deletions(-) diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index fdd60495bfe..862af1648e1 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -904,6 +904,9 @@ to refresh its XML before it can hand off to a newer install. ### `ocx service [install|repair|restart|start|stop|status|uninstall|remove]` +If `ocx service start` reports that the Windows Task Scheduler service is not installed, +run `ocx service install` to register it. `start` exits with status 1 when the registration is missing. + On Windows Task Scheduler, the service wrapper restarts the proxy after five seconds even when an external tool terminates it with exit code 0. If another opencodex proxy already owns the port, the wrapper exits deliberately. Use `ocx stop` or diff --git a/src/service/cli.ts b/src/service/cli.ts index a891f052655..3cce746d4ca 100644 --- a/src/service/cli.ts +++ b/src/service/cli.ts @@ -24,7 +24,7 @@ import { ownershipMutationLeaseStatusLine } from "./ownership-mutation-lease.mjs import { foreignServiceOwnerRefusal, unknownServiceOwnerRefusal } from "./repair"; import type { ServiceBackend } from "./state"; import { unitPath } from "./systemd"; -import { inspectWindowsSchedulerServiceStatus, schtasksErrorDetail, probeWindowsSchedulerTask } from "./windows-scheduler"; +import { inspectWindowsSchedulerServiceStatus, schtasksErrorDetail, probeWindowsSchedulerTask, startWindowsSchedulerService, windowsSchedulerStartRecovery } from "./windows-scheduler"; import type { WindowsSchedulerTaskProbe } from "./windows-scheduler"; import { win32 } from "node:path"; import { serviceDiagnosticsSummary } from "./diagnostics"; @@ -393,7 +393,14 @@ export async function serviceCommand(...args: (string | undefined)[]): Promise { ops.start(); }, + process.platform === "win32" && backend === "scheduler" ? windowsSchedulerStartRecovery : () => null); + if (missingTask) { + console.error(`❌ ${missingTask}`); + process.exitCode = 1; + break; + } await reportServiceServing("started"); break; } diff --git a/src/service/windows-scheduler.ts b/src/service/windows-scheduler.ts index f04f8c62660..1f4834194ab 100644 --- a/src/service/windows-scheduler.ts +++ b/src/service/windows-scheduler.ts @@ -2,7 +2,7 @@ import { execFileSync } from "node:child_process"; import { findLiveProxy } from "../server/proxy-liveness"; import { existsSync, readFileSync } from "node:fs"; import { randomUUID } from "node:crypto"; -import { ELEVATION_REQUEST_TIMEOUT_MS, OCX_ELEVATED_PROTOCOL_FAILED, raceWithTimeout, resolveTrustedWindowsSchtasksExe, startElevatedSchtasksCreateAndRun, runWindowsElevated, toWindowsSchtasksError, WindowsElevationError, type ElevatedSchedulerOutcome, type ElevatedSchtasksCreateAndRunExecution, type ElevatedSchtasksCreateAndRunResult } from "../lib/windows-elevation"; +import { ELEVATION_REQUEST_TIMEOUT_MS, OCX_ELEVATED_PROTOCOL_FAILED, raceWithTimeout, resolveTrustedWindowsSchtasksExe, startElevatedSchtasksCreateAndRun, runWindowsElevated, toWindowsSchtasksError, WindowsElevationError, WindowsSchtasksError, type ElevatedSchedulerOutcome, type ElevatedSchtasksCreateAndRunExecution, type ElevatedSchtasksCreateAndRunResult } from "../lib/windows-elevation"; import { statusWinswRaw } from "../lib/winsw"; import { decodeWindowsTextBytes, type WindowsTextDecodeOptions } from "../lib/windows-text"; import { isTestHomeGuardArmed } from "../lib/test-home-guard"; @@ -257,6 +257,36 @@ export function probeWindowsSchedulerTask(taskName = TASK): WindowsSchedulerTask } } +/** Explain a missing registration at the CLI boundary while preserving other start failures. */ +export function windowsSchedulerStartRecovery( + error: unknown, + probe = probeWindowsSchedulerTask, +): string | null { + // /run uses the same exit code for multiple failures. Confirm registration independently + // so the install advice does not depend on the locale or mask an explicit access denial. + if (!(error instanceof WindowsSchtasksError) || error.operation !== "run" || error.reason !== "other" + || probe().status !== "absent") return null; + return "Service is not installed (Task Scheduler). Run 'ocx service install' first."; +} + +/** + * `ocx service start` on the Scheduler backend: run the start and return install advice only for a + * confirmed missing registration. Every other failure propagates unchanged; success returns null. + */ +export function startWindowsSchedulerService( + start: () => void, + recovery: (error: unknown) => string | null = windowsSchedulerStartRecovery, +): string | null { + try { + start(); + return null; + } catch (error) { + const advice = recovery(error); + if (!advice) throw error; + return advice; + } +} + /** True when the Task Scheduler registration for the default proxy task is proven present. */ export function windowsSchedulerTaskInstalled(taskName = TASK): boolean { return probeWindowsSchedulerTask(taskName).status === "present"; diff --git a/structure/ops/service-and-sidecars.md b/structure/ops/service-and-sidecars.md index 01b1e3deeb1..df1be91805e 100644 --- a/structure/ops/service-and-sidecars.md +++ b/structure/ops/service-and-sidecars.md @@ -22,7 +22,7 @@ any platform status probe. macOS and Linux choose from the registration file's p Windows combines the Task Scheduler and WinSW probes into `installed`, `absent`, or `unknown`. Only proven absence enters registration. A query failure refuses the bare command with status guidance, because treating `unknown` as absent can rerun elevated `schtasks /create` against an -existing task. Explicit `ocx service install` remains the operator-owned registration request. +existing task. Explicit `ocx service install` remains the operator-owned registration request. After a generic Scheduler `/run` failure, `ocx service start` uses the same registration probe before giving install advice. Confirmed absence returns exit 1 with the install command. Present or unreadable registrations and explicit access denials retain the original failure. `src/lib/windows-elevation.ts` formats scheduler exec failures without echoing child stderr; generic failures retain the numeric exit status. Delete, run and end access denials name the exact command to run from an elevated terminal. `src/service/windows-scheduler.ts` also classifies an owned-task delete exiting 1 as denied when a fresh probe proves the task survived; absent, unreadable and failed probes do not establish that classification. `src/service/windows-ops.ts` retains service assets until deletion is proven complete. `tests/windows/windows-scheduler-errors.test.ts` exercises these paths with injected runners. diff --git a/tests/windows/windows-scheduler-errors.test.ts b/tests/windows/windows-scheduler-errors.test.ts index fa41e83e202..7ed37c51040 100644 --- a/tests/windows/windows-scheduler-errors.test.ts +++ b/tests/windows/windows-scheduler-errors.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; import { WindowsSchtasksError, WINDOWS_SCHTASKS_CREATE_ACCESS_DENIED_MARKER } from "../../src/lib/windows-elevation"; -import { schtasks, schtasksErrorDetail, type WindowsSchedulerTaskProbe } from "../../src/service/windows-scheduler"; +import { schtasks, schtasksErrorDetail, startWindowsSchedulerService, windowsSchedulerStartRecovery, type WindowsSchedulerTaskProbe } from "../../src/service/windows-scheduler"; import { isWindowsSchedulerEndBenign } from "../../src/service/windows-ops"; const task = "opencodex-proxy"; @@ -89,3 +89,40 @@ describe("Task Scheduler failure diagnostics (#7772)", () => { expect(schtasksErrorDetail(failure())).toBe("Task Scheduler command failed (exit code 1): schtasks /query"); }); }); + +describe("Windows Scheduler start recovery (#9038)", () => { + const runFailure = () => failedCommand(["/run", "/tn", task], failure(1, Buffer.from("ERROR: The system cannot find the file specified."))); + + test("proven absence returns install guidance after the start attempt fails", () => { + expect(windowsSchedulerStartRecovery(runFailure(), () => ({ status: "absent" }))) + .toBe("Service is not installed (Task Scheduler). Run 'ocx service install' first."); + }); + + for (const state of [{ status: "present" }, { status: "unknown", detail: "query failed" }] as const) { + test(`gives no install advice when the registration is ${state.status}`, () => { + expect(windowsSchedulerStartRecovery(runFailure(), () => state)).toBeNull(); + }); + } + + test("explicit permission and other command failures do not query registration", () => { + const probe = () => { throw new Error("unexpected registration probe"); }; + const denied = failedCommand(["/run", "/tn", task], failure(1, Buffer.from("ERROR: Access is denied."))); + expect(windowsSchedulerStartRecovery(denied, probe)).toBeNull(); + expect(windowsSchedulerStartRecovery(failedCommand(["/end", "/tn", task], failure()), probe)).toBeNull(); + }); + + test("the start runs once and only a confirmed missing registration becomes advice", () => { + let starts = 0; + const missing = runFailure(); + const advice = startWindowsSchedulerService(() => { starts++; throw missing; }, error => windowsSchedulerStartRecovery(error, () => ({ status: "absent" }))); + expect(advice).toBe("Service is not installed (Task Scheduler). Run 'ocx service install' first."); + expect(starts).toBe(1); + expect(startWindowsSchedulerService(() => { starts++; })).toBeNull(); + expect(starts).toBe(2); + // A present or unreadable registration rethrows the original Scheduler error, unchanged. + for (const state of [{ status: "present" }, { status: "unknown", detail: "query failed" }] as const) { + expect(() => startWindowsSchedulerService(() => { throw missing; }, error => windowsSchedulerStartRecovery(error, () => state))) + .toThrow(missing); + } + }); +}); From 3ec89d26623c41a07234459838bb58ec1e830373 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 13:35:05 +0900 Subject: [PATCH 16/60] fix(egress): keep an explicit provider proxy authoritative over process NO_PROXY (#9112) * fix(egress): keep an explicit provider proxy authoritative over process NO_PROXY * fix(egress): match NO_PROXY as broadly as Bun and guard the ChatHub socket dial * fix(egress): port Bun NO_PROXY matching for the explicit-proxy guard * docs(structure): name the Bun matcher without a foreign path * fix(egress): follow explicit-proxy redirects in-house and recheck every hop * fix(egress): mirror Bun redirect header stripping and redirected flag in the explicit-proxy follower * fix(egress): refuse explicit-proxy redirects while NO_PROXY is set instead of following them * fix(egress): refuse an exempted provider proxy route before dispatch side effects * fix(egress): decide the NO_PROXY exemption on the rewritten destination * test(egress): the TLS profile transport never receives an exempted route --- .../es/reference/configuration/providers.md | 2 +- .../docs/reference/configuration/providers.md | 7 + .../test-layout/layout-server-inbound.json | 1 + src/adapters/m365-copilot/transport.ts | 11 +- src/lib/provider-egress.ts | 14 +- src/lib/provider-outbound.ts | 7 +- src/lib/proxy-env.ts | 178 ++++++++++ src/server/responses/fetch-helpers.ts | 6 +- src/server/responses/ws-upstream.ts | 5 +- structure/transports/inventory.md | 14 +- tests/fixtures/test-layout-expected.json | 2 +- tests/lib/explicit-proxy-no-proxy.test.ts | 327 ++++++++++++++++++ tests/providers/m365-copilot.test.ts | 19 +- .../provider-egress-outbound.test.ts | 16 +- 14 files changed, 588 insertions(+), 21 deletions(-) create mode 100644 tests/lib/explicit-proxy-no-proxy.test.ts diff --git a/docs-site/src/content/docs/es/reference/configuration/providers.md b/docs-site/src/content/docs/es/reference/configuration/providers.md index 08174bb0057..e497dd6420c 100644 --- a/docs-site/src/content/docs/es/reference/configuration/providers.md +++ b/docs-site/src/content/docs/es/reference/configuration/providers.md @@ -221,7 +221,7 @@ Los proveedores pueden exponer una abreviatura incorporada, como `agy` para `goo | --- | --- | --- | | `adapter` | `string` | Uno de `openai-chat`, `openai-responses`, `anthropic`, `claude-cli`, `step-cli`, `google`, `kiro`, `cursor`, `ollama-native`, `azure-openai` (o alias `azure`), `codebuddy`, `qoder`. | | `baseUrl` | `string` | URL de base ascendente API. La mayoría de los puntos finales fijos incorporados ignoran una falta de coincidencia; los ajustes preestablecidos de clave seguros contra colisiones conservan un destino personalizado con el mismo nombre más antiguo. | -| `proxy?` | `string \| null` | Ruta de salida por proveedor. Omita que herede la decisión de proxy global; use `"direct"` o `null` para forzar la salida directa; o proporcione una URL proxy absoluta `http://`, `https://`, `socks5://` o `socks5h://`. Se rechaza una cadena vacía. | +| `proxy?` | `string \| null` | Ruta de salida por proveedor. Omita que herede la decisión de proxy global; use `"direct"` o `null` para forzar la salida directa; o proporcione una URL proxy absoluta `http://`, `https://`, `socks5://` o `socks5h://`. Se rechaza una cadena vacía. Un `proxy` HTTP(S) no se combina con una entrada de `NO_PROXY` del proceso que coincida con el mismo destino, porque el entorno de ejecución se conectaría directamente: esa solicitud se rechaza. Para conectar directamente, añada el host a `noProxy` del proveedor. Mientras `NO_PROXY` esté definido, una redirección en respuesta a esa solicitud se rechaza en lugar de seguirse. | | `noProxy?` | `string \| string[]` | Destinos a los que este proveedor llega directamente, utilizando la sintaxis de patrón de host `NO_PROXY`. Una coincidencia pasa por alto tanto el propio proxy de este proveedor como un proxy global heredado. | | `requestPacing?` | `{ enabled, requestsPerMinute?, minIntervalMs?, maxConcurrentRequests?, models?, keySelection?, keys? }` | Indicadores opcionales de inicio de solicitud de salida del lado del cliente, separados del uso ascendente, la facturación y los indicadores de límite de solicitudes. RPM se convierte en un intervalo uniforme; `minIntervalMs` puede imponer un intervalo más largo. `maxConcurrentRequests` es un límite de enteros positivo en las solicitudes en vuelo. Una regla de proveedor o modelo puede usar el límite de concurrencia solo; los límites de proveedor se aplican a todos los modelos, mientras que las entradas `models` usan ID de modelo ascendente exactos (por ejemplo, `nvidia/llama-3.1-nemotron-ultra-253b-v1`) y solo pueden agregar retardo o concurrencia estrecha. Los esperas de cola no consumen el tiempo de espera del encabezado de respuesta ascendente. HTTP y el adaptador explícito `fetchResponse` / `runTurn` despachos están cubiertos. Un giro canónico Responses WebSocket con límite de concurrencia usa HTTP / SSE para que su arrendamiento pueda liberarse cuando el cuerpo de respuesta se complete, se equivoque o se cancele. Para los adaptadores `runTurn`, incluyendo Cursor, el cap cuenta los giros activos en lugar de los envíos físicos: RunSSE y BidiAppend pueden superponerse en un giro, mientras que otro turno espera. Seguimiento envía todavía obedecer intervalos de inicio. | | `requestPacing.keySelection?` | `"active"`, `"round-robin"` | Selección normal de la tecla de petición. El valor predeterminado `active` conserva la clave guardada y la rotación de fallas existente; `round-robin` distribuye las selecciones locales de solicitud a través de referencias de grupo de claves API elegibles sin cambiar la clave activa guardada. Equilibra las asignaciones, no los tokens o el costo. | diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index 1f1810476d4..b476d90119a 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -599,6 +599,13 @@ to choose direct egress explicitly. evaluated for each request. A matching destination goes direct whether the provider would otherwise use its own `proxy` or inherit a global proxy. +An HTTP(S) `proxy` on a provider and a process `NO_PROXY` entry that matches the same destination +cannot both apply, because the runtime would connect directly. Such a request is refused rather than +sent without the configured proxy. List the host in the provider's `noProxy` to connect directly, or +remove it from `NO_PROXY` to keep the proxy. While `NO_PROXY` is set, a redirect answered to such a +request is refused rather than followed, because the next hop could leave without the proxy. A +`socks5://` or `socks5h://` proxy is not affected. + #### What the route covers The route is applied to routed inference, provider discovery and connection tests, and API-key diff --git a/scripts/test-layout/layout-server-inbound.json b/scripts/test-layout/layout-server-inbound.json index 55e5756d102..13ec55a193e 100644 --- a/scripts/test-layout/layout-server-inbound.json +++ b/scripts/test-layout/layout-server-inbound.json @@ -1,4 +1,5 @@ { + "explicit-proxy-no-proxy.test.ts": "lib", "gemini-native.test.ts": "server", "gemini-native-wire.test.ts": "server", "gemini-native-routes.test.ts": "server", diff --git a/src/adapters/m365-copilot/transport.ts b/src/adapters/m365-copilot/transport.ts index d476ba57142..c81efee294b 100644 --- a/src/adapters/m365-copilot/transport.ts +++ b/src/adapters/m365-copilot/transport.ts @@ -1,7 +1,7 @@ import { m365CopilotClaims } from "../../oauth/m365-copilot"; import { getToneForModel, m365CopilotScenario, M365_COPILOT_BASE_URL } from "../../providers/m365-copilot-models"; import { resolveProviderEgress, providerSocketRoute } from "../../lib/provider-egress"; -import { effectiveProxyFor, noProxyMatches } from "../../lib/proxy-env"; +import { effectiveProxyFor, explicitProxyExemptedError, isSocks5ProxyUrl, noProxyMatches, processNoProxyExempts } from "../../lib/proxy-env"; import type { OcxProviderConfig } from "../../types"; import type { TranslatorBudget } from "../../lib/translator-budget"; import { isTranslatorBudgetExceededError } from "../../lib/translator-budget"; @@ -98,7 +98,14 @@ export function m365SocketDialOptions(route: M365TurnOptions["route"], url: stri route = m365RequestSocketRoute(route); if (typeof route.fetch === "function") throw new M365CopilotTurnError("Microsoft 365 Copilot ChatHub cannot use a custom fetch executor; remove providers.m365-copilot.fetch", 400); const egress = resolveProviderEgress({ providerName: "m365-copilot", provider: route, url }); - if (egress.kind === "proxy") return proxyDialOptions(egress.proxyUrl, headers); + if (egress.kind === "proxy") { + // Bun's WebSocket skips an explicit proxy for a destination the process NO_PROXY exempts and + // would connect directly; this socket's URL carries the access token, so refuse instead. + if (!isSocks5ProxyUrl(egress.proxyUrl) && processNoProxyExempts(new URL(url))) { + throw new M365CopilotTurnError(explicitProxyExemptedError(new URL(url)).message, 400); + } + return proxyDialOptions(egress.proxyUrl, headers); + } if (egress.kind === "direct") return { headers }; const https = new URL(url); https.protocol = "https:"; diff --git a/src/lib/provider-egress.ts b/src/lib/provider-egress.ts index bff5c16340f..0ee65652f3a 100644 --- a/src/lib/provider-egress.ts +++ b/src/lib/provider-egress.ts @@ -26,7 +26,7 @@ * therefore a configuration error naming both real alternatives. */ import type { OcxProviderConfig } from "../types"; -import { isSocks5ProxyUrl, noProxyMatches } from "./proxy-env"; +import { explicitProxyExemptedError, isSocks5ProxyUrl, noProxyMatches, processNoProxyExempts } from "./proxy-env"; export class InvalidProviderEgressError extends Error { override readonly name = "InvalidProviderEgressError"; @@ -277,10 +277,22 @@ export function providerEgressSendInit( binding: ProviderEgressBinding, physicalFetch: unknown, input: string | URL | Request, + /** False for an early check whose destination a plugin rewrite or an override may still change. */ + options: { exemption?: boolean } = {}, ): { proxy?: string | false } { const url = egressTargetUrl(input); if (url === null) return {}; const egress = resolveProviderEgress({ providerName: binding.providerName, provider: binding.provider, url }); + // An HTTP(S) proxy route toward a destination the process NO_PROXY exempts would leave without the + // proxy. Decided against the destination actually sent, before the dispatch receipt and before + // any byte leaves; `providerFetch` also asks early, before `beforeDispatch`, when nothing can still + // change the destination. `configuredOutboundFetch` keeps the check as a backstop for other callers. + if (options.exemption !== false && egress.kind === "proxy" && egress.transport === "http") { + const target = parseTargetUrl(binding.providerName, url); + if ((target.protocol === "http:" || target.protocol === "https:") && processNoProxyExempts(target)) { + throw explicitProxyExemptedError(target); + } + } if (providerEgressIsExplicit(egress) && !isEgressTransparentExecutor(physicalFetch)) { // Name the field that actually made the route explicit. A bypass-list match with no // `proxy` field at all would otherwise tell the operator to remove an override they diff --git a/src/lib/provider-outbound.ts b/src/lib/provider-outbound.ts index 939fabe4b30..fc57ff1a173 100644 --- a/src/lib/provider-outbound.ts +++ b/src/lib/provider-outbound.ts @@ -311,9 +311,10 @@ async function providerOutboundRequest( // proxy-only DNS answers. // // A provider route replaces that decision outright rather than combining with it. An - // explicit provider proxy applies even where global NO_PROXY exempts the host, because the - // operator named this proxy for this provider; `providers..noProxy` is the exemption - // that belongs to that choice, and `resolveProviderEgress` has already applied it. A + // explicit provider proxy is never traded for direct egress where global NO_PROXY exempts the + // host: `configuredOutboundFetch` refuses that send, because Bun would skip the proxy there. + // `providers..noProxy` is the exemption that belongs to the operator's choice, and + // `resolveProviderEgress` has already applied it. A // provider pinned to `direct` keeps the DNS-pinned transport, which reaches the peer // through no proxy at all — the one route on this path that needs nothing from Bun. const proxyApplies = egress.kind === "inherit" diff --git a/src/lib/proxy-env.ts b/src/lib/proxy-env.ts index 3222cdff7b3..03e0400ccaf 100644 --- a/src/lib/proxy-env.ts +++ b/src/lib/proxy-env.ts @@ -201,6 +201,146 @@ export function socks5ProxyFromEnv(env: ProxyEnvMap = process.env): string | und */ export type ProxyCapableRequestInit = RequestInit & { proxy?: string | false }; +/** A request named an HTTP(S) proxy for a destination the process `NO_PROXY` exempts. */ +export class ExplicitProxyExemptedError extends Error { + override readonly name: string = "ExplicitProxyExemptedError"; + readonly code: string = "explicit_proxy_exempted"; +} + +/** + * Bun's own `NO_PROXY` match, ported from `src/dotenv/no_proxy.rs` at the pinned `bun-v1.4.4`. + * + * Entries split on commas and whitespace. `*` matches everything. An entry containing `/` is a CIDR + * block and matches only an IP-literal host inside it. Otherwise an optional `:port` must equal the + * destination port numerically, a leading `*.` or `.` and one trailing `.` are dropped, an IP-literal + * host matches only an equal address (compared canonically, so `::ffff:127.0.0.1` is `127.0.0.1`), + * and a name matches itself and every subdomain, case-insensitively. + */ +function bunNoProxyMatches(list: string, url: URL): boolean { + const hostname = stripOneTrailingDot(stripIpv6Brackets(url.hostname)); + if (!hostname) return false; + const port = Number(url.port || (url.protocol === "https:" || url.protocol === "wss:" ? "443" : "80")); + const hostIp = parseIpLiteral(hostname); + for (const entry of list.split(/[,\s]+/)) { + if (!entry) continue; + if (entry === "*") return true; + const slash = entry.indexOf("/"); + if (slash !== -1) { + if (hostIp && cidrContains(entry, slash, hostIp)) return true; + continue; + } + const [rawHost, entryPort] = splitEntryPort(entry); + if (entryPort !== undefined && (!/^\d+$/.test(entryPort) || Number(entryPort) !== port)) continue; + const entryHost = stripOneTrailingDot(rawHost.startsWith("*.") ? rawHost.slice(2) : rawHost.startsWith(".") ? rawHost.slice(1) : rawHost); + if (!entryHost) continue; + if (hostIp) { + const entryIp = parseIpLiteral(entryHost); + if (entryIp && sameIp(entryIp, hostIp)) return true; + continue; + } + const host = hostname.toLowerCase(); + const name = entryHost.toLowerCase(); + if (host === name || (host.length > name.length && host.endsWith(`.${name}`))) return true; + } + return false; +} + +interface IpLiteral { v6: boolean; bytes: number[] } + +function stripOneTrailingDot(host: string): string { return host.endsWith(".") ? host.slice(0, -1) : host; } +function stripIpv6Brackets(host: string): string { + return host.startsWith("[") && host.endsWith("]") ? host.slice(1, -1) : host; +} + +/** `host[:port]` where host may be a bracketed or bare IPv6 literal (only one colon means a port). */ +function splitEntryPort(entry: string): [string, string | undefined] { + if (entry.startsWith("[")) { + const close = entry.indexOf("]"); + if (close === -1) return [entry, undefined]; + const rest = entry.slice(close + 1); + return [entry.slice(1, close), rest.startsWith(":") ? rest.slice(1) : undefined]; + } + const colons = entry.split(":").length - 1; + if (colons === 1) { + const colon = entry.indexOf(":"); + return [entry.slice(0, colon), entry.slice(colon + 1)]; + } + return [entry, undefined]; +} + +/** A dotted quad or an IPv6 literal as bytes, with `::ffff:a.b.c.d` folded to IPv4. */ +function parseIpLiteral(text: string): IpLiteral | null { + if (/^\d{1,3}(?:\.\d{1,3}){3}$/.test(text)) { + const bytes = text.split(".").map(Number); + return bytes.every(byte => byte <= 255) ? { v6: false, bytes } : null; + } + if (!text.includes(":")) return null; + let canonical: string; + try { canonical = new URL(`http://[${text}]/`).hostname.slice(1, -1); } catch { return null; } + const halves = canonical.split("::"); + if (halves.length > 2) return null; + const head = halves[0] ? halves[0].split(":") : []; + const tail = halves.length === 2 && halves[1] ? halves[1].split(":") : []; + const groups = halves.length === 2 ? [...head, ...Array(8 - head.length - tail.length).fill("0"), ...tail] : head; + if (groups.length !== 8 || !groups.every(group => /^[0-9a-f]{1,4}$/.test(group))) return null; + const bytes = groups.flatMap(group => { const value = parseInt(group, 16); return [value >> 8, value & 0xff]; }); + const mapped = bytes.slice(0, 10).every(byte => byte === 0) && bytes[10] === 0xff && bytes[11] === 0xff; + return mapped ? { v6: false, bytes: bytes.slice(12) } : { v6: true, bytes }; +} + +function sameIp(a: IpLiteral, b: IpLiteral): boolean { + return a.v6 === b.v6 && a.bytes.every((byte, index) => byte === b.bytes[index]); +} + +function cidrContains(entry: string, slash: number, host: IpLiteral): boolean { + const writtenText = stripIpv6Brackets(entry.slice(0, slash)); + const network = parseIpLiteral(writtenText); + const prefix = entry.slice(slash + 1); + if (!network || !/^\d+$/.test(prefix)) return false; + let bits = Number(prefix); + // `::ffff:10.0.0.0/104` is `10.0.0.0/8`. + if (writtenText.includes(":") && !network.v6) { + if (bits < 96) return false; + bits -= 96; + } + if (network.v6 !== host.v6 || bits > network.bytes.length * 8) return false; + const whole = Math.floor(bits / 8); + const rem = bits % 8; + for (let index = 0; index < whole; index += 1) if (network.bytes[index] !== host.bytes[index]) return false; + return rem === 0 || ((network.bytes[whole]! ^ host.bytes[whole]!) >> (8 - rem)) === 0; +} + +/** + * Whether the process `NO_PROXY` or `no_proxy` exempts `url`, as broadly as Bun reads it. + * + * Bun's fetch and WebSocket connect directly to such a destination even when the request names a + * proxy, as a string or as `{ url }`; only `proxy: false` outranks the environment. This guard + * therefore has to match at least everything Bun matches (`bunNoProxyMatches`: whitespace separators, + * subdomains, CIDR blocks, numeric ports, canonical addresses), and either spelling is enough. It also + * accepts anything + * `noProxyMatches` accepts, so it never answers narrower than the routing decisions elsewhere. + * Over-matching only refuses a request; under-matching would send it around the proxy. + */ +export function processNoProxyExempts(url: URL, env: ProxyEnvMap = process.env): boolean { + // Bun reads `no_proxy`, else `NO_PROXY`; checking each on its own covers whichever it picks. + return [env.NO_PROXY, env.no_proxy].some(value => typeof value === "string" && value.trim() !== "" + && (bunNoProxyMatches(value, url) || noProxyMatches(url, { NO_PROXY: value }))); +} + +/** A redirect answer to an explicit-proxy request that Bun would have followed around the proxy. */ +export class ExplicitProxyRedirectRefusedError extends ExplicitProxyExemptedError { + override readonly name = "ExplicitProxyRedirectRefusedError"; + override readonly code = "explicit_proxy_redirect_refused"; +} + +/** The refusal for an explicit HTTP(S) proxy that the process environment would make Bun skip. */ +export function explicitProxyExemptedError(url: URL): ExplicitProxyExemptedError { + return new ExplicitProxyExemptedError( + `the configured proxy for ${url.origin} cannot be applied because NO_PROXY in the process environment ` + + "exempts this destination; remove it from NO_PROXY to keep the proxy, or list it in the provider's noProxy to connect directly", + ); +} + export function configuredOutboundFetch( input: RequestInfo | URL, init?: RequestInit, @@ -224,6 +364,19 @@ export function configuredOutboundFetch( } catch { return base!(input, init); } + // An HTTP(S) proxy string reaches Bun's fetch as `init.proxy`, and Bun ignores it for a + // destination the process NO_PROXY exempts. The caller named this proxy, so the request must not + // leave without it: refuse instead. SOCKS5 strings never reach Bun's proxy option (below). + if (typeof explicitProxy === "string" && !isSocks5ProxyUrl(explicitProxy) + && (url.protocol === "http:" || url.protocol === "https:")) { + if (processNoProxyExempts(url)) return Promise.reject(explicitProxyExemptedError(url)); + // Bun would follow a redirect itself and apply NO_PROXY to the new destination, so with any + // bypass list in the environment a redirect is refused instead of followed. + const redirectMode = init?.redirect ?? (input instanceof Request ? input.redirect : "follow"); + if (redirectMode === "follow" && processNoProxyConfigured()) { + return refuseExplicitProxyRedirects(base!, input, init, url); + } + } // A mixed inherited SOCKS/HTTP ALL_PROXY environment cannot put bare "localhost" in // NO_PROXY: Bun would also bypass its HTTP proxy for app.localhost. Keep the name exact // here and force native fetch direct so the opposite-case HTTP proxy cannot take over. @@ -237,6 +390,31 @@ export function configuredOutboundFetch( return base!(input, init); } +function processNoProxyConfigured(env: ProxyEnvMap = process.env): boolean { + return [env.NO_PROXY, env.no_proxy].some(value => typeof value === "string" && value.trim() !== ""); +} + +const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]); + +/** + * Send an explicit HTTP(S)-proxy request whose caller asked Bun to follow redirects, without letting + * Bun follow them: Bun would apply the process NO_PROXY to each new destination and could send the + * request, credentials and body included, around the proxy. The single hop goes out with + * `redirect: "manual"`; a redirect answer is refused before any second hop is contacted. Callers + * that handle redirects themselves pass `redirect: "manual"` and never reach this. + */ +async function refuseExplicitProxyRedirects( + base: typeof globalThis.fetch, input: RequestInfo | URL, init: RequestInit | undefined, firstUrl: URL, +): Promise { + const response = await base(input, { ...init, redirect: "manual" } as RequestInit); + if (!REDIRECT_STATUSES.has(response.status) || !response.headers.has("location")) return response; + await response.body?.cancel().catch(() => {}); + throw new ExplicitProxyRedirectRefusedError( + `a redirect from ${firstUrl.origin} was not followed through the configured proxy because NO_PROXY is set in the ` + + 'process environment and could route the next hop around it; handle redirects with redirect: "manual"', + ); +} + type FetchWithPreconnect = typeof globalThis.fetch & { preconnect?: typeof globalThis.fetch.preconnect; }; diff --git a/src/server/responses/fetch-helpers.ts b/src/server/responses/fetch-helpers.ts index 8d802ad417c..6750fe5b767 100644 --- a/src/server/responses/fetch-helpers.ts +++ b/src/server/responses/fetch-helpers.ts @@ -25,7 +25,7 @@ import { providerTlsFetch } from "../../lib/provider-tls-profile"; import { inheritPassiveKeyProof, markPassiveKeyTransparent } from "../../lib/passive-key-fetch-proof"; import type { CodexWsQuotaObserver } from "./codex-ws-metadata"; import { configuredOutboundFetch } from "../../lib/proxy-env"; -import { isLoopbackUrl, rewriteUpstream } from "../../plugins/upstream-hooks"; +import { hasUpstreamRewriters, isLoopbackUrl, rewriteUpstream } from "../../plugins/upstream-hooks"; import { describeProviderEgressForLog, bindProviderSocketRoute, @@ -405,8 +405,10 @@ export function providerFetch( // full decision can be made now. With an override, only the configured value is checked: // the override may rebuild against a different host and select a different transport, and // refusing on this destination would reject a request whose real route is fine. + // The NO_PROXY exemption is asked early only when this URL is final: a plugin rewrite may + // still move it, and is then decided at the physical send, before its receipt. if (override) egressFor(input); - else providerEgressSendInit(egressBinding, transport, input); + else providerEgressSendInit(egressBinding, transport, input, { exemption: !hasUpstreamRewriters() }); // The hook inspects the outgoing headers and refuses the send by throwing; it is not a // mutator, and the copy it receives is deliberately not threaded onward. `Connection` // is decided inside `dispatch`, which runs after this, so the fresh-connection policy diff --git a/src/server/responses/ws-upstream.ts b/src/server/responses/ws-upstream.ts index 2b088dd24e5..88e1a40aba8 100644 --- a/src/server/responses/ws-upstream.ts +++ b/src/server/responses/ws-upstream.ts @@ -18,7 +18,7 @@ import type { NativeResponseControl } from "./native-response-control"; import { codexWsReuseAcrossTurnsEnabled } from "../../config/codex-ws-reuse-setting"; import { compareBunVersions } from "../../lib/bun-stream-caps"; -import { resolveProxyRoute, socks5ProxyFromEnv } from "../../lib/proxy-env"; +import { processNoProxyExempts, resolveProxyRoute, socks5ProxyFromEnv } from "../../lib/proxy-env"; import { estimateTokens } from "../../lib/token-estimate"; import type { CodexWsQuotaObserver } from "./codex-ws-metadata"; import { CODEX_RESPONSES_HTTP_URL, CODEX_RESPONSES_WS_URL, CODEX_WS_FRAME_HEADERS, prepareCodexHttpInit, prepareCodexWsRequest } from "./codex-ws-request"; @@ -214,6 +214,9 @@ export async function codexWsUpstreamFetch( } const wsUrl = wsUpstreamUrlFor(url); + // Bun's WebSocket also skips an explicit proxy for a destination the process NO_PROXY exempts. + // The HTTP path refuses that route rather than dialing around it. + if (explicitProxy && processNoProxyExempts(new URL(wsUrl))) return sseFallback(url, init); const proxyRoute = explicitProxy ? { kind: "proxy" as const, proxy: explicitProxy } : resolveProxyRoute(new URL(wsUrl)); if (proxyRoute.kind === "fallback") return sseFallback(url, init); const proxy = proxyRoute.kind === "proxy" ? proxyRoute.proxy : undefined; diff --git a/structure/transports/inventory.md b/structure/transports/inventory.md index 75f49e69e55..b62c444bc19 100644 --- a/structure/transports/inventory.md +++ b/structure/transports/inventory.md @@ -195,7 +195,19 @@ Kiro generation in `src/adapters/kiro-retry.ts` passes the routed provider execu A reset-triggered rebuild may retarget the request to another region's canonical host mid-flight; that admission is marked `rebasedTarget` and does not consume or require an unused transition/alternate-target allowance (the total-send and replay-safety checks still apply), and the alternate-host fallback resolves the legacy gateway from the current request URL so rebuilt credentials stay with their own region. `src/lib/provider-egress.ts` resolves a provider route for one destination. The route is carried only -by transports that can preserve that request-local decision: +by transports that can preserve that request-local decision. An explicit HTTP(S) proxy is never sent +toward a destination that the process `NO_PROXY` or `no_proxy` exempts, because Bun's fetch and +WebSocket connect directly there: `providerEgressSendInit` refuses such a route against the destination +actually sent, before its dispatch receipt (and before `beforeDispatch` when no plugin rewrite or +dispatch override can still change the destination), `configuredOutboundFetch` refuses the send with +`ExplicitProxyExemptedError` as a backstop for every other caller (the Antigravity TLS profile +transport, reachable only through `providerFetch`, therefore never receives such a route), the Responses WebSocket upstream leaves such a turn to that HTTP path, and +the Microsoft 365 Copilot ChatHub dial refuses before creating its socket. `processNoProxyExempts` +matches at least as broadly as Bun: `bunNoProxyMatches` ports the `NO_PROXY` matcher of Bun 1.4.4 +(comma and whitespace separators, subdomains, CIDR blocks, numeric ports, canonical addresses), unioned +with `noProxyMatches`, for either spelling. While a bypass list is set, an explicit-proxy request in `follow` mode is sent with `redirect: "manual"` +and a redirect answer is refused (`ExplicitProxyRedirectRefusedError`) instead of being followed, because +Bun would apply the bypass list to the next hop; callers that handle redirects pass `manual` themselves. `tests/lib/explicit-proxy-no-proxy.test.ts` checks the route on real loopback sockets. | Request path | Per-provider route | Current contract | | --- | --- | --- | diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 0330e14613e..468acc03a6a 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1,4 +1,4 @@ -{ "gemini-native.test.ts": "server", "gemini-native-wire.test.ts": "server", "gemini-native-routes.test.ts": "server", "provider-upstream-deadlines.test.ts": "responses", "web-search-local-deadline-provenance.test.ts": "web-search", "responses-combo-unavailable-cause.test.ts": "responses", "responses-native-sse-stall.test.ts": "responses", "client-restart-sync-fence.test.ts": "clients", "service-scheduler-restart-respawn-refusal.test.ts": "service", "route-to-home-sync-review.test.ts": "routing", "route-intent-connect-post-commit.test.ts": "clients", "route-intent-file-originals.test.ts": "clients", "route-to-child-defaults.test.ts": "routing", "route-to-home-live-flags.test.ts": "routing", "route-to-home-native-truth.test.ts": "routing", "route-to-home-decisions.test.ts": "routing", "route-to-ephemeral.test.ts": "server", "link-pinned-sync-overwrite.test.ts": "clients", "cli-sync-fanout-ephemeral.test.ts": "cli", "route-intent-home-consent.test.ts": "clients", "management-route-intent-native-errors.test.ts": "server", "route-intent-offline-mode-switch.test.ts": "clients", "route-intent-parity-withdrawal.test.ts": "clients", "service-scheduler-restart-cleanup.test.ts": "service", "route-to-retirement-review.test.ts": "server", "route-to-policy-review.test.ts": "server", "management-route-intent-native-review.test.ts": "server", "route-to-home-off-review.test.ts": "routing", "codex-journal-provider-reserialization.test.ts": "codex-integration", "route-intent-parity-fallback.test.ts": "clients", "route-intent-native-originals.test.ts": "clients", "route-intent-native-review.test.ts": "clients", "route-intent-connected-capabilities.test.ts": "clients", "route-intent-connected-review.test.ts": "clients", "route-intent-connect-recovery.test.ts": "clients", "client-disconnect-field-snapshot.test.ts": "clients", "cli-route-to-confirmation.test.ts": "cli", "route-intent-runtime-stop.test.ts": "clients", "route-intent-codex-connect-disabled.test.ts": "clients", "route-intent-codex-transitions.test.ts": "clients", "route-to-live-settings.test.ts": "server", "route-intent-claude-surface.test.ts": "clients", "route-intent-local-receipt.test.ts": "clients", "route-intent-scheduler.test.ts": "clients", "route-intent-watch-client.test.ts": "clients", "route-intent-watch-boundary.test.ts": "server", "route-intent-watch-waiters.test.ts": "server", "home-route-intent-upgrade.test.ts": "clients", "route-intent-overwrite.test.ts": "clients", "codex-disconnect-owned-recovery.test.ts": "codex-integration", "service-restart-registration-guard.test.ts": "service", "client-disconnect-config-recovery.test.ts": "clients", "route-intent-aside.test.ts": "clients", "route-intent-connected.test.ts": "clients", "cli-link-route-intent.test.ts": "cli", "cli-route-to-aliases.test.ts": "cli", "cli-route-to.test.ts": "cli", "client-disconnect-edited-codex.test.ts": "clients", "codex-disconnect-fields.test.ts": "codex-integration", "link-home-route-intent.test.ts": "clients", "link-route-intent.test.ts": "server", "route-intent-desktop.test.ts": "clients", "route-intent-materializer.test.ts": "clients", "route-intent-parity.test.ts": "clients", "route-intent-reporter.test.ts": "clients", "route-intent-state.test.ts": "clients", "route-intent.test.ts": "clients", "route-to-routes.test.ts": "server", "route-to-sync-child.test.ts": "routing", "service-disconnected-client-restart.test.ts": "service", "responses-forward-client-headers-live.test.ts": "responses", "pool-retry-client-metadata.test.ts": "responses", "responses-websocket-workflow-ceiling.test.ts": "responses", "responses-workflow-send-ceiling.test.ts": "responses", "kimi-monthly-quota.test.ts": "providers", "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "lmstudio-system-policy.test.ts": "config", "openai-chat-single-system.test.ts": "adapters/openai", "update-reclaim-authorizer.test.ts": "update", "update-capability-policy.test.ts": "update", "update-service-home.test.ts": "update", "update-service-home-policy.test.ts": "update", "update-home-recovery.test.ts": "update", "update-recovery-authority.test.ts": "update", "update-recovery-boundaries.test.ts": "update", "update-home-launcher.test.ts": "update", "update-home-worker.test.ts": "update", "update-mutation-boundaries.test.ts": "update", "update-mutation-guard.test.ts": "update", "update-guarded-ops.test.ts": "update", "update-effect-authority.test.ts": "update", "update-windows-wrapper-authority.test.ts": "update", "update-mutation-scanner.test.ts": "update", "refreshed-upstream-deadlines.test.ts": "responses", "local-upstream-deadlines.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "provider-input-modalities.test.ts": "providers", "turn-membership.test.ts": "responses", "turn-membership-ingress.test.ts": "responses", "workbuddy-quota.test.ts": "providers", "workbuddy-login.test.ts": "oauth", "workbuddy-adapter.test.ts": "adapters", "workbuddy-provider.test.ts": "providers", "link-tunnel-history.test.ts": "clients", "link-readiness.test.ts": "clients", "link-tunnel-status.test.ts": "clients", "link-diagnostics.test.ts": "clients", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "responses-chat-raw-summary.test.ts": "responses", "responses-phase-inference.test.ts": "responses", "cli-message-mcp-resume.test.ts": "cli", "messaging-mcp-resume.test.ts": "codex-integration", "link-diagnostics-read.test.ts": "clients", "cli-link-diagnostics.test.ts": "cli", "link-diagnostics-route.test.ts": "server", "provider-passive-wire-model.test.ts": "providers", "passive-key-observation.test.ts": "providers", "responses-passive-key-limits.test.ts": "responses", "passive-key-limits.test.ts": "providers", "terminal-safe-text.test.ts": "lib", +{ "explicit-proxy-no-proxy.test.ts": "lib", "gemini-native.test.ts": "server", "gemini-native-wire.test.ts": "server", "gemini-native-routes.test.ts": "server", "provider-upstream-deadlines.test.ts": "responses", "web-search-local-deadline-provenance.test.ts": "web-search", "responses-combo-unavailable-cause.test.ts": "responses", "responses-native-sse-stall.test.ts": "responses", "client-restart-sync-fence.test.ts": "clients", "service-scheduler-restart-respawn-refusal.test.ts": "service", "route-to-home-sync-review.test.ts": "routing", "route-intent-connect-post-commit.test.ts": "clients", "route-intent-file-originals.test.ts": "clients", "route-to-child-defaults.test.ts": "routing", "route-to-home-live-flags.test.ts": "routing", "route-to-home-native-truth.test.ts": "routing", "route-to-home-decisions.test.ts": "routing", "route-to-ephemeral.test.ts": "server", "link-pinned-sync-overwrite.test.ts": "clients", "cli-sync-fanout-ephemeral.test.ts": "cli", "route-intent-home-consent.test.ts": "clients", "management-route-intent-native-errors.test.ts": "server", "route-intent-offline-mode-switch.test.ts": "clients", "route-intent-parity-withdrawal.test.ts": "clients", "service-scheduler-restart-cleanup.test.ts": "service", "route-to-retirement-review.test.ts": "server", "route-to-policy-review.test.ts": "server", "management-route-intent-native-review.test.ts": "server", "route-to-home-off-review.test.ts": "routing", "codex-journal-provider-reserialization.test.ts": "codex-integration", "route-intent-parity-fallback.test.ts": "clients", "route-intent-native-originals.test.ts": "clients", "route-intent-native-review.test.ts": "clients", "route-intent-connected-capabilities.test.ts": "clients", "route-intent-connected-review.test.ts": "clients", "route-intent-connect-recovery.test.ts": "clients", "client-disconnect-field-snapshot.test.ts": "clients", "cli-route-to-confirmation.test.ts": "cli", "route-intent-runtime-stop.test.ts": "clients", "route-intent-codex-connect-disabled.test.ts": "clients", "route-intent-codex-transitions.test.ts": "clients", "route-to-live-settings.test.ts": "server", "route-intent-claude-surface.test.ts": "clients", "route-intent-local-receipt.test.ts": "clients", "route-intent-scheduler.test.ts": "clients", "route-intent-watch-client.test.ts": "clients", "route-intent-watch-boundary.test.ts": "server", "route-intent-watch-waiters.test.ts": "server", "home-route-intent-upgrade.test.ts": "clients", "route-intent-overwrite.test.ts": "clients", "codex-disconnect-owned-recovery.test.ts": "codex-integration", "service-restart-registration-guard.test.ts": "service", "client-disconnect-config-recovery.test.ts": "clients", "route-intent-aside.test.ts": "clients", "route-intent-connected.test.ts": "clients", "cli-link-route-intent.test.ts": "cli", "cli-route-to-aliases.test.ts": "cli", "cli-route-to.test.ts": "cli", "client-disconnect-edited-codex.test.ts": "clients", "codex-disconnect-fields.test.ts": "codex-integration", "link-home-route-intent.test.ts": "clients", "link-route-intent.test.ts": "server", "route-intent-desktop.test.ts": "clients", "route-intent-materializer.test.ts": "clients", "route-intent-parity.test.ts": "clients", "route-intent-reporter.test.ts": "clients", "route-intent-state.test.ts": "clients", "route-intent.test.ts": "clients", "route-to-routes.test.ts": "server", "route-to-sync-child.test.ts": "routing", "service-disconnected-client-restart.test.ts": "service", "responses-forward-client-headers-live.test.ts": "responses", "pool-retry-client-metadata.test.ts": "responses", "responses-websocket-workflow-ceiling.test.ts": "responses", "responses-workflow-send-ceiling.test.ts": "responses", "kimi-monthly-quota.test.ts": "providers", "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "lmstudio-system-policy.test.ts": "config", "openai-chat-single-system.test.ts": "adapters/openai", "update-reclaim-authorizer.test.ts": "update", "update-capability-policy.test.ts": "update", "update-service-home.test.ts": "update", "update-service-home-policy.test.ts": "update", "update-home-recovery.test.ts": "update", "update-recovery-authority.test.ts": "update", "update-recovery-boundaries.test.ts": "update", "update-home-launcher.test.ts": "update", "update-home-worker.test.ts": "update", "update-mutation-boundaries.test.ts": "update", "update-mutation-guard.test.ts": "update", "update-guarded-ops.test.ts": "update", "update-effect-authority.test.ts": "update", "update-windows-wrapper-authority.test.ts": "update", "update-mutation-scanner.test.ts": "update", "refreshed-upstream-deadlines.test.ts": "responses", "local-upstream-deadlines.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "provider-input-modalities.test.ts": "providers", "turn-membership.test.ts": "responses", "turn-membership-ingress.test.ts": "responses", "workbuddy-quota.test.ts": "providers", "workbuddy-login.test.ts": "oauth", "workbuddy-adapter.test.ts": "adapters", "workbuddy-provider.test.ts": "providers", "link-tunnel-history.test.ts": "clients", "link-readiness.test.ts": "clients", "link-tunnel-status.test.ts": "clients", "link-diagnostics.test.ts": "clients", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "responses-chat-raw-summary.test.ts": "responses", "responses-phase-inference.test.ts": "responses", "cli-message-mcp-resume.test.ts": "cli", "messaging-mcp-resume.test.ts": "codex-integration", "link-diagnostics-read.test.ts": "clients", "cli-link-diagnostics.test.ts": "cli", "link-diagnostics-route.test.ts": "server", "provider-passive-wire-model.test.ts": "providers", "passive-key-observation.test.ts": "providers", "responses-passive-key-limits.test.ts": "responses", "passive-key-limits.test.ts": "providers", "terminal-safe-text.test.ts": "lib", "codex-ws-recovery-budget.test.ts": "responses", "codex-ws-cache-miss.test.ts": "responses", "codex-ws-incremental.test.ts": "responses", diff --git a/tests/lib/explicit-proxy-no-proxy.test.ts b/tests/lib/explicit-proxy-no-proxy.test.ts new file mode 100644 index 00000000000..b1cbaac0ed7 --- /dev/null +++ b/tests/lib/explicit-proxy-no-proxy.test.ts @@ -0,0 +1,327 @@ +/** + * An explicit provider HTTP(S) proxy stays authoritative over the process NO_PROXY. + * + * Bun's fetch connects directly to a destination the process NO_PROXY exempts, even when the + * request names a proxy. These cases use a real transport (two loopback listeners) because a + * mocked fetch only sees the option, not the route the request actually takes. + */ +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from "bun:test"; +import { + configuredOutboundFetch, + ExplicitProxyExemptedError, + ExplicitProxyRedirectRefusedError, + processNoProxyExempts, + type ProxyCapableRequestInit, +} from "../../src/lib/proxy-env"; +import { providerEgressFetchInit, resolveProviderEgress } from "../../src/lib/provider-egress"; +import { providerFetch } from "../../src/server/responses/fetch-helpers"; +import { registerUpstreamRewriter } from "../../src/plugins/upstream-hooks"; +import { resetProviderTlsProfileForTests, setProviderTlsRuntimeForTest } from "../../src/lib/provider-tls-profile"; +import type { OcxProviderConfig } from "../../src/types"; + +const ENV_KEYS = ["NO_PROXY", "no_proxy", "HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "ALL_PROXY", "all_proxy"] as const; +const saved = new Map(); +const hits = { dest: 0, proxy: 0 }; +let dest: ReturnType; +let proxy: ReturnType; +let destUrl: string; +let proxyUrl: string; + +beforeAll(() => { + dest = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => { hits.dest += 1; return new Response("dest"); } }); + proxy = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: () => { hits.proxy += 1; return new Response("proxy"); } }); + destUrl = `http://127.0.0.1:${dest.port}/v1/models`; + proxyUrl = `http://127.0.0.1:${proxy.port}`; +}); +afterAll(() => { dest.stop(true); proxy.stop(true); }); +beforeEach(() => { + for (const key of ENV_KEYS) { saved.set(key, process.env[key]); delete process.env[key]; } + hits.dest = 0; + hits.proxy = 0; +}); +afterEach(() => { + for (const key of ENV_KEYS) { + const value = saved.get(key); + if (value === undefined) delete process.env[key]; else process.env[key] = value; + } +}); + +const send = (init: ProxyCapableRequestInit, target = destUrl) => + configuredOutboundFetch(target, { ...init, headers: { authorization: "Bearer synthetic-test-token" } } as RequestInit); + +test("without NO_PROXY the explicit proxy carries the request", async () => { + const response = await send({ proxy: proxyUrl }); + expect(await response.text()).toBe("proxy"); + expect(hits).toEqual({ dest: 0, proxy: 1 }); +}); + +for (const spelling of ["NO_PROXY", "no_proxy"] as const) { + for (const entry of ["127.0.0.1", "*"]) { + test(`a process ${spelling}=${entry} never sends an explicit-proxy request directly`, async () => { + process.env[spelling] = entry; + const error = await send({ proxy: proxyUrl }).then(() => null, (cause: unknown) => cause); + expect(error).toBeInstanceOf(ExplicitProxyExemptedError); + expect((error as ExplicitProxyExemptedError).code).toBe("explicit_proxy_exempted"); + expect((error as Error).message).not.toContain("synthetic-test-token"); + expect(hits).toEqual({ dest: 0, proxy: 0 }); + }); + } +} + +test("a provider proxy route resolved by the egress authority is refused the same way", async () => { + process.env.NO_PROXY = "127.0.0.1"; + const egress = resolveProviderEgress({ providerName: "p", provider: { proxy: proxyUrl }, url: destUrl }); + expect(egress.kind).toBe("proxy"); + await expect(send(providerEgressFetchInit(egress))).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(hits).toEqual({ dest: 0, proxy: 0 }); +}); + +test("the provider's own noProxy remains the way to connect such a host directly", async () => { + process.env.NO_PROXY = "127.0.0.1"; + const egress = resolveProviderEgress({ providerName: "p", provider: { proxy: proxyUrl, noProxy: "127.0.0.1" }, url: destUrl }); + expect(egress).toEqual({ kind: "direct", reason: "noProxy" }); + expect(await (await send(providerEgressFetchInit(egress))).text()).toBe("dest"); + expect(hits).toEqual({ dest: 1, proxy: 0 }); +}); + +test("an inherited route and proxy:false keep their existing behavior", async () => { + process.env.NO_PROXY = "127.0.0.1"; + expect(await (await send({})).text()).toBe("dest"); + expect(await (await send({ proxy: false })).text()).toBe("dest"); + expect(hits).toEqual({ dest: 2, proxy: 0 }); +}); + +test("exemption matching covers both spellings, wildcards, domains and WebSocket destinations", () => { + const url = new URL("wss://chatgpt.com/backend-api/codex/responses"); + expect(processNoProxyExempts(url, {})).toBe(false); + expect(processNoProxyExempts(url, { NO_PROXY: "example.com" })).toBe(false); + expect(processNoProxyExempts(url, { NO_PROXY: ".chatgpt.com" })).toBe(true); + expect(processNoProxyExempts(url, { no_proxy: "chatgpt.com" })).toBe(true); + expect(processNoProxyExempts(url, { NO_PROXY: "example.com", no_proxy: "*" })).toBe(true); + expect(processNoProxyExempts(url, { NO_PROXY: " " })).toBe(false); +}); + +// Bun's own matcher splits on whitespace and lets a bare entry cover subdomains; the guard must too. +for (const spelling of ["NO_PROXY", "no_proxy"] as const) { + test(`a whitespace-separated ${spelling} entry is honored like Bun honors it`, async () => { + process.env[spelling] = "example.com localhost"; + await expect(send({ proxy: proxyUrl }, `http://localhost:${dest.port}/v1/models`)).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(hits).toEqual({ dest: 0, proxy: 0 }); + }); + test(`a bare ${spelling} entry also exempts its subdomains, like Bun`, async () => { + process.env[spelling] = "localhost"; + await expect(send({ proxy: proxyUrl }, `http://app.localhost:${dest.port}/v1/models`)).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(hits).toEqual({ dest: 0, proxy: 0 }); + }); +} + +for (const spelling of ["NO_PROXY", "no_proxy"] as const) { + test(`a ${spelling} CIDR block covering the destination is honored like Bun honors it`, async () => { + process.env[spelling] = "10.0.0.0/8 127.0.0.0/8"; + await expect(send({ proxy: proxyUrl })).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(hits).toEqual({ dest: 0, proxy: 0 }); + }); + test(`a ${spelling} entry with a zero-padded port is compared numerically, like Bun`, async () => { + process.env[spelling] = `127.0.0.1:00${dest.port}`; + await expect(send({ proxy: proxyUrl })).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(hits).toEqual({ dest: 0, proxy: 0 }); + }); +} + +test("addresses compare canonically and CIDR blocks cover both families", () => { + const v4 = new URL("http://127.0.0.1:8080/x"); + const v6 = new URL("http://[::1]:8080/x"); + for (const entry of ["127.0.0.1", "::ffff:127.0.0.1", "[::ffff:127.0.0.1]", "127.0.0.0/8", "::ffff:127.0.0.0/104", "0.0.0.0/0", "127.0.0.1:08080"]) { + expect(processNoProxyExempts(v4, { NO_PROXY: entry }), entry).toBe(true); + } + for (const entry of ["10.0.0.0/8", "127.0.0.2/32", "127.0.0.1:80", "::ffff:127.0.0.0/95"]) { + expect(processNoProxyExempts(v4, { NO_PROXY: entry }), entry).toBe(false); + } + for (const entry of ["::1", "[::1]", "0:0:0:0:0:0:0:1", "0000::1", "::1/128", "::/0", "[::1]:8080", "[::1]:08080"]) { + expect(processNoProxyExempts(v6, { NO_PROXY: entry }), entry).toBe(true); + } + for (const entry of ["fe80::/10", "[::1]:80", "::2"]) { + expect(processNoProxyExempts(v6, { NO_PROXY: entry }), entry).toBe(false); + } +}); + +test("every entry form Bun 1.4.4 treats as a bypass is a bypass here", () => { + const url = new URL("http://api.example.com/x"); + // Each of these made Bun connect directly to api.example.com despite an explicit proxy. + for (const entry of ["example.com", ".example.com", "*.example.com", "api.example.com", "api.example.com:80", "EXAMPLE.COM", + "other.org example.com", "other.org\texample.com", " example.com ", "*", "com", ".com", "example.com.", "other.org,,example.com"]) { + expect(processNoProxyExempts(url, { NO_PROXY: entry }), entry).toBe(true); + expect(processNoProxyExempts(url, { no_proxy: entry }), entry).toBe(true); + } + // Bun kept the proxy for these, and so does the guard. + for (const entry of ["ample.com", "xample.com", "api.example", "api.example.com:8080", "[::1]", "example.*"]) { + expect(processNoProxyExempts(url, { NO_PROXY: entry }), entry).toBe(false); + } + expect(processNoProxyExempts(new URL("https://api.example.com/x"), { NO_PROXY: "api.example.com:443" })).toBe(true); + expect(processNoProxyExempts(new URL("http://[::1]:8080/x"), { NO_PROXY: "[::1]" })).toBe(true); +}); + +describe("the provider send boundary", () => { + const provider = () => ({ adapter: "openai-chat", baseUrl: `http://127.0.0.1:${dest.port}/v1`, proxy: proxyUrl }) as unknown as OcxProviderConfig; + + test("an exempted provider proxy route is refused before any dispatch side effect", async () => { + process.env.NO_PROXY = "127.0.0.1"; + let receipts = 0; + let checked = 0; + const send = providerFetch(provider(), undefined, { + providerName: "p", onPhysicalDispatch: () => { receipts += 1; }, beforeDispatch: () => { checked += 1; }, + }); + await expect(send(destUrl, { method: "POST", body: "synthetic-body" })).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect({ receipts, checked }).toEqual({ receipts: 0, checked: 0 }); + expect(hits).toEqual({ dest: 0, proxy: 0 }); + }); + + test("a destination rebuilt by a dispatch override is decided before its dispatch receipt", async () => { + process.env.NO_PROXY = "localhost"; + let receipts = 0; + const send = providerFetch(provider(), undefined, { + providerName: "p", onPhysicalDispatch: () => { receipts += 1; }, + // The queued request is rebuilt against another host at its physical send. + dispatchOverride: (_input, init, execute) => execute(`http://localhost:${dest.port}/v1/models`, init), + }); + await expect(send(destUrl, { method: "POST", body: "synthetic-body" })).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(receipts).toBe(0); + expect(hits).toEqual({ dest: 0, proxy: 0 }); + }); + + test("an exempted original URL that a plugin rewrites to a local sidecar is not refused early", async () => { + process.env.NO_PROXY = "example.com"; + const unregister = registerUpstreamRewriter("test-sidecar", target => { + if (target.url.startsWith("https://example.com/")) target.url = `http://127.0.0.1:${dest.port}/v1/models`; + }); + try { + const send = providerFetch({ adapter: "openai-chat", baseUrl: "https://example.com/v1", proxy: proxyUrl } as unknown as OcxProviderConfig, + undefined, { providerName: "p" }); + expect(await (await send("https://example.com/v1/models")).text()).toBe("dest"); + // A rewrite onto this machine's loopback dials directly, as before. + expect(hits).toEqual({ dest: 1, proxy: 0 }); + } finally { + unregister(); + } + }); + + test("the Antigravity TLS profile transport never receives an exempted proxy route", async () => { + process.env.NO_PROXY = ".googleapis.com"; + let tlsSends = 0; + setProviderTlsRuntimeForTest({ env: { ...process.env }, fetch: async () => { tlsSends += 1; return new Response("tls"); } }); + try { + const send = providerFetch({ + adapter: "google", authMode: "oauth", googleMode: "cloud-code-assist", baseUrl: "https://cloudcode-pa.googleapis.com", + tlsProfile: "antigravity-browser", proxy: proxyUrl, + } as unknown as OcxProviderConfig, undefined, { providerName: "google-antigravity" }); + await expect(send("https://cloudcode-pa.googleapis.com/v1internal:streamGenerateContent", { method: "POST", body: "{}" })) + .rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(tlsSends).toBe(0); + expect(hits).toEqual({ dest: 0, proxy: 0 }); + } finally { + resetProviderTlsProfileForTests(); + } + }); + + test("a route that is not exempted still dispatches once through the proxy", async () => { + process.env.NO_PROXY = "example.invalid"; + let receipts = 0; + const send = providerFetch(provider(), undefined, { providerName: "p", onPhysicalDispatch: () => { receipts += 1; } }); + expect(await (await send(destUrl, { method: "POST", body: "synthetic-body" })).text()).toBe("proxy"); + expect(receipts).toBe(1); + expect(hits).toEqual({ dest: 0, proxy: 1 }); + }); +}); + +describe("redirects of an explicit-proxy request", () => { + type Seen = { method: string; path: string; body: string }; + const viaProxy: Seen[] = []; + const atExempt: Seen[] = []; + let redirectTo = ""; + let redirectStatus = 307; + let exempt: ReturnType; + let forwardProxy: ReturnType; + const seen = async (req: Request): Promise => ({ method: req.method, path: new URL(req.url).pathname, body: await req.text() }); + + beforeAll(() => { + exempt = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: async req => { atExempt.push(await seen(req)); return new Response("exempt"); } }); + // A forward proxy: it answers every proxied request itself, redirecting /start. + forwardProxy = Bun.serve({ port: 0, hostname: "127.0.0.1", fetch: async req => { + const request = await seen(req); + viaProxy.push(request); + if (request.path === "/start") return new Response(null, { status: redirectStatus, headers: { location: redirectTo } }); + return new Response(`landed ${request.method} ${request.body}`); + } }); + }); + afterAll(() => { exempt.stop(true); forwardProxy.stop(true); }); + beforeEach(() => { viaProxy.length = 0; atExempt.length = 0; redirectStatus = 307; }); + + const proxied = (init: RequestInit = {}) => ({ ...init, proxy: `http://127.0.0.1:${forwardProxy.port}` }) as ProxyCapableRequestInit as RequestInit; + const startUrl = () => `http://127.0.0.1:${dest.port}/start`; + const post = () => configuredOutboundFetch(startUrl(), proxied({ + method: "POST", body: "synthetic-body", headers: { authorization: "Bearer synthetic-test-token", "x-api-key": "synthetic-test-key" } })); + + for (const spelling of ["NO_PROXY", "no_proxy"] as const) { + test(`a redirect toward a destination ${spelling} exempts is refused and that destination is never contacted`, async () => { + process.env[spelling] = `127.0.0.1:${exempt.port}`; + redirectTo = `http://127.0.0.1:${exempt.port}/landing`; + await expect(post()).rejects.toBeInstanceOf(ExplicitProxyRedirectRefusedError); + expect(viaProxy.map(request => request.path)).toEqual(["/start"]); + expect(atExempt).toEqual([]); + }); + } + + for (const status of [301, 302, 303, 307, 308]) { + test(`with a bypass list set, a ${status} is refused after exactly one send`, async () => { + process.env.NO_PROXY = "example.invalid"; + redirectStatus = status; + redirectTo = `http://127.0.0.1:${dest.port}/landing`; + const error = await post().then(() => null, (cause: unknown) => cause); + expect(error).toBeInstanceOf(ExplicitProxyRedirectRefusedError); + expect((error as ExplicitProxyRedirectRefusedError).code).toBe("explicit_proxy_redirect_refused"); + expect(viaProxy).toEqual([{ method: "POST", path: "/start", body: "synthetic-body" }]); + }); + } + + test("a Request carrying a streamed body is sent once and its redirect refused", async () => { + process.env.NO_PROXY = "example.invalid"; + redirectTo = `http://127.0.0.1:${dest.port}/landing`; + const body = new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode("streamed")); controller.close(); } }); + const request = new Request(startUrl(), { method: "POST", body, duplex: "half" } as RequestInit); + await expect(configuredOutboundFetch(request, proxied())).rejects.toBeInstanceOf(ExplicitProxyRedirectRefusedError); + expect(viaProxy).toEqual([{ method: "POST", path: "/start", body: "streamed" }]); + }); + + test("without a bypass list Bun's own redirect handling is unchanged", async () => { + redirectTo = `http://127.0.0.1:${dest.port}/landing`; + const response = await post(); + expect(await response.text()).toBe("landed POST synthetic-body"); + expect(response.redirected).toBe(true); + expect(viaProxy.map(request => request.path)).toEqual(["/start", "/landing"]); + }); + + test("an unredirected response passes through untouched", async () => { + process.env.NO_PROXY = "example.invalid"; + const response = await configuredOutboundFetch(`http://127.0.0.1:${dest.port}/landing`, proxied()); + expect(response.redirected).toBe(false); + expect(response.clone().redirected).toBe(false); + expect(await response.text()).toBe("landed GET "); + }); + + test("a caller's error redirect mode reaches Bun unchanged and makes no second request", async () => { + process.env.NO_PROXY = "example.invalid"; + redirectTo = `http://127.0.0.1:${dest.port}/landing`; + const error = await configuredOutboundFetch(startUrl(), proxied({ redirect: "error" })).then(() => null, (cause: unknown) => cause); + expect(error).toBeInstanceOf(Error); + expect(error).not.toBeInstanceOf(ExplicitProxyRedirectRefusedError); + expect(viaProxy.map(request => request.path)).toEqual(["/start"]); + }); + + test("a caller's manual redirect mode is left to the caller", async () => { + process.env.NO_PROXY = `127.0.0.1:${exempt.port}`; + redirectTo = `http://127.0.0.1:${exempt.port}/landing`; + const response = await configuredOutboundFetch(startUrl(), proxied({ redirect: "manual" })); + expect(response.status).toBe(307); + expect(atExempt).toEqual([]); + }); +}); diff --git a/tests/providers/m365-copilot.test.ts b/tests/providers/m365-copilot.test.ts index 41c0c63412e..05802853981 100644 --- a/tests/providers/m365-copilot.test.ts +++ b/tests/providers/m365-copilot.test.ts @@ -437,16 +437,31 @@ describe("Microsoft 365 Copilot socket egress", () => { expect(() => m365SocketDialOptions({ fetch: globalThis.fetch }, socketUrl, headers)).toThrow("cannot use a custom fetch executor"); expect(() => m365SocketDialOptions({ proxy: "" }, socketUrl, headers)).toThrow(/providers[.]m365-copilot[.]proxy is invalid/); }); - test("inherited proxy respects the global bypass list without overriding an explicit provider proxy", () => { + test("inherited proxy respects the global bypass list, and an exempted explicit provider proxy is refused", () => { const previousProxy = process.env.HTTPS_PROXY, previousNoProxy = process.env.NO_PROXY; process.env.HTTPS_PROXY = "http://127.0.0.1:9"; process.env.NO_PROXY = "substrate.office.com"; try { expect(m365SocketDialOptions({}, socketUrl, headers).proxy).toBeUndefined(); - expect(m365SocketDialOptions({ proxy: "http://127.0.0.1:9" }, socketUrl, headers).proxy).toBe("http://127.0.0.1:9/"); + // Bun's WebSocket would skip an explicit proxy here and connect directly, so the dial is refused. + expect(() => m365SocketDialOptions({ proxy: "http://127.0.0.1:9" }, socketUrl, headers)).toThrow("NO_PROXY"); + expect(m365SocketDialOptions({ proxy: "http://127.0.0.1:9", noProxy: ["substrate.office.com"] }, socketUrl, headers).proxy).toBeUndefined(); } finally { if (previousProxy === undefined) delete process.env.HTTPS_PROXY; else process.env.HTTPS_PROXY = previousProxy; if (previousNoProxy === undefined) delete process.env.NO_PROXY; else process.env.NO_PROXY = previousNoProxy; } }); + test("an exempted explicit provider proxy refuses the turn before any socket is created", () => { + const previousNoProxy = process.env.NO_PROXY; + process.env.NO_PROXY = "office.com"; + let sockets = 0; + try { + // The dial is planned synchronously, like the other dial refusals, before any socket exists. + expect(() => runM365CopilotTurn({ token: token(), model: "Claude_Sonnet", text: "fixture", conversation: createM365Conversation(), onText() {}, + route: { proxy: "http://127.0.0.1:9" }, createSocket() { sockets += 1; return new WebSocket("ws://127.0.0.1:9"); } })).toThrow("NO_PROXY"); + expect(sockets).toBe(0); + } finally { + if (previousNoProxy === undefined) delete process.env.NO_PROXY; else process.env.NO_PROXY = previousNoProxy; + } + }); }); diff --git a/tests/providers/provider-egress-outbound.test.ts b/tests/providers/provider-egress-outbound.test.ts index bdf233dc1df..862a4cbcb58 100644 --- a/tests/providers/provider-egress-outbound.test.ts +++ b/tests/providers/provider-egress-outbound.test.ts @@ -113,24 +113,26 @@ describe("per-provider egress on the discovery and quota transport", () => { } }); - test("a provider proxy applies where global NO_PROXY exempts the host", async () => { - // The operator named this proxy for this provider. A global bypass list describes the - // global route and must not silently cancel the provider's own choice; the exemption that - // belongs to that choice is providers..noProxy, asserted below. + test("a provider proxy is never traded for direct egress where global NO_PROXY exempts the host", async () => { + // The operator named this proxy for this provider, but Bun skips a request-scoped proxy for a + // destination the process NO_PROXY exempts and would connect directly. The send is refused + // instead; the exemption that belongs to the provider's choice is providers..noProxy, + // asserted below. tests/lib/explicit-proxy-no-proxy.test.ts proves the route on a real socket. for (const key of proxyKeys) delete process.env[key]; process.env.HTTPS_PROXY = GLOBAL_PROXY; process.env.NO_PROXY = "provider.example"; process.env.no_proxy = "provider.example"; const { providerOutboundGet } = await import("../../src/lib/provider-outbound"); + const { ExplicitProxyExemptedError } = await import("../../src/lib/proxy-env"); const { dependencies } = pinnedDependencies(); const proxied = captureProxiedFetch(); try { - await providerOutboundGet( + await expect(providerOutboundGet( "vendor", { baseUrl: "https://provider.example", proxy: PROVIDER_PROXY }, MODELS_URL, {}, dependencies, - ); - expect(proxied.calls).toEqual([`${PROVIDER_PROXY}/`]); + )).rejects.toBeInstanceOf(ExplicitProxyExemptedError); + expect(proxied.calls).toEqual([]); } finally { proxied.restore(); } From c3aa113919e6062efc96e1fa9aa98b21af9405cc Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Wed, 25 Nov 2026 13:48:06 +0900 Subject: [PATCH 17/60] test(web-search): isolate sticky selection from the header-timeout fixture (#9070) Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- .../web-search-local-deadline-provenance.test.ts | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/tests/web-search/web-search-local-deadline-provenance.test.ts b/tests/web-search/web-search-local-deadline-provenance.test.ts index ef2f27264c3..b107bc18e97 100644 --- a/tests/web-search/web-search-local-deadline-provenance.test.ts +++ b/tests/web-search/web-search-local-deadline-provenance.test.ts @@ -322,6 +322,7 @@ describe("combo web-search deadline provenance", () => { const secondary = { provider: "fixture-backup", model: "fixture-model" }; async function comboRun(stallOnBody: boolean, surface = "responses", upstream = false, stream = true, backup = false): Promise { + const stickyBodyDeadline = backup && stallOnBody; let releaseSpendHome: (() => void) | undefined; let warn: ReturnType> | undefined; const home = createTempHome("ocx-combo-web-search-deadline-"); @@ -349,7 +350,9 @@ describe("combo web-search deadline provenance", () => { }) as typeof fetch; const config: OcxConfig = { - port: 0, defaultProvider: "fixture-routed", connectTimeoutMs: HEADER_MS, + port: 0, defaultProvider: "fixture-routed", + // This case stalls after visible body bytes. Healthy responses use the normal header budget. + ...(stickyBodyDeadline ? {} : { connectTimeoutMs: HEADER_MS }), providers: { "fixture-routed": { adapter: "openai-chat", baseUrl: "https://routed.test/v1", authMode: "key", apiKey: "fixture" }, ...(backup && { "fixture-backup": { adapter: "openai-chat", baseUrl: "https://backup.test/v1", authMode: "key", apiKey: "fixture" } as const }), @@ -403,11 +406,15 @@ describe("combo web-search deadline provenance", () => { } const outcome = await send(); - if (backup && stallOnBody) { + if (stickyBodyDeadline) { expect(outcome.wire).toContain(output); expect(outcome.row.failureDetail).toEqual({ code: "generation_timeout", value: comboStallMs }); expect(isComboTargetInCooldown(comboId, primary)).toBe(false); - expect((await send()).wire).toContain("primary answered"); + const next = await send(); + expect(next.row.attempts?.map(({ provider, status }) => ({ provider, status }))).toEqual([ + { provider: primary.provider, status: 200 }, + ]); + expect(next.wire).toContain("primary answered"); expect((await send()).wire).toContain("backup answered"); expect(sends).toEqual([primaryUrl, primaryUrl, backupUrl]); return outcome; From 927c3f3324e5e80217062809d85fd1803b75ea1f Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Wed, 25 Nov 2026 13:49:00 +0900 Subject: [PATCH 18/60] fix(step-cli): bound new sessions while preserving existing conversations (#9065) Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- .../src/content/docs/es/guides/step-cli.md | 4 ++ docs-site/src/content/docs/guides/step-cli.md | 4 ++ src/adapters/step-cli/errors.ts | 3 ++ src/adapters/step-cli/session-pool.ts | 8 +++ structure/providers/step-cli-transport.md | 2 + tests/adapters/step-cli-session.test.ts | 50 +++++++++++++++++++ 6 files changed, 71 insertions(+) diff --git a/docs-site/src/content/docs/es/guides/step-cli.md b/docs-site/src/content/docs/es/guides/step-cli.md index 838bde97a84..60ed925993b 100644 --- a/docs-site/src/content/docs/es/guides/step-cli.md +++ b/docs-site/src/content/docs/es/guides/step-cli.md @@ -56,6 +56,10 @@ aprobarlas y ejecutarlas: notificación de salida. Si el lanzador ya ha salido o la limpieza sigue sin confirmarse después de que la utilidad haya podido ejecutarse, OpenCodex pone la sesión en cuarentena, registra una advertencia fija e informa de que la limpieza quedó incompleta. +- **Capacidad de conversaciones.** Cada proxy admite ocho sesiones de StepCode por directorio de OpenCodex. + Si las ocho plazas están ocupadas, las conversaciones existentes pueden continuar. Una nueva + recibe el error `step_cli_pool_full` y puede reintentarse cuando se libere una plaza. + Las sesiones inactivas siguen contando hasta que termina su cierre tras diez minutos de inactividad. - **Límites de sesión.** Si una herramienta tarda más de dos minutos en devolver un resultado, el turno informa del error `step_cli_tool_result_too_late`. El protocolo no permite reemplazar el mensaje de sistema de la sesión. OpenCodex antepone las instrucciones del cliente al turno. diff --git a/docs-site/src/content/docs/guides/step-cli.md b/docs-site/src/content/docs/guides/step-cli.md index ab55701c8e6..469211f17c9 100644 --- a/docs-site/src/content/docs/guides/step-cli.md +++ b/docs-site/src/content/docs/guides/step-cli.md @@ -55,6 +55,10 @@ StepCode: accepted this residual risk on 2026-11-19 alongside the POSIX reap-ordering risk. If the wrapper has already exited or cleanup is unconfirmed after the helper may have run, OpenCodex quarantines the session, logs a fixed warning and reports incomplete cleanup. +- **Conversation capacity:** A proxy can keep eight StepCode sessions per OpenCodex home. When all + slots are occupied, existing conversations can continue. A new one receives `step_cli_pool_full` + and can retry after a slot frees up. Idle sessions still count until + cleanup after the ten-minute idle timeout completes. - **Two documented limits:** a tool that takes longer than two minutes to come back exceeds the CLI's own tool-result window and the turn reports `step_cli_tool_result_too_late`; and the CLI's session system prompt cannot be replaced through this protocol, so your instructions are prepended diff --git a/src/adapters/step-cli/errors.ts b/src/adapters/step-cli/errors.ts index d9909e21a37..3b9a889d6b7 100644 --- a/src/adapters/step-cli/errors.ts +++ b/src/adapters/step-cli/errors.ts @@ -4,6 +4,7 @@ import type { StepProtocolErrorPayload } from "./stdio-frames"; type StepSessionErrorCode = | "step_cli_session_failed" | "step_cli_session_busy" + | "step_cli_pool_full" | "step_cli_binary_missing" | "step_cli_capability_missing" | "step_cli_protocol_violation" @@ -68,6 +69,8 @@ export function mapSessionFailure(error: unknown): AdapterEvent { return refusal(failure.message, 401, failure.code, "authentication_error"); case "step_cli_subscription_cooldown": return refusal(failure.message, 429, failure.code, "rate_limit_error"); + case "step_cli_pool_full": + return refusal(failure.message, 503, failure.code, "server_error", true); case "timeout": return refusal(failure.message, 504, failure.code, "upstream_error", true); default: diff --git a/src/adapters/step-cli/session-pool.ts b/src/adapters/step-cli/session-pool.ts index 3cbcafdf415..10a39257301 100644 --- a/src/adapters/step-cli/session-pool.ts +++ b/src/adapters/step-cli/session-pool.ts @@ -1,5 +1,7 @@ import { StepCliSession, StepSessionError, type StepSessionDeps, type StepSessionEvent, type StepSessionHandlers, type StepSessionOptions } from "./session"; +const MAX_SESSIONS_PER_HOME = 8; + /** Conversation identity the client echoes back through `providerState`. */ export interface StepConversationRef { sessionId: string; @@ -114,6 +116,12 @@ export class StepSessionPool implements StepConversationHost { } const inFlight = this.#opening.get(ref.handle); if (inFlight) return inFlight; + if (this.#sessions.size >= MAX_SESSIONS_PER_HOME) { + throw new StepSessionError( + `The StepCode pool for this OpenCodex home is full (${MAX_SESSIONS_PER_HOME} sessions). Retry when a session closes.`, + "step_cli_pool_full", + ); + } const opening = (async () => { const session = await StepCliSession.open(this.#options.buildOptions(), this.#handlers, this.#deps, owned => { this.#sessions.add(owned); diff --git a/structure/providers/step-cli-transport.md b/structure/providers/step-cli-transport.md index 25d6a0e0a87..bd974780d10 100644 --- a/structure/providers/step-cli-transport.md +++ b/structure/providers/step-cli-transport.md @@ -41,6 +41,8 @@ permission denials. `session-pool.ts` latches shutdown before awaiting sessions and in-flight opens. The pool owns each session before workspace setup, so shutdown can close an opening session before it spawns. +At eight owned sessions a home pool refuses new conversations with retryable `step_cli_pool_full`. +Existing handles and coalesced opens still work. Only confirmed cleanup releases capacity. The pool retains ownership of adapter, idle-timer and sweep closes until termination is confirmed. Shutdown drains those receipts and propagates failures. Closing handles refuse replacement. Session close is idempotent and clears held-request timers. diff --git a/tests/adapters/step-cli-session.test.ts b/tests/adapters/step-cli-session.test.ts index 184d95a9ed5..3a266467bd7 100644 --- a/tests/adapters/step-cli-session.test.ts +++ b/tests/adapters/step-cli-session.test.ts @@ -5,6 +5,7 @@ import { join } from "node:path"; import { PassThrough } from "node:stream"; import { describe, expect, test } from "bun:test"; +import { mapSessionFailure } from "../../src/adapters/step-cli/errors"; import { StepSessionPool } from "../../src/adapters/step-cli/session-pool"; import { StepCliSession, @@ -389,6 +390,55 @@ describe("StepCode session pool", () => { killGraceMs: 10, }); + test("pool capacity counts opening and closing sessions while existing conversations can continue", async () => { + const children: FakeStep["child"][] = []; + const pool = new StepSessionPool( + { openCodexHome: tmpdir(), idleTimeoutMs: 60_000, buildOptions: () => ({ ...options(), cwd: tmpdir() }) }, + { onEvent: () => undefined }, + { spawn: () => { + const child = fakeChild(); + children.push(child); + return child; + }, platform: "linux" }, + ); + const refs = Array.from({ length: 8 }, () => pool.nextRef()); + const next = pool.nextRef(); + try { + const opening = refs.map(ref => pool.open(ref)); + const reuse = pool.open(refs[0]!); + await expect(pool.open(next).catch(mapSessionFailure)).resolves.toMatchObject({ + status: 503, code: "step_cli_pool_full", errorType: "server_error", retryable: true, + }); + const sessions = await Promise.all(opening); + expect(await reuse).toBe(sessions[0]!); + expect(await pool.open(refs[1]!)).toBe(sessions[1]!); + expect(children).toHaveLength(8); + + const closingPeer = Promise.withResolvers(); + for (const child of children) { + child.kill = () => { + closingPeer.resolve(child); + return true; + }; + } + const closing = sessions[0]!.close(); + const child = await closingPeer.promise; + await expect(pool.open(next)).rejects.toMatchObject({ code: "step_cli_pool_full" }); + child.exitCode = 0; + child.emit("close", 0, null); + await closing; + const replacement = await pool.open(next); + expect(pool.get(next)).toBe(replacement); + expect(children).toHaveLength(9); + } finally { + for (const child of children) { + child.exitCode = 0; + child.emit("close", 0, null); + } + await pool.closeAll(); + } + }); + test("two concurrent opens of one conversation share a single process", async () => { // Regression: `open` was async with no in-flight coalescing, so a Codex retry (or two clients on one // handle) spawned two processes, the second `#entries.set` orphaned the first, and the orphan's From 846ebcd4031ed1838a082a6a7a9c34aaca6372e8 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Wed, 25 Nov 2026 13:49:24 +0900 Subject: [PATCH 19/60] fix(gemini): bound pending tool data in translated streams (#9067) Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- .../content/docs/reference/proxy-formats.md | 2 + src/protocols/codecs/gemini.ts | 51 ++++++++++++--- src/server/gemini-inbound.ts | 5 +- structure/data-planes/gemini-inbound.md | 6 +- .../responses/responses-gemini-codec.test.ts | 62 +++++++++++++++++++ tests/server/server-native-final-log.test.ts | 33 ++++++++++ 6 files changed, 146 insertions(+), 13 deletions(-) diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index def6d1b613e..ec6b577433a 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -874,6 +874,8 @@ from the URL and headers before the request is logged or forwarded. Errors use G `contents`, `systemInstruction`, inline images, function declarations and calls, and `generationConfig`. Thought signatures on `functionCall` parts are carried in both directions. With `alt=sse` the stream is SSE; without it the answer is one JSON array, as Google's REST API sends it. + For streaming responses, the Chat bridge buffers up to 2 MiB of arguments per tool call and 32 MiB of pending tool data + per turn. Exceeding either limit ends the translated stream with an error. Hosted Gemini tools are ignored. A `candidateCount` other than 1, non-image inline data and file parts are refused with 400. - `:countTokens` returns `{ "totalTokens": n }` from a local estimate and sends nothing upstream. diff --git a/src/protocols/codecs/gemini.ts b/src/protocols/codecs/gemini.ts index a4051167930..44994ca828b 100644 --- a/src/protocols/codecs/gemini.ts +++ b/src/protocols/codecs/gemini.ts @@ -9,6 +9,7 @@ * complete functionCall part, because Gemini clients expect whole calls. */ import { normalizedClientExtraContent } from "../../responses/provider-opaque-metadata"; +import { createTranslatorBudget, type TranslatorBudget } from "../../lib/translator-budget"; type Obj = Record; @@ -387,16 +388,37 @@ export function chatToGeminiResponse(model: string, input: unknown): Obj { return { candidates: [candidate(parts, reason)], ...(usage ? { usageMetadata: usage } : {}), modelVersion: model }; } -type StreamTool = { id?: string; name: string; arguments: string; signature?: string }; +type StreamTool = { id?: string; name: string; arguments: string; signature?: string; nameTail?: number; argumentsTail?: number }; export interface GeminiStreamState { model: string; finishReason?: unknown; usage?: Obj; tools: Map; toolsEmitted: boolean; + toolBudget?: TranslatorBudget | null; } -export function createGeminiStreamState(model: string): GeminiStreamState { - return { model, tools: new Map(), toolsEmitted: false }; +export function createGeminiStreamState(model: string, toolBudget?: TranslatorBudget): GeminiStreamState { + return { model, tools: new Map(), toolsEmitted: false, toolBudget }; +} + +/** The stream owns its tool budget; finishing the calls or closing the stream releases it. */ +export function disposeGeminiStreamTools(state: GeminiStreamState): void { + state.tools.clear(); + state.toolBudget?.dispose(); + // An in-flight read may settle after cancellation. A closed stream must not open a new budget. + state.toolBudget = null; +} + +function appendToolFragment(tool: StreamTool, field: "name" | "arguments", fragment: string, budget: TranslatorBudget, callId?: string): void { + if (!fragment) return; + const tail = field === "name" ? "nameTail" : "argumentsTail"; + const previous = tool[tail]; + const first = fragment.charCodeAt(0); + // Two isolated surrogate halves cost three UTF-8 bytes each, but together cost four. + const completesPair = previous !== undefined && previous >= 0xd800 && previous <= 0xdbff && first >= 0xdc00 && first <= 0xdfff; + budget.chargeRetained(Buffer.byteLength(fragment) - (completesPair ? 2 : 0), { kind: "tool_args", callId }); + tool[field] += fragment; + tool[tail] = fragment.charCodeAt(fragment.length - 1); } function streamChunk(state: GeminiStreamState, parts: Obj[]): Obj { @@ -424,24 +446,34 @@ export function consumeGeminiChatChunk(state: GeminiStreamState, input: unknown) if (value) records.push(streamChunk(state, [{ text: value }])); } if (delta.tool_calls !== undefined) { - if (!Array.isArray(delta.tool_calls) || state.toolsEmitted) throw new Error("Invalid Chat tool delta"); + if (!Array.isArray(delta.tool_calls) || state.toolsEmitted || state.toolBudget === null) throw new Error("Invalid Chat tool delta"); for (const raw of delta.tool_calls) { const call = object(raw, "tool delta"); if (!Number.isSafeInteger(call.index) || (call.index as number) < 0) throw new Error("Invalid tool index"); const index = call.index as number; - if (!state.tools.has(index) && state.tools.size >= MAX_GEMINI_TOOL_CALLS) throw new Error("Too many tool calls"); - const current = state.tools.get(index) ?? { name: "", arguments: "" }; + const previous = state.tools.get(index); + if (!previous && state.tools.size >= MAX_GEMINI_TOOL_CALLS) throw new Error("Too many tool calls"); + const budget = state.toolBudget ??= createTranslatorBudget(); + const callId = String(index); + if (!previous) budget.openCall(callId); + const current = previous ?? { name: "", arguments: "" }; if (call.id !== undefined) { const id = text(call.id, "tool id", true); if (current.id && current.id !== id) throw new Error("Conflicting tool id"); + if (!current.id) budget.chargeRetained(Buffer.byteLength(id), { kind: "tool_args" }); current.id = id; } const signature = chatCallSignature(call.extra_content); - if (signature) current.signature = signature; + if (signature && signature !== current.signature) { + const delta = Buffer.byteLength(signature) - Buffer.byteLength(current.signature ?? ""); + if (delta > 0) budget.chargeRetained(delta, { kind: "tool_args" }); + if (delta < 0) budget.releaseRetained(-delta, { kind: "tool_args" }); + current.signature = signature; + } if (call.function !== undefined) { const fn = object(call.function, "tool function"); - if (fn.name !== undefined) current.name += text(fn.name, "tool name"); - if (fn.arguments !== undefined) current.arguments += text(fn.arguments, "tool arguments"); + if (fn.name !== undefined) appendToolFragment(current, "name", text(fn.name, "tool name"), budget); + if (fn.arguments !== undefined) appendToolFragment(current, "arguments", text(fn.arguments, "tool arguments"), budget, callId); } state.tools.set(index, current); } @@ -453,6 +485,7 @@ export function consumeGeminiChatChunk(state: GeminiStreamState, input: unknown) .map(([index, tool]) => functionCallPart(tool.id, text(tool.name, "tool name", true), tool.arguments, index, tool.signature)); records.push(streamChunk(state, parts)); state.toolsEmitted = true; + disposeGeminiStreamTools(state); } } return records; diff --git a/src/server/gemini-inbound.ts b/src/server/gemini-inbound.ts index 6ff831de6ad..df9708dcf4b 100644 --- a/src/server/gemini-inbound.ts +++ b/src/server/gemini-inbound.ts @@ -8,7 +8,7 @@ * the ordinary Chat path, and this handler owns the final request-log row. Errors use the Gemini * `{ error: { code, message, status } }` body with a fixed message chosen by HTTP status. */ -import { GeminiCodecError, chatToGeminiResponse, consumeGeminiChatChunk, createGeminiStreamState, geminiStreamTerminal, geminiToChat } from "../protocols/codecs/gemini"; +import { GeminiCodecError, chatToGeminiResponse, consumeGeminiChatChunk, createGeminiStreamState, disposeGeminiStreamTools, geminiStreamTerminal, geminiToChat } from "../protocols/codecs/gemini"; import { createTranslatorBudget, isTranslatorBudgetExceededError } from "../lib/translator-budget"; import type { OcxConfig, OcxParsedRequest } from "../types"; import type { RouteResult } from "../router"; @@ -256,11 +256,12 @@ const arrayFraming = (): GeminiFraming => { return { contentType: "application/json", frames, end: records => [...frames(records), encoder.encode("\n]")] }; }; -function streamGemini(model: string, sse: boolean, body: ReadableStream, finalLog: NativeFinalLog, signal: AbortSignal): Response { +export function streamGemini(model: string, sse: boolean, body: ReadableStream, finalLog: NativeFinalLog, signal: AbortSignal): Response { const state = createGeminiStreamState(model); const framing = sse ? sseFraming() : arrayFraming(); return streamNativeFromChat({ contentType: framing.contentType, + dispose: () => disposeGeminiStreamTools(state), chunk: parsed => framing.frames(consumeGeminiChatChunk(state, parsed)), terminal() { const record = geminiStreamTerminal(state); diff --git a/structure/data-planes/gemini-inbound.md b/structure/data-planes/gemini-inbound.md index 79d81c45613..3c1445304bf 100644 --- a/structure/data-planes/gemini-inbound.md +++ b/structure/data-planes/gemini-inbound.md @@ -51,8 +51,10 @@ schema) onto one Chat body, reading camelCase or snake_case. Hosted Gemini tools that would change the answer (`candidateCount` other than 1, non-image inline data, file parts, more than 1,024 function calls) is a 400. Responses map Chat finish `stop` and `tool_calls` to `STOP`, `length` to `MAX_TOKENS` and `content_filter` to `SAFETY`; an unknown or missing finish is an -error, never a success. A streamed tool call is accumulated and emitted as one whole `functionCall` -part. Usage becomes `usageMetadata`, with reasoning tokens reported as `thoughtsTokenCount`. +error, never a success. The Chat bridge assembles a streamed `functionCall` under the shared +translator limits for each call's arguments and for all retained tool fields in the turn. It releases +those buffers on emission, failure or cancellation. Usage becomes `usageMetadata`, with reasoning +tokens reported as `thoughtsTokenCount`. `src/server/gemini-inbound.ts` owns translated delivery. With `alt=sse` a stream is `data: \r\n\r\n` frames; without it, one streamed JSON array. The closing chunk (finish reason and usage) is emitted diff --git a/tests/responses/responses-gemini-codec.test.ts b/tests/responses/responses-gemini-codec.test.ts index 486c81d21df..abac2dd6097 100644 --- a/tests/responses/responses-gemini-codec.test.ts +++ b/tests/responses/responses-gemini-codec.test.ts @@ -1,10 +1,12 @@ import { describe, expect, test } from "bun:test"; +import { createTranslatorBudget, TranslatorBudgetExceededError } from "../../src/lib/translator-budget"; import { GeminiCodecError, MAX_GEMINI_TOOL_CALLS, chatToGeminiResponse, consumeGeminiChatChunk, createGeminiStreamState, + disposeGeminiStreamTools, geminiStreamTerminal, geminiToChat, } from "../../src/protocols/codecs/gemini"; @@ -142,6 +144,66 @@ describe("Gemini codec response mapping", () => { consumeGeminiChatChunk(state, { choices: [{ index: 0, delta: { content: "a" }, finish_reason: "stop" }] }); expect(() => consumeGeminiChatChunk(state, { choices: [{ index: 0, delta: { content: "b" } }] })).toThrow(); }); + + test("completed tools release their UTF-8 budget before a trailing usage record", () => { + const budget = createTranslatorBudget({ maxCallArgumentBytes: 2, maxTurnBytes: 8 }); + const state = createGeminiStreamState("m", budget); + const part = (tool: Record) => ({ choices: [{ delta: { tool_calls: [{ index: 0, ...tool }] } }] }); + const signature = (value: string) => ({ extra_content: { google: { thought_signature: value } } }); + try { + consumeGeminiChatChunk(state, part({ id: "a", function: { name: "한", arguments: "{" }, ...signature("xy") })); + expect(budget.snapshot().currentBytes).toBe(7); + consumeGeminiChatChunk(state, part({ id: "a", function: { arguments: "}" }, ...signature("z") })); + expect(budget.snapshot().currentBytes).toBe(7); + const records = consumeGeminiChatChunk(state, { choices: [{ delta: {}, finish_reason: "tool_calls" }] }); + expect(records[0]?.candidates).toMatchObject([{ content: { parts: [{ functionCall: { id: "a", name: "한", args: {} }, thoughtSignature: "z" }] } }]); + expect(budget.snapshot()).toMatchObject({ currentBytes: 0, activeCalls: 0 }); + consumeGeminiChatChunk(state, { choices: [], usage: { completion_tokens: 3 } }); + expect(geminiStreamTerminal(state)?.usageMetadata).toMatchObject({ candidatesTokenCount: 3 }); + } finally { + disposeGeminiStreamTools(state); + } + }); + + test("streamed calls share the turn budget and keep an independent argument budget", () => { + for (const limits of [{ maxCallArgumentBytes: 1, maxTurnBytes: 20 }, { maxCallArgumentBytes: 8, maxTurnBytes: 4 }]) { + const budget = createTranslatorBudget(limits); + const state = createGeminiStreamState("m", budget); + const part = (index: number, fn: Record) => ({ choices: [{ delta: { tool_calls: [{ index, function: fn }] } }] }); + try { + consumeGeminiChatChunk(state, part(0, { name: "a", arguments: "{" })); + consumeGeminiChatChunk(state, part(1, { name: "b", arguments: "{" })); + expect(() => consumeGeminiChatChunk(state, part(0, { arguments: "}" }))).toThrow(TranslatorBudgetExceededError); + expect(state.tools.get(0)?.arguments).toBe("{"); + } finally { + disposeGeminiStreamTools(state); + } + expect(budget.snapshot()).toMatchObject({ currentBytes: 0, activeCalls: 0 }); + expect(() => consumeGeminiChatChunk(state, part(1, { arguments: "}" }))).toThrow("Invalid Chat tool delta"); + } + }); + + test("split Unicode tool fragments have the same UTF-8 size as a complete value", () => { + const name = "tool🙂"; + const args = '{"v":"🙂"}'; + const bytes = Buffer.byteLength(name) + Buffer.byteLength(args); + for (const split of [false, true]) { + const budget = createTranslatorBudget({ maxCallArgumentBytes: Buffer.byteLength(args), maxTurnBytes: bytes }); + const state = createGeminiStreamState("m", budget); + const parts = split + ? [{ name: name.slice(0, -1), arguments: args.slice(0, 7) }, { name: "", arguments: "" }, + { name: name.slice(-1), arguments: args.slice(7) }] + : [{ name, arguments: args }]; + try { + for (const fn of parts) consumeGeminiChatChunk(state, { choices: [{ delta: { tool_calls: [{ index: 0, function: fn }] } }] }); + expect(budget.snapshot().currentBytes).toBe(bytes); + const records = consumeGeminiChatChunk(state, { choices: [{ delta: {}, finish_reason: "tool_calls" }] }); + expect(records[0]?.candidates).toMatchObject([{ content: { parts: [{ functionCall: { name, args: { v: "🙂" } } }] } }]); + } finally { + disposeGeminiStreamTools(state); + } + } + }); }); diff --git a/tests/server/server-native-final-log.test.ts b/tests/server/server-native-final-log.test.ts index 549f0be0b6d..954925c748a 100644 --- a/tests/server/server-native-final-log.test.ts +++ b/tests/server/server-native-final-log.test.ts @@ -7,6 +7,39 @@ import { type RequestLogEntry, } from "../../src/server/request-log"; import { createNativeFinalLog, NATIVE_FINAL_LOG_CUTOFF_CODE } from "../../src/server/native-final-log"; +import { streamGemini } from "../../src/server/gemini-inbound"; +import { translatorLiveBudgetCountForTests } from "../../src/lib/translator-budget"; + +test.each(["cancel", "read error"] as const)("Gemini stream %s releases pending calls and commits once", async how => { + const before = translatorLiveBudgetCountForTests(); + const outcomes: number[] = []; + const { readable, writable } = new TransformStream(); + const writer = writable.getWriter(); + const reader = streamGemini("m", true, readable, { + innerSettled: () => true, + waitForInner: async () => true, + commit: row => { outcomes.push(row.status); return true; }, + }, new AbortController().signal).body!.getReader(); + const delta = { content: "hello", tool_calls: [{ index: 0, function: { name: "find" } }] }; + const sent = writer.write(new TextEncoder().encode("data: " + JSON.stringify({ choices: [{ delta }] }) + "\n\n")); + try { + expect(new TextDecoder().decode((await reader.read()).value)).toContain("hello"); + await sent; + expect(translatorLiveBudgetCountForTests()).toBe(before + 1); + if (how === "cancel") { + await reader.cancel(); + } else { + await writer.abort(new Error("fixture stream ended")); + expect(new TextDecoder().decode((await reader.read()).value)).toContain("upstream stream failed"); + expect((await reader.read()).done).toBe(true); + } + expect(outcomes).toEqual([how === "cancel" ? 499 : 502]); + expect(translatorLiveBudgetCountForTests()).toBe(before); + } finally { + await reader.cancel().catch(() => {}); + writer.releaseLock(); + } +}); function context(): RequestLogContext { const attempt = beginRequestAttempt(1, "fixture", "model", "openai-chat"); From f9ffbbd1fe69a1ba1e55b5e2470c90800c1df081 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Wed, 25 Nov 2026 13:49:49 +0900 Subject: [PATCH 20/60] perf(images): validate inline edit sources without decoding them (#9072) Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- src/server/images.ts | 37 +++++++++++------- structure/data-planes/images.md | 5 ++- tests/server/server-images-xai-relay.test.ts | 41 +++++++++++++++++++- 3 files changed, 67 insertions(+), 16 deletions(-) diff --git a/src/server/images.ts b/src/server/images.ts index 5afd1023f5d..641b5408269 100644 --- a/src/server/images.ts +++ b/src/server/images.ts @@ -131,16 +131,23 @@ export async function readImageResponseBytes( } const CCA_IMAGE_MODEL = "gemini-3.1-flash-image"; +const BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; /** An edit source xAI can fetch: an https URL without credentials, or a base64 image data URL. */ function isXaiEditSourceUrl(value: string): boolean { - const data = /^data:image\/(?:png|jpeg|jpg|webp);base64,(.*)$/is.exec(value); - if (data) { - // Canonical base64 only: whole quads, padding at the end and nowhere else, and unused - // padding bits zero (decoding and re-encoding must give back the same text). - const payload = data[1]!; - return payload.length > 0 && payload.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(payload) - && Buffer.from(payload, "base64").toString("base64") === payload; + const header = /^data:image\/(?:png|jpeg|jpg|webp);base64,/i.exec(value); + if (header) { + const start = header[0].length; + if (value.length === start || (value.length - start) % 4 !== 0) return false; + const nonAlphabet = /[^A-Za-z0-9+/]/g; + nonAlphabet.lastIndex = start; + const firstNonAlphabet = nonAlphabet.exec(value)?.index; + if (firstNonAlphabet === undefined) return true; + const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0; + if (firstNonAlphabet !== value.length - padding) return false; + // Canonical padding leaves four unused bits before "==" or two before "=". + const lastSextet = BASE64_ALPHABET.indexOf(value[firstNonAlphabet - 1]!); + return (lastSextet & (padding === 2 ? 0x0f : 0x03)) === 0; } try { const url = new URL(value); @@ -534,15 +541,20 @@ async function tryXaiImageRelay( let imageUrl: string | undefined; let imageUrls: string[] | undefined; if (endpoint === "edits") { - const sources: string[] = []; + const sources = new Set(); // Every supplied source must be a usable URL: silently dropping one would buy an edit // missing an image the caller sent. xAI takes a public https URL or a base64 image data URL; // an explicit null counts as supplied. let unusable = false; const add = (value: unknown) => { const url = typeof value === "string" ? value.trim() : ""; - if (isXaiEditSourceUrl(url)) sources.push(url); - else unusable = true; + if (sources.has(url)) return; + if (!isXaiEditSourceUrl(url)) { + unusable = true; + return; + } + // One extra source records overflow. A later invalid source still takes precedence. + if (sources.size <= XAI_MAX_EDIT_IMAGES) sources.add(url); }; if (obj.image !== undefined) add(obj.image); if (obj.image_url !== undefined) add(obj.image_url); @@ -565,9 +577,8 @@ async function tryXaiImageRelay( } if (unusable) return formatErrorResponse(400, "invalid_request_error", "xAI image edits need every image as a URL"); // Same rule as callXaiImages: duplicates collapse first, then the five-source limit applies. - const unique = [...new Set(sources)]; - if (unique.length > XAI_MAX_EDIT_IMAGES) return formatErrorResponse(400, "invalid_request_error", "xAI image edits accept at most 5 images"); - [imageUrl, ...imageUrls] = unique; + if (sources.size > XAI_MAX_EDIT_IMAGES) return formatErrorResponse(400, "invalid_request_error", "xAI image edits accept at most 5 images"); + [imageUrl, ...imageUrls] = sources; if (!imageUrl) return formatErrorResponse(400, "invalid_request_error", "image edits require an image URL"); } const timeoutMs = config.images?.timeoutMs ?? IMAGES_UPSTREAM_TIMEOUT_MS; diff --git a/structure/data-planes/images.md b/structure/data-planes/images.md index 375f973aa30..71b93a1ec9b 100644 --- a/structure/data-planes/images.md +++ b/structure/data-planes/images.md @@ -49,8 +49,9 @@ remains independent. Edits through `callXaiImages` and the `/v1/images/edits` re source URLs in caller order; both drop duplicate URLs first and then apply the limit, and the relay checks it before resolving credentials or sending a request. The relay refuses the request when any supplied source, an explicit `null` included, is not an https URL or a canonical base64 PNG/JPEG/WebP -data URL (for example a `file_id` or plain text) instead of dropping it; every URL-bearing property of -an `images[]` entry (`image_url`, `image_url.url`, `url`) counts as a source. The `image_gen` bridge tool sends one +data URL (for example a `file_id` or plain text) instead of dropping it. It checks the base64 alphabet +and padding directly in the supplied text. Every URL-bearing property of an `images[]` entry +(`image_url`, `image_url.url`, `url`) counts as a source. The `image_gen` bridge tool sends one source. Safe upstream validation details are reconstructed from a closed vocabulary of quality, field, resolution and bounded keyframe tokens; unknown bodies and arbitrary upstream text never reach the caller. diff --git a/tests/server/server-images-xai-relay.test.ts b/tests/server/server-images-xai-relay.test.ts index dba7b36c845..b7dbb3993cf 100644 --- a/tests/server/server-images-xai-relay.test.ts +++ b/tests/server/server-images-xai-relay.test.ts @@ -1,4 +1,4 @@ -import { afterEach, expect, test } from "bun:test"; +import { afterEach, expect, spyOn, test } from "bun:test"; import { handleImages } from "../../src/server/images"; import type { OcxConfig } from "../../src/types"; const oldFetch = globalThis.fetch; @@ -21,6 +21,45 @@ test("relay collapses duplicate sources before the five-source limit, like the c expect(calls[0].image).toEqual({url:"https://example.com/a.png",type:"image_url"}); }); +test("relay validates canonical edit data URLs without decoding their payloads", async () => { + const sources = [ + "DATA:IMAGE/JPG;BASE64,/w==", + "data:image/jpeg;base64,//8=", + "data:image/webp;base64,+///", + ]; + let forwarded: string[] = []; + globalThis.fetch = (async (_input, init) => { + const body = JSON.parse(String(init?.body)) as { images: { url: string }[] }; + forwarded = body.images.map(image => image.url); + return Response.json({ data: [{ b64_json: "iVBORw0KGgo=" }] }); + }) as typeof fetch; + using from = spyOn(Buffer, "from"); + const res = await relay({ prompt: "edit", images: sources }); + expect(res.status).toBe(200); + expect(forwarded).toEqual(sources); + for (const source of sources) { + expect(from).not.toHaveBeenCalledWith(source.split(",")[1], "base64"); + } +}); + +test("relay keeps five distinct sources in order and validates entries after the limit", async () => { + const sources = Array.from({ length: 5 }, (_, i) => `https://example.com/${i}.png`); + const calls: string[][] = []; + globalThis.fetch = (async (_input, init) => { + const body = JSON.parse(String(init?.body)) as { images: { url: string }[] }; + calls.push(body.images.map(image => image.url)); + return Response.json({ data: [{ b64_json: "iVBORw0KGgo=" }] }); + }) as typeof fetch; + const accepted = await relay({ prompt: "edit", images: [sources[0], ` ${sources[0]} `, ...sources] }); + expect(accepted.status).toBe(200); + expect(calls).toEqual([sources]); + + const rejected = await relay({ prompt: "edit", images: [...sources, "https://example.com/six.png", "not-a-url"] }); + expect(rejected.status).toBe(400); + expect(await rejected.text()).toContain("every image"); + expect(calls).toHaveLength(1); +}); + test("relay refuses a request where any supplied edit source is unusable, before any upstream call", async () => { const calls: unknown[] = []; globalThis.fetch = (async (_input, init) => { calls.push(init?.body); return Response.json({data:[]}); }) as typeof fetch; From 693454f541a5bfa2c90e9a8df71f554ba0051306 Mon Sep 17 00:00:00 2001 From: Rafael Moreira Lima <137737127+rafaelmoreiraai@users.noreply.github.com> Date: Wed, 25 Nov 2026 01:50:15 -0300 Subject: [PATCH 21/60] fix(gui): report consumed quota share in the per-account quota table (#9077) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(gui): report consumed quota share in the per-account quota table The Providers Accounts table rendered 'N% left' from PoolCell.remaining (100 - usedPercent) and filled each bar to the remaining share, while Accounts & limits, ProviderCapacityQuota/QuotaBars and QuotaSummaryBar all report the consumed share. The same reading therefore appeared as '87% left' on one surface and '13% used' on another, with the bars filling in opposite directions, and the shared warn/exhaustion thresholds (isQuotaWarn, isQuotaExhausted) are expressed on the consumed share. Carry PoolCell.used (the wire value) instead of its inverse, render the existing quota.usedPercent string, and state the two threshold rewrites in the new direction: remaining <= 20 becomes used >= 80 and remaining <= 0 becomes used >= 100. Both are exactly equivalent across 0-100%. Remove the now-unused acctTable.left copy row and update the two documents that described this table as remaining per pool. * fix(gui): take the quota table's warn tone from the shared helper The cell hardcoded `used >= 80`, which is the value `ProviderCapacityQuota` passes to `QuotaBars`, but nothing tied the two together: changing the provider threshold would have left this table disagreeing with the cards it is being aligned to. `QUOTA_WARN_THRESHOLD` now names that value once. Also corrects the body's equivalence claim: the thresholds agree over the 101 integer percentages, not 1001, and not on fractional input (79.5 rounds to 21 remaining under the old rule and 80 used under the new one). Two new tests hold the direction: the warn boundary at the threshold, and parity with quotaBarTone for the same reading. * test(gui): drop the parity example that compared the helper with itself Both sides of that assertion called `quotaBarTone(x, QUOTA_WARN_THRESHOLD)`, so it could not fail for any implementation that imported the helper — it certified nothing beyond the import. The boundary example stays and was verified red under a strict `used > 80`. Body corrected in the same push: the fractional equivalence note now covers the exhausted guard too (99.5 shifts like 79.5 does), and the test plan lists the commands that actually ran on this head. * test(gui): assert consumed quota in the account table, and say used in the docs The table now carries used share, so the root expectations still read the inverted remaining values. The dashboard guide and the Spanish account reference also still described the table as percentage left. --------- Co-authored-by: JUN --- .../es/reference/cli/providers-accounts.md | 2 +- .../src/content/docs/guides/web-dashboard.md | 2 +- .../docs/reference/cli/providers-accounts.md | 2 +- gui/src/components/QuotaBars.tsx | 7 ++++ .../provider-workspace/AccountQuotaTable.tsx | 17 +++++---- gui/src/i18n/account-probe-copy.ts | 1 - .../provider-workspace/account-quota-table.ts | 12 +++---- .../account-quota-table-stacked.test.tsx | 36 ++++++++++++++++--- .../anthropic-subscription-label.test.tsx | 8 ++--- .../provider-auth-target-capture.test.tsx | 2 +- structure/gui-and-management-api.md | 2 +- tests/gui/gui-account-quota-table.test.ts | 12 +++---- 12 files changed, 71 insertions(+), 32 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/cli/providers-accounts.md b/docs-site/src/content/docs/es/reference/cli/providers-accounts.md index 6fe67434f17..bf01c97ff6c 100644 --- a/docs-site/src/content/docs/es/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/es/reference/cli/providers-accounts.md @@ -559,7 +559,7 @@ o `error`, con el estado HTTP y un código de motivo reconocido. Los estados `pa (cuenta en pausa) y `token_expired` (token caducado) se determinan localmente, sin enviar una solicitud. La comprobación conserva los tokens y el estado de la cuenta. Los botones **Probar** y **Probar todas** de la tabla de cuotas de Antigravity llaman al mismo endpoint, -`POST /api/oauth/accounts/probe`. La tabla muestra el plan, las cuotas restantes por grupo, +`POST /api/oauth/accounts/probe`. La tabla muestra el plan, la cuota consumida por grupo, los plazos de restablecimiento y las acciones de cada cuenta. Si falla una actualización, la tabla conserva la cuota anterior e indica el error y las horas de lectura. Se ejecutan hasta cuatro comprobaciones a la vez. Espera a que termine la comprobación actual antes de iniciar otra. diff --git a/docs-site/src/content/docs/guides/web-dashboard.md b/docs-site/src/content/docs/guides/web-dashboard.md index fac0c0fe4cc..88ba70ff136 100644 --- a/docs-site/src/content/docs/guides/web-dashboard.md +++ b/docs-site/src/content/docs/guides/web-dashboard.md @@ -200,7 +200,7 @@ is visible) and never forces an upstream refresh. | **Windows tray** | Install a per-user login tray for one-click proxy start, stop, restart, dashboard access, and status. The tray is a controller, not a proxy restart service. | | **Codex autostart** | Allow an already-installed Codex launcher shim to run `ocx ensure`. This toggle does not install a shim or background service. | | **Telemetry** | Toggle **Share anonymous usage statistics** and inspect **Preview the JSON** under **Proxy details** (`#proxy-telemetry`). On first run or after an update while undecided, the consent popup saves a choice only when **Continue** is clicked (`PUT /api/telemetry`); dismissing it records nothing. See [Telemetry and Privacy](/guides/telemetry/). | -| **Providers** | Add, edit, set the default (enabled providers only), enable/disable, and remove providers; manage OAuth account pools and API-key pools where supported. Removing the current default switches to the first remaining enabled provider when one exists; otherwise deletion is refused and the current default is kept. Provider Settings can disable live model discovery for endpoints with missing, slow, or oversized `/models` catalogs. For Claude (Anthropic) OAuth pools, each logged-in account shows its own 5-hour and weekly rate-limit bars (usage is per credential); a failed probe keeps the last-known bars and marks them unavailable until the next successful refresh. An account pool settings card (Claude, Claude Pool 2, and Codex usage-based switching) shows only its title and on/off switch; select the title to show its other settings, and the dashboard remembers which cards you opened. Each account's quota lists the pool name, then its 5-hour bar, then its weekly bar, each on its own line with the percentage left and the reset countdown. Refreshing quota skips paused OAuth accounts and disabled API keys; skipped rows without a cached reading remain unavailable but do not affect the refresh result. Refreshing reports failure when an unpaused OAuth account or enabled API key that supports quota reads has an unavailable reading. The Provider Overview shown when no provider is selected carries a **Refresh all quotas** control that forces one server-side re-read of every configured provider; a provider whose upstream probe fails keeps its last-good row, so the status line reports that the check completed rather than claiming every value is fresh, and each row's own age stays the per-provider freshness signal. Unsaved Settings and JSON edits are kept in memory per logical dashboard server: switching servers parks the draft, saving writes only to the server where editing began, and a changed saved configuration asks you to keep your draft or use the saved values. Keeping a JSON draft merges only your changes into the latest config and names any field changed on both sides; Settings saves only the fields you changed. On a relay that predates target-bound saves, the dashboard checks the target immediately before sending but cannot verify it atomically, and says so once; update the proxy for the stronger guarantee. Closing or reloading the dashboard discards these drafts. | +| **Providers** | Add, edit, set the default (enabled providers only), enable/disable, and remove providers; manage OAuth account pools and API-key pools where supported. Removing the current default switches to the first remaining enabled provider when one exists; otherwise deletion is refused and the current default is kept. Provider Settings can disable live model discovery for endpoints with missing, slow, or oversized `/models` catalogs. For Claude (Anthropic) OAuth pools, each logged-in account shows its own 5-hour and weekly rate-limit bars (usage is per credential); a failed probe keeps the last-known bars and marks them unavailable until the next successful refresh. An account pool settings card (Claude, Claude Pool 2, and Codex usage-based switching) shows only its title and on/off switch; select the title to show its other settings, and the dashboard remembers which cards you opened. Each account's quota lists the pool name, then its 5-hour bar, then its weekly bar, each on its own line with the percentage used and the reset countdown. Refreshing quota skips paused OAuth accounts and disabled API keys; skipped rows without a cached reading remain unavailable but do not affect the refresh result. Refreshing reports failure when an unpaused OAuth account or enabled API key that supports quota reads has an unavailable reading. The Provider Overview shown when no provider is selected carries a **Refresh all quotas** control that forces one server-side re-read of every configured provider; a provider whose upstream probe fails keeps its last-good row, so the status line reports that the check completed rather than claiming every value is fresh, and each row's own age stays the per-provider freshness signal. Unsaved Settings and JSON edits are kept in memory per logical dashboard server: switching servers parks the draft, saving writes only to the server where editing began, and a changed saved configuration asks you to keep your draft or use the saved values. Keeping a JSON draft merges only your changes into the latest config and names any field changed on both sides; Settings saves only the fields you changed. On a relay that predates target-bound saves, the dashboard checks the target immediately before sending but cannot verify it atomically, and says so once; update the proxy for the stronger guarantee. Closing or reloading the dashboard discards these drafts. | | **Add provider** | One search above the tabs reaches all four at once — Accounts, Free, Local, Paid. While a query is live the results are grouped by tab with a count each, and the selected tab stays put rather than jumping. Press ArrowDown in the search box to focus the first available result action, skipping disabled buttons; if no action is available, focus stays in the search box. Local runtimes (Ollama, vLLM, LM Studio, LiteLLM) have their own tab, and a long provider note clamps to two lines with the full text one click away. Claude Code CLI (subscription) sits under Paid with a Subscription CLI badge, and selecting it warns that it bills the signed-in Claude subscription through `claude -p` and never uses an API key (use `anthropic-apikey` for key billing). | | **Codex Auth** | Add ChatGPT/Codex pool accounts, select the next-session account, refresh 5h / weekly / 30d quotas, enable or disable quota auto-switch, set its 1–100% threshold, and configure transient-failure failover. | | **Subagents** | Set the first five `spawn_agent` priorities through `subagentModels`, using bare native or namespaced routed models. This is not an allowlist: unused positions may be filled from visible catalog rows. The **Workflow limits for subagents** panel sets how many turns one task may run in parallel and how many model requests and distinct subagents it may use per 10-minute window. See [workflow limits](/reference/configuration/server/#workflow-limits). | 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 4572a1f9a98..8786b9a7387 100644 --- a/docs-site/src/content/docs/reference/cli/providers-accounts.md +++ b/docs-site/src/content/docs/reference/cli/providers-accounts.md @@ -1075,7 +1075,7 @@ locally and send nothing: `paused` (the account is paused; resume it to test it) (the stored token has expired). The probe never refreshes a token, never writes the auth store and never changes pause, active, cooldown or health state. The dashboard's **Test** and **Test all** buttons on the Antigravity account quota table call the same endpoint, `POST /api/oauth/accounts/probe`. -The table shows each account’s plan, remaining quota by pool, reset times, and account actions. +The table shows each account’s plan, quota consumed by pool, reset times, and account actions. If a quota refresh fails, the table keeps the cached quota and shows the failure and read times. A batch runs up to four checks at a time. Wait for the current check to finish before starting another. diff --git a/gui/src/components/QuotaBars.tsx b/gui/src/components/QuotaBars.tsx index 6b87dc4b2d9..02d65055898 100644 --- a/gui/src/components/QuotaBars.tsx +++ b/gui/src/components/QuotaBars.tsx @@ -227,6 +227,13 @@ export function isQuotaExhausted(percent: number): boolean { return percent >= 99.5; } +/** + * Threshold every provider quota surface warns at, so the table, the capacity card and + * the pool settings cannot drift apart. Callers that track a per-account override pass + * their own value to `isQuotaWarn` instead. + */ +export const QUOTA_WARN_THRESHOLD = 80; + export function isQuotaWarn(percent: number, threshold: number): boolean { return threshold > 0 && percent >= threshold; } diff --git a/gui/src/components/provider-workspace/AccountQuotaTable.tsx b/gui/src/components/provider-workspace/AccountQuotaTable.tsx index 99d759f542a..2fb6b6778d5 100644 --- a/gui/src/components/provider-workspace/AccountQuotaTable.tsx +++ b/gui/src/components/provider-workspace/AccountQuotaTable.tsx @@ -1,5 +1,6 @@ import { useEffect, useState, type CSSProperties, type ReactNode } from "react"; import { useT, type TKey } from "../../i18n/shared"; +import { QUOTA_WARN_THRESHOLD, quotaBarTone } from "../QuotaBars"; import { buildQuotaTable, formatCountdown, type AccountFlag, type PoolCell, type PoolKey, type QuotaTableAccount, type QuotaTableRow, @@ -22,14 +23,17 @@ function useMinuteClock(): number { function PoolBar({ label, cell, now }: { label: string; cell: PoolCell; now: number }) { const t = useT(); - const remaining = Math.round(cell.remaining); - const tone = remaining <= 20 ? "bar-warn" : "bar-green"; + // Consumed share, matching QuotaBars and the Codex account cards: the bar fills as the + // allowance is spent, so a fresh account reads 0% and an exhausted one reads 100%. + // The tone comes from the shared helpers so this cell cannot drift from the other surfaces. + const used = Math.round(cell.used); + const tone = quotaBarTone(used, QUOTA_WARN_THRESHOLD); const countdown = cell.resetAt === undefined ? null : formatCountdown(cell.resetAt, now); return (
    {label} -
    - {t("acctTable.left", { percent: remaining })} +
    + {t("quota.usedPercent", { pct: used })} {countdown ? t("acctTable.resetsIn", { time: countdown }) : ""}
    ); @@ -68,8 +72,9 @@ function hasContent(node: ReactNode): boolean { /** * The one account list of a multi-account provider: plan, each quota pool's 5-hour and weekly - * remaining with a reset countdown, a status flag and, when the caller passes them, the row's - * controls and a detail line. Below a container width the rows stack instead of scrolling, so + * consumed share with a reset countdown, a status flag and, when the caller passes them, the + * row's controls and a detail line. Every other quota surface in the dashboard reports consumed + * share, so this table does too. Below a container width the rows stack instead of scrolling, so * the controls never leave the screen. */ export function AccountQuotaTable({ accounts, strategy, renderRowContent }: AccountQuotaTableProps) { diff --git a/gui/src/i18n/account-probe-copy.ts b/gui/src/i18n/account-probe-copy.ts index c08642757ee..cfd11e0fcd0 100644 --- a/gui/src/i18n/account-probe-copy.ts +++ b/gui/src/i18n/account-probe-copy.ts @@ -41,7 +41,6 @@ const rows = { "acctTable.scarce": ["scarce", "희소", "knapp", "rare", "稀缺", "稀缺", "дефицит", "希少", "kıt", "khan hiếm", "escassa"], "acctTable.fiveHour": ["5h", "5시간", "5 Std.", "5 h", "5 小时", "5 小時", "5 ч", "5時間", "5 sa", "5 giờ", "5 h"], "acctTable.weekly": ["Week", "주간", "Woche", "Semaine", "每周", "每週", "Неделя", "週", "Hafta", "Tuần", "Semana"], - "acctTable.left": ["{percent}% left", "{percent}% 남음", "{percent} % übrig", "{percent} % restant", "剩 {percent}%", "剩 {percent}%", "осталось {percent}%", "残り {percent}%", "%{percent} kaldı", "còn {percent}%", "{percent}% restante"], "acctTable.resetsIn": ["resets in {time}", "{time} 후 초기화", "Reset in {time}", "réinit. dans {time}", "{time} 后重置", "{time} 後重置", "сброс через {time}", "{time} 後リセット", "{time} sonra sıfırlanır", "đặt lại sau {time}", "reinicia em {time}"], "acctTable.next": ["next", "다음", "als Nächstes", "suivant", "优先", "優先", "следующий", "次", "sıradaki", "kế tiếp", "próxima"], "acctTable.nextHint": ["Resets soonest among usable accounts, so reset-first spends it first", "사용 가능한 계정 중 가장 먼저 초기화되어 reset-first가 먼저 사용합니다", "Wird unter nutzbaren Konten zuerst zurückgesetzt, daher nutzt reset-first es zuerst", "Se réinitialise en premier parmi les comptes utilisables : reset-first l’utilise d’abord", "在可用账号里最先重置,「最快重置优先」会先用它", "在可用帳號中最先重置,「最快重置優先」會先用它", "Сбрасывается раньше других доступных аккаунтов, поэтому reset-first расходует его первым", "使用可能なアカウントで最も早くリセットされるため、reset-first が先に使います", "Kullanılabilir hesaplar arasında ilk sıfırlanan; reset-first önce bunu kullanır", "Đặt lại sớm nhất trong các tài khoản dùng được, nên reset-first dùng trước", "Reinicia antes entre as contas utilizáveis, então reset-first a usa primeiro"], diff --git a/gui/src/provider-workspace/account-quota-table.ts b/gui/src/provider-workspace/account-quota-table.ts index 55d461dd241..82ad52137af 100644 --- a/gui/src/provider-workspace/account-quota-table.ts +++ b/gui/src/provider-workspace/account-quota-table.ts @@ -113,8 +113,8 @@ export interface QuotaTableAccount { } export interface PoolCell { - /** Remaining share, 0–100. */ - remaining: number; + /** Consumed share, 0–100 — the same direction every other quota surface reports. */ + used: number; /** Epoch milliseconds. */ resetAt?: number; } @@ -141,8 +141,8 @@ function toMs(value: number | undefined): number | undefined { return value > 10_000_000_000 ? value : value * 1000; } -function clampRemaining(usedPercent: number): number { - return Math.max(0, Math.min(100, 100 - usedPercent)); +function clampUsed(usedPercent: number): number { + return Math.max(0, Math.min(100, usedPercent)); } function accountFlag(account: QuotaTableAccount): { flag: AccountFlag; probeStatus?: string } { @@ -177,7 +177,7 @@ export function buildQuotaTable(accounts: readonly QuotaTableAccount[], now = Da const reading = readings[window]; if (!reading || !Number.isFinite(reading.percent)) continue; const resetAt = toMs(reading.resetAt); - cell[window] = { remaining: clampRemaining(reading.percent), ...(resetAt && resetAt > now ? { resetAt } : {}) }; + cell[window] = { used: clampUsed(reading.percent), ...(resetAt && resetAt > now ? { resetAt } : {}) }; } if (cell.fiveHour || cell.weekly) cells[pool.key] = cell; } @@ -194,7 +194,7 @@ export function buildQuotaTable(accounts: readonly QuotaTableAccount[], now = Da const cell = row.cells[pool.key]; if (!cell || !USABLE.has(row.flag)) continue; const windows = [cell.fiveHour, cell.weekly].filter((window): window is PoolCell => window !== undefined); - if (windows.some(window => window.remaining <= 0)) continue; + if (windows.some(window => window.used >= 100)) continue; const resetAt = (cell.weekly ?? cell.fiveHour)?.resetAt; if (resetAt === undefined) continue; if (!best || resetAt < best.resetAt) best = { row, resetAt }; diff --git a/gui/tests/account-quota-table-stacked.test.tsx b/gui/tests/account-quota-table-stacked.test.tsx index 6f92e4d1974..8efb8c30659 100644 --- a/gui/tests/account-quota-table-stacked.test.tsx +++ b/gui/tests/account-quota-table-stacked.test.tsx @@ -1,13 +1,14 @@ /** * Per-account quota rows stack again (#fb-2100): in the card layout the pool name sits on its own - * line, the 5-hour bar on the next and the weekly bar on the third, each with its "% left" and - * reset countdown, as v2.100.5 showed them. #8740 had put the three side by side. + * line, the 5-hour bar on the next and the weekly bar on the third, each with its consumed share + * and reset countdown, as v2.100.5 showed them. #8740 had put the three side by side. */ import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { Window } from "happy-dom"; import { act } from "react"; import type { Root } from "react-dom/client"; import { AccountQuotaTable } from "../src/components/provider-workspace/AccountQuotaTable"; +import { QUOTA_WARN_THRESHOLD } from "../src/components/QuotaBars"; import { LanguageProvider } from "../src/i18n/provider"; import { DICTS } from "../src/i18n/shared"; @@ -77,9 +78,36 @@ describe("account quota rows", () => { expect(cell.children[0]!.getAttribute("aria-hidden")).toBe("true"); } const first = cells[0]!.children; - expect(first[1]!.textContent).toContain("100% left"); + expect(first[1]!.textContent).toContain("0% used"); expect(first[1]!.textContent).toContain("resets in"); - expect(first[2]!.textContent).toContain("0% left"); + expect(first[2]!.textContent).toContain("100% used"); + }); + + test("the warn tone flips at the consumed-share threshold the other surfaces use", async () => { + // `isQuotaWarn`/`quotaBarTone` drive QuotaBars and the harness; this cell must agree with + // them at the boundary instead of hardcoding its own number. + const now = Date.now(); + const host = testWindow.document.createElement("div"); + testWindow.document.body.appendChild(host as never); + const { createRoot } = await import("react-dom/client"); + await act(async () => { + root = createRoot(host); + root.render( + + + , + ); + }); + const fills = Array.from(host.querySelectorAll("td.aqt-pool .bar-fill")); + expect(fills).toHaveLength(2); + // 80% consumed is warn (threshold is inclusive); 79% is not. + expect(fills[0]!.className).toContain("bar-warn"); + expect(fills[1]!.className).toContain("bar-green"); + // The bar tracks the consumed share, not the remainder. + expect((fills[0] as HTMLElement).style.getPropertyValue("--bar-scale")).toBe(String(QUOTA_WARN_THRESHOLD / 100)); }); test("no card-layout rule lays a pool's name and bars out side by side", async () => { diff --git a/gui/tests/anthropic-subscription-label.test.tsx b/gui/tests/anthropic-subscription-label.test.tsx index 8cf9e03f21b..3194fe7a40b 100644 --- a/gui/tests/anthropic-subscription-label.test.tsx +++ b/gui/tests/anthropic-subscription-label.test.tsx @@ -25,14 +25,14 @@ for (const provider of ["anthropic", "anthropic2"]) { expect(markup).toContain(`>${label}`); expect(markup).not.toContain("private@example.test"); expect(markup).not.toContain("synthetic-private-account"); - // The quota table shows remaining capacity: 37% used weekly -> 63% left, 18% used 5-hour -> 82% left. - expect(markup).toContain("63% left"); + // The quota table reports consumed share, like every other quota surface: 37% used weekly, 18% used 5-hour. + expect(markup).toContain("37% used"); if (plan === "pro" || plan === "max_5x") { expect(markup).toContain(`class="aqt-bar-label">${en["acctTable.fiveHour"]}`); - expect(markup).toContain("82% left"); + expect(markup).toContain("18% used"); } else { expect(markup).not.toContain(`class="aqt-bar-label">${en["acctTable.fiveHour"]}`); - expect(markup).not.toContain("82% left"); + expect(markup).not.toContain("18% used"); } }); } diff --git a/gui/tests/provider-auth-target-capture.test.tsx b/gui/tests/provider-auth-target-capture.test.tsx index 99523582a4b..8c6da25ff96 100644 --- a/gui/tests/provider-auth-target-capture.test.tsx +++ b/gui/tests/provider-auth-target-capture.test.tsx @@ -113,7 +113,7 @@ test("cached Gemini quota keeps its timeout and distinct read timestamps in the }], }); const table = host.querySelector('[data-testid="account-quota-table"]')!; - expect(table.textContent).toContain("80% left"); + expect(table.textContent).toContain("20% used"); expect(table.textContent).toContain("The quota request timed out."); expect(table.textContent).toMatch(/Quota updated: 10m ago/); expect(table.textContent).toMatch(/Last read: 2m ago/); diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index f040f5d4a86..088754559c5 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -277,7 +277,7 @@ per-request first-party callback reads that live object; a failed write leaves i | Updates | `GET /api/update/check`, `POST /api/update/run`, and `GET /api/update/status` own dashboard self-update state. A launched worker PID is persisted in `update-job.json`; dead PIDs recover immediately when a new run starts, and `GET /api/update/status` already reports such a record as `failed` without writing it (`readUpdateJobForStatus`), while legacy active records without a PID recover only after ten minutes. Live PIDs remain exclusive regardless of record age. `GET /api/update/check` and `POST /api/update/run` await one per-channel asynchronous registry lookup and write successful results through to the package cache; run passes that result to the job starter. `GET /api/update/badge` only reads the cache and reports unknown after 40 hours, on missing cache, or on channel mismatch. The badge links to the update surface rather than gating other actions. `GET /api/update/badge?surface=desktop&session=` projects only that process-local Tauri session; missing or expired state is unknown and never falls back to the package cache. `POST /api/update/desktop-snapshot` is a 1 KiB bounded display-state mutation with no install permission. It accepts the existing admin-token principal or a dedicated single-use, ten-second snapshot capability bound to nonce, method, path, PID, port and the SHA-256 digest of the exact body bytes; that capability cannot authorize another route. | | Providers | Create/update/delete ordinary provider configs and enrich registry metadata. A `POST /api/providers` overwrite of an existing name keeps the operator compatibility settings listed in `PROVIDER_COMPAT_CARRY_FIELDS` (`src/server/management/provider-overwrite-carry.ts`), including both hosted-tool denial lists, and the stored key pool only while the destination (adapter, normalized base URL, auth mode when named) is unchanged. It keeps omitted `hideRawReasoning` and `rawReasoningAsSummary` on every overwrite of the same name, including destination moves, because they are display policies; a submitted boolean wins. An omitted `inferContextWindow` likewise keeps the latest live same-name state after asynchronous validation, including `false` or a concurrent clear; a submitted boolean wins. An omitted `creditPriceUsd` keeps the live same-name price under the mutation lock, including zero. The provider-level `modelDiscovery` block (`PROVIDER_DISCOVERY_CARRY_FIELDS`, #7910) follows the same destination rule. An omitted `cacheAffinity` keeps the latest live same-name mode, including `off`, so unrelated dashboard saves cannot re-enable affinity; a submitted mode wins. It never merges the rest of the old row. `PATCH` is a field mask and keeps every field it does not name; `hideRawReasoning`, `rawReasoningAsSummary`, `preserveResponsesReasoningContent`, `promoteAdditionalTools` and `inferContextWindow` accept a boolean or `null` to clear them, rejecting other types; `modelDiscovery` accepts `{ skipInvalidRows?: boolean }` or `null`/`{}` to clear it, and every write path rejects any other shape through `providerManagementConfigError`. `GET /api/providers` exposes configured `inferContextWindow` as an optional boolean without substituting a default; its [custom-only, default-off inference policy](catalog-vendor-context.md) is unchanged. Custom Responses provider forms expose `preserveResponsesReasoningContent` as a default-off plaintext replay switch; unrelated settings saves preserve omission and curated/OpenAI destinations keep their existing defaults. The reserved `openai` card exposes Pool(default)/Direct account mode; `openai-apikey` remains the separate API route. | | Models | Fetch routed model lists, disabled model visibility, and catalog-facing ids. New non-OAuth registration holds exposure until authoritative discovery; 20 or more distinct switch rows start OFF without disabling the provider. Pending rows cannot accept visibility changes. `GET /api/models` renders superseded successes with request-local visibility when a newer observation wins publication. Ordinary model reads also apply the [new-arrival catalog contract](catalog.md#shared-catalog) before returning models. With a matching persisted configuration, discovery records the baseline, NEW badges, and automatic disables together; HTTP listing does not wait for a separate Codex sync. Inventory already drifted from disk uses a detached policy projection: arrivals remain disabled in management rows without changing live config or disk. `POST /api/model-discovery/refresh` fetches one live provider and keeps the full configuration in scope for alias ownership and arrival policy. A manual request during discovery for that provider returns HTTP 409 (`discovery_in_progress`). During the 30-second failure cooldown the route returns the existing failure and keeps the last good rows. This endpoint does not run Codex catalog convergence. | -| OAuth | Login/status/logout for OAuth-backed providers, plus multiauth account management: `GET /api/oauth/accounts`, `PUT /api/oauth/accounts/active`, `PUT /api/oauth/accounts/alias`, `PUT /api/oauth/accounts/pause`, and `DELETE /api/oauth/accounts` list masked accounts per provider, switch the active one, edit its display-only alias, pause/resume a generic OAuth account, and remove one. Paused generic OAuth accounts are excluded from request selection, 429 failover, and proactive token refresh; pausing an active account selects the next usable account when available, and resuming an account restores an active selection if the current one remains paused. With no unpaused account, requests return 403 rather than a login error. Kiro account-list rows include the current automatic-selection projection and closed exclusion reason; an active singleton may still send. The login flow itself is `GET /api/oauth/providers`, `POST /api/oauth/login`, `POST /api/oauth/login/code`, `POST /api/oauth/login/cancel`, `POST /api/oauth/logout`, and `GET /api/oauth/status`; pool controls are `GET/PUT/PATCH /api/oauth/accounts/pool` and `POST /api/oauth/accounts/clear-cooldown`. Login accepts `addAccount: true` to force a fresh browser identity. Meta Muse login start and manual-code continuation require the server-resolved `gui-session` principal before credential acquisition or code submission (including reauth); see the [provider contract](providers-and-adapters.md). Device flows return a structured `deviceCode`; the GUI highlights and copies it before the user opens the verification page. `POST /api/oauth/accounts/probe` accepts admin-token and dashboard-session callers for Google Antigravity. It reads the store passively, runs at most four per-account requests, refuses overlapping batches, and returns closed verdicts plus recognized quota windows. The plain Antigravity account list reads the same passive store for CLI target resolution. For generic OAuth providers `AccountQuotaTable` is the account list itself (one or more accounts; there is no second card list): one row per account with the plan (a known tier id mapped to its product name, the raw id otherwise, "unknown plan" when upstream sent none), each quota pool's 5-hour and weekly remaining with a reset countdown, one status flag, and an actions column (pause/resume, reauthenticate, probe, alias, remove, reset grants or coupons). A detail line under the row carries hints, probe results, the Anthropic per-account threshold, and any quota window no pool column shows. Failed quota refreshes display the failure and read times alongside cached pool values. Below a 1100px container width rows stack instead of scrolling so the actions stay on screen, and each pool reads as three lines: its name, the 5-hour bar, the weekly bar. The pool settings cards above the list (Claude and Claude Pool 2 in `AnthropicAccountPoolSettings`, Codex usage-based switching in `CodexAutoSwitchSetting`) show only their title and on/off switch; `PoolSettingsDisclosure` makes the title a disclosure button and remembers opened cards per id in `localStorage`, while a load failure or the two-account requirement that disables the switch stays visible. An account auto-paused with `pauseDetails.reason` `account_permission_denied` reads "banned upstream": one notice replaces its quota cells, with a disclosure for the redacted upstream `message`, `pausedAt` and `statusCode` when recorded; resume is the manual way back. `needsReauthReason: "verify_account"` reads "verification needed". The Codex pool still renders the table above its own cards when it has two or more accounts. Pools come from the registry in `gui/src/provider-workspace/account-quota-table.ts`; the `next` marker on a scarce pool mirrors reset-first ordering, appears only when the pool's effective strategy is reset-first (today the Codex pool; generic OAuth pools pass no strategy and show none), and is display only. | +| OAuth | Login/status/logout for OAuth-backed providers, plus multiauth account management: `GET /api/oauth/accounts`, `PUT /api/oauth/accounts/active`, `PUT /api/oauth/accounts/alias`, `PUT /api/oauth/accounts/pause`, and `DELETE /api/oauth/accounts` list masked accounts per provider, switch the active one, edit its display-only alias, pause/resume a generic OAuth account, and remove one. Paused generic OAuth accounts are excluded from request selection, 429 failover, and proactive token refresh; pausing an active account selects the next usable account when available, and resuming an account restores an active selection if the current one remains paused. With no unpaused account, requests return 403 rather than a login error. Kiro account-list rows include the current automatic-selection projection and closed exclusion reason; an active singleton may still send. The login flow itself is `GET /api/oauth/providers`, `POST /api/oauth/login`, `POST /api/oauth/login/code`, `POST /api/oauth/login/cancel`, `POST /api/oauth/logout`, and `GET /api/oauth/status`; pool controls are `GET/PUT/PATCH /api/oauth/accounts/pool` and `POST /api/oauth/accounts/clear-cooldown`. Login accepts `addAccount: true` to force a fresh browser identity. Meta Muse login start and manual-code continuation require the server-resolved `gui-session` principal before credential acquisition or code submission (including reauth); see the [provider contract](providers-and-adapters.md). Device flows return a structured `deviceCode`; the GUI highlights and copies it before the user opens the verification page. `POST /api/oauth/accounts/probe` accepts admin-token and dashboard-session callers for Google Antigravity. It reads the store passively, runs at most four per-account requests, refuses overlapping batches, and returns closed verdicts plus recognized quota windows. The plain Antigravity account list reads the same passive store for CLI target resolution. For generic OAuth providers `AccountQuotaTable` is the account list itself (one or more accounts; there is no second card list): one row per account with the plan (a known tier id mapped to its product name, the raw id otherwise, "unknown plan" when upstream sent none), each quota pool's 5-hour and weekly consumed share with a reset countdown, one status flag, and an actions column (pause/resume, reauthenticate, probe, alias, remove, reset grants or coupons). A detail line under the row carries hints, probe results, the Anthropic per-account threshold, and any quota window no pool column shows. Failed quota refreshes display the failure and read times alongside cached pool values. Below a 1100px container width rows stack instead of scrolling so the actions stay on screen, and each pool reads as three lines: its name, the 5-hour bar, the weekly bar. The pool settings cards above the list (Claude and Claude Pool 2 in `AnthropicAccountPoolSettings`, Codex usage-based switching in `CodexAutoSwitchSetting`) show only their title and on/off switch; `PoolSettingsDisclosure` makes the title a disclosure button and remembers opened cards per id in `localStorage`, while a load failure or the two-account requirement that disables the switch stays visible. An account auto-paused with `pauseDetails.reason` `account_permission_denied` reads "banned upstream": one notice replaces its quota cells, with a disclosure for the redacted upstream `message`, `pausedAt` and `statusCode` when recorded; resume is the manual way back. `needsReauthReason: "verify_account"` reads "verification needed". The Codex pool still renders the table above its own cards when it has two or more accounts. Pools come from the registry in `gui/src/provider-workspace/account-quota-table.ts`; the `next` marker on a scarce pool mirrors reset-first ordering, appears only when the pool's effective strategy is reset-first (today the Codex pool; generic OAuth pools pass no strategy and show none), and is display only. | | Key providers | `GET /api/key-providers` exposes API-key provider presets for setup and dashboard flows, and `GET/POST/DELETE /api/keys` owns the proxy's own admission keys. Machine links live in `src/server/management/link-routes.ts`: dashboard sessions reach `GET /api/link/candidates`, `POST /api/link/probe`, `POST /api/link/confirm-host` and `POST /api/link/apply`, meaning a paired session or, on a standalone runtime, the current loopback-issued session on trusted loopback ingress; [caller-supplied explicit routes](remote-link.md#explicit-route) instead require an operator-paired session or the admin token on trusted loopback ingress; `POST /api/link/join` instead requires an operator-paired session because it durably redirects local client traffic, and also refuses a runtime that is not standalone (`409 standalone_required`) or not listening on its configured port (`409 join_port_mismatch`) before any SSH, then restarts this runtime as a client; `GET /api/link/status` reports `joinAvailable` and typed `joinDenied` causes only to GUI-session callers, distinguishing pairing, runtime-role and port refusals without changing the admin/CLI DTO, so the dashboard enables the Child role only when the join gates pass; `GET /api/link/status`, the read-only `GET /api/link/diagnostics` (this runtime's bounded diagnostics file, re-sanitized on read), `POST /api/link/{id}/reconnect` and `DELETE /api/link/{id}` also accept the admin token on a trusted loopback ingress, and reconnect restarts a Home-initiated link's tunnel now; `POST /api/link/issue` accepts only that admin token. Tailscale-identity sessions are refused on every link route. See [Remote Link](remote-link.md). Multi-key pool per key-auth provider: `GET /api/providers/keys`, `POST /api/providers/keys`, `PUT /api/providers/keys/active`, `PUT /api/providers/keys/alias`, `DELETE /api/providers/keys` masked list, add (upsert + activate), switch, rename, and remove keys. `provider.apiKey` always mirrors the active pool entry so routing stays single-key. | | OpenAI account mode | Report one OpenAI Codex card with Pool/Direct controls and one API-key card. Mode PATCH persists live without restart or catalog identity changes; Pool owns account/quota controls and Direct uses caller/main login only. Main-account DTOs report real credential presence and terminal `needsReauth` state instead of treating missing/invalid native auth as an unknown quota. Selection order has its own route: `PUT /api/codex-auth/accounts/priority` takes `{ id, priority }`, where `priority` is an integer -100..100 or `null` to restore the default, accepts `__main__`, 404s an unknown id, and echoes the stored value. Re-ordering never clears thread affinity, so the response carries no `appliesImmediately`, but it does release any pin — see [`openai-tiers.md`](providers/openai-tiers.md) for why. `PUT /api/codex-auth/active` with a null id releases one too, but that drops the operator's account selection along with it, so this route is the only operator-facing way to clear a pin while leaving the selected account in place. `GET /api/codex-auth/active` reports `pinned`, true only while the manually selected account is still the effective active one, plus `pinnedAccountId`, which names the pinned account whether or not it is the active one. Surfaces should render `pinnedAccountId`: under round-robin and fill-first the pin caps the tier ceiling at its own tier while the strategy cursor moves freely inside that tier, so `pinned` goes false on a sibling's turn even though the pin is still suppressing every higher tier — which is why the dashboard badges `pinnedAccountId` and the GUI controller tracks only the id. `pinned` answers the narrower question of whether routing is *currently* on the operator's choice; no surface in this repo asks it, and a new one almost certainly wants the id instead. | | Subagents | Read/write the featured `subagentModels` list capped at five ids. `GET/PUT /api/injection-model` manages the shared delegation model/effort selection, the independent OpenCodex guidance switch, and the default-off `syncCodexSubagentDefaults` opt-in for native Codex subagent defaults. When OpenCodex owns the active Codex routing, native `[agents]` defaults apply to newly created Codex tasks after sync/restart; external user-managed provider configs remain untouched. The defaults do not cause delegation and preserve existing user-owned defaults rather than overwriting them. PUT is partial-update: absent keys are unchanged, `null` clears, and non-object bodies are rejected with 400 before field validation. `syncCodexSubagentDefaults: true` requires a nonblank `model` and a supported Codex reasoning effort when effort is set; clearing `model` (null/empty) always clears effort and disables native-default sync even when the stored effort was invalid. | diff --git a/tests/gui/gui-account-quota-table.test.ts b/tests/gui/gui-account-quota-table.test.ts index 58cdfe40a4d..0df631af70d 100644 --- a/tests/gui/gui-account-quota-table.test.ts +++ b/tests/gui/gui-account-quota-table.test.ts @@ -15,15 +15,15 @@ function antigravity(id: string, overrides: Partial = {}, win } describe("account quota table", () => { - test("Antigravity windows land in Gemini, Claude & GPT and Argon pools as remaining percent", () => { + test("Antigravity windows land in Gemini, Claude & GPT and Argon pools as consumed percent", () => { const table = buildQuotaTable([ antigravity("a", {}, [["Gem", 10, 2], ["Gem (Weekly)", 40, 50], ["Cla", 75, 3], ["Cla (Weekly)", 20, 100], ["Argon", 5, 1]]), antigravity("b", {}, [["Gem", 0, 4], ["Cla", 30, 1]]), ], NOW); expect(table.pools.map(pool => pool.key)).toEqual(["gemini", "claudeGpt", "argon"]); const a = table.rows[0]!; - expect(a.cells.gemini).toEqual({ fiveHour: { remaining: 90, resetAt: NOW + 2 * HOUR }, weekly: { remaining: 60, resetAt: NOW + 50 * HOUR } }); - expect(a.cells.claudeGpt?.fiveHour?.remaining).toBe(25); + expect(a.cells.gemini).toEqual({ fiveHour: { used: 10, resetAt: NOW + 2 * HOUR }, weekly: { used: 40, resetAt: NOW + 50 * HOUR } }); + expect(a.cells.claudeGpt?.fiveHour?.used).toBe(75); expect(table.rows[1]!.cells.argon).toBeUndefined(); }); @@ -39,8 +39,8 @@ describe("account quota table", () => { }], NOW); expect(table.pools.map(pool => [pool.key, pool.scarce])).toEqual([["subscription", true]]); expect(table.rows[0]!.cells.subscription).toEqual({ - fiveHour: { remaining: 36, resetAt: NOW + HOUR }, - weekly: { remaining: 88, resetAt: NOW + 72 * HOUR }, + fiveHour: { used: 64, resetAt: NOW + HOUR }, + weekly: { used: 12, resetAt: NOW + 72 * HOUR }, }); }); @@ -99,7 +99,7 @@ describe("account quota table", () => { test("a reset already in the past shows no countdown", () => { const table = buildQuotaTable([antigravity("a", {}, [["Cla", 10, -1]])], NOW); - expect(table.rows[0]!.cells.claudeGpt?.fiveHour).toEqual({ remaining: 90 }); + expect(table.rows[0]!.cells.claudeGpt?.fiveHour).toEqual({ used: 10 }); }); test("countdown text", () => { From 030bdc3b59b6966c269717d4c838e789456cf5bf Mon Sep 17 00:00:00 2001 From: Hojoon Kim <99799197+HojooonKim@users.noreply.github.com> Date: Wed, 25 Nov 2026 13:50:56 +0900 Subject: [PATCH 22/60] feat(messaging): list local Claude Code sessions (#8992) * feat(messaging): list local Claude Code sessions * fix(messaging): preserve Claude agent-view opt-out during discovery * fix(messaging): honor Claude's boolean Agent View opt-out --------- Co-authored-by: HojoonKim Co-authored-by: JUN --- .../docs/es/reference/cli/messaging.md | 30 ++++ .../content/docs/reference/cli/messaging.md | 25 ++++ .../docs/tr/reference/cli/messaging.md | 4 + .../ocx/references/01_management_surface.md | 8 +- .../references/01_surface_agents-routing.md | 19 ++- src/cli/capabilities-agents-routing.ts | 9 ++ src/cli/message-claude-command.ts | 40 ++++++ src/cli/message-command.ts | 3 +- src/cli/registry.ts | 4 +- src/messaging/claude-discovery.ts | 62 ++++++++ structure/local-messaging.md | 23 ++- .../messaging-local-cli.test.ts | 133 +++++++++++++++++- .../messaging-local-lifecycle.test.ts | 8 +- 13 files changed, 354 insertions(+), 14 deletions(-) create mode 100644 src/cli/message-claude-command.ts create mode 100644 src/messaging/claude-discovery.ts diff --git a/docs-site/src/content/docs/es/reference/cli/messaging.md b/docs-site/src/content/docs/es/reference/cli/messaging.md index a185fd0a750..de15ffbc2bf 100644 --- a/docs-site/src/content/docs/es/reference/cli/messaging.md +++ b/docs-site/src/content/docs/es/reference/cli/messaging.md @@ -116,6 +116,36 @@ respuestas guardadas de Codex. Para una prueba de ida y vuelta: y vuelta. Si la espera vence, vuelve a comprobar el mismo recibo o revisa la conversación de Codex. Un tiempo de espera agotado no justifica otro envío. + + +## Listar sesiones locales de Claude Code + +En macOS o Linux, indica la ruta absoluta a un ejecutable de confianza de +Claude Code. Debe admitir [`claude agents --json`](https://code.claude.com/docs/en/agent-view#list-sessions-as-json). + +```bash +ocx message claude-sessions --claude /absolute/path/to/claude --json +``` + +El resultado `ocx-claude-sessions/1` incluye el UUID de cada sesión (`id`), +su tipo (`kind`, con valor `interactive` o `background`) y el estado de +actividad que informa Claude Code (`busy`, `waiting` o `idle`). Se omiten +las filas cuyo identificador de sesión o PID sea nulo o esté ausente. Si +ambos campos están presentes, un UUID de sesión abreviado o inválido, o +un PID inválido, provoca un fallo en toda la consulta. Si se define +`CLAUDE_CONFIG_DIR`, esta variable selecciona la configuración local de +Claude. El resultado omite los nombres, las rutas, los PID y el historial. +El comando ejecuta la CLI de Claude una vez con un plazo de cinco segundos, +un límite de salida de 256 KiB y un máximo de 256 filas. Respeta +`CLAUDE_CODE_DISABLE_AGENT_VIEW` y desactiva el tráfico no esencial de la CLI +de Claude durante la consulta. Claude Code puede inicializar su propia +configuración en el primer uso. Si la consulta falla, el comando devuelve +un error sin datos sensibles y sin resultados parciales. + +La lista solo refleja las sesiones locales observadas. El comando no +comprueba si pueden recibir mensajes, no envía mensajes y no usa los pares +SSH registrados. + ## Descubrir y enviar diff --git a/docs-site/src/content/docs/reference/cli/messaging.md b/docs-site/src/content/docs/reference/cli/messaging.md index 2d52efc5fdc..8d19f8fee16 100644 --- a/docs-site/src/content/docs/reference/cli/messaging.md +++ b/docs-site/src/content/docs/reference/cli/messaging.md @@ -214,6 +214,31 @@ text with the client. For a round trip: the round trip. If the wait expires, check the same receipt again or inspect the Codex conversation. A wait timeout does not justify another send. +## List local Claude Code sessions + +On macOS or Linux, pass the absolute path to your trusted native Claude Code +executable. It must support [`claude agents --json`](https://code.claude.com/docs/en/agent-view#list-sessions-as-json). + +```bash +ocx message claude-sessions --claude /absolute/path/to/claude --json +``` + +The `ocx-claude-sessions/1` result lists session UUIDs (`id`), `kind` +(`interactive` or `background`) and the activity reported by Claude Code +(`busy`, `waiting` or `idle`). Rows with a missing or null session ID or PID +are skipped. When both fields are present, a shortened or otherwise invalid +session UUID or an invalid PID causes the entire lookup to fail. +`CLAUDE_CONFIG_DIR`, if set, selects the local Claude configuration. Names, +paths, PIDs and history are omitted from the result. The command invokes the +Claude CLI once with a five-second deadline, 256 KiB output limit and 256-row +limit. It respects the `CLAUDE_CODE_DISABLE_AGENT_VIEW` opt-out and disables +nonessential Claude CLI traffic for the lookup. Claude Code can initialize +its own configuration on first use. On failure the command returns a +sanitized error and no partial list. + +A listed session is an observed local session. This command does not test +inbox reachability, send messages, or use enrolled SSH peers. + ## Discover and send ```bash diff --git a/docs-site/src/content/docs/tr/reference/cli/messaging.md b/docs-site/src/content/docs/tr/reference/cli/messaging.md index 1377182d678..983645ddd8c 100644 --- a/docs-site/src/content/docs/tr/reference/cli/messaging.md +++ b/docs-site/src/content/docs/tr/reference/cli/messaging.md @@ -31,6 +31,10 @@ yardımcı kapatma bunu geçersiz kılmaz, son tarihten sonra tamamlanan okumala kullanılmaz. Mesaj gönderme ve yanıt bekleme ayrı çağrılardır. [Ayrıntılar ve sınırlar](/reference/cli/messaging/#opt-in-stored-turn-replies). +Yerel Claude Code oturumlarını listelemek için +[`ocx message claude-sessions`](/reference/cli/messaging/#list-local-claude-code-sessions) +komutunu kullanın. Liste, bir oturumun mesaj alabileceğini doğrulamaz. + ## Keşfetme ve gönderme ```bash diff --git a/skills/ocx/references/01_management_surface.md b/skills/ocx/references/01_management_surface.md index 7b6470b3737..b22c4097c28 100644 --- a/skills/ocx/references/01_management_surface.md +++ b/skills/ocx/references/01_management_surface.md @@ -28,7 +28,7 @@ These answer in the CLI head and never reach the proxy, so they work with nothin | [lifecycle](01_surface_lifecycle.md) | 14 | | [providers-models](01_surface_providers-models.md) | 54 | | [accounts](01_surface_accounts.md) | 44 | -| [agents-routing](01_surface_agents-routing.md) | 71 | +| [agents-routing](01_surface_agents-routing.md) | 72 | | [integrations](01_surface_integrations.md) | 41 | | [observe-system](01_surface_observe-system.md) | 105 | | [access-remote](01_surface_access-remote.md) | 55 | @@ -711,6 +711,10 @@ Original invocation order. These headings preserve links to the previous single- [State-changing task](01_surface_agents-routing.md#ocx-message-mcp) +### `ocx message claude-sessions` + +[Read-oriented task](01_surface_agents-routing.md#ocx-message-claude-sessions) + ### `ocx advisor` [State-changing task](01_surface_agents-routing.md#ocx-advisor) @@ -1669,6 +1673,6 @@ Original invocation order. These headings preserve links to the previous single- ## Counts -- declared capabilities: 405 +- declared capabilities: 406 - of those, state-changing: 254 - head-resolved invocations: 2 diff --git a/skills/ocx/references/01_surface_agents-routing.md b/skills/ocx/references/01_surface_agents-routing.md index 05d206617a9..566e1a4a8b3 100644 --- a/skills/ocx/references/01_surface_agents-routing.md +++ b/skills/ocx/references/01_surface_agents-routing.md @@ -8,7 +8,7 @@ Use these declarations to choose a task, then check its flags and authority before execution. Non-mutating probes may still contact providers, consume quota or refresh caches. -Declared capabilities: 71. +Declared capabilities: 72. ### `ocx agent subagents force` @@ -202,6 +202,23 @@ Drives no management route. - macOS/Linux only. Default queue/read tools need no proxy/control socket; resume uses the explicitly configured existing Unix socket. Starts bounded stdio helpers only when a tool is called; existing sessions/send behavior stays unchanged. - Stored threads are not verified live sessions. queued is not processing; unknown is never replayed. --allow-reply-read exposes bounded same-turn final text, not exclusive reply ownership or goal completion. No daemon start, steer, automatic replies or registration. Resume preflight is separate opt-in through a same-home existing Unix server; managed requirements and unavailable profiles refuse. The checked native API cannot enforce unloaded-only resume atomically, so execution is blocked with resume_atomicity_unsupported; no thread/resume is sent. +### `ocx message claude-sessions` + +Usage: `ocx message claude-sessions --claude [--json]` + +List local Claude Code session IDs and their reported activity. + +State-changing: no. JSON mode: `envelope`. + +Drives no management route. + +| Flag | Value | Meaning | +|---|---|---| +| `--claude` | string | Absolute path to a trusted Claude Code CLI with agents --json support. | +| `--json` | boolean | Emit a versioned Claude Code session directory. | + +- macOS/Linux only. Invokes the selected local CLI once. Returns only UUID, interactive/background kind and busy/waiting/idle status. Does not test reachability or send a message. + ### `ocx advisor` Inspect and configure the advisor sidecar (expert consultation for routed workers). diff --git a/src/cli/capabilities-agents-routing.ts b/src/cli/capabilities-agents-routing.ts index 2cd4abed478..f1c96299c45 100644 --- a/src/cli/capabilities-agents-routing.ts +++ b/src/cli/capabilities-agents-routing.ts @@ -39,6 +39,15 @@ export const AGENT_ROUTING_CAPABILITIES: readonly Capability[] = [ details: ["macOS/Linux only. Default queue/read tools need no proxy/control socket; resume uses the explicitly configured existing Unix socket. Starts bounded stdio helpers only when a tool is called; existing sessions/send behavior stays unchanged.", "Stored threads are not verified live sessions. queued is not processing; unknown is never replayed. --allow-reply-read exposes bounded same-turn final text, not exclusive reply ownership or goal completion. No daemon start, steer, automatic replies or registration. Resume preflight is separate opt-in through a same-home existing Unix server; managed requirements and unavailable profiles refuse. The checked native API cannot enforce unloaded-only resume atomically, so execution is blocked with resume_atomicity_unsupported; no thread/resume is sent."], }, + { + command: ["message", "claude-sessions"], + usage: "ocx message claude-sessions --claude [--json]", + summary: "List local Claude Code session IDs and their reported activity.", + routes: [], mutates: false, json: "envelope", + flags: [{ name: "--claude", value: "string", required: true, summary: "Absolute path to a trusted Claude Code CLI with agents --json support." }, + { name: "--json", value: "boolean", summary: "Emit a versioned Claude Code session directory." }], + details: ["macOS/Linux only. Invokes the selected local CLI once. Returns only UUID, interactive/background kind and busy/waiting/idle status. Does not test reachability or send a message."], + }, { command: ["advisor"], summary: "Inspect and configure the advisor sidecar (expert consultation for routed workers).", diff --git a/src/cli/message-claude-command.ts b/src/cli/message-claude-command.ts new file mode 100644 index 00000000000..2595bba7a99 --- /dev/null +++ b/src/cli/message-claude-command.ts @@ -0,0 +1,40 @@ +import { isAbsolute } from "node:path"; +import { discoverClaudeSessions } from "../messaging/claude-discovery"; +import { LocalMessagingError } from "../messaging/types"; + +export async function runMessageClaudeCommand(argv: readonly string[], env: NodeJS.ProcessEnv): Promise { + let claude: string | undefined; + let json = false; + for (let index = 0; index < argv.length; index++) { + const flag = argv[index]; + if (flag === "--json" && !json) json = true; + else if (flag === "--claude" && claude === undefined) claude = argv[++index]; + else { claude = undefined; break; } + } + if (!claude || !isAbsolute(claude) || /[\x00-\x1f]/.test(claude)) { + console.error("Usage: ocx message claude-sessions --claude [--json]"); + return 64; + } + const controller = new AbortController(); + const cancel = () => controller.abort(); + process.once("SIGINT", cancel); + process.once("SIGTERM", cancel); + try { + if (process.platform !== "linux" && process.platform !== "darwin") { + throw new LocalMessagingError("unsupported_platform", "Claude Code session discovery currently supports macOS and Linux only."); + } + const sessions = await discoverClaudeSessions(claude, env, controller.signal); + if (json) console.log(JSON.stringify({ schema: "ocx-claude-sessions/1", sessions })); + else for (const session of sessions) console.log(`${session.id}\t${session.kind}\t${session.status}`); + return 0; + } catch (cause) { + const error = cause instanceof LocalMessagingError ? { code: cause.code, message: cause.message } + : { code: "claude_directory_unavailable", message: "Local Claude Code session discovery failed." }; + if (json) console.log(JSON.stringify({ schema: "ocx-message-error/1", error })); + else console.error(error.message); + return 1; + } finally { + process.removeListener("SIGINT", cancel); + process.removeListener("SIGTERM", cancel); + } +} diff --git a/src/cli/message-command.ts b/src/cli/message-command.ts index e0d11a34427..464d5e53cc9 100644 --- a/src/cli/message-command.ts +++ b/src/cli/message-command.ts @@ -8,11 +8,12 @@ import { terminalSafeText } from "./runtime-api"; /** Run one local messaging operation after pure syntax validation, then release owned resources. */ export async function runMessageCommand(argv: readonly string[], env: NodeJS.ProcessEnv = process.env): Promise { if (argv[0] === "mcp") return (await import("./message-mcp-command")).runMessageMcpCommand(argv.slice(1)); + if (argv[0] === "claude-sessions") return (await import("./message-claude-command")).runMessageClaudeCommand(argv.slice(1), env); const remote = parseRemoteMessageArgs(argv); if (remote) return (await import("./message-remote-command")).runRemoteMessageCommand(remote, env); const args = parseMessageArgs(argv); if (!args) { - console.error("Usage: ocx message sessions [--host ] [--json] | send (--thread | --name ) --stdin [--host ] [--kind request|response|notification] [--in-reply-to ] [--json] | mcp --codex --codex-home [--allow-reply-read] [--allow-resume --resume-socket --resume-permissions ] | enable [--port ] | disable | status | hosts | serve [--host ]..."); + console.error("Usage: ocx message sessions [--host ] [--json] | send (--thread | --name ) --stdin [--host ] [--kind request|response|notification] [--in-reply-to ] [--json] | mcp --codex --codex-home [--allow-reply-read] [--allow-resume --resume-socket --resume-permissions ] | claude-sessions --claude [--json] | enable [--port ] | disable | status | hosts | serve [--host ]..."); return 64; } const controller = new AbortController(); diff --git a/src/cli/registry.ts b/src/cli/registry.ts index 1c56d0875ad..f84b0da4fb9 100644 --- a/src/cli/registry.ts +++ b/src/cli/registry.ts @@ -18,8 +18,8 @@ export const CLI_COMMANDS: CliCommandEntry[] = [ }, { name: "message", - usage: "ocx message [options]", - summary: "Discover loaded Codex sessions and queue messages locally or through explicit SSH peers.", + usage: "ocx message [options]", + summary: "Discover local Codex or Claude Code sessions and queue Codex messages locally or through explicit SSH peers.", details: ["Remote listeners/tunnels require explicit foreground serve; no daemon start. queued is submission, not processing; never replay an unknown send."], }, { diff --git a/src/messaging/claude-discovery.ts b/src/messaging/claude-discovery.ts new file mode 100644 index 00000000000..d491ce72cd5 --- /dev/null +++ b/src/messaging/claude-discovery.ts @@ -0,0 +1,62 @@ +import { readBoundedResponseBytes } from "../lib/bounded-body"; +import { isRecord, isThreadId, LocalMessagingError } from "./types"; + +interface ClaudeSession { + id: string; + kind: "interactive" | "background"; + status: "busy" | "waiting" | "idle"; +} + +const invalidDirectory = () => new LocalMessagingError("invalid_claude_directory", "Claude Code returned an invalid or oversized session directory."); + +/** Use the documented agent directory. Its entries are metadata, not delivery routes. */ +export async function discoverClaudeSessions(claude: string, env: NodeJS.ProcessEnv, signal: AbortSignal): Promise { + if (/^(?:1|true|yes|on)$/i.test(env.CLAUDE_CODE_DISABLE_AGENT_VIEW?.trim() ?? "")) { + throw new LocalMessagingError("claude_agent_view_disabled", "Claude Code agent view is disabled."); + } + const deadline = AbortSignal.any([signal, AbortSignal.timeout(5000)]); + const unavailable = () => new LocalMessagingError("claude_directory_unavailable", "Claude Code could not list local sessions. Check that the selected CLI supports agents --json."); + const childEnv = Object.fromEntries(["HOME", "PATH", "TMPDIR", "LANG", "LC_ALL", "CLAUDE_CONFIG_DIR", "CLAUDE_CODE_DISABLE_AGENT_VIEW"] + .flatMap(key => env[key] === undefined ? [] : [[key, env[key]!] as const])); + let child; + try { + deadline.throwIfAborted(); + child = Bun.spawn([claude, "agents", "--json"], { + env: { ...childEnv, CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1" }, + stdin: "ignore", stdout: "pipe", stderr: "ignore", signal: deadline, killSignal: "SIGKILL", + }); + } catch { throw unavailable(); } + let bytes: Uint8Array; + try { + const capture = await readBoundedResponseBytes(new Response(child.stdout), { maxBytes: 256 * 1024, signal: deadline }); + if (capture.oversized) throw invalidDirectory(); + if (await child.exited !== 0 || deadline.aborted) throw unavailable(); + bytes = capture.bytes; + } catch (error) { + if (error instanceof LocalMessagingError) throw error; + throw unavailable(); + } finally { + if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); + await child.exited; + } + + let rows: unknown; + try { rows = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); } + catch { throw invalidDirectory(); } + if (!Array.isArray(rows) || rows.length > 256) throw invalidDirectory(); + const sessions: ClaudeSession[] = []; + const seen = new Set(); + for (const row of rows) { + if (!isRecord(row)) throw invalidDirectory(); + if (row.sessionId == null || row.pid == null) continue; + const { sessionId, pid, kind, status } = row; + if (!isThreadId(sessionId) || typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0 + || (kind !== "interactive" && kind !== "background") + || (status !== "busy" && status !== "waiting" && status !== "idle")) throw invalidDirectory(); + const id = sessionId.toLowerCase(); + if (seen.has(id)) throw invalidDirectory(); + seen.add(id); + sessions.push({ id, kind, status }); + } + return sessions; +} diff --git a/structure/local-messaging.md b/structure/local-messaging.md index 2b3698125af..618c56db71c 100644 --- a/structure/local-messaging.md +++ b/structure/local-messaging.md @@ -72,7 +72,7 @@ no recipient, daemon or proxy is stopped. > Decision record: [ADR-6479](decisions/ADR-6479-local-messaging-command.md) `src/cli/dispatch.ts` dynamically imports the command runner for the message verb. -`src/cli/message-args.ts` rejects malformed, duplicate and remote/Claude options +`src/cli/message-args.ts` rejects malformed, duplicate and remote options on the Codex path before any command resource or home selection. `src/cli/codex-shim-autorestore.ts` skips repair for the whole namespace. Registry, capability and help declarations describe sessions/send; no management route is claimed. The separate pure remote @@ -80,7 +80,7 @@ parser selects a dynamic remote-command import only for explicit remote operatio local operations do not read peer state or start an owner. `src/cli/message-runtime.ts` reuses effective Codex-home resolution without -persistence. Messaging needs no selected CLI binary or version pin. The existing +persistence. The local Codex path needs no selected CLI binary or version pin. The existing Codex daemon must support experimental `thread/queue/add`; there is no installation, repair, daemon start or runtime fallback when it rejects the method. @@ -89,6 +89,25 @@ rejecting invalid bytes, empty text and NUL. The final envelope is bounded at 32 KiB. Message text travels only in the existing Unix RPC connection, never in spawned process arguments. No request-body logging is added. +## Local Claude Code session directory + +`src/cli/message-claude-command.ts` validates the explicit `claude-sessions` +invocation before `src/messaging/claude-discovery.ts` spawns one user-selected +absolute Claude executable with fixed `agents --json` arguments. The subprocess +receives no stdin or inherited credentials, disables Claude's nonessential +traffic, and has a five-second deadline and 256 KiB output limit. An enabled +`CLAUDE_CODE_DISABLE_AGENT_VIEW` refuses before spawn; other values pass to +the native CLI. The executable can initialize its own local configuration. +Cancellation stops only the directly owned executable; raw diagnostics are discarded. + +The snapshot has at most 256 source rows. Rows with a missing or null session +ID or process ID are skipped. Invalid rows with both IDs present, including +shortened session UUIDs, and duplicate session UUIDs fail the snapshot. +Results expose only UUID, session kind and activity status; they give no +inbox address or permission to send and do not prove reachability. +No history, working directory, session title or process ID is returned. Neither +the Codex transport nor the remote-peer mode uses this directory. + ## Envelope and receipt semantics `src/messaging/envelope.ts` assembles the caller-generated UUID, kind, response diff --git a/tests/codex-integration/messaging-local-cli.test.ts b/tests/codex-integration/messaging-local-cli.test.ts index 12efb8c7ffe..484cf764486 100644 --- a/tests/codex-integration/messaging-local-cli.test.ts +++ b/tests/codex-integration/messaging-local-cli.test.ts @@ -1,5 +1,6 @@ import { expect, test } from "bun:test"; -import { existsSync } from "node:fs"; +import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { messageCodexHome } from "../../src/cli/message-runtime"; import { skipsCodexShimAutoRestore } from "../../src/cli/codex-shim-autorestore"; @@ -13,8 +14,12 @@ test("local commands stay registered and skip global repair even on malformed us expect(caps.map(cap => cap.command[1])).toContain("sessions"); expect(caps.map(cap => cap.command[1])).toContain("send"); expect(caps.every(cap => cap.routes.length === 0)).toBe(true); - expect(caps[1]!.mutates).toBe(true); - expect(caps[1]!.flags.map(flag => flag.name)).toContain("--host"); + const send = caps.find(cap => cap.command[1] === "send"); + expect(send?.mutates).toBe(true); + expect(send?.flags.map(flag => flag.name)).toContain("--host"); + const claude = caps.find(cap => cap.command[1] === "claude-sessions"); + expect(claude?.mutates).toBe(false); + expect(claude?.flags.map(flag => flag.name)).toContain("--claude"); }); test("invalid usage allocates no timer, socket, helper or runtime-selection work", async () => { @@ -22,7 +27,20 @@ test("invalid usage allocates no timer, socket, helper or runtime-selection work const { runMessageCommand } = await import(${JSON.stringify(repoPath("src/cli/message-command.ts"))}); const fail = () => { throw new Error('Unexpected resource allocation'); }; globalThis.setTimeout = fail; Bun.spawn = fail; globalThis.WebSocket = class { constructor() { fail(); } }; - process.exitCode = await runMessageCommand(['send', '--host', 'remote', '--stdin'], { CODEX_HOME: '/must-not-read' }); + globalThis.AbortController = class { constructor() { fail(); } }; + for (const args of [ + ['send', '--host', 'remote', '--stdin'], + ['claude-sessions'], + ['claude-sessions', '--claude', 'relative'], + ['claude-sessions', '--claude', '/must-not-run', '--json', '--json'], + ['claude-sessions', '--claude', '/must-not-run', '--claude', '/must-not-run'], + ['claude-sessions', '--claude', '/must-not-run', '--host', 'remote'], + ]) { + if (await runMessageCommand(args, { CODEX_HOME: '/must-not-read' }) !== 64) { + throw new Error('Expected invalid usage exit code'); + } + } + process.exitCode = 64; `; const child = Bun.spawn([process.execPath, "-e", script], { stdout: "pipe", stderr: "pipe" }); const [code, output, errors] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); @@ -77,3 +95,110 @@ test.skipIf(process.platform === "win32")("full CLI uses the daemon directly, em } finally { await fixture.close(); } } }, 30_000); + +test.skipIf(process.platform === "win32")("Claude discovery projects live sessions and sanitizes failed lookups", async () => { + const root = mkdtempSync(join(tmpdir(), "ocx-claude-sessions-")); + const executable = join(root, "fake claude"); + const responsePath = join(root, "response.json"); + const failPath = join(root, "fail"); + const hangPath = join(root, "hang"); + const env = { + PATH: process.env.PATH, HOME: root, CODEX_HOME: join(root, "codex"), + OPENCODEX_HOME: join(root, "ocx"), OCX_TEST_HOME_GUARD: "1", + ANTHROPIC_API_KEY: "fixture-private-env", + }; + const cli = [process.execPath, repoPath("src/cli/index.ts"), "message", "claude-sessions"]; + const run = async (args: string[], extraEnv: Record = {}) => { + const child = Bun.spawn([...cli, ...args], { + env: { ...env, ...extraEnv }, stdin: new Blob(["fixture-private-stdin\n"]), stdout: "pipe", stderr: "pipe", + }); + const timer = setTimeout(() => child.kill(), 10_000); + try { + const [exitCode, stdout, stderr] = await Promise.all([ + child.exited, new Response(child.stdout).text(), new Response(child.stderr).text(), + ]); + return { exitCode, stdout, stderr }; + } finally { clearTimeout(timer); } + }; + try { + writeFileSync(executable, `#!/bin/sh +[ "$#" -eq 2 ] && [ "$1" = agents ] && [ "$2" = --json ] || exit 40 +if IFS= read -r line; then exit 41; fi +[ -z "$ANTHROPIC_API_KEY" ] || exit 44 +[ "$CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC" = 1 ] || exit 45 +printf '%s\\n' fixture-private-stderr >&2 +/bin/cat "\${0%/*}/response.json" || exit 42 +if [ -f "\${0%/*}/fail" ]; then exit 43; fi +if [ -f "\${0%/*}/hang" ]; then exec /bin/sleep 30; fi +`, { mode: 0o700 }); + const records = [ + { sessionId: "1111111A-1111-4111-8111-111111111111", pid: 123, kind: "interactive", status: "busy", cwd: "/fixture-private-cwd" }, + { sessionId: "22222222-2222-4222-8222-222222222222", pid: 456, kind: "background", status: "idle", name: "fixture-private-name" }, + { sessionId: "33333333-3333-4333-8333-333333333333", pid: 789, kind: "interactive", status: "waiting", summary: "fixture-private-summary" }, + ]; + writeFileSync(responsePath, JSON.stringify([ + ...records, + { sessionId: LOCAL_TARGET, summary: "fixture-private-stopped" }, + { pid: 987, status: "busy" }, + { ...records[0], sessionId: null }, + ])); + const args = ["--claude", executable]; + for (const value of ["1", "true", " Yes ", "ON"]) { + const disabled = await run(["--claude", join(root, "missing executable"), "--json"], { CLAUDE_CODE_DISABLE_AGENT_VIEW: value }); + expect(disabled.exitCode).toBe(1); + expect(JSON.parse(disabled.stdout).error.code).toBe("claude_agent_view_disabled"); + } + const json = await run([...args, "--json"]); + expect(json.exitCode).toBe(0); + expect(json.stderr).toBe(""); + expect(JSON.parse(json.stdout)).toEqual({ + schema: "ocx-claude-sessions/1", + sessions: records.map(({ sessionId, kind, status }) => ({ id: sessionId.toLowerCase(), kind, status })), + }); + const human = await run(args); + expect(human.exitCode).toBe(0); + expect(human.stderr).toBe(""); + expect(human.stdout).not.toContain("fixture-private"); + for (const { sessionId, kind, status } of records) { + expect(human.stdout).toContain(`${sessionId.toLowerCase()}\t${kind}\t${status}\n`); + } + + const expectFailure = async (path = executable) => { + const result = await run(["--claude", path, "--json"]); + expect(result.exitCode).toBe(1); + expect(result.stderr).toBe(""); + expect(result.stdout).not.toContain("fixture-private"); + expect(result.stdout).not.toContain(root); + expect(JSON.parse(result.stdout)).toMatchObject({ + schema: "ocx-message-error/1", error: { message: expect.any(String) }, + }); + }; + writeFileSync(responsePath, "[]"); + const empty = await run([...args, "--json"]); + expect(empty.exitCode).toBe(0); + expect(JSON.parse(empty.stdout)).toEqual({ schema: "ocx-claude-sessions/1", sessions: [] }); + const first = records[0]!; + for (const response of [ + "fixture-private-invalid-json", + JSON.stringify({ sessions: records }), + JSON.stringify([records[0], { ...records[1], pid: 0 }]), + JSON.stringify([records[0], { ...records[1], sessionId: "fixture-private-invalid-id" }]), + JSON.stringify([records[0], { ...records[1], sessionId: "12345678" }]), + JSON.stringify([records[0], { ...records[1], kind: "fixture-private-invalid-kind" }]), + JSON.stringify([records[0], { ...records[1], status: "fixture-private-invalid-status" }]), + JSON.stringify([first, { ...first, sessionId: first.sessionId.toLowerCase() }]), + JSON.stringify(Array.from({ length: 257 }, () => ({}))), + " ".repeat(256 * 1024) + "[]", + ]) { + writeFileSync(responsePath, response); + await expectFailure(); + } + writeFileSync(responsePath, "[]"); + writeFileSync(failPath, ""); + await expectFailure(); + await expectFailure(join(root, "missing executable")); + rmSync(failPath); + writeFileSync(hangPath, ""); + await expectFailure(); + } finally { rmSync(root, { recursive: true, force: true }); } +}, 30_000); diff --git a/tests/codex-integration/messaging-local-lifecycle.test.ts b/tests/codex-integration/messaging-local-lifecycle.test.ts index c0988317eb6..d1d6a5afa93 100644 --- a/tests/codex-integration/messaging-local-lifecycle.test.ts +++ b/tests/codex-integration/messaging-local-lifecycle.test.ts @@ -19,7 +19,7 @@ test("transport rejects remote URLs and unsupported platforms without opening a }); test("importing the unactivated subsystem allocates no listener, timer, child or socket", async () => { - const modules = ["types", "budget", "socket", "rpc", "discovery", "envelope", "input", "send", "mcp-queue-rpc", "mcp-queue-tools", "mcp-queue-server", "mcp-reply-tools", "mcp-reply-cursor", "mcp-reply-wait", "mcp-resume-tools", "resume-permissions"].map(name => repoPath("src", "messaging", `${name}.ts`)); + const modules = ["types", "budget", "socket", "rpc", "discovery", "claude-discovery", "envelope", "input", "send", "mcp-queue-rpc", "mcp-queue-tools", "mcp-queue-server", "mcp-reply-tools", "mcp-reply-cursor", "mcp-reply-wait", "mcp-resume-tools", "resume-permissions"].map(name => repoPath("src", "messaging", `${name}.ts`)); const script = ` const forbidden = () => { throw new Error("unexpected messaging resource allocation"); }; globalThis.setTimeout = forbidden; @@ -35,7 +35,7 @@ test("importing the unactivated subsystem allocates no listener, timer, child or test("messaging activation is command-local, never on an ordinary proxy startup path", async () => { // Native parser inventory, not graph completeness: catches static/dynamic literal imports. - const allowed = new Set(["src/cli/message-args.ts", "src/cli/message-command.ts", "src/cli/message-remote-args.ts", "src/cli/message-remote-command.ts", "src/cli/message-mcp-command.ts"]); + const allowed = new Set(["src/cli/message-args.ts", "src/cli/message-command.ts", "src/cli/message-remote-args.ts", "src/cli/message-remote-command.ts", "src/cli/message-mcp-command.ts", "src/cli/message-claude-command.ts"]); const transpiler = new Bun.Transpiler({ loader: "ts" }); for await (const scanned of new Bun.Glob("src/**/*.{ts,mts}").scan({ cwd: repoPath() })) { const path = scanned.replaceAll("\\", "/"); // Bun.Glob yields native separators on Windows. @@ -43,6 +43,10 @@ test("messaging activation is command-local, never on an ordinary proxy startup const imports = transpiler.scanImports(readFileSync(repoPath(path), "utf8").replace(/^#![^\n]*\n/, "")); const incoming = imports.filter(entry => /(?:^|\/)messaging(?:\/|$)/.test(entry.path)); if (!allowed.has(path)) expect(incoming, path).toEqual([]); + for (const entry of imports.filter(entry => entry.path.endsWith("/message-claude-command"))) { + expect(path).toBe("src/cli/message-command.ts"); + expect(entry.kind).toBe("dynamic-import"); + } for (const entry of imports.filter(entry => /(?:^|\/)message-(?:command|args|runtime)$/.test(entry.path))) { expect(["src/cli/dispatch.ts", "src/cli/message-command.ts", "src/cli/message-remote-command.ts", "src/cli/message-remote-args.ts"], path).toContain(path); if (path === "src/cli/dispatch.ts") { From 9a29289356965404f8556a527b3b959d28f2c0a5 Mon Sep 17 00:00:00 2001 From: wang-biubiu <26735292+wang-biubiu@users.noreply.github.com> Date: Wed, 25 Nov 2026 12:51:22 +0800 Subject: [PATCH 23/60] fix(codex): learn exact refusals for registered native models (#9050) * fix(codex): learn exact refusals for registered native models * fix(codex): invalidate stale rosters only after accepted model refusals * fix(codex): fence roster flights across account invalidation * fix(codex): retire invalidated entitlement snapshots --------- Co-authored-by: biubiu Co-authored-by: JUN --- .../troubleshooting/codex-cannot-sign-in.md | 6 + .../troubleshooting/codex-cannot-sign-in.md | 6 + src/codex/model-entitlements.ts | 98 +++++- src/codex/observed-model-denials.ts | 8 +- structure/catalog.md | 4 +- structure/providers/openai-accounts.md | 10 +- ...odex-account-selection-preferences.test.ts | 150 ++++++++ .../codex-model-denial-evidence.test.ts | 331 ++++++++++++++++-- 8 files changed, 549 insertions(+), 64 deletions(-) diff --git a/docs-site/src/content/docs/troubleshooting/codex-cannot-sign-in.md b/docs-site/src/content/docs/troubleshooting/codex-cannot-sign-in.md index 45e8341e6c0..84ea0ebe917 100644 --- a/docs-site/src/content/docs/troubleshooting/codex-cannot-sign-in.md +++ b/docs-site/src/content/docs/troubleshooting/codex-cannot-sign-in.md @@ -142,3 +142,9 @@ Before a response starts, this temporary refusal returns HTTP 503 with error. Capacity refusal does not mark the account as needing reauthentication, so signing in again is unnecessary for this error. A refresh that never settles can continue occupying capacity; the limit does not impose a refresh deadline. + +## A listed model is unavailable + +A model in the picker is not a grant for every account in the pool. For a registered ungated native model, when an account returns the exact unsupported-model refusal, automatic routing remembers that account/model pair and prefers another usable account on later requests. This also covers newly configured and discovered native models; an absent roster entry alone does not deny them. Explicit account selections remain authoritative, and no alternative can serve the request when every usable account lacks that model or has exhausted its quota. + +Check the failed request's account and error in **Usage & Logs**. As an immediate workaround, pause the refusing account in **Accounts & Quotas**, or select an account that has served that model and still has quota. Pausing preserves its login and does not cancel already-sent requests. Overload and timeout errors are separate failures; signing in again does not resolve them. diff --git a/docs-site/src/content/docs/zh-cn/troubleshooting/codex-cannot-sign-in.md b/docs-site/src/content/docs/zh-cn/troubleshooting/codex-cannot-sign-in.md index 0d205ac7f14..1003cd5de1d 100644 --- a/docs-site/src/content/docs/zh-cn/troubleshooting/codex-cannot-sign-in.md +++ b/docs-site/src/content/docs/zh-cn/troubleshooting/codex-cannot-sign-in.md @@ -59,3 +59,9 @@ ocx account login openai --device ``` 有关注入的配置及路由选择方式,请参阅 [Codex 集成](/zh-cn/guides/codex-integration/)。 + +## 列表中的模型提示不可用 + +模型出现在列表中,不代表池中每个账号都有使用权限。对于已注册且不受账号模型门控的原生模型,账号明确返回“不支持该模型”后,自动路由会记住这个账号与模型的组合,后续请求优先选择其他可用账号。新配置和自动发现的原生模型也适用;仅在模型列表中缺失不会被视为拒绝。手动指定账号仍然有效;其他账号也无权限或额度耗尽时,仍可能无法完成请求。 + +在“用量与日志”检查失败请求对应的账号及错误。临时处理可以在“账号与额度”暂停拒绝该模型的账号,或选择实际成功使用过该模型且仍有额度的账号。暂停会保留登录,并且不取消已发送的请求。服务过载和超时属于另外的问题,重新登录不能解决。 diff --git a/src/codex/model-entitlements.ts b/src/codex/model-entitlements.ts index 255d5a3bf63..fc8e600c894 100644 --- a/src/codex/model-entitlements.ts +++ b/src/codex/model-entitlements.ts @@ -18,6 +18,7 @@ import { ACCOUNT_GATED_NATIVE_OPENAI_MODELS, BUILT_IN_NATIVE_OPENAI_MODELS, NATIVE_GPT6_ASTRA_MODEL, + SUPPORTED_NATIVE_OPENAI_SLUGS, } from "./catalog/native-models"; import { loadPersistedCodexRuntime } from "./runtime"; import { codexRuntimeStateEpoch } from "./runtime"; @@ -503,6 +504,17 @@ export interface CodexEntitlementFreshnessOptions extends Pick< const accountModelsCache = new Map(); const accountModelsFlights = new Map>(); +// Weak ownership follows callers' snapshot lifetimes without retaining account history. +let retiredAccountModels = new WeakSet(); +let snapshotAccountModels = new WeakMap(); + +interface AccountModelsFlightFence { + invalidationGeneration: number; + pending: number; +} + +// Retained only while an account has pending flights, never as an unbounded invalidation history. +const accountModelsFlightFences = new Map(); interface NegativeCredentialMemo { readonly credentialIdentity: string | null; @@ -537,6 +549,26 @@ function accountIdOfCacheKey(key: string): string { return separator === -1 ? key : key.slice(0, separator); } +/** Retire the exact evidence object, including snapshots that already captured it. */ +function deleteCachedAccountModels(key: string): void { + const entry = accountModelsCache.get(key); + if (entry) retiredAccountModels.add(entry); + accountModelsCache.delete(key); +} + +/** An invalidated fetch is unknown to every consumer, not just absent from the cache. */ +function retiredAccountModelsResult(result: CachedAccountModels): CachedAccountModels { + const unknown: CachedAccountModels = { + credentialIdentity: result.credentialIdentity, + clientVersion: result.clientVersion, + expiresAt: 0, + models: new Set(), + confirmed: false, + }; + retiredAccountModels.add(unknown); + return unknown; +} + /** * Direct-caller entries are evicted separately from main/Pool entries. * @@ -549,7 +581,7 @@ function accountIdOfCacheKey(key: string): string { */ function boundedCacheSet(accountId: string, value: CachedAccountModels): void { const key = cacheKeyFor(accountId, value.clientVersion); - accountModelsCache.delete(key); + if (accountModelsCache.get(key) !== value) deleteCachedAccountModels(key); accountModelsCache.set(key, value); const isDirect = (candidate: string): boolean => accountIdOfCacheKey(candidate).startsWith(DIRECT_CALLER_ACCOUNT_PREFIX); @@ -558,7 +590,7 @@ function boundedCacheSet(accountId: string, value: CachedAccountModels): void { // own older entries and never reaches another account's evidence. const ownKeys = [...accountModelsCache.keys()].filter(k => accountIdOfCacheKey(k) === accountId); for (const stale of ownKeys.slice(0, Math.max(0, ownKeys.length - MODEL_ROSTER_VERSIONS_PER_ACCOUNT_MAX))) { - accountModelsCache.delete(stale); + deleteCachedAccountModels(stale); } // Then bound the class by DISTINCT ACCOUNTS. Counting keys would let one account's versions @@ -575,7 +607,7 @@ function boundedCacheSet(accountId: string, value: CachedAccountModels): void { for (const victim of accountsInOrder.slice(0, Math.max(0, accountsInOrder.length - MODEL_ROSTER_CACHE_MAX))) { if (victim === accountId) continue; for (const key of [...accountModelsCache.keys()]) { - if (accountIdOfCacheKey(key) === victim) accountModelsCache.delete(key); + if (accountIdOfCacheKey(key) === victim) deleteCachedAccountModels(key); } } }; @@ -974,8 +1006,12 @@ async function modelsForCredential( && cached.expiresAt > now ) return cached; + const fence = accountModelsFlightFences.get(credential.accountId) + ?? { invalidationGeneration: 0, pending: 0 }; + const invalidationGeneration = fence.invalidationGeneration; const flightKey = `${credential.accountId}\u0000${credential.credentialIdentity}\u0000${clientVersion}` - + (credentialMutationEpoch === undefined ? "" : `\u0000${credentialMutationEpoch}`); + + (credentialMutationEpoch === undefined ? "" : `\u0000${credentialMutationEpoch}`) + + `\u0000${invalidationGeneration}`; const existing = accountModelsFlights.get(flightKey); if (existing) return existing; @@ -1008,8 +1044,14 @@ async function modelsForCredential( confirmed: false, }; } + accountModelsFlightFences.set(credential.accountId, fence); + fence.pending += 1; const flight = fetchAccountModels(credential, fetcher, now, clientVersion) .then(result => { + if (accountModelsFlightFences.get(credential.accountId) !== fence + || fence.invalidationGeneration !== invalidationGeneration) { + return retiredAccountModelsResult(result); + } if ( currentCredentialIdentity(credential.accountId) === credential.credentialIdentity && (credentialMutationEpoch === undefined @@ -1021,6 +1063,12 @@ async function modelsForCredential( }) .finally(() => { if (accountModelsFlights.get(flightKey) === flight) accountModelsFlights.delete(flightKey); + fence.pending -= 1; + // Keep old flights in the concurrency budget until they settle. Retire their fence only + // when none remain, so a post-invalidation flight cannot reuse an earlier generation. + if (fence.pending === 0 && accountModelsFlightFences.get(credential.accountId) === fence) { + accountModelsFlightFences.delete(credential.accountId); + } }); accountModelsFlights.set(flightKey, flight); return flight; @@ -1351,7 +1399,7 @@ export async function resolveCodexModelEntitlements( // real snapshot releases it as soon as the main token settles; this boundary // release keeps the guarantee when a seam snapshot never invokes it. options.releaseNativeMainCredentialLease?.(); - const results = await Promise.all(credentials.map(async credential => ({ + const capturedResults = await Promise.all(credentials.map(async credential => ({ credential, result: await modelsForCredential( credential, @@ -1365,7 +1413,12 @@ export async function resolveCodexModelEntitlements( options.credentialMutationEpoch, ), }))); - return { + // A sibling fetch may have kept this snapshot pending after another account was invalidated. + const results = capturedResults.map(({ credential, result }) => ({ + credential, + result: retiredAccountModels.has(result) ? retiredAccountModelsResult(result) : result, + })); + const snapshot: CodexModelEntitlementSnapshot = { modelsByAccount: new Map(results.map(({ credential, result }) => [credential.accountId, result.models])), capabilitiesByAccount: new Map(results.flatMap(({ credential, result }) => ( result.confirmed && result.capabilitiesByModel @@ -1385,6 +1438,8 @@ export async function resolveCodexModelEntitlements( confirmedAccountIds: new Set(results.flatMap(({ credential, result }) => result.confirmed ? [credential.accountId] : [])), credentialIdentities: new Map(results.map(({ credential }) => [credential.accountId, credential.credentialIdentity])), }; + snapshotAccountModels.set(snapshot, capturedResults.map(({ result }) => result)); + return snapshot; } function codexModelEntitlementStateForRoster( @@ -1505,7 +1560,8 @@ export const ENTITLEMENT_PREFERRED_NATIVE_OPENAI_MODELS: ReadonlySet = n * "no account is denied" with "no evidence exists" — both mean the same thing here, which is that * selection must be left exactly as it was. * - * Only `denied` counts. `unknown` covers an unconfirmed account, a roster fetched under a client + * Roster absence counts only for the legacy preferred set; all registered ungated natives also + * read exact upstream refusals. `unknown` covers an unconfirmed account or a roster under a client * version too old to return the model, and an expired or credential-stale entry; none of those is * proof that the account lacks the model, and treating them as proof is how 2.36.0 removed * sol/terra/luna from accounts that owned them (#3022). @@ -1515,7 +1571,7 @@ export function cachedDeniedCodexAccountIdsForModel( now = Date.now(), options: { excludeAccountIds?: ReadonlySet } = {}, ): ReadonlySet | undefined { - if (!modelId || !ENTITLEMENT_PREFERRED_NATIVE_OPENAI_MODELS.has(modelId)) return undefined; + if (!modelId || !SUPPORTED_NATIVE_OPENAI_SLUGS.has(modelId) || ACCOUNT_GATED_NATIVE_OPENAI_MODELS.has(modelId)) return undefined; const denied = new Set(); const granted = new Set(); // One resolver for the whole pass: the loop below runs once per cached (account, client version) @@ -1548,7 +1604,7 @@ export function cachedDeniedCodexAccountIdsForModel( modelId, ); if (state === "granted") granted.add(accountId); - else if (state === "denied") denied.add(accountId); + else if (state === "denied" && ENTITLEMENT_PREFERRED_NATIVE_OPENAI_MODELS.has(modelId)) denied.add(accountId); } // The roster is not the only evidence, and on this path it is usually the weaker one. A cached // roster expires in five minutes and nothing on the flagship request path refetches it, so @@ -1579,11 +1635,9 @@ export function cachedDeniedCodexAccountIdsForModel( /** * Record an authenticated upstream refusal as this account's own evidence about `modelId`. * - * Scoped to {@link ENTITLEMENT_PREFERRED_NATIVE_OPENAI_MODELS} because that is the set whose - * availability varies per account while the row stays visible, and it is the set - * {@link cachedDeniedCodexAccountIdsForModel} will read back. A model outside it either has no - * per-account variance or is gated by the fail-closed roster path, where an ordering preference - * would change nothing. + * Every registered ungated native can learn this exact refusal, including configured and + * discovered models. Roster-absence ordering stays scoped to the legacy preferred set; + * newer models need an actual refusal, so a lagging roster cannot shrink their pool. * * The caller must have matched the exact allow-listed refusal body first. A status alone is not * admissible here: 400 covers every malformed request too, and remembering one of those as an @@ -1600,13 +1654,17 @@ export function recordCodexModelDenialEvidence( now = Date.now(), ): void { if (!accountId || !modelId) return; - if (!ENTITLEMENT_PREFERRED_NATIVE_OPENAI_MODELS.has(modelId)) return; + if (!SUPPORTED_NATIVE_OPENAI_SLUGS.has(modelId) || ACCOUNT_GATED_NATIVE_OPENAI_MODELS.has(modelId)) return; // A caller that cannot name a credential generation records ACCOUNT-scoped evidence rather // than none. The one production context in that position is `main-pool`, whose credential // lives in `auth.json` and has no pool generation; discarding its refusals would revert // #4906 for the stored main login (#4952). Request-owned `main` never reaches here — its // `accountId` is null and the guard above returns. - recordObservedCodexModelDenial(accountId, modelId, typeof generation === "number" ? generation : undefined, now); + if (recordObservedCodexModelDenial(accountId, modelId, typeof generation === "number" ? generation : undefined, now)) { + // A cached grant predates this accepted refusal, on both initial and alternate sends. + // Keep later roster grants authoritative without letting a stale credential erase them. + invalidateCodexModelEntitlementsForAccount(accountId); + } } /** Drop the refusal evidence for a pair the account has just served successfully. */ @@ -1653,6 +1711,7 @@ export function cachedAvailableAccountGatedNativeModels( } export function isCodexModelEntitlementSnapshotCurrent(snapshot: CodexModelEntitlementSnapshot): boolean { + if (snapshotAccountModels.get(snapshot)?.some(result => retiredAccountModels.has(result))) return false; for (const [accountId, identity] of snapshot.credentialIdentities) { // Deliberately per-id, unlike the passes above. This is a fail-closed publication gate asking // whether a snapshot is STILL current, so the freshest possible answer per account is the @@ -1666,10 +1725,12 @@ export function isCodexModelEntitlementSnapshotCurrent(snapshot: CodexModelEntit export function invalidateCodexModelEntitlementsForAccount(accountId: string | null | undefined): void { if (!accountId) return; + const fence = accountModelsFlightFences.get(accountId); + if (fence) fence.invalidationGeneration += 1; // Every version's entry for this account, since a credential change invalidates the // account's entitlement evidence regardless of which client version asked for it. for (const key of [...accountModelsCache.keys()]) { - if (accountIdOfCacheKey(key) === accountId) accountModelsCache.delete(key); + if (accountIdOfCacheKey(key) === accountId) deleteCachedAccountModels(key); } accountModelsMisses.delete(accountId); } @@ -1677,6 +1738,9 @@ export function invalidateCodexModelEntitlementsForAccount(accountId: string | n export function resetCodexModelEntitlementCacheForTests(): void { accountModelsCache.clear(); accountModelsFlights.clear(); + accountModelsFlightFences.clear(); + retiredAccountModels = new WeakSet(); + snapshotAccountModels = new WeakMap(); accountModelsMisses.clear(); negativeCredentialMemo.clear(); entitlementEnsureFlights.clear(); diff --git a/src/codex/observed-model-denials.ts b/src/codex/observed-model-denials.ts index e8a0c9ec32f..374da69cd92 100644 --- a/src/codex/observed-model-denials.ts +++ b/src/codex/observed-model-denials.ts @@ -115,25 +115,26 @@ function modelIdOfDenialKey(key: string): string { * * Re-recording refreshes the entry rather than extending an older one, so a pair that keeps * being refused stays remembered and one that stops being refused ages out. + * Returns false for superseded evidence, so its caller cannot invalidate a replacement roster. */ export function recordObservedCodexModelDenial( accountId: string, modelId: string, generation: number | undefined, now = Date.now(), -): void { +): boolean { // A refusal dispatched under generation G can arrive after G+1 has been saved. Reject it // BEFORE touching the map at all, not merely when this key already holds newer evidence: // with no entry for this key the stale row would otherwise be inserted, and at the entry // bound it would evict a valid row that nothing can restore (#4952). - if (generation !== undefined && !beginGenerationLiveCheck()(accountId, generation)) return; + if (generation !== undefined && !beginGenerationLiveCheck()(accountId, generation)) return false; const key = denialKey(accountId, modelId); const existing = observedDenials.get(key); // Second fence, for the window where the replacement credential has been dispatched but the // store read above still answers live. Both sides must name a generation to be comparable; // an account-scoped entry is not older or newer than a credential-scoped one. if (existing !== undefined && existing.generation !== undefined && generation !== undefined - && existing.generation > generation) return; + && existing.generation > generation) return false; // Delete before set so the refreshed entry moves to the back of the eviction order. observedDenials.delete(key); observedDenials.set(key, { expiresAt: now + OBSERVED_DENIAL_TTL_MS, generation }); @@ -142,6 +143,7 @@ export function recordObservedCodexModelDenial( if (oldest.done) break; observedDenials.delete(oldest.value); } + return true; } /** diff --git a/structure/catalog.md b/structure/catalog.md index 169ea69d711..f03b3d48fd4 100644 --- a/structure/catalog.md +++ b/structure/catalog.md @@ -145,7 +145,7 @@ are emitted only as selector-qualified rows whose account provenance matches. Th the bare native or API-key model list. This keeps account-scoped upstream ids such as `gpt-daybreak-blue-latest` callable without treating them as a static release allowlist. -Configured natives widen the bare list without a release: eligible bare `gpt-*` ids under `providers.openai.models` on the canonical Codex forward provider join the shared registry in place (`src/codex/catalog/native-models.ts`). Each borrows the pinned `gpt-6.2-sol` row under its generated name, takes `NATIVE_GPT6_CONTEXT` (272,000 / 872,000), and is ungated. Built-in, retired and reserve ids never register. `src/config/derived-registries.ts` filters the config and refreshes registration on load, persist and reconcile; removing a configured id unregisters it unless it is also discovered. Configured natives have no entitlement routing preference or main-drain sentinel and cannot be combo `nativeAlias` targets because schema validation precedes registration. When a configured id later gains its own pinned row, sync promotes a retained fallback that earlier releases wrote from an older Sol template (gpt-6.1-sol, gpt-6-sol): it matches the generated name and that historical description, every borrowed field equals the template, build-derived fields hold the exact values those builds wrote, and no field was added (`isUnchangedHistoricalConfiguredFallback` in `src/codex/catalog/metadata.ts`). A fallback with any user edit is kept. Covered by `tests/codex-integration/configured-native-models.test.ts` and `tests/codex-integration/gpt62-configured-fallback-promotion.test.ts`. +Configured natives widen the bare list without a release: eligible bare `gpt-*` ids under `providers.openai.models` on the canonical Codex forward provider join the shared registry in place (`src/codex/catalog/native-models.ts`). Each borrows the pinned `gpt-6.2-sol` row under its generated name, takes `NATIVE_GPT6_CONTEXT` (272,000 / 872,000), and is ungated. Built-in, retired and reserve ids never register. `src/config/derived-registries.ts` filters the config and refreshes registration on load, persist and reconcile; removing a configured id unregisters it unless it is also discovered. Configured natives have no roster-absence routing preference or main-drain sentinel and cannot be combo `nativeAlias` targets because schema validation precedes registration. When a configured id later gains its own pinned row, sync promotes a retained fallback that earlier releases wrote from an older Sol template (gpt-6.1-sol, gpt-6-sol): it matches the generated name and that historical description, every borrowed field equals the template, build-derived fields hold the exact values those builds wrote, and no field was added (`isUnchangedHistoricalConfiguredFallback` in `src/codex/catalog/metadata.ts`). A fallback with any user edit is kept. Covered by `tests/codex-integration/configured-native-models.test.ts` and `tests/codex-integration/gpt62-configured-fallback-promotion.test.ts`. Authenticated discovery also widens the set: after a successful nonempty roster fetch, `src/codex/model-entitlements.ts` passes full eligible rows to `src/codex/catalog/discovered-natives.ts`. Rows require a visible, API-supported bare `gpt-*` slug, display name and sane reasoning-level array; built-in, retired, reserve, malformed, oversized and non-scalar Unicode rows are rejected. Existing discoveries and configured natives remain eligible for refresh, so an already-supported slug does not freeze its metadata or keep borrowing a template. @@ -153,7 +153,7 @@ The store keeps version-1 `discovered-native-models.json` under the resolved Ope The entitlement roster asks under the installed client version, and upstream's rollout gate can hide a new model from it regardless of the row's `minimal_client_version` (GPT-6.1 Sol reported 0.153.0 but was served only from 0.159.0 while the installed Codex was 0.158). So each scheduler tick also runs `discoverCodexNativeRoster` in `src/codex/model-entitlements.ts`, which asks as `CODEX_ROSTER_DISCOVERY_CLIENT_VERSION` with `If-None-Match`, feeds only the discovery store, and never writes or satisfies the entitlement cache. -The import-free registry unions configured and discovered membership in place; removing either retains the other. Discoveries join the self-described set, use their own label and exact reasoning ladder, and derive context from their row with `NATIVE_GPT6_CONTEXT` for omitted values. Real metadata outranks a configured template; later built-in registration makes old discoveries inert. They are ungated under the flagship owner policy, without granting account entitlement or routing preference. Shared capability projection omits access programs and availability prompts, which remain scoped entitlement evidence. The next catalog merge replaces a discovered row with its latest metadata. Covered by `tests/codex-integration/discovered-native-models.test.ts`. +The import-free registry unions configured and discovered membership in place; removing either retains the other. Discoveries join the self-described set, use their own label and exact reasoning ladder, and derive context from their row with `NATIVE_GPT6_CONTEXT` for omitted values. Real metadata outranks a configured template; later built-in registration makes old discoveries inert. They are ungated under the flagship owner policy, without granting account entitlement or roster-absence routing preference. Exact upstream unsupported-model refusals can still order automatic routing under the [account denial policy](providers/openai-accounts.md#model-and-wire-identity). Shared capability projection omits access programs and availability prompts, which remain scoped entitlement evidence. The next catalog merge replaces a discovered row with its latest metadata. Covered by `tests/codex-integration/discovered-native-models.test.ts`. Retirement is a catalog/evidence policy, not a universal request denylist. Manually supplied model ids still follow generic routing. User-selected config and historical usage remain stored. diff --git a/structure/providers/openai-accounts.md b/structure/providers/openai-accounts.md index 32c1bb46183..360cd9dd645 100644 --- a/structure/providers/openai-accounts.md +++ b/structure/providers/openai-accounts.md @@ -71,8 +71,7 @@ Native Spark membership and its model-specific request/tool exceptions are remov `gpt-6-astra`, `gpt-6-sol`, `gpt-6-luna`, `gpt-6.1-sol`, `gpt-6.1-terra`, `gpt-6.2-sol` and `gpt-6.2-astra` (Sol and Luna added 2026-09-23 from a live roster probe; https://openai.com/index/introducing-gpt-6-sol-and-luna/; 6.1 Sol added 2026-09-30 and 6.1 Terra on 2026-10-27 from openai/codex models.json). None is gated, and all are native-main - drain sentinels. The confirmed-denial ordering below is still scoped to the first four - (`ENTITLEMENT_PREFERRED_NATIVE_OPENAI_MODELS`); the GPT-6 and GPT-6.1 rows do not feed it yet. + drain sentinels. Roster-absence ordering stays scoped to the first four (`ENTITLEMENT_PREFERRED_NATIVE_OPENAI_MODELS`); every registered ungated native also learns exact upstream unsupported-model refusals, including configured and discovered models. - The always-visible flagships (`gpt-5.6-sol`, `gpt-5.6-terra`, `gpt-5.6-luna`, `gpt-6-astra`) use the same rosters with the opposite polarity, and are never gated on them. Only a CONFIRMED @@ -89,10 +88,11 @@ Native Spark membership and its model-specific request/tool exceptions are remov therefore the second source: an exact pre-stream unsupported-model 400 from a Pool account is recorded per (account, model) in `src/codex/observed-model-denials.ts` and unioned into `cachedDeniedCodexAccountIdsForModel`. It is confirmed, authenticated evidence, never a plan - name and never remaining quota. It is bounded and retained for six hours, it is outranked by any - confirmed roster grant for the same pair, it is cleared when that account successfully serves + name and never remaining quota. An accepted refusal invalidates that account's cached rosters; rejected old-generation evidence does not. Invalidation also advances the account's pending-flight generation: earlier fetches cannot be joined or republish cached grants, but remain in the concurrency budget until they settle. Invalidated results return unconfirmed with no model or capability grants, including when a sibling fetch delays snapshot assembly. Snapshot validation rejects retired evidence after invalidation, replacement or eviction; weak references track the exact result objects without retaining account history. Flight fences retire when no fetch remains; a post-invalidation fetch can publish a later grant. Refusal evidence is bounded and retained for six hours, and a later + confirmed roster grant for the same pair outranks it, it is cleared when that account successfully serves that model, and it is discarded when the account's credential identity changes. Recording is - scoped to the always-visible flagships, so a 400 anywhere else cannot steer routing. Every + scoped to registered ungated natives, so an unrelated 400 cannot steer routing. Newer models + never infer denial from roster absence; a lagging roster leaves routing unchanged. Every consumer treats it exactly like a roster denial, so the restore-on-empty and pin-exempt rules above continue to hold and no request is refused before dispatch. Detection reads the model upstream actually named rather than rebuilding the sentence from diff --git a/tests/codex-integration/codex-account-selection-preferences.test.ts b/tests/codex-integration/codex-account-selection-preferences.test.ts index cb0ebce4da0..683fa40d91c 100644 --- a/tests/codex-integration/codex-account-selection-preferences.test.ts +++ b/tests/codex-integration/codex-account-selection-preferences.test.ts @@ -15,8 +15,10 @@ import { readCodexAccountRecord, saveCodexAccountCredential } from "../../src/co import { getEffectiveActiveCodexAccountId, rememberActiveCodexAccount } from "../../src/codex/routing/active-account"; import { cachedDeniedCodexAccountIdsForModel, + cachedAvailableAccountGatedNativeModels, recordCodexModelDenialEvidence, resetCodexModelEntitlementCacheForTests, + seedCodexModelEntitlementsForTests, } from "../../src/codex/model-entitlements"; import { clearAccountNeedsReauth, @@ -28,6 +30,11 @@ import { flushConfigDirHardeningForTests } from "../../src/config/paths"; import { setAsyncIcaclsRunnerForTests, setIcaclsRunnerForTests } from "../../src/lib/windows-secret-acl"; import type { OcxConfig } from "../../src/types"; import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { handleResponses } from "../../src/server/responses"; +import type { RequestLogContext } from "../../src/server/request-log"; +import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; +import { installHarness, restorePool401Fetch } from "../helpers/pool-401-fetch"; +import { clearResponseStateForTests } from "../../src/responses/state"; /** * Selection PREFERENCES, as distinct from selection ELIGIBILITY. @@ -136,6 +143,24 @@ describe("model entitlement ordering (#4768)", () => { beforeEach(installScratchState); afterEach(removeScratchState); + test.each(["gpt-6.1-sol", "gpt-6.2-sol", "gpt-6.2-astra"])("%s moves away from a refused account on the next request", modelId => { + const config = makeConfig(); + const now = Date.now(); + updateAccountQuota("a", 10); + updateAccountQuota("b", 20); + expect(resolveCodexAccountForThread(null, config)).toBe("a"); + recordCodexModelDenialEvidence("a", modelId, readCodexAccountRecord("a")!.generation, now); + const deniedModelAccountIds = cachedDeniedCodexAccountIdsForModel(modelId, now); + expect(deniedModelAccountIds).toEqual(new Set(["a"])); + expect(resolveCodexAccountForThreadDetailed(null, config, now, "shared", { deniedModelAccountIds }, modelId)) + .toMatchObject({ status: "selected", accountId: "b" }); + expect(config.activeCodexAccountId).toBe("a"); + // Evidence orders automatic routing; an explicit operator selection stays authoritative. + config.activeCodexAccountPinned = "a"; + expect(resolveCodexAccountForThreadDetailed(null, config, now, "shared", { deniedModelAccountIds }, modelId)) + .toMatchObject({ status: "selected", accountId: "a" }); + }); + test.each([ ["observed Astra denial selects available main", true, MAIN_CODEX_ACCOUNT_ID], ["unknown Astra access preserves the exhausted automatic cursor", false, "a"], @@ -333,6 +358,131 @@ describe("model entitlement ordering (#4768)", () => { }); }); +describe("Responses learns a native model refusal across requests", () => { + beforeEach(installScratchState); + afterEach(removeScratchState); + + function responsesConfig(): OcxConfig { + return makeConfig({ defaultProvider: "openai", providers: { openai: { + adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", + authMode: "forward", codexAccountMode: "pool", upstreamWebsocket: false, + } } }); + } + + function request(model: string, input: unknown = "fixture request"): Request { + return new Request("http://localhost/v1/responses", { method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ model, input, stream: false }), + }); + } + + test.each(["gpt-6.1-sol", "gpt-6.2-sol", "gpt-6.2-astra"])( + "%s retries another account once, then avoids the refused account without a roster fetch", async model => { + const release = acquireOwnedSpendHome(); + const harness = installHarness({ responseForSend(authorization) { + if (authorization === "Bearer access-a") return Response.json({ + detail: `The '${model}' model is not supported when using Codex with a ChatGPT account.`, + }, { status: 400 }); + } }); + try { + updateAccountQuota("a", 10); + updateAccountQuota("b", 20); + const config = responsesConfig(); + const generation = readCodexAccountRecord("a")!.generation; + let discoveryCalls = 0; + for (let turn = 0; turn < 2; turn++) { + const response = await handleResponses(request(model), config, { model: "", provider: "" } as RequestLogContext, { + resolveCodexModelEntitlements: async () => { discoveryCalls++; throw new Error("unexpected roster fetch"); }, + }); + await response.text(); + expect(response.status).toBe(200); + } + expect(harness.sends).toEqual(["Bearer access-a", "Bearer access-b", "Bearer access-b"]); + expect(harness.refreshes).toEqual([]); + expect(discoveryCalls).toBe(0); + expect(cachedDeniedCodexAccountIdsForModel(model)).toEqual(new Set(["a"])); + expect(config.activeCodexAccountId).toBe("a"); + expect(readCodexAccountRecord("a")!.generation).toBe(generation); + } finally { + release(); + restorePool401Fetch(); + clearResponseStateForTests(); + } + }, + ); + + test.each(["first", "alternate"] as const)("a stale grant cannot mask a refusal from the %s account", async refused => { + const release = acquireOwnedSpendHome(); + const model = "gpt-6.2-sol"; + const harness = installHarness({ responseForSend(authorization) { + if (refused === "alternate" && authorization === "Bearer access-a") { + return Response.json({ error: { message: "quota exhausted" } }, { status: 429 }); + } + if (authorization === (refused === "first" ? "Bearer access-a" : "Bearer access-b")) { + return Response.json({ detail: `The '${model}' model is not supported when using Codex with a ChatGPT account.` }, { status: 400 }); + } + } }); + try { + updateAccountQuota("a", 10); + updateAccountQuota("b", 20); + const id = refused === "first" ? "a" : "b"; + const record = readCodexAccountRecord(id)!; + seedCodexModelEntitlementsForTests(id, [model], Date.now(), "0.146.0", + `pool:${record.generation}:${record.credential!.chatgptAccountId}`); + const otherId = id === "a" ? "b" : "a"; + const other = readCodexAccountRecord(otherId)!; + seedCodexModelEntitlementsForTests(otherId, [model, "gpt-daybreak-blue-latest"], Date.now(), "0.146.0", + `pool:${other.generation}:${other.credential!.chatgptAccountId}`); + const config = responsesConfig(); + const response = await handleResponses(request(model), config, { model: "", provider: "" } as RequestLogContext); + await response.text(); + expect(response.status).toBe(refused === "first" ? 200 : 400); + expect(harness.sends).toEqual(["Bearer access-a", "Bearer access-b"]); + expect(cachedDeniedCodexAccountIdsForModel(model)).toEqual(new Set([id])); + expect(cachedAvailableAccountGatedNativeModels(Date.now(), new Set([otherId])).has("gpt-daybreak-blue-latest")).toBe(true); + expect(harness.refreshes).toEqual([]); + } finally { + release(); + restorePool401Fetch(); + clearResponseStateForTests(); + } + }); + + test.each(["exact-selector", "uploaded-file", "all-refused", "unrelated-400"] as const)( + "a new-model refusal preserves the %s boundary", async boundary => { + const release = acquireOwnedSpendHome(); + const model = "gpt-6.2-sol"; + const harness = installHarness({ responseForSend(authorization) { + if (authorization === "Bearer access-a" || boundary === "all-refused") return Response.json({ + detail: boundary === "unrelated-400" ? "Invalid tool schema" + : `The '${model}' model is not supported when using Codex with a ChatGPT account.`, + }, { status: 400 }); + } }); + try { + updateAccountQuota("a", 10); + updateAccountQuota("b", 20); + const config = responsesConfig(); + config.codexAccountNamespaces = { work: "a" }; + const response = await handleResponses(request( + boundary === "exact-selector" ? `work/${model}` : model, + boundary === "uploaded-file" ? [{ role: "user", content: [{ type: "input_file", file_id: "file-fixture" }] }] : undefined, + ), config, { model: "", provider: "" } as RequestLogContext); + await response.text(); + expect(response.status).toBe(400); + expect(harness.sends).toEqual(boundary === "all-refused" + ? ["Bearer access-a", "Bearer access-b"] : ["Bearer access-a"]); + expect(harness.refreshes).toEqual([]); + expect(cachedDeniedCodexAccountIdsForModel(model)).toEqual(boundary === "unrelated-400" + ? undefined : new Set(boundary === "all-refused" ? ["a", "b"] : ["a"])); + } finally { + release(); + restorePool401Fetch(); + clearResponseStateForTests(); + } + }, + ); +}); + describe("uploaded-file account retention (#4778)", () => { beforeEach(installScratchState); afterEach(removeScratchState); diff --git a/tests/codex-integration/codex-model-denial-evidence.test.ts b/tests/codex-integration/codex-model-denial-evidence.test.ts index 4dcb6f38561..6ffb0bfd0c7 100644 --- a/tests/codex-integration/codex-model-denial-evidence.test.ts +++ b/tests/codex-integration/codex-model-denial-evidence.test.ts @@ -1,11 +1,17 @@ -import { beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { cachedDeniedCodexAccountIdsForModel, + cachedAvailableAccountGatedNativeModels, clearCodexModelDenialEvidence, + codexModelEntitlementStateForAccount, + isCodexModelEntitlementSnapshotCurrent, recordCodexModelDenialEvidence, + resolveCodexModelEntitlements, resetCodexModelEntitlementCacheForTests, seedCodexModelEntitlementsForTests, + type CodexModelEntitlementCredentialSnapshot, } from "../../src/codex/model-entitlements"; +import { beginCodexAccountGenerationLiveCheck, readCodexAccountRecord, saveCodexAccountCredential } from "../../src/codex/account-store"; import { setObservedDenialGenerationCheck } from "../../src/codex/observed-model-denials"; import { codexUnsupportedModelFromDetail, @@ -13,6 +19,8 @@ import { shouldRetryCodexPoolAccountModel400, } from "../../src/server/responses/core-codex-account"; import { markResponseNonReplayable } from "../../src/lib/upstream-retry"; +import { setConfiguredNativeOpenAiModels, setDiscoveredNativeOpenAiModels } from "../../src/codex/catalog/native-models"; +import { installIsolatedCodexHome } from "../helpers/isolated-codex-home"; /** Credential generation these fixtures record under (#4952). */ const GEN = 1; @@ -38,6 +46,202 @@ function refusalResponse(modelId: string): Response { beforeEach(() => resetCodexModelEntitlementCacheForTests()); +describe("a refusal fences roster fetches that started before it", () => { + let isolated: ReturnType; + const credentials: CodexModelEntitlementCredentialSnapshot[] = []; + const config = { codexAccounts: [] }; + const now = 1_800_000_000_000; + + function roster(...models: string[]): Response { + return Response.json({ models: models.map(slug => ({ slug, supported_in_api: true, visibility: "list", + supports_reasoning_effort_updates: true, context_window: 500_000, + available_access_programs: { cyber: ["standard"] }, availability_nux: { message: "fixture grant" }, + })) }); + } + + function deferredRoster(): { promise: Promise; resolve: (response: Response) => void } { + let resolve!: (response: Response) => void; + const promise = new Promise(settle => { resolve = settle; }); + return { promise, resolve }; + } + + beforeEach(() => { + isolated = installIsolatedCodexHome("ocx-refusal-roster-flight-"); + credentials.length = 0; + for (const accountId of ["a", "b"]) { + saveCodexAccountCredential(accountId, { + accessToken: `access-${accountId}`, refreshToken: `refresh-${accountId}`, + expiresAt: now + 3600_000, chatgptAccountId: `chatgpt-${accountId}`, + }); + credentials.push({ accountId, accessToken: `access-${accountId}`, chatgptAccountId: `chatgpt-${accountId}`, + credentialIdentity: `pool:${readCodexAccountRecord(accountId)!.generation}:chatgpt-${accountId}` }); + } + setObservedDenialGenerationCheck(beginCodexAccountGenerationLiveCheck); + }); + + afterEach(() => { + resetCodexModelEntitlementCacheForTests(); + isolated.restore(); + }); + + test.each([SOL, "gpt-6.2-sol"].flatMap(model => ["old-first", "new-first"].map(order => [model, order] as const)))( + "%s does not rejoin or publish a pre-refusal grant (%s)", async (model, order) => { + const old = deferredRoster(); + const fresh = deferredRoster(); + let calls = 0; + const options = { credentials: [credentials[0]!], now, clientVersion: TEST_CLIENT_VERSION, + fetcher: (async () => ++calls === 1 ? old.promise : fresh.promise) as typeof fetch }; + const earlier = resolveCodexModelEntitlements(config, options); + let later: ReturnType | undefined; + try { + expect(calls).toBe(1); + recordCodexModelDenialEvidence("a", model, readCodexAccountRecord("a")!.generation, now); + later = resolveCodexModelEntitlements(config, options); + expect(calls).toBe(2); + if (order === "old-first") { + old.resolve(roster(model, DAYBREAK)); + const stale = await earlier; + expect(stale.confirmedAccountIds.has("a")).toBe(false); + expect(codexModelEntitlementStateForAccount(stale, "a", DAYBREAK)).toBe("unknown"); + expect(isCodexModelEntitlementSnapshotCurrent(stale)).toBe(false); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toEqual(new Set(["a"])); + expect(cachedAvailableAccountGatedNativeModels(now).has(DAYBREAK)).toBe(false); + } + fresh.resolve(roster(model)); + const current = await later; + expect(current.confirmedAccountIds.has("a")).toBe(true); + expect(isCodexModelEntitlementSnapshotCurrent(current)).toBe(true); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toBeUndefined(); + old.resolve(roster(model, DAYBREAK)); + const stale = await earlier; + expect(stale.confirmedAccountIds.has("a")).toBe(false); + expect(stale.modelsByAccount.get("a")?.size).toBe(0); + expect(stale.capabilitiesByAccount?.has("a")).toBe(false); + expect(stale.accessProgramsByAccount?.has("a")).toBe(false); + expect(stale.availabilityNuxByAccount?.has("a")).toBe(false); + expect(isCodexModelEntitlementSnapshotCurrent(stale)).toBe(false); + const cached = await resolveCodexModelEntitlements(config, options); + expect([...cached.modelsByAccount.get("a")!]).toEqual([model]); + expect(cachedAvailableAccountGatedNativeModels(now).has(DAYBREAK)).toBe(false); + expect(calls).toBe(2); + } finally { + old.resolve(roster()); + fresh.resolve(roster()); + await Promise.all([earlier, later]); + } + }, + ); + + test("a completed cached snapshot stops being current after refusal, but another account's stays current", async () => { + const model = "gpt-6.2-sol"; + const options = { now, clientVersion: TEST_CLIENT_VERSION, + fetcher: (async () => roster(model, DAYBREAK)) as typeof fetch }; + const original = await resolveCodexModelEntitlements(config, { ...options, credentials: [credentials[0]!] }); + const cached = await resolveCodexModelEntitlements(config, { ...options, credentials: [credentials[0]!] }); + const other = await resolveCodexModelEntitlements(config, { ...options, credentials: [credentials[1]!] }); + expect(isCodexModelEntitlementSnapshotCurrent(original)).toBe(true); + expect(isCodexModelEntitlementSnapshotCurrent(cached)).toBe(true); + recordCodexModelDenialEvidence("a", model, readCodexAccountRecord("a")!.generation, now); + expect(isCodexModelEntitlementSnapshotCurrent(original)).toBe(false); + expect(isCodexModelEntitlementSnapshotCurrent(cached)).toBe(false); + expect(isCodexModelEntitlementSnapshotCurrent(other)).toBe(true); + const restored = await resolveCodexModelEntitlements(config, { ...options, credentials: [credentials[0]!] }); + expect(restored.confirmedAccountIds.has("a")).toBe(true); + expect(isCodexModelEntitlementSnapshotCurrent(restored)).toBe(true); + expect(isCodexModelEntitlementSnapshotCurrent(original)).toBe(false); + }); + + test("an account invalidated while a sibling is pending cannot contribute a confirmed snapshot grant", async () => { + const model = "gpt-6.2-sol"; + const gate = deferredRoster(); + const options = { credentials, now, clientVersion: TEST_CLIENT_VERSION, + fetcher: (async (_input, init) => new Headers(init?.headers).get("chatgpt-account-id") === "chatgpt-b" + ? gate.promise : roster(model, DAYBREAK)) as typeof fetch }; + const pending = resolveCodexModelEntitlements(config, options); + try { + for (let i = 0; i < 100 && !cachedAvailableAccountGatedNativeModels(now, new Set(["a"])).has(DAYBREAK); i++) { + await new Promise(resolve => setTimeout(resolve, 0)); + } + expect(cachedAvailableAccountGatedNativeModels(now, new Set(["a"])).has(DAYBREAK)).toBe(true); + recordCodexModelDenialEvidence("a", model, readCodexAccountRecord("a")!.generation, now); + gate.resolve(roster(model, DAYBREAK)); + const snapshot = await pending; + expect(snapshot.confirmedAccountIds).toEqual(new Set(["b"])); + expect(codexModelEntitlementStateForAccount(snapshot, "a", DAYBREAK)).toBe("unknown"); + expect(codexModelEntitlementStateForAccount(snapshot, "b", DAYBREAK)).toBe("granted"); + expect(isCodexModelEntitlementSnapshotCurrent(snapshot)).toBe(false); + } finally { + gate.resolve(roster()); + await pending; + } + }); + + test("cache replacement retires an older snapshot without rejecting its replacement", async () => { + const options = { credentials: [credentials[0]!], now, clientVersion: TEST_CLIENT_VERSION, + fetcher: (async () => roster(SOL, DAYBREAK)) as typeof fetch }; + const original = await resolveCodexModelEntitlements(config, options); + const replacement = await resolveCodexModelEntitlements(config, { ...options, now: now + 5 * 60_000 + 1 }); + expect(isCodexModelEntitlementSnapshotCurrent(original)).toBe(false); + expect(isCodexModelEntitlementSnapshotCurrent(replacement)).toBe(true); + }); + + test("evicting a roster does not leave an untracked snapshot able to pass later validation", async () => { + const original = await resolveCodexModelEntitlements(config, { credentials: [credentials[0]!], now, + clientVersion: TEST_CLIENT_VERSION, fetcher: (async () => roster(SOL, DAYBREAK)) as typeof fetch }); + for (let i = 0; i < 64; i++) seedCodexModelEntitlementsForTests(`evict-${i}`, [SOL], now); + recordCodexModelDenialEvidence("a", SOL, readCodexAccountRecord("a")!.generation, now); + expect(isCodexModelEntitlementSnapshotCurrent(original)).toBe(false); + }); + + test("invalidating pending rosters preserves the four-flight account budget", async () => { + const gate = deferredRoster(); + let calls = 0; + const options = { credentials: [credentials[0]!], now, + loadPersistedRuntime: () => ({ selectedVersion: TEST_CLIENT_VERSION }), + fetcher: (async () => { calls += 1; return (await gate.promise).clone(); }) as typeof fetch }; + const pending = [TEST_CLIENT_VERSION, "0.147.0", "0.148.0", "0.149.0"].map(clientVersion => ( + resolveCodexModelEntitlements(config, { ...options, clientVersion }) + )); + try { + expect(calls).toBe(4); + recordCodexModelDenialEvidence("a", "gpt-6.2-sol", readCodexAccountRecord("a")!.generation, now); + const blocked = resolveCodexModelEntitlements(config, { ...options, clientVersion: TEST_CLIENT_VERSION }); + expect(calls).toBe(4); + gate.resolve(roster("gpt-6.2-sol")); + await Promise.all(pending); + expect((await blocked).confirmedAccountIds.size).toBe(0); + expect(cachedDeniedCodexAccountIdsForModel("gpt-6.2-sol", now)).toEqual(new Set(["a"])); + const restored = await resolveCodexModelEntitlements(config, { ...options, clientVersion: TEST_CLIENT_VERSION }); + expect(restored.confirmedAccountIds.has("a")).toBe(true); + expect(calls).toBe(5); + expect(cachedDeniedCodexAccountIdsForModel("gpt-6.2-sol", now)).toBeUndefined(); + } finally { + gate.resolve(roster()); + await Promise.all(pending); + } + }); + + test("a refusal does not invalidate another account's pending roster", async () => { + const gate = deferredRoster(); + let calls = 0; + const options = { credentials: [credentials[1]!], now, clientVersion: TEST_CLIENT_VERSION, + fetcher: (async () => { calls += 1; return gate.promise; }) as typeof fetch }; + const pending = resolveCodexModelEntitlements(config, options); + try { + recordCodexModelDenialEvidence("a", "gpt-6.2-sol", readCodexAccountRecord("a")!.generation, now); + gate.resolve(roster("gpt-6.2-sol", DAYBREAK)); + await pending; + await resolveCodexModelEntitlements(config, options); + expect(calls).toBe(1); + expect(cachedAvailableAccountGatedNativeModels(now).has(DAYBREAK)).toBe(true); + expect(cachedDeniedCodexAccountIdsForModel("gpt-6.2-sol", now)).toEqual(new Set(["a"])); + } finally { + gate.resolve(roster()); + await pending; + } + }); +}); + /** * #4906. `#4797` taught selection to order by roster denial, and the reporter still lands on a * Free account for Sol and Astra after a refresh and a catalog sync. @@ -78,6 +282,16 @@ describe("upstream refusal as per-account model denial evidence", () => { expect(cachedDeniedCodexAccountIdsForModel(ASTRA, now)).toBeUndefined(); }); + test("an accepted refusal invalidates an older roster grant, but a later grant still restores it", () => { + const now = 1_800_000_000_000; + const model = "gpt-6.2-sol"; + seedCodexModelEntitlementsForTests("free", [model], now, TEST_CLIENT_VERSION); + recordCodexModelDenialEvidence("free", model, GEN, now + 1); + expect(cachedDeniedCodexAccountIdsForModel(model, now + 1)).toEqual(new Set(["free"])); + seedCodexModelEntitlementsForTests("free", [model], now + 2, TEST_CLIENT_VERSION); + expect(cachedDeniedCodexAccountIdsForModel(model, now + 2)).toBeUndefined(); + }); + test("a success clears the refusal for that pair only", () => { const now = 1_800_000_000_000; recordCodexModelDenialEvidence("free", SOL, GEN, now); @@ -102,12 +316,45 @@ describe("upstream refusal as per-account model denial evidence", () => { expect(cachedDeniedCodexAccountIdsForModel(SOL, now + 6 * 60 * 60_000 + 1)).toBeUndefined(); }); - test("only always-visible natives are recorded, so a 400 elsewhere cannot steer routing", () => { + test.each(["gpt-5.5", "gpt-6-sol", "gpt-6-luna", "gpt-6.1-sol", "gpt-6.1-terra", "gpt-6.2-sol", "gpt-6.2-astra"])( + "%s remembers exact refusal without using roster absence as denial", model => { + const now = 1_800_000_000_000; + seedCodexModelEntitlementsForTests("free", ["gpt-6-astra"], now, TEST_CLIENT_VERSION); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toBeUndefined(); + recordCodexModelDenialEvidence("free", model, GEN, now); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toEqual(new Set(["free"])); + expect(cachedDeniedCodexAccountIdsForModel(model, now, { excludeAccountIds: new Set(["free"]) })).toBeUndefined(); + clearCodexModelDenialEvidence("free", model, GEN); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toBeUndefined(); + recordCodexModelDenialEvidence("free", model, GEN, now); + seedCodexModelEntitlementsForTests("free", [model], now, TEST_CLIENT_VERSION); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toBeUndefined(); + }, + ); + + test("configured and discovered natives learn refusals without another model-name list", () => { + const now = 1_800_000_000_000; + try { + setConfiguredNativeOpenAiModels(["gpt-future-configured"]); + setDiscoveredNativeOpenAiModels([{ slug: "gpt-future-discovered" }]); + for (const model of ["gpt-future-configured", "gpt-future-discovered"]) { + recordCodexModelDenialEvidence("free", model, GEN, now); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toEqual(new Set(["free"])); + } + } finally { + setConfiguredNativeOpenAiModels([]); + setDiscoveredNativeOpenAiModels([]); + } + expect(cachedDeniedCodexAccountIdsForModel("gpt-future-configured", now)).toBeUndefined(); + expect(cachedDeniedCodexAccountIdsForModel("gpt-future-discovered", now)).toBeUndefined(); + }); + + test("only registered ungated natives are recorded, so a 400 elsewhere cannot steer routing", () => { const now = 1_800_000_000_000; - recordCodexModelDenialEvidence("free", "gpt-5.5", GEN, now); + recordCodexModelDenialEvidence("free", "gpt-not-registered", GEN, now); recordCodexModelDenialEvidence("free", DAYBREAK, GEN, now); - expect(cachedDeniedCodexAccountIdsForModel("gpt-5.5", now)).toBeUndefined(); + expect(cachedDeniedCodexAccountIdsForModel("gpt-not-registered", now)).toBeUndefined(); // Daybreak is account-gated and fails closed through the eligibility path instead. expect(cachedDeniedCodexAccountIdsForModel(DAYBREAK, now)).toBeUndefined(); }); @@ -226,7 +473,7 @@ describe("unsupported-model refusal detection", () => { // to be relied on sits behind a condition requiring a previously cached roster, // so with no roster it never runs; these pin the store's own behaviour instead. -describe("denial evidence is scoped to the credential generation (#4952)", () => { +describe.each([SOL, "gpt-6.2-sol"])("denial evidence is scoped to the credential generation (#4952), %s", model => { beforeEach(() => { resetCodexModelEntitlementCacheForTests(); }); @@ -236,15 +483,25 @@ describe("denial evidence is scoped to the credential generation (#4952)", () => setObservedDenialGenerationCheck(() => (_id, generation) => generation === live); } + test("a late old-generation refusal cannot invalidate the replacement's cached roster", () => { + const now = Date.now(); + onlyGenerationIsLive(2); + seedCodexModelEntitlementsForTests("pooled", [model, DAYBREAK], now, TEST_CLIENT_VERSION); + expect(cachedAvailableAccountGatedNativeModels(now).has(DAYBREAK)).toBe(true); + recordCodexModelDenialEvidence("pooled", model, 1, now); + expect(cachedAvailableAccountGatedNativeModels(now).has(DAYBREAK)).toBe(true); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toBeUndefined(); + }); + test("evidence from a superseded credential stops denying the replacement", () => { const now = Date.now(); - recordCodexModelDenialEvidence("pooled", SOL, 1, now); - expect(cachedDeniedCodexAccountIdsForModel(SOL, now)).toEqual(new Set(["pooled"])); + recordCodexModelDenialEvidence("pooled", model, 1, now); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toEqual(new Set(["pooled"])); // The account reauthenticates: same id, generation 1 is no longer live. onlyGenerationIsLive(2); - expect(cachedDeniedCodexAccountIdsForModel(SOL, now)).toBeUndefined(); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toBeUndefined(); }); test("a late refusal from the old generation cannot deny the replacement", () => { @@ -252,38 +509,38 @@ describe("denial evidence is scoped to the credential generation (#4952)", () => // The replacement has already been refused and re-granted, so nothing is recorded // for generation 2 — then generation 1's in-flight 400 finally lands. onlyGenerationIsLive(2); - recordCodexModelDenialEvidence("pooled", SOL, 1, now); + recordCodexModelDenialEvidence("pooled", model, 1, now); - expect(cachedDeniedCodexAccountIdsForModel(SOL, now)).toBeUndefined(); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toBeUndefined(); }); test("a late refusal cannot overwrite newer evidence", () => { const now = Date.now(); - recordCodexModelDenialEvidence("pooled", SOL, 2, now); + recordCodexModelDenialEvidence("pooled", model, 2, now); // Generation 1's refusal arrives afterwards; it must not take the entry back a // generation, which would make it vanish the moment the reader checks liveness. - recordCodexModelDenialEvidence("pooled", SOL, 1, now); + recordCodexModelDenialEvidence("pooled", model, 1, now); onlyGenerationIsLive(2); - expect(cachedDeniedCodexAccountIdsForModel(SOL, now)).toEqual(new Set(["pooled"])); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toEqual(new Set(["pooled"])); }); test("a late success from the old generation cannot clear newer evidence", () => { const now = Date.now(); - recordCodexModelDenialEvidence("pooled", SOL, 2, now); + recordCodexModelDenialEvidence("pooled", model, 2, now); // Generation 1's 200 lands after generation 2 was refused. Clearing here would // re-admit an account that the current credential has just been refused by. - clearCodexModelDenialEvidence("pooled", SOL, 1); + clearCodexModelDenialEvidence("pooled", model, 1); onlyGenerationIsLive(2); - expect(cachedDeniedCodexAccountIdsForModel(SOL, now)).toEqual(new Set(["pooled"])); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toEqual(new Set(["pooled"])); }); test("a success from the same generation still clears, which is the ordinary case", () => { const now = Date.now(); - recordCodexModelDenialEvidence("pooled", SOL, 2, now); - clearCodexModelDenialEvidence("pooled", SOL, 2); - expect(cachedDeniedCodexAccountIdsForModel(SOL, now)).toBeUndefined(); + recordCodexModelDenialEvidence("pooled", model, 2, now); + clearCodexModelDenialEvidence("pooled", model, 2); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toBeUndefined(); }); // A `main-pool` context — the stored main login taking part in rotation — has a real account @@ -292,23 +549,23 @@ describe("denial evidence is scoped to the credential generation (#4952)", () => // the login just refused, on every request. Its evidence is account-scoped instead. test("evidence with no generation is account-scoped, not discarded", () => { const now = Date.now(); - recordCodexModelDenialEvidence("main-pool-account", SOL, undefined, now); - expect(cachedDeniedCodexAccountIdsForModel(SOL, now)).toEqual(new Set(["main-pool-account"])); + recordCodexModelDenialEvidence("main-pool-account", model, undefined, now); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toEqual(new Set(["main-pool-account"])); }); test("account-scoped evidence is not expired by a pool generation rolling over", () => { const now = Date.now(); - recordCodexModelDenialEvidence("main-pool-account", SOL, undefined, now); + recordCodexModelDenialEvidence("main-pool-account", model, undefined, now); // No generation was ever claimed, so there is nothing for the liveness fence to supersede. onlyGenerationIsLive(7); - expect(cachedDeniedCodexAccountIdsForModel(SOL, now)).toEqual(new Set(["main-pool-account"])); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toEqual(new Set(["main-pool-account"])); }); test("an account-scoped success clears account-scoped evidence", () => { const now = Date.now(); - recordCodexModelDenialEvidence("main-pool-account", SOL, undefined, now); - clearCodexModelDenialEvidence("main-pool-account", SOL, undefined); - expect(cachedDeniedCodexAccountIdsForModel(SOL, now)).toBeUndefined(); + recordCodexModelDenialEvidence("main-pool-account", model, undefined, now); + clearCodexModelDenialEvidence("main-pool-account", model, undefined); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toBeUndefined(); }); // The write fence has to reject a stale refusal BEFORE it mutates the map, not only when the @@ -317,16 +574,16 @@ describe("denial evidence is scoped to the credential generation (#4952)", () => // read fence can restore, because the evidence is simply gone. test("a stale refusal for an unseen key cannot evict valid evidence at the entry bound", () => { const now = Date.now(); - recordCodexModelDenialEvidence("first-pooled", SOL, 2, now); - for (let i = 0; i < 511; i++) recordCodexModelDenialEvidence(`filler-${i}`, SOL, 2, now); - expect(cachedDeniedCodexAccountIdsForModel(SOL, now)?.has("first-pooled")).toBe(true); + recordCodexModelDenialEvidence("first-pooled", model, 2, now); + for (let i = 0; i < 511; i++) recordCodexModelDenialEvidence(`filler-${i}`, model, 2, now); + expect(cachedDeniedCodexAccountIdsForModel(model, now)?.has("first-pooled")).toBe(true); // Generation 1 is dead and this account has no entry of its own. The insert would take the // map to 513 and evict the oldest row, which is the valid one recorded first. onlyGenerationIsLive(2); - recordCodexModelDenialEvidence("late-stale", SOL, 1, now); + recordCodexModelDenialEvidence("late-stale", model, 1, now); - const denied = cachedDeniedCodexAccountIdsForModel(SOL, now); + const denied = cachedDeniedCodexAccountIdsForModel(model, now); expect(denied?.has("first-pooled")).toBe(true); expect(denied?.has("late-stale")).toBe(false); }); @@ -336,14 +593,14 @@ describe("denial evidence is scoped to the credential generation (#4952)", () => // store read on its behalf, and must stay unknown rather than denied. test("an excluded account is skipped before the liveness check reads anything", () => { const now = Date.now(); - recordCodexModelDenialEvidence("excluded", SOL, 1, now); + recordCodexModelDenialEvidence("excluded", model, 1, now); let lookups = 0; setObservedDenialGenerationCheck(() => { lookups += 1; return () => true; }); - expect(cachedDeniedCodexAccountIdsForModel(SOL, now, { + expect(cachedDeniedCodexAccountIdsForModel(model, now, { excludeAccountIds: new Set(["excluded"]), })).toBeUndefined(); expect(lookups).toBe(0); @@ -351,16 +608,16 @@ describe("denial evidence is scoped to the credential generation (#4952)", () => test("the credential store is opened at most once per lookup", () => { const now = Date.now(); - recordCodexModelDenialEvidence("pool-a", SOL, 1, now); - recordCodexModelDenialEvidence("pool-b", SOL, 1, now); - recordCodexModelDenialEvidence("pool-c", SOL, 1, now); + recordCodexModelDenialEvidence("pool-a", model, 1, now); + recordCodexModelDenialEvidence("pool-b", model, 1, now); + recordCodexModelDenialEvidence("pool-c", model, 1, now); let opens = 0; setObservedDenialGenerationCheck(() => { opens += 1; return () => true; }); - expect(cachedDeniedCodexAccountIdsForModel(SOL, now)).toEqual(new Set(["pool-a", "pool-b", "pool-c"])); + expect(cachedDeniedCodexAccountIdsForModel(model, now)).toEqual(new Set(["pool-a", "pool-b", "pool-c"])); expect(opens).toBe(1); }); }); From 9e714a6087f7bd4a3fd69b5a2e7156f74d0085df Mon Sep 17 00:00:00 2001 From: Gaurav Dubey Date: Wed, 25 Nov 2026 10:21:53 +0530 Subject: [PATCH 24/60] fix(opencode): write the loopback placeholder key for the keyless listener (#9071) * fix(opencode): write the loopback placeholder key for the keyless listener OpenCode refuses an empty apiKey before it sends a request. When the managed integration pointed OpenCode at the Home's unauthenticated loopback listener, the generator still wrote {env:OPENCODEX_OPENCODE_API_KEY}, so with the variable unset (as the guide allows for that listener) every request failed with "Missing auth credential: apiKey" even though the listener reads no key. exportContextOf is the only caller that selects the listener URL, so it now marks the context keylessInference and opencodeProviderBlocks writes the non-secret opencodex-loopback placeholder in both provider generations. The dedicated auth-header branch is unchanged. Nothing is inferred from a loopback URL: an SSH forward can be loopback and still authenticated, so ocx export, the launcher, and a loopback bind without the listener keep the reference. Existing managed blocks classify as stale and refresh to the placeholder. Closes #9069 Co-Authored-By: Claude * fix(opencode): give the dashboard client config the same keyless key /api/client-config resolves its base URL through the serving config, so with the unauthenticated loopback listener enabled it already dials that listener, and it still wrote the env reference. Mark that context keylessInference as well, so the dashboard's OpenCode config matches what the managed integration writes. The CLI-built ocx export --client opencode does not select the listener and keeps the reference. Refs #9069 Co-Authored-By: Claude * docs(opencode): separate loopback admission from OpenCode's key check The guide said the {env:...} reference can stay unset on a loopback listener, then that OpenCode refuses an unset key. Both were about different checks. State that a loopback bind checks no admission key but OpenCode still needs a nonempty apiKey, that the managed integration and the dashboard config write the placeholder for the keyless listener, and what to export on the other paths. The Spanish guide carried the same claim and gets the same correction. Refs #9069 Co-Authored-By: Claude * docs(opencode): stop telling translated readers the loopback key can stay unset OpenCode refuses an unset apiKey reference before it sends the request, so the fr, ja, ko, ru, tr, zh-cn and zh-tw guides now match the corrected English text: the managed integration writes the opencodex-loopback placeholder, and other paths need any nonempty value on loopback. * docs(opencode): explain the loopback placeholder in the zh-tw guide The Traditional Chinese guide had no paragraph on the keyless listener, so add the managed-integration placeholder and the ocx export distinction. * docs(opencode): keep the any-value hint to keyless loopback binds The translated guides said any nonempty value works "on loopback" and dropped the English caveat that a loopback URL alone does not prove no key is checked. Restore that caveat in fr, ja, ko, ru, tr and zh-cn, and name the SSH-forward case in every locale: a forward to an authenticated listener looks like loopback and still needs the real admission key. Co-Authored-By: Claude Opus 5.5 * docs(opencode): require the key export only where the destination checks it A 0.0.0.0 bind with the unauthenticated loopback listener enabled gets the loopback placeholder from the managed integration, so the hostname rule alone contradicted the preceding paragraph. Applied to the translations too. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Co-authored-by: JUN --- .../src/content/docs/es/guides/opencode.md | 4 +- .../src/content/docs/fr/guides/opencode.md | 15 +++- docs-site/src/content/docs/guides/opencode.md | 19 +++-- .../src/content/docs/ja/guides/opencode.md | 4 +- .../src/content/docs/ko/guides/opencode.md | 17 ++-- .../src/content/docs/ru/guides/opencode.md | 17 ++-- .../src/content/docs/tr/guides/opencode.md | 19 +++-- .../src/content/docs/zh-cn/guides/opencode.md | 4 +- .../src/content/docs/zh-tw/guides/opencode.md | 4 +- src/clients/config-export.ts | 16 +++- src/clients/config-export/contracts.ts | 7 ++ src/integrations/state.ts | 5 +- src/server/management/model-routes.ts | 2 + structure/clients/integrations.md | 2 +- tests/clients/integrations-writer.test.ts | 85 ++++++++++++++++++- .../server/management-inference-port.test.ts | 17 ++++ 16 files changed, 197 insertions(+), 40 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/opencode.md b/docs-site/src/content/docs/es/guides/opencode.md index d2bdc87ee39..f871c0f940a 100644 --- a/docs-site/src/content/docs/es/guides/opencode.md +++ b/docs-site/src/content/docs/es/guides/opencode.md @@ -121,7 +121,7 @@ ocx export --client opencode --out ~/opencodex-opencode.json El bloque añadido manualmente es una instantánea estática: no sigue los cambios del catálogo como el bloque del lanzador. Vuelve a ejecutar `ocx export` después de añadir un proveedor o cambiar la visibilidad o los metadatos de un modelo. También puedes [activar la integración administrada](/es/guides/integrations/): `ocx sync` actualiza los bloques que ya administra, conservando los editados o eliminados manualmente. -Después de combinar los bloques, exporta la clave de acceso antes de abrir OpenCode si el listener de inferencia exige autenticación. Un listener vinculado únicamente a loopback no la requiere: +Después de combinar los bloques, exporta la clave de acceso antes de abrir OpenCode. Un listener vinculado únicamente a loopback no la comprueba, pero OpenCode rechaza una clave sin establecer, así que allí sirve cualquier valor no vacío: ```bash export OPENCODEX_OPENCODE_API_KEY= @@ -157,7 +157,7 @@ Este ejemplo se configura manualmente en el cliente remoto. Prepara primero un f El valor real solo se transmite mediante el entorno del proceso hijo. `OPENCODEX_API_AUTH_TOKEN` tiene prioridad, seguido del archivo protegido de token del servicio y de una clave API configurada. Un listener vinculado fuera de loopback exige una credencial aceptada. -Un listener vinculado a loopback (`127.0.0.1`, el valor predeterminado) no exige una clave del plano de datos, aunque haya claves de cliente configuradas. Para ese listener puedes dejar sin establecer la variable de la referencia `{env:…}`. La URL local por sí sola no basta: un listener público vinculado a `0.0.0.0` sigue exigiendo una clave aceptada aunque se acceda por `127.0.0.1`. Exporta la clave cuando `hostname` esté configurado fuera de loopback; consulta [Acceso remoto](/es/reference/configuration/server/#remote-access). Esta clave pertenece a opencodex y es distinta de las claves de los [proveedores de origen](/es/guides/providers/). +Un listener vinculado a loopback (`127.0.0.1`, el valor predeterminado) no exige una clave del plano de datos, aunque haya claves de cliente configuradas. Aun así, OpenCode necesita un `apiKey` no vacío: rechaza una referencia `{env:…}` sin establecer con `Missing auth credential: apiKey` antes de enviar la solicitud. Cuando la [integración gestionada](/es/guides/integrations/) o la configuración de cliente del panel apuntan al [listener de loopback sin autenticación](/es/reference/configuration/server/), escriben como `apiKey` el marcador no secreto `opencodex-loopback`, así que no hace falta exportar nada. Las demás rutas, incluidas `ocx export` y un enlace a loopback sin ese listener, conservan la referencia: exporta `OPENCODEX_OPENCODE_API_KEY` con la clave de acceso donde se exija, o con cualquier valor no vacío en un enlace a loopback, que no la comprueba. La URL local por sí sola no basta para saber que no se comprueba ninguna clave: un listener público vinculado a `0.0.0.0` sigue exigiendo una clave aceptada aunque se acceda por `127.0.0.1`, y lo mismo ocurre con un listener autenticado al que se llega mediante un reenvío SSH. Exporta la clave siempre que el destino la compruebe, por ejemplo cuando `hostname` esté configurado fuera de loopback y el cliente no apunte al listener de loopback sin autenticación; consulta [Acceso remoto](/es/reference/configuration/server/#remote-access). Esta clave pertenece a opencodex y es distinta de las claves de los [proveedores de origen](/es/guides/providers/). diff --git a/docs-site/src/content/docs/fr/guides/opencode.md b/docs-site/src/content/docs/fr/guides/opencode.md index 6990b6880af..ee5a1dca96f 100644 --- a/docs-site/src/content/docs/fr/guides/opencode.md +++ b/docs-site/src/content/docs/fr/guides/opencode.md @@ -77,8 +77,8 @@ ocx export --client opencode --out ~/opencodex-opencode.json Contrairement au bloc d'exécution du lanceur, un bloc fusionné est un instantané statique : il ne suit pas votre catalogue. Réexécutez `ocx export` après avoir ajouté un fournisseur ou modifié la visibilité du modèle. -Une fois fusionné, exportez la clé d'admission avant de lancer l'opencode — sauf si le proxy est en bouclage, -là où aucun n'est nécessaire : +Une fois fusionné, exportez la clé d'admission avant de lancer opencode. Une liaison limitée au bouclage ne la +vérifie pas, mais OpenCode refuse une clé non définie ; toute valeur non vide convient alors : ```bash export OPENCODEX_OPENCODE_API_KEY= @@ -117,8 +117,15 @@ La valeur réelle est transmise uniquement via l'environnement du processus enfa `OPENCODEX_API_AUTH_TOKEN` est prioritaire, puis le fichier de jeton de service renforcé, puis une clé API configurée — ce qui est ce qu'exige une liaison sans bouclage. -Une liaison de bouclage (`127.0.0.1`, la valeur par défaut) n'authentifie rien, donc la référence `{env:…}` est -inerte et vous pouvez laisser la variable non définie. Cela n'a d'importance que lorsque `hostname` est défini au-delà du bouclage ; +Une liaison de bouclage (`127.0.0.1`, la valeur par défaut) n'exige pas de clé du plan de données. OpenCode exige +toutefois un `apiKey` non vide : il refuse une référence `{env:…}` non définie avec `Missing auth credential: apiKey` +avant d'envoyer la requête. Lorsque l'intégration gérée ou la configuration client du tableau de bord cible l'écouteur +de bouclage sans authentification, elle écrit l'espace réservé non secret `opencodex-loopback` comme `apiKey` ; il n'y a +rien à exporter. Les autres chemins, dont `ocx export`, conservent la référence : exportez `OPENCODEX_OPENCODE_API_KEY` +avec la clé d'admission là où elle est exigée, ou avec n'importe quelle valeur non vide sur une liaison de bouclage, qui ne la vérifie pas. Une URL de +bouclage ne suffit pas à établir qu'aucune clé n'est vérifiée : un écouteur public lié à `0.0.0.0` exige toujours une +clé acceptée lorsqu'on l'atteint via `127.0.0.1`, tout comme un écouteur authentifié atteint par une redirection SSH. Exportez la clé dès que la destination la vérifie, par exemple lorsque `hostname` est défini au-delà du bouclage +et que le client ne cible pas l'écouteur de bouclage sans authentification ; voir [Accès à distance](/fr/reference/configuration/server/#accès-à-distance). Cette clé d'admission est celle de opencodex propre et n'est pas lié aux clés du fournisseur en amont configurées sous [Prestataires](/fr/guides/providers/). diff --git a/docs-site/src/content/docs/guides/opencode.md b/docs-site/src/content/docs/guides/opencode.md index 63ecb1baf08..cee6b169344 100644 --- a/docs-site/src/content/docs/guides/opencode.md +++ b/docs-site/src/content/docs/guides/opencode.md @@ -150,8 +150,8 @@ catalog. Re-run `ocx export` after you add a provider or change model visibility Alternatively, [enable the managed integration](/guides/integrations/): `ocx sync` safely refreshes its already-owned blocks, leaving hand-edited or removed blocks untouched. -Once merged, export the admission key before launching opencode if the inference listener requires -authentication. A listener bound only to loopback does not require it: +Once merged, export the admission key before launching opencode. A listener bound only to loopback +does not check it, but OpenCode still refuses an unset key, so any nonempty value works there: ```bash export OPENCODEX_OPENCODE_API_KEY= @@ -191,10 +191,17 @@ The real value is passed only through the child process environment. a configured API key — which is what a non-loopback bind requires. A listener bound to loopback (`127.0.0.1`, the default) does not require a data-plane key, even -when client API keys are configured, so the `{env:…}` reference can remain unset for that listener. -A loopback URL alone does not establish this: a public listener bound to `0.0.0.0` still requires -an accepted key when reached through `127.0.0.1`. Export the key when `hostname` is set beyond loopback; -see [Remote access](/reference/configuration/server/#remote-access). This admission key is opencodex's +when client API keys are configured. OpenCode itself still needs a nonempty `apiKey`: it refuses an +unset `{env:…}` reference with `Missing auth credential: apiKey` before sending the request. When the +[managed integration](/guides/integrations/) or the dashboard's client config targets the +[unauthenticated loopback listener](/reference/configuration/server/), it writes the non-secret +`opencodex-loopback` placeholder as `apiKey`, so nothing has to be exported. Other paths, including +`ocx export` and a loopback bind without that listener, keep the reference, so export +`OPENCODEX_OPENCODE_API_KEY` for them: the admission key where one is required, or any nonempty +value on a loopback bind, which does not check it. A loopback URL alone does not establish that no +key is checked: a public listener bound to `0.0.0.0` still requires an accepted key when reached +through `127.0.0.1`, and so does an authenticated listener reached through an SSH forward. Export the key whenever the destination checks it, for example when `hostname` is set beyond +loopback and the client does not target the unauthenticated loopback listener; see [Remote access](/reference/configuration/server/#remote-access). This admission key is opencodex's own, and is unrelated to the upstream provider keys configured under [Providers](/guides/providers/). diff --git a/docs-site/src/content/docs/ja/guides/opencode.md b/docs-site/src/content/docs/ja/guides/opencode.md index 9f3d49c1c98..64c647dcbe8 100644 --- a/docs-site/src/content/docs/ja/guides/opencode.md +++ b/docs-site/src/content/docs/ja/guides/opencode.md @@ -54,7 +54,7 @@ ocx export --client opencode --out ~/opencodex-opencode.json ランチャーのランタイム ブロックとは異なり、マージされたブロックは静的なスナップショットであり、カタログに従いません。プロバイダーを追加するか、モデルの可視性を変更した後、`ocx export` を再実行します。 -マージしたら、オープンコードを起動する前にアドミッション キーをエクスポートします。プロキシがループバック上にある場合を除き、何も必要ありません。 +マージしたら、opencode を起動する前にアドミッション キーをエクスポートします。ループバックのみにバインドされたリスナーはキーを検証しませんが、OpenCode は未設定のキーを拒否するため、その場合は空でない任意の値で構いません。 ```bash export OPENCODEX_OPENCODE_API_KEY= @@ -88,7 +88,7 @@ export OPENCODEX_OPENCODE_API_KEY= 実際の値は、子プロセス環境を介してのみ渡されます。 `OPENCODEX_API_AUTH_TOKEN` が優先され、次に強化されたサービス トークン ファイル、次に設定された API キーが優先されます。これは、非ループバック バインドに必要なものです。 -ループバック バインド (`127.0.0.1`、デフォルト) は何も認証しないため、`{env:…}` 参照は不活性であり、変数を設定しないままにすることができます。 `hostname` がループバックを超えて設定されている場合にのみ問題になります。 [リモートアクセス](/ja/reference/configuration/server/#リモートアクセス)を参照してください。このアドミッション キーは opencodex 独自のものであり、[プロバイダー](/guides/providers/) で構成されたアップストリーム プロバイダー キーとは無関係です。 +ループバック バインド (`127.0.0.1`、デフォルト) はデータ プレーン キーを要求しません。ただし OpenCode 自体は空でない `apiKey` を必要とし、未設定の `{env:…}` 参照をリクエスト送信前に `Missing auth credential: apiKey` で拒否します。管理統合またはダッシュボードのクライアント設定が認証なしのループバック リスナーを対象とする場合は、秘密ではないプレースホルダー `opencodex-loopback` を `apiKey` に書き込むため、エクスポートは不要です。`ocx export` などその他の経路は参照を保持するため、必要な場所ではアドミッション キーを、キーを検査しないループバック バインドでは空でない任意の値を `OPENCODEX_OPENCODE_API_KEY` にエクスポートしてください。ループバック URL だけではキーが検査されないとは言えません。`0.0.0.0` にバインドされた公開リスナーは `127.0.0.1` 経由でも受理されるキーを要求し、SSH フォワード経由で到達する認証付きリスナーも同様です。接続先がキーを検査する場合は必ずキーをエクスポートしてください。たとえば `hostname` がループバックを超えて設定され、クライアントが認証なしのループバック リスナーを対象としていない場合です。 [リモートアクセス](/ja/reference/configuration/server/#リモートアクセス)を参照してください。このアドミッション キーは opencodex 独自のものであり、[プロバイダー](/guides/providers/) で構成されたアップストリーム プロバイダー キーとは無関係です。 ## 元に戻す diff --git a/docs-site/src/content/docs/ko/guides/opencode.md b/docs-site/src/content/docs/ko/guides/opencode.md index 4c9b5f2168a..2be33661fb6 100644 --- a/docs-site/src/content/docs/ko/guides/opencode.md +++ b/docs-site/src/content/docs/ko/guides/opencode.md @@ -82,8 +82,8 @@ ocx export --client opencode --out ~/opencodex-opencode.json 않습니다. provider를 추가하거나 모델 노출을 바꾼 뒤에는 `ocx export`를 다시 실행하세요. -병합한 뒤에는 opencode를 실행하기 전에 인증 키를 export하세요. 단, 프록시가 -loopback에 바인딩되어 있으면 필요하지 않습니다: +병합한 뒤에는 opencode를 실행하기 전에 인증 키를 export하세요. loopback에만 바인딩된 +리스너는 키를 검사하지 않지만 OpenCode가 설정되지 않은 키를 거부하므로, 그때는 비어 있지 않은 아무 값이면 됩니다: ```bash export OPENCODEX_OPENCODE_API_KEY= @@ -123,9 +123,16 @@ export OPENCODEX_OPENCODE_API_KEY= 그다음에 구성된 API 키가 옵니다. 루프백이 아닌 바인드에는 바로 이 API 키가 필요합니다. -루프백 바인드(`127.0.0.1`, 기본값)는 아무 인증도 하지 않으므로 `{env:…}` 참조는 -아무 효과가 없고, 변수를 비워 둬도 됩니다. 이것이 중요해지는 것은 `hostname`이 -루프백을 벗어날 때뿐입니다. [원격 접속](/ko/reference/configuration/server/#remote-access)을 +루프백 바인드(`127.0.0.1`, 기본값)는 데이터 플레인 키를 요구하지 않습니다. 하지만 +OpenCode는 비어 있지 않은 `apiKey`가 필요해, 설정되지 않은 `{env:…}` 참조를 요청 전에 +`Missing auth credential: apiKey`로 거부합니다. 관리형 통합이나 대시보드 클라이언트 설정이 인증 없는 +loopback 리스너를 대상으로 하면 비밀이 아닌 자리표시자 `opencodex-loopback`을 `apiKey`로 기록하므로 +따로 export할 필요가 없습니다. `ocx export` 등 다른 경로는 참조를 유지하므로, 키가 필요한 곳에서는 +인증 키를, 키를 검사하지 않는 loopback 바인드에서는 비어 있지 않은 아무 값을 `OPENCODEX_OPENCODE_API_KEY`로 +export하세요. loopback URL만으로는 키를 검사하지 않는다고 단정할 수 없습니다. `0.0.0.0`에 바인드된 공개 리스너는 +`127.0.0.1`로 접근해도 허용된 키를 요구하며, SSH 포워드로 접근하는 인증 리스너도 마찬가지입니다. +대상이 키를 검사하면 인증 키를 export하세요. 예를 들어 `hostname`이 루프백을 벗어나고 클라이언트가 인증 없는 +loopback 리스너를 대상으로 하지 않는 경우입니다. [원격 접속](/ko/reference/configuration/server/#remote-access)을 보세요. 이 인증 키는 opencodex 전용이며, [공급자](/guides/providers/) 아래에 설정한 upstream provider 키와는 무관합니다. diff --git a/docs-site/src/content/docs/ru/guides/opencode.md b/docs-site/src/content/docs/ru/guides/opencode.md index 77ebba83440..cc62cbe1080 100644 --- a/docs-site/src/content/docs/ru/guides/opencode.md +++ b/docs-site/src/content/docs/ru/guides/opencode.md @@ -80,8 +80,8 @@ ocx export --client opencode --out ~/opencodex-opencode.json каталогом. После добавления провайдера или изменения видимости моделей заново выполните `ocx export`. -После merge экспортируйте admission key перед запуском opencode — если только прокси не работает -на loopback, где ключ не нужен: +После merge экспортируйте admission key перед запуском opencode. Привязка только к loopback ключ +не проверяет, но OpenCode отклоняет незаданный ключ, поэтому там подойдёт любое непустое значение: ```bash export OPENCODEX_OPENCODE_API_KEY= @@ -120,9 +120,16 @@ upstream-заголовка `Authorization`. `OPENCODEX_API_AUTH_TOKEN` имеет приоритет, затем идёт hardened service token file, затем настроенный API key — именно он требуется для не-loopback-привязки. -Loopback-привязка (`127.0.0.1`, по умолчанию) не требует аутентификации, поэтому ссылка `{env:…}` -остаётся инертной, и переменную можно не задавать. Она важна только когда `hostname` выходит за -пределы loopback; см. [Удалённый доступ](/ru/reference/configuration/server/#удалённый-доступ). Этот admission key +Loopback-привязка (`127.0.0.1`, по умолчанию) не требует ключа плоскости данных. Но самому OpenCode +нужен непустой `apiKey`: незаданную ссылку `{env:…}` он отклоняет с `Missing auth credential: apiKey` +ещё до отправки запроса. Когда управляемая интеграция или клиентская конфигурация панели нацелены на +loopback-слушатель без аутентификации, они записывают в `apiKey` несекретную заглушку `opencodex-loopback`, +и экспортировать ничего не нужно. Другие пути, включая `ocx export`, сохраняют ссылку: экспортируйте +`OPENCODEX_OPENCODE_API_KEY` с admission key там, где он требуется, или с любым непустым значением на +loopback-привязке, которая его не проверяет. Одного loopback URL недостаточно, чтобы считать, что ключ не +проверяется: публичный слушатель, привязанный к `0.0.0.0`, требует принятый ключ и при обращении через +`127.0.0.1`, как и аутентифицированный слушатель, доступный через SSH-проброс. Экспортируйте ключ, когда его проверяет целевой слушатель, например когда `hostname` выходит за +пределы loopback, а клиент не нацелен на loopback-слушатель без аутентификации; см. [Удалённый доступ](/ru/reference/configuration/server/#удалённый-доступ). Этот admission key относится к самому opencodex и не связан с upstream-ключами провайдеров, настраиваемыми в [Провайдерах](/guides/providers/). diff --git a/docs-site/src/content/docs/tr/guides/opencode.md b/docs-site/src/content/docs/tr/guides/opencode.md index aa66dca9f62..dc76f48d24c 100644 --- a/docs-site/src/content/docs/tr/guides/opencode.md +++ b/docs-site/src/content/docs/tr/guides/opencode.md @@ -87,8 +87,8 @@ anlık görüntüdür: kataloğunuzu takip etmez. Bir sağlayıcı ekledikten ve görünürlüğünü değiştirdikten sonra `ocx export`'u yeniden çalıştırın. Birleştirildikten sonra opencode'u başlatmadan önce kabul anahtarını dışa -aktarın — proxy'nin geri döngüde olduğu durumlar hariç (orada hiçbir anahtar -gerekmez): +aktarın. Yalnızca geri döngüye bağlı bir dinleyici anahtarı denetlemez, ancak OpenCode +ayarlanmamış bir anahtarı reddeder; orada boş olmayan herhangi bir değer yeterlidir: ```bash export OPENCODEX_OPENCODE_API_KEY= @@ -130,10 +130,17 @@ Gerçek değer yalnızca alt süreç ortamı üzerinden iletilir. belirteci dosyası, ardından yapılandırılmış bir API anahtarı gelir — geri döngü olmayan bir bağlantının gerektirdiği budur. -Bir geri döngü bağlantısı (`127.0.0.1`, varsayılan) hiçbir şeyi doğrulamaz, bu -nedenle `{env:…}` referansı etkisizdir ve değişkeni ayarlanmamış -bırakabilirsiniz. Yalnızca `hostname` geri döngünün ötesine ayarlandığında -önemlidir; bkz. [Uzaktan erişim](/tr/reference/configuration/server/#uzaktan-erişim). Bu +Bir geri döngü bağlantısı (`127.0.0.1`, varsayılan) veri düzlemi anahtarı istemez. +Ancak OpenCode boş olmayan bir `apiKey` gerektirir ve ayarlanmamış bir `{env:…}` referansını +istek gönderilmeden `Missing auth credential: apiKey` ile reddeder. Yönetilen entegrasyon veya +panodaki istemci yapılandırması kimlik doğrulamasız geri döngü dinleyicisini hedeflediğinde `apiKey` +olarak gizli olmayan `opencodex-loopback` yer tutucusunu yazar; dışa aktarılacak bir şey kalmaz. +`ocx export` dahil diğer yollar referansı korur: gerektiği yerde kabul anahtarını, anahtarı denetlemeyen bir geri döngü bağlantısında ise boş +olmayan herhangi bir değeri `OPENCODEX_OPENCODE_API_KEY` olarak dışa aktarın. Yalnızca bir geri döngü URL'si, +hiçbir anahtarın denetlenmediğini göstermez: `0.0.0.0` adresine bağlı genel bir dinleyici `127.0.0.1` üzerinden +erişildiğinde de kabul edilen bir anahtar ister; SSH yönlendirmesiyle erişilen kimlik doğrulamalı bir dinleyici de +öyledir. Hedef anahtarı denetlediğinde anahtarı dışa aktarın; örneğin `hostname` geri +döngünün ötesine ayarlandığında ve istemci kimlik doğrulamasız geri döngü dinleyicisini hedeflemediğinde; bkz. [Uzaktan erişim](/tr/reference/configuration/server/#uzaktan-erişim). Bu kabul anahtarı opencodex'in kendisine aittir ve [Sağlayıcılar](/tr/guides/providers/) altında yapılandırılan yukarı akış sağlayıcı anahtarlarıyla ilgisizdir. diff --git a/docs-site/src/content/docs/zh-cn/guides/opencode.md b/docs-site/src/content/docs/zh-cn/guides/opencode.md index 6fc3feb6931..e3ffcffd062 100644 --- a/docs-site/src/content/docs/zh-cn/guides/opencode.md +++ b/docs-site/src/content/docs/zh-cn/guides/opencode.md @@ -54,7 +54,7 @@ ocx export --client opencode --out ~/opencodex-opencode.json 与启动器的运行时 block 不同,合并后的 block 是一个静态快照:它不会跟随你的目录变化。每当你新增 provider 或调整 model 可见性后,都要重新运行 `ocx export`。 -合并完成后,在启动 opencode 之前导出 admission key - 除非代理绑定在 loopback 上,那种情况下不需要: +合并完成后,在启动 opencode 之前导出 admission key。仅绑定 loopback 的监听器不会校验它,但 OpenCode 会拒绝未设置的 key,因此在那里任意非空值即可: ```bash export OPENCODEX_OPENCODE_API_KEY= @@ -88,7 +88,7 @@ loopback 示例: 真实值只会通过子进程环境传递。`OPENCODEX_API_AUTH_TOKEN` 优先,然后是加固后的服务 token 文件,最后才是配置的 API key - 而非 loopback 绑定正是需要这个 API key。 -loopback 绑定(`127.0.0.1`,默认值)不会进行任何认证,所以 `{env:…}` 引用是惰性的,你可以不设置该变量。它只在 `hostname` 超出 loopback 范围时才有意义;参见 [Remote access](/zh-cn/reference/configuration/server/#远程访问)。这个 admission key 是 opencodex 自己的,与在 [Providers](/guides/providers/) 下配置的上游 provider keys 无关。 +loopback 绑定(`127.0.0.1`,默认值)不要求数据面 key。但 OpenCode 本身需要非空的 `apiKey`:未设置的 `{env:…}` 引用会在发送请求前以 `Missing auth credential: apiKey` 被拒绝。当托管集成或仪表盘的客户端配置指向无认证的 loopback 监听器时,会把非机密占位符 `opencodex-loopback` 写为 `apiKey`,无需导出任何内容。包括 `ocx export` 在内的其他路径保留该引用:在需要的地方导出 admission key,在不检查 key 的 loopback 绑定上把任意非空值导出为 `OPENCODEX_OPENCODE_API_KEY`。仅凭 loopback URL 无法确定不会检查 key:绑定在 `0.0.0.0` 的公开监听器即使经由 `127.0.0.1` 访问,仍然要求可接受的 key;经由 SSH 转发访问的已认证监听器也是如此。只要目标会检查 key 就必须导出,例如 `hostname` 超出 loopback 范围且客户端未指向无认证的 loopback 监听器时;参见 [Remote access](/zh-cn/reference/configuration/server/#远程访问)。这个 admission key 是 opencodex 自己的,与在 [Providers](/guides/providers/) 下配置的上游 provider keys 无关。 ## 回滚 diff --git a/docs-site/src/content/docs/zh-tw/guides/opencode.md b/docs-site/src/content/docs/zh-tw/guides/opencode.md index 88a3244a71d..517f5ce066e 100644 --- a/docs-site/src/content/docs/zh-tw/guides/opencode.md +++ b/docs-site/src/content/docs/zh-tw/guides/opencode.md @@ -61,7 +61,7 @@ ocx export --client opencode --out ~/opencodex-opencode.json 與啟動器的 runtime 區塊不同,合併後的區塊是靜態快照:它不會跟著你的目錄變動。新增供應商或變更 模型可見度之後,請重新執行 `ocx export`。 -合併完成後,在啟動 opencode 之前先匯出 admission key——除非 proxy 在 loopback 上,此時不需要: +合併完成後,在啟動 opencode 之前先匯出 admission key。僅綁定 loopback 的監聽器不會檢查它,但 OpenCode 會拒絕未設定的金鑰,因此在那裡任何非空值即可: ```bash export OPENCODEX_OPENCODE_API_KEY= @@ -95,6 +95,8 @@ Loopback 範例: 真實值只會經由子程序環境傳遞。優先順序為 `OPENCODEX_API_AUTH_TOKEN`,再來是 hardened service token 檔,然後才是已設定的 API 金鑰——非 loopback 綁定需要後者。 +Loopback 綁定(`127.0.0.1`,預設值)不要求資料面金鑰。但 OpenCode 本身需要非空的 `apiKey`:未設定的 `{env:…}` 參考會在送出請求前以 `Missing auth credential: apiKey` 被拒絕。當託管整合或儀表板的用戶端設定指向無驗證的 loopback 監聽器時,會把非機密的占位符 `opencodex-loopback` 寫為 `apiKey`,因此不需要匯出任何東西。包括 `ocx export` 在內的其他路徑保留該參考:在需要的地方匯出 admission key,在不檢查金鑰的 loopback 綁定上則把任意非空值匯出為 `OPENCODEX_OPENCODE_API_KEY`。只憑 loopback URL 無法確定不會檢查金鑰:綁定在 `0.0.0.0` 的公開監聽器,即使經由 `127.0.0.1` 連線,仍然要求可接受的金鑰;經由 SSH 轉發連到的已驗證監聽器也是如此。 + ## 還原 沒有需要還原的東西——`~/.opencodex` 下不會寫入產生的設定檔。直接執行 `opencode`,就會完全照你自己的設定讀取。 diff --git a/src/clients/config-export.ts b/src/clients/config-export.ts index eeda562c774..77db8f4c977 100644 --- a/src/clients/config-export.ts +++ b/src/clients/config-export.ts @@ -735,7 +735,11 @@ export function raycastConfigPath(env: OpencodeLaunchEnv = process.env, home: st } /** Same endpoint and credentials, with the admission header serialized by generation. */ -function opencodeProviderConnection(baseURL: string, config: OcxConfig): OpencodeProviderConnection { +function opencodeProviderConnection( + baseURL: string, + config: OcxConfig, + keylessInference: boolean, +): OpencodeProviderConnection { const options: OpencodeProviderConnection = { baseURL }; // Opt-in opencode-side timeout overrides. Omitted by default so opencode keeps its native // header/chunk waits for every upstream routed through the proxy (current V2 defaults the @@ -756,7 +760,10 @@ function opencodeProviderConnection(baseURL: string, config: OcxConfig): Opencod options.apiKey = LOOPBACK_API_KEY_PLACEHOLDER; return options; } - options.apiKey = OPENCODE_API_KEY_ENV_REF; + // OpenCode refuses an empty key before it sends anything, so an unset reference fails even + // against a listener that never reads one (#9069). Only a caller that selected the keyless + // listener may say so; everything else keeps the reference. + options.apiKey = keylessInference ? LOOPBACK_API_KEY_PLACEHOLDER : OPENCODE_API_KEY_ENV_REF; return options; } @@ -785,6 +792,7 @@ export function opencodeProviderBlocks( baseURL: string, catalogModels: readonly OpencodeCatalogModel[], config: OcxConfig, + { keylessInference = false }: { keylessInference?: boolean } = {}, ): OpencodeProviderBlocks { const v1Models: Record = {}; const v2Models: Record = {}; @@ -830,7 +838,7 @@ export function opencodeProviderBlocks( variants: opencodeEffortVariants(model), }; } - const connection = opencodeProviderConnection(baseURL, config); + const connection = opencodeProviderConnection(baseURL, config, keylessInference); const { headers, ...settings } = connection; return { v1: { @@ -892,7 +900,7 @@ export function buildOpencodeProviderBlockFromCatalog( function buildOpencodeClientConfig(ctx: ExportContext): OpencodeGeneratedConfig { const models = normalizeExportModels(ctx.models); const config = ctx.config ?? OPENCODE_PROVIDER_BLOCK_DEFAULT_CONFIG; - const blocks = opencodeProviderBlocks(ctx.baseUrl, models, config); + const blocks = opencodeProviderBlocks(ctx.baseUrl, models, config, { keylessInference: ctx.keylessInference === true }); return { $schema: OPENCODE_CONFIG_SCHEMA, provider: { [OPENCODE_PROVIDER_ID]: blocks.v1 }, diff --git a/src/clients/config-export/contracts.ts b/src/clients/config-export/contracts.ts index 30ae06a4e4c..b89e924e974 100644 --- a/src/clients/config-export/contracts.ts +++ b/src/clients/config-export/contracts.ts @@ -205,6 +205,13 @@ export interface ExportContext { * admission from `apiKey` to the `x-opencodex-api-key` header. */ config?: OcxConfig; + /** + * `baseUrl` is this Home's unauthenticated loopback listener, so inference needs no + * admission key. Set only where the serving config selected the listener itself (the + * managed-integration context and `/api/client-config`). Never inferred from the URL: an + * SSH forward can look like loopback and still lead to an authenticated listener. + */ + keylessInference?: boolean; droidReasoningDefaults?: DroidReasoningDefaults; /** * The parsed target document, when the caller has one in hand. diff --git a/src/integrations/state.ts b/src/integrations/state.ts index 2f8a5eaeaea..73f56f1ac82 100644 --- a/src/integrations/state.ts +++ b/src/integrations/state.ts @@ -519,7 +519,8 @@ export function exportContextOf(input: { port: number; droidReasoningDefaults?: Record; document?: unknown; -}): { baseUrl: string; models: readonly ExportModel[]; config: OcxConfig; droidReasoningDefaults?: Record; document?: unknown } { +}): { baseUrl: string; models: readonly ExportModel[]; config: OcxConfig; keylessInference?: boolean; droidReasoningDefaults?: Record; document?: unknown } { + const keylessListener = input.config.unauthenticatedLoopbackListener?.enabled === true; return { /* * Composed through the SAME helper `ocx export` uses. Interpolating the @@ -533,6 +534,8 @@ export function exportContextOf(input: { baseUrl: opencodeProxyBaseUrl(input.port, input.config.hostname, input.config), models: input.models, config: input.config, + // `opencodeProxyBaseUrl` above dials the keyless listener whenever it is enabled. + ...(keylessListener ? { keylessInference: true } : {}), ...(input.droidReasoningDefaults === undefined ? {} : { droidReasoningDefaults: input.droidReasoningDefaults }), // Forwarded only when the caller parsed a target: a client that resolves // between two document roots (Command Code) needs the bytes on disk. diff --git a/src/server/management/model-routes.ts b/src/server/management/model-routes.ts index e57648fd3b9..f1b7d7f9a92 100644 --- a/src/server/management/model-routes.ts +++ b/src/server/management/model-routes.ts @@ -697,6 +697,8 @@ export async function handleModelRoutes(ctx: ManagementContext): Promise { expect(readIntegrationState(request)).toMatchObject({ state: "current" }); }); + describe("OpenCode admission key per destination (#9069)", () => { + type OpencodeDocument = { + provider: { opencodex: { options: Record } }; + providers: { opencodex: { settings: Record; headers?: Record } }; + }; + const LISTENER_HUB = { + ...CONFIG, + runtimeRole: "hub", + hostname: "100.64.0.10", + unauthenticatedLoopbackListener: { enabled: true, port: 10102 }, + } as unknown as OcxConfig; + const read = (path: string) => JSON.parse(readFileSync(path, "utf8")) as OpencodeDocument; + + test("the keyless listener gets the placeholder in both generations, on enable and refresh", () => { + const configPath = installOpencode(); + const request = input({ clientId: "opencode", config: LISTENER_HUB }); + expect(applyIntegration(request).ok).toBe(true); + + const document = read(configPath); + // An unset `{env:…}` reference resolves to "", which OpenCode refuses before sending. + expect(document.provider.opencodex.options).toMatchObject({ + baseURL: "http://127.0.0.1:10102/v1", + apiKey: "opencodex-loopback", + }); + expect(document.provider.opencodex.options.headers).toBeUndefined(); + expect(document.providers.opencodex.settings).toMatchObject({ + baseURL: "http://127.0.0.1:10102/v1", + apiKey: "opencodex-loopback", + }); + expect(document.providers.opencodex.headers).toBeUndefined(); + expect(readIntegrationState(request)).toMatchObject({ state: "current" }); + + // A block the previous generator wrote carries the reference; refresh replaces it. + const previous = read(configPath); + previous.provider.opencodex.options.apiKey = "{env:OPENCODEX_OPENCODE_API_KEY}"; + previous.providers.opencodex.settings.apiKey = "{env:OPENCODEX_OPENCODE_API_KEY}"; + const previousText = `${JSON.stringify(previous, null, 2)}\n`; + writeFileSync(configPath, previousText); + const written = { + clientId: "opencode" as const, + fragments: [ + { path: ["provider", "opencodex"], value: previous.provider.opencodex }, + { path: ["providers", "opencodex"], value: previous.providers.opencodex }, + ], + }; + store.putRecord({ + ...store.readRecords().opencode!, + fileFingerprint: fingerprint(previousText), + blockFingerprint: fingerprint(canonicalContribution(written)), + semanticBlockFingerprint: fingerprint(semanticContribution(written)), + }); + expect(readIntegrationState(request)).toMatchObject({ state: "stale" }); + + const refreshed = refreshIntegration(request); + expect(refreshed.ok).toBe(true); + if (refreshed.ok) expect(refreshed.changed).toBe(true); + const after = read(configPath); + expect(after.provider.opencodex.options.apiKey).toBe("opencodex-loopback"); + expect(after.providers.opencodex.settings.apiKey).toBe("opencodex-loopback"); + expect(readIntegrationState(request)).toMatchObject({ state: "current" }); + }); + + test("an authenticated bind keeps the admission header and a loopback bind keeps the reference", () => { + const authenticatedPath = installOpencode(); + const authenticated = input({ clientId: "opencode", config: { ...CONFIG, hostname: "100.64.0.10" } as OcxConfig }); + expect(applyIntegration(authenticated).ok).toBe(true); + const remote = read(authenticatedPath); + expect(remote.provider.opencodex.options).toMatchObject({ + apiKey: "opencodex-loopback", + headers: { "x-opencodex-api-key": "{env:OPENCODEX_OPENCODE_API_KEY}" }, + }); + expect(remote.providers.opencodex.headers).toEqual({ "x-opencodex-api-key": "{env:OPENCODEX_OPENCODE_API_KEY}" }); + expect(disableIntegration(authenticated).ok).toBe(true); + + // Without the listener, a loopback base URL does not prove a keyless destination. + expect(applyIntegration(input({ clientId: "opencode" })).ok).toBe(true); + const loopback = read(authenticatedPath); + expect(loopback.provider.opencodex.options.apiKey).toBe("{env:OPENCODEX_OPENCODE_API_KEY}"); + expect(loopback.providers.opencodex.settings.apiKey).toBe("{env:OPENCODEX_OPENCODE_API_KEY}"); + expect(exportContextOf({ models: MODELS, config: CONFIG, port: 10100 }).keylessInference).toBeUndefined(); + }); + }); + test("ZCode key-order normalization stays refreshable with derived metadata (#2759)", () => { const configPath = installZcode(); const models: ExportModel[] = [ diff --git a/tests/server/management-inference-port.test.ts b/tests/server/management-inference-port.test.ts index b1c457b8d64..7c347c3f5b0 100644 --- a/tests/server/management-inference-port.test.ts +++ b/tests/server/management-inference-port.test.ts @@ -52,6 +52,23 @@ test.each([10100, 10101])("OpenCode export uses runtime port, not ingress %s", a const body = await response.json() as { config: { provider: { opencodex: { options: { baseURL: string } } } } }; expect(body.config.provider.opencodex.options.baseURL).toBe("http://127.0.0.1:23456/v1"); }); +test("OpenCode export and apply on the keyless listener write the placeholder key in both generations (#9069)", async () => { + type Doc = { provider: { opencodex: { options: Record } }; providers: { opencodex: { settings: Record; headers?: unknown } } }; + const exported = await route(config(), "/api/client-config?client=opencode", 10101, 23456); + expect(exported.status).toBe(200); + const spec = INTEGRATION_CLIENTS.opencode; + mkdirSync(spec.detectDir({}, home.root), { recursive: true }); + const applied = await route(config(), "/api/client-integrations/opencode", 10101, 23456, { + method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ enabled: true }), + }); + expect(applied.status).toBe(200); + for (const doc of [((await exported.json()) as { config: Doc }).config, JSON.parse(readFileSync(spec.configPath({}, home.root), "utf8")) as Doc]) { + expect(doc.provider.opencodex.options).toMatchObject({ baseURL: "http://127.0.0.1:23456/v1", apiKey: "opencodex-loopback" }); + expect(doc.provider.opencodex.options.headers).toBeUndefined(); + expect(doc.providers.opencodex.settings.apiKey).toBe("opencodex-loopback"); + expect(doc.providers.opencodex.headers).toBeUndefined(); + } +}); test("an explicit loopback inference port stays distinct from both runtime and management ports", async () => { const cfg = config(); cfg.unauthenticatedLoopbackListener = { enabled: true, port: 10500 }; From bb4a19a1af4c0b7607ba58ed2860711daec7ec86 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 13:54:04 +0900 Subject: [PATCH 25/60] test(cli): follow the per-endpoint inherited receipt count in the sibling stop oracle (#9114) --- tests/cli/cli-dispatch.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/cli/cli-dispatch.test.ts b/tests/cli/cli-dispatch.test.ts index e88eccf44d9..ca8c276474f 100644 --- a/tests/cli/cli-dispatch.test.ts +++ b/tests/cli/cli-dispatch.test.ts @@ -662,7 +662,7 @@ describe("a sibling start leaves shared client routing to the live owner", () => expect(stop).toContain(": stoppingSibling || connectedClientAlreadyStopped ? noServiceStop() : await (async () => {"); const managerBranch = stop.slice(stop.indexOf(": stoppingSibling || connectedClientAlreadyStopped ? noServiceStop()"), stop.indexOf("record.service = serviceStop;")); - expect(managerBranch).toMatch(/else claimHandoverBeforeManager\(\);\s+return stopServiceForOcxStop\(\{ receiptNonce: \(\) => teardownNonce, inheritedReceipts: inheritedTeardowns\.length \}\);\s+\}\)\(\);/); + expect(managerBranch).toMatch(/else claimHandoverBeforeManager\(\);\s+return stopServiceForOcxStop\(\{ receiptNonce: \(\) => teardownNonce, inheritedReceipts: inheritedTeardownProbeCount\(inheritedTeardowns\) \}\);\s+\}\)\(\);/); // The guarded desktop step refuses a manager approval for a sibling before #7771 wiring. const guardedSiblingAt = stop.indexOf('if (stoppingSibling && snapshot && snapshot.manager.kind !== "absent") {\n return approvalChanged('); expect(guardedSiblingAt).toBeGreaterThan(siblingAt); From b426995d06fb9a893a216dbb470951eb151e674e Mon Sep 17 00:00:00 2001 From: ingwannu Date: Wed, 25 Nov 2026 13:56:23 +0900 Subject: [PATCH 26/60] docs: explain native compaction replay across model changes (#9044) * docs: explain native compaction replay across model changes * docs: name the other cleanup triggers for native compaction replay A remembered opaque-blob rejection or stripped reasoning ciphertext replaces opaque compaction items even when the serving identity matches, so destination capability alone does not decide forwarding (core-replay.ts, passthrough.ts). * docs: list the request-wide cleanups that replace native compaction items Only the whole-request strip flags replace opaque compaction items; a provider-specific reasoning removal does not. Name the actual triggers: remembered rejection and its recovery retry, account change, and compaction or hard-lock fallback outside the credential domain. * docs: narrow the account-change trigger to its continuation-state cleanup An account change replaces compaction items only when the scrub removed continuation state or a turn-state header (account-change-state.ts). * docs(es): carry the native compaction replay paragraph into the Spanish server reference The English paragraph now names modelSwitch, and the Spanish localization guard requires the same inline identifiers. * docs(es): say the rejection record takes precedence over both switches --------- Co-authored-by: Ingwannu <186453546+Ingwannu@users.noreply.github.com> Co-authored-by: JUN --- .../src/content/docs/es/reference/configuration/server.md | 4 +++- docs-site/src/content/docs/reference/configuration/server.md | 4 +++- structure/transports/native-reasoning-retention.md | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/configuration/server.md b/docs-site/src/content/docs/es/reference/configuration/server.md index a4fd7616b9b..251a9fdc754 100644 --- a/docs-site/src/content/docs/es/reference/configuration/server.md +++ b/docs-site/src/content/docs/es/reference/configuration/server.md @@ -81,7 +81,9 @@ El resumen del panel ofrece dos opciones independientes: conservar el razonamien Este ejemplo conserva el razonamiento `encrypted_content` al cambiar a un modelo conocido dentro del mismo destino nativo de ChatGPT y con la misma credencial. Establezca `accountSwitch` en `true` solo si desea el reenvío experimental entre cuentas. Si cambian tanto el modelo como la cuenta, deben estar activadas ambas opciones. La política se aplica a cada destino nativo real de un Combo y a los reintentos del grupo; no habilita la retención para destinos de terceros ni para los que usan claves API. -La retención permite que OpenCodex reenvíe el texto cifrado recibido; no confirma que el proveedor acepte o reutilice ese razonamiento. Un rechazo de descifrado detectado activa la recuperación existente con limpieza limitada, y ese rechazo tiene prioridad sobre ambas opciones. Las referencias de respuestas y conversaciones, los ID de razonamiento ajeno, las restricciones de cuenta de los archivos subidos y el aislamiento de la caché mantienen sus propias reglas de propiedad. Los bloques de compactación nativa conservan su limpieza habitual; el saneamiento nativo directo de `/v1/responses/compact` no cambia. +La retención permite que OpenCodex reenvíe el texto cifrado del razonamiento recibido. Que el proveedor lo acepte y reutilice depende del destino. Un rechazo de descifrado detectado activa la recuperación existente con limpieza limitada, y el registro de ese rechazo tiene prioridad sobre ambas opciones. Las referencias de respuestas y conversaciones, los ID de razonamiento ajeno, las restricciones de cuenta de los archivos subidos y el aislamiento de la caché siguen sus propias reglas de propiedad. + +Los elementos de compactación nativa siguen una regla aparte en los turnos ordinarios de Responses. Si OpenCodex detecta un cambio de modelo, proveedor, destino, adaptador o credencial de servicio en la misma conversación de reproducción, sustituye el elemento de compactación opaco por una nota que indica que el resumen anterior no está disponible. Esto incluye un cambio solo de modelo en el mismo destino de ChatGPT y con la misma credencial, aunque `modelSwitch` esté activado. Cuando la identidad coincide o no se puede resolver la identidad de servicio anterior, OpenCodex reenvía los elementos de compactación opacos solo a destinos cuyas capacidades permiten reproducir la compactación nativa, y solo si no se aplica ninguna otra limpieza de toda la solicitud. Un rechazo de descifrado recordado y su reintento de recuperación, una limpieza por cambio de cuenta que elimina el estado de continuación, y un respaldo de compactación o de bloqueo estricto hacia un destino fuera del dominio de credenciales provocan la misma sustitución. Si el elemento se reenvía, el destino determina qué puede leer de él. Utilice `GET /api/native-reasoning-retention` para leer los booleanos efectivos y `PUT` con un objeto booleano parcial para modificarlos. `PUT` con JSON `null` restaura ambos valores predeterminados. Los campos no válidos y las claves desconocidas se rechazan; un bloque mal formado en el archivo desactiva la retención y genera una advertencia. Los cambios desde el panel o la API se aplican a las solicitudes posteriores. Los cambios locales con `ocx config set/unset` requieren reiniciar el proxy. diff --git a/docs-site/src/content/docs/reference/configuration/server.md b/docs-site/src/content/docs/reference/configuration/server.md index 89b1434b65d..55fb8facac2 100644 --- a/docs-site/src/content/docs/reference/configuration/server.md +++ b/docs-site/src/content/docs/reference/configuration/server.md @@ -88,7 +88,9 @@ The dashboard overview exposes two independent opt-ins: retain reasoning when sw This example retains reasoning `encrypted_content` on a known model switch within the same native ChatGPT destination and credential. Set `accountSwitch` to `true` only to opt into experimental cross-account forwarding. When both model and account change, both switches must be enabled. The policy applies to each actual native Combo target and pool retry; it does not grant retention to third-party or API-key destinations. -Retention means that OpenCodex may forward the carried ciphertext. It cannot confirm that the upstream accepts or reuses that reasoning. A detected decrypt rejection still enters the existing bounded cleanup recovery, and the rejection memo takes precedence over either switch. Response and conversation references, foreign reasoning item ids, uploaded-file account restrictions and cache isolation continue using their own ownership rules. Native compaction blocks keep their existing cleanup behavior; direct native `/v1/responses/compact` sanitization is unchanged. +Retention means that OpenCodex may forward the carried reasoning ciphertext. Upstream acceptance and reuse depend on the destination. A detected decrypt rejection still enters the existing bounded cleanup recovery, and the rejection memo takes precedence over either switch. Response and conversation references, foreign reasoning item IDs, uploaded-file account restrictions and cache isolation follow their own ownership rules. + +Native compaction items follow a separate rule on ordinary Responses turns. If OpenCodex detects a change in the serving model, provider, destination, adapter, or credential for the same replay conversation, it replaces the opaque compaction item with a note that the earlier summary is unavailable. This includes a model-only change on the same ChatGPT destination and credential, even with `modelSwitch` enabled. When the identity matches or the prior serving identity cannot be resolved, OpenCodex forwards opaque compaction items only to destinations whose capabilities permit native compaction replay, and only while no other request-wide cleanup applies. A remembered decrypt rejection and its recovery retry, an account-change cleanup that removes continuation state, and a compaction or hard-lock fallback to a destination outside the credential domain trigger the same replacement. If the item is forwarded, the destination determines what it can read from it. Use `GET /api/native-reasoning-retention` to read the resolved booleans and `PUT` with a partial boolean object to update them. `PUT` with JSON `null` restores both defaults. Invalid fields or unknown keys are rejected; a malformed file block disables retention with a warning. Dashboard/API changes apply to subsequent requests. Local `ocx config set/unset` edits require a restart to converge the running proxy. diff --git a/structure/transports/native-reasoning-retention.md b/structure/transports/native-reasoning-retention.md index 1d3a67e0cbe..56a7aef38c2 100644 --- a/structure/transports/native-reasoning-retention.md +++ b/structure/transports/native-reasoning-retention.md @@ -31,7 +31,7 @@ physical identity. Google's durable signature bindings retain their own identity Account retention is experimental forwarding permission, not evidence that the backend accepts or reuses another caller's reasoning. `src/server/responses/account-change-state.ts` continues removing account-bound continuation references and foreign reasoning item ids; uploaded-file refusal stays independent. Opaque-blob rejection recovery and its rejection memo override retention. When retention actually kept ciphertext across a change, `src/server/responses/passthrough-dispatch.ts` also inspects the zero-output stream prelude, so a refusal ChatGPT sends inside a 200 stream (a Codex WebSocket `error` frame or `response.failed`) takes the same single sanitized rebuild as an HTTP 4xx refusal. Previously stripped ciphertext is never restored in a later recovery leg. Claude-native per-blob replay tags remain authoritative: retention never permits a blob whose durable endpoint or generation-bearing credential fails its tag check. -Only reasoning `encrypted_content` is covered. Native compaction cleanup has its own internal flag and preserves the existing identity-change behavior. Direct native `/v1/responses/compact` sanitization is unchanged. API-key providers, arbitrary forward aliases and translated destinations receive no new permission. The configuration and management surface is described above. +Only reasoning `encrypted_content` is covered. On ordinary Responses turns, the separate native compaction flag replaces opaque compaction items with a note on any known serving identity change, including a model-only change. With matching or unresolved provenance, and no other request-wide cleanup (a remembered opaque-blob rejection, its recovery retry, an account-change cleanup that removes continuation state, or a compaction or hard-lock fallback outside the credential domain), the destination capability governs whether opaque compaction items are forwarded. Direct native `/v1/responses/compact` follows its own compaction rules. API-key providers, arbitrary forward aliases and translated destinations receive no new reasoning retention permission. The configuration and management surface is described above. ## Combo tool-loop continuation From ea9a9e6767a7ac9efdbca283f5037dacbcccd06a Mon Sep 17 00:00:00 2001 From: SeongwoongCho <35558061+SeongwoongCho@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:03:50 +0900 Subject: [PATCH 27/60] docs(update): describe preview version names and ordering (#9073) * docs(update): describe preview version names and ordering The update check accepts X.Y.Z-preview.. since #8977, but the public update reference did not say what a preview version looks like or how previews and stable releases are compared. Add one paragraph to the ocx update reference in every language that has the page. Co-Authored-By: Claude Fable 5.2 * docs(update): scope preview ordering to update checks; explain ocx update --tag The ordering and offer rules come from isNewer, which update checks, notifications and the dashboard use. ocx update itself installs whatever the selected tag points to when it differs from the installed version (src/update/index.ts), so say so in all nine locales. --------- Co-authored-by: seongwoong Co-authored-by: Claude Fable 5.2 Co-authored-by: JUN --- docs-site/src/content/docs/es/reference/cli/lifecycle.md | 2 ++ docs-site/src/content/docs/fr/reference/cli/lifecycle.md | 2 ++ docs-site/src/content/docs/ja/reference/cli/lifecycle.md | 2 ++ docs-site/src/content/docs/ko/reference/cli/lifecycle.md | 2 ++ docs-site/src/content/docs/reference/cli/lifecycle.md | 2 ++ docs-site/src/content/docs/ru/reference/cli/lifecycle.md | 2 ++ docs-site/src/content/docs/tr/reference/cli/lifecycle.md | 2 ++ docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md | 2 ++ docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md | 2 ++ 9 files changed, 18 insertions(+) diff --git a/docs-site/src/content/docs/es/reference/cli/lifecycle.md b/docs-site/src/content/docs/es/reference/cli/lifecycle.md index 2b36f1fca34..2dcea720ea7 100644 --- a/docs-site/src/content/docs/es/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/es/reference/cli/lifecycle.md @@ -804,6 +804,8 @@ En Linux, un servicio en segundo plano cuyo lanzador registrado es el lanzador d Auto-actualización opencodex de npm. Las instalaciones estables usan `@latest`; las instalaciones de vista previa permanecen en `@preview` a menos que pase `--tag latest|preview`. Detecta una comprobación de origen y le dice que `git pull && bun install` en su lugar, y es una opción prohibida si ya está en la versión más reciente para esa etiqueta. Antes de detener cualquier cosa, las instalaciones npm ejecutan una propiedad de caché Unix limitada y una verificación de acceso. Los enlaces simbólicos anidados se verifican con `lstat` pero no se siguen; Windows omite explícitamente esta comprobación de solo Unix. Un error se aborta mientras la bandeja y el proxy siguen ejecutándose. Un proxy en ejecución se detiene antes de reemplazar los archivos; un servicio instalado se reconstruye y se inicia automáticamente, mientras que una instalación en primer plano imprime `ocx start` como el siguiente paso. Los registros de actualización del panel de control redactan las rutas de perfil/caché y los valores UID/GID antes de que persistan. Cuando la dirección IP literal de un oyente detenido deja caer el dial de vitalidad en lugar de rechazarlo (por ejemplo, en una red Tailscale), el actualizador intenta brevemente vincular esa misma dirección y puerto. Un enlace exitoso confirma la ausencia en ese instante; un enlace fallido o una sonda de nombre de host no concluyente aún impide la actualización. +Las versiones preliminares se llaman `X.Y.Z-preview.` o `X.Y.Z-preview..`, por ejemplo `2.100.6-preview.20261119.1`; el intento numera las publicaciones de esa fecha. En el canal preview, las versiones preliminares se ordenan por versión base, luego por fecha y luego por intento, y una versión sin intento cuenta como intento 0. En ambos canales, una versión estable solo se ofrece a una instalación preliminar cuando su versión base es superior a la de la preliminar, y el canal estable nunca ofrece una versión preliminar. Estas reglas rigen las comprobaciones de actualización, las notificaciones y la oferta de actualización del panel. `ocx update` instala la versión a la que apunta la etiqueta seleccionada siempre que difiera de la instalada, así que `ocx update --tag latest` en una instalación preliminar pasa a la versión estable actual aunque su versión base no sea superior. + En Windows, las instalaciones predeterminadas de Scoop `nodejs` y `nodejs-lts` `npm` se pueden usar desde el directorio de inicio del usuario cuando su unión `current` permanece dentro del directorio de la aplicación Node; también se admite el directorio `bin` persistente predeterminado. Ejecutando dentro de esa instalación (incluyendo su directorio de versiones resueltas o persistentes `bin`), las entradas de directorio de versiones `npm`, `NO_JUNCTION` de project-local y las raíces Scoop personalizadas debajo de la casa permanecen excluidas. Si el paso de instalación falla, la versión anterior permanece instalada y su servicio se reinicia; la salida del terminal nombra el siguiente paso, y [Fallo de actualización en Windows](/es/troubleshooting/update-failed/) cubre terminar la actualización y las carpetas que un intento fallido puede dejar atrás. diff --git a/docs-site/src/content/docs/fr/reference/cli/lifecycle.md b/docs-site/src/content/docs/fr/reference/cli/lifecycle.md index ecf09065a3d..781cc6bd4e8 100644 --- a/docs-site/src/content/docs/fr/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/fr/reference/cli/lifecycle.md @@ -410,6 +410,8 @@ Sous Linux, un service en arrière-plan dont le lanceur enregistré est le lance Met à jour opencodex depuis npm. Les installations stables utilisent `@latest` ; les préversions restent sur `@preview`, sauf si vous indiquez `--tag latest|preview`. La commande détecte un dépôt de sources et vous invite alors à exécuter `git pull && bun install`. Elle ne fait rien si la version la plus récente correspondant à cette balise est déjà installée. +Les préversions sont nommées `X.Y.Z-preview.` ou `X.Y.Z-preview..`, par exemple `2.100.6-preview.20261119.1` ; la tentative numérote les publications de cette date. Sur le canal preview, les préversions sont classées par version de base, puis par date, puis par tentative, et une version sans tentative compte comme la tentative 0. Sur les deux canaux, une version stable n'est proposée à une installation en préversion que si sa version de base est supérieure à celle de la préversion, et le canal stable ne propose jamais de préversion. Ces règles régissent les vérifications de mise à jour, les notifications et l'offre de mise à jour du tableau de bord. `ocx update` installe la version désignée par l'étiquette choisie dès qu'elle diffère de la version installée ; ainsi `ocx update --tag latest` sur une installation en préversion passe à la version stable actuelle même si sa version de base n'est pas supérieure. + Avant tout arrêt, les installations npm effectuent sous Unix un contrôle borné de la propriété et de l’accès au cache. Les liens symboliques imbriqués sont examinés avec `lstat`, sans être suivis ; Windows ignore explicitement ce contrôle propre à Unix. En cas d’échec, l’opération s’interrompt tandis que l’icône et le proxy fonctionnent encore. Le proxy actif est ensuite arrêté avant le remplacement des fichiers. Un service installé est reconstruit et redémarré automatiquement ; pour une installation au premier plan, la commande indique `ocx start` comme étape suivante. Avant leur conservation, les enregistrements de mise à jour du tableau de bord masquent les chemins de profil et de cache ainsi que les valeurs UID/GID. ```bash diff --git a/docs-site/src/content/docs/ja/reference/cli/lifecycle.md b/docs-site/src/content/docs/ja/reference/cli/lifecycle.md index eed0e216316..c3c98eb676d 100644 --- a/docs-site/src/content/docs/ja/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ja/reference/cli/lifecycle.md @@ -355,6 +355,8 @@ Linux では、記録されたランチャーが mise のパッケージラン npm から opencodex を自己更新します。安定したインストールでは `@latest` を使用します。 `--tag latest|preview` を渡さない限り、プレビュー インストールは `@preview` に残ります。ソース チェックアウトを検出し、代わりに `git pull && bun install` を使用するように指示しますが、そのタグの最新バージョンをすでに使用している場合は何もしません。npm インストールでは、何かを停止する前に Unix キャッシュの所有権とアクセスを上限付きで検査します。ネストされたシンボリックリンクは `lstat` で確認しますが追跡しません。Windows では、この Unix 専用検査を明示的にスキップします。検査に失敗した場合、トレイとプロキシを実行したまま更新を中止します。その後、実行中のプロキシはファイルが置き換えられる前に停止されます。インストールされたサービスは再構築されて自動的に開始されますが、フォアグラウンド インストールでは次のステップとして `ocx start` が出力されます。ダッシュボードの更新記録では、保存前にプロファイル/キャッシュのパスと UID/GID 値が秘匿されます。 +プレビュー版の名前は `X.Y.Z-preview.` または `X.Y.Z-preview..` です(例: `2.100.6-preview.20261119.1`)。試行はその日付の公開回数を表します。preview チャンネルでは、プレビュー版をベースバージョン、日付、試行の順に比較し、試行のないバージョンは試行 0 として扱います。どちらのチャンネルでも、安定版がプレビュー版のインストールに提示されるのは、ベースバージョンがそのプレビュー版より高い場合だけです。安定チャンネルがプレビュー版を提示することはありません。これらの規則は更新チェック、通知、ダッシュボードの更新提示に適用されます。`ocx update` 自体は、選択したタグが指すバージョンがインストール済みのバージョンと異なれば、それをインストールします。そのため、プレビュー版のインストールで `ocx update --tag latest` を実行すると、ベースバージョンが高くなくても現在の安定版に切り替わります。 + ```bash ocx update ocx update --tag preview 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 7d1b179ac53..928134c2276 100644 --- a/docs-site/src/content/docs/ko/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ko/reference/cli/lifecycle.md @@ -501,6 +501,8 @@ Unix 전용 검사를 명시적으로 건너뜁니다. 검사에 실패하면 서비스는 자동으로 다시 빌드해 시작하며, 포그라운드 설치에서는 다음 단계로 `ocx start`를 출력합니다. 대시보드 업데이트 기록은 저장 전에 프로필/캐시 경로와 UID/GID 값을 가립니다. +프리뷰 버전의 이름은 `X.Y.Z-preview.` 또는 `X.Y.Z-preview..`입니다(예: `2.100.6-preview.20261119.1`). 시도는 해당 날짜의 게시 차수입니다. preview 채널에서는 프리뷰 버전을 기본 버전, 날짜, 시도 순으로 비교하며, 시도가 없는 버전은 시도 0으로 봅니다. 어느 채널에서든 안정 릴리스는 기본 버전이 프리뷰보다 높을 때만 프리뷰 설치에 제안되고, 안정 채널은 프리뷰 버전을 제안하지 않습니다. 이 규칙은 업데이트 확인, 알림, 대시보드의 업데이트 제안에 적용됩니다. `ocx update` 자체는 선택한 태그가 가리키는 버전이 설치된 버전과 다르면 그 버전을 설치하므로, 프리뷰 설치에서 `ocx update --tag latest`를 실행하면 기본 버전이 더 높지 않아도 현재 안정 릴리스로 바뀝니다. + ```bash ocx update ocx update --tag preview diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index 862af1648e1..822aa6a7225 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -1513,6 +1513,8 @@ When a stopped listener's literal IP address drops the liveness dial instead of A successful bind confirms absence at that instant; a failed bind or an inconclusive hostname probe still prevents the update. +Preview versions are named `X.Y.Z-preview.` or `X.Y.Z-preview..`, for example `2.100.6-preview.20261119.1`; the attempt numbers the publications of that date. On the preview channel, previews are ordered by base version, then date, then attempt, and a version without an attempt counts as attempt 0. On either channel a stable release is offered to a preview install only when its base version is higher than the preview's, and the stable channel never offers a preview. These rules govern update checks, notifications and the dashboard's update offer. `ocx update` itself installs the version its selected tag points to whenever that differs from the installed version, so `ocx update --tag latest` on a preview install moves to the current stable release even when its base version is not higher. + On Windows, Scoop's default `nodejs` and `nodejs-lts` `npm` installations can be used from the user home directory when their `current` junction stays inside the Node app directory; the default persistent `bin` directory is also supported. Running inside 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 b8ba43e3f4b..aadc1a9e35f 100644 --- a/docs-site/src/content/docs/ru/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ru/reference/cli/lifecycle.md @@ -509,6 +509,8 @@ source checkout и предлагает вместо этого `git pull && bun запускается заново, а для foreground-установки печатается подсказка `ocx start`. В записях обновления дашборда пути профиля/кэша и значения UID/GID скрываются до сохранения. +Предварительные версии называются `X.Y.Z-preview.` или `X.Y.Z-preview..`, например `2.100.6-preview.20261119.1`; попытка нумерует публикации за эту дату. В канале preview предварительные версии сравниваются по базовой версии, затем по дате, затем по попытке, а версия без попытки считается попыткой 0. В обоих каналах стабильный выпуск предлагается установке с предварительной версией, только если его базовая версия выше, а стабильный канал никогда не предлагает предварительную версию. Эти правила действуют для проверок обновлений, уведомлений и предложения обновления в панели. Сама команда `ocx update` устанавливает версию, на которую указывает выбранный тег, если она отличается от установленной, поэтому `ocx update --tag latest` на предварительной версии переходит на текущий стабильный выпуск, даже если его базовая версия не выше. + ```bash ocx update ocx update --tag preview diff --git a/docs-site/src/content/docs/tr/reference/cli/lifecycle.md b/docs-site/src/content/docs/tr/reference/cli/lifecycle.md index cefd3d6c106..b51bae76a75 100644 --- a/docs-site/src/content/docs/tr/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/tr/reference/cli/lifecycle.md @@ -582,6 +582,8 @@ başlatılır, ön plan kurulumu ise sonraki adım olarak `ocx start` yazdırır Kontrol paneli güncelleme kayıtları kalıcı hale getirilmeden önce profil/önbellek yollarını ve UID/GID değerlerini maskeler. +Önizleme sürümleri `X.Y.Z-preview.` veya `X.Y.Z-preview..` biçiminde adlandırılır, örneğin `2.100.6-preview.20261119.1`; deneme, o tarihteki yayınları numaralandırır. preview kanalında önizlemeler önce temel sürüme, sonra tarihe, sonra denemeye göre sıralanır ve denemesi olmayan bir sürüm deneme 0 sayılır. Her iki kanalda da kararlı bir sürüm, bir önizleme kurulumuna yalnızca temel sürümü önizlemeninkinden yüksekse önerilir ve kararlı kanal hiçbir zaman önizleme önermez. Bu kurallar güncelleme denetimleri, bildirimler ve panodaki güncelleme önerisi için geçerlidir. `ocx update` ise seçilen etiketin gösterdiği sürüm kurulu sürümden farklı olduğunda onu kurar; bu yüzden bir önizleme kurulumunda `ocx update --tag latest`, temel sürümü daha yüksek olmasa bile güncel kararlı sürüme geçer. + ```bash ocx update ocx update --tag preview diff --git a/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md b/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md index 61b8180824d..a69574f15a7 100644 --- a/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md @@ -342,6 +342,8 @@ Unix 包管理器升级保留私有 wrapper;未激活时,请加载输出的 从 npm 自更新 opencodex。稳定版安装使用 `@latest`;预览版安装保持在 `@preview`,除非你传入 `--tag latest|preview`。它会检测源码检出,并提示你改为运行 `git pull && bun install`;如果你已经是该标签的最新版本,则不会执行任何操作。对于 npm 安装,它会在停止任何进程之前,对 Unix 缓存的所有权和访问权限执行有界检查。嵌套符号链接会通过 `lstat` 检查但不会跟随;Windows 会明确跳过这项仅适用于 Unix 的检查。检查失败时,更新会在托盘和代理仍运行的情况下中止。随后才会在替换文件之前停止正在运行的代理;已安装的服务会自动重建并启动,而前台安装则会打印 `ocx start` 作为下一步。持久化前,仪表板更新记录会隐去用户配置文件/缓存路径以及 UID/GID 值。 +预览版的命名为 `X.Y.Z-preview.` 或 `X.Y.Z-preview..`,例如 `2.100.6-preview.20261119.1`;次数是该日期的发布序号。在 preview 通道中,预览版依次按基础版本、日期、次数比较,没有次数的版本视为次数 0。在任一通道中,只有当稳定版的基础版本高于预览版时,才会向预览版安装提供该稳定版;稳定通道从不提供预览版。这些规则适用于更新检查、通知和仪表盘的更新提示。`ocx update` 本身只要所选标签指向的版本与已安装版本不同就会安装它,因此在预览版安装上运行 `ocx update --tag latest` 会切换到当前稳定版,即使其基础版本并不更高。 + ```bash ocx update ocx update --tag preview diff --git a/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md b/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md index 78c8fad96ff..56f49e6bd29 100644 --- a/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md @@ -328,6 +328,8 @@ Unix 解除安裝後,請從 shell 啟動檔移除載入行,並重新啟動 s 從 npm 自我更新 opencodex。穩定安裝使用 `@latest`;預覽安裝停留在 `@preview`,除非你傳入 `--tag latest|preview`。它偵測原始碼 checkout 並告訴你改用 `git pull && bun install`,且若你已是該 tag 的最新版本則為 no-op。執行中的代理會在檔案被替換前停止;已安裝的服務會自動重建並啟動,而前景安裝會印出 `ocx start` 作為下一步。 +預覽版的命名為 `X.Y.Z-preview.` 或 `X.Y.Z-preview..`,例如 `2.100.6-preview.20261119.1`;次數是該日期的發布序號。在 preview 通道中,預覽版依序按基礎版本、日期、次數比較,沒有次數的版本視為次數 0。在任一通道中,只有當穩定版的基礎版本高於預覽版時,才會向預覽版安裝提供該穩定版;穩定通道從不提供預覽版。這些規則適用於更新檢查、通知和儀表板的更新提示。`ocx update` 本身只要所選標籤指向的版本與已安裝版本不同就會安裝它,因此在預覽版安裝上執行 `ocx update --tag latest` 會切換到目前的穩定版,即使其基礎版本並不更高。 + ```bash ocx update ocx update --tag preview From a16e380afe19e1ae125e1c268785b2225c42711e Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 14:11:35 +0900 Subject: [PATCH 28/60] fix(link): serve ocx link status over the local control socket on Windows (#8998) (#9022) * fix(link): serve ocx link status over the local control socket on Windows (#8998) #8370 gave a hub whose public listener is not loopback a private AF_UNIX socket for ocx link status, but only on macOS and Linux. A Windows hub answered the CLI with 403 on every TCP listener. Windows has AF_UNIX sockets; what it lacks is a readable socket identity (lstat refuses the file with EACCES) and a mode-based private directory. - windowsTrustedPath proves the whole path: canonical spelling, every component a real directory with no reparse point, the run directory private-runtime-directory, the config home write-private and every ancestor trusted-ancestry. The runtime checks the path above the run directory before creating it, hardens it, and serves nothing unless the check passes; the CLI checks the same before sending the token. - A Windows socket entry is one readdir lists and lstat refuses with EACCES; a readable file at the public path is left alone. - Without inode identity, release unlinks only inside the claim mutex while the lease still names this runtime's token; orphan cleanup matches the exact .c.<8 hex> name, never the lease; a failed publication removes its private name before giving the lease up, or keeps the lease and retries when it cannot. structure/remote-link.md describes the Windows rules. * docs(devlog): record the #8998 branch base after #9018 * fix(link): keep a lease that could not be deleted for the next stop or start removeOwnedLease treated every unlink error as "already gone". When Windows removed the socket names but the lease unlink failed, the release reported success, stop() dropped pendingRelease, and a later start() in the same process read its own record as a live owner and served no socket. Only ENOENT now counts as removed; any other failure makes the release fail and keeps it for retry. A publish rollback whose lease unlink fails retains just the record. The Windows test holds the lease open without FILE_SHARE_DELETE from another process, expects stop() to throw LocalControlReleaseError, then expects start() to finish the retained release and serve again. * test(link): pass the held lease path to the PowerShell holder as a literal * fix(link): refuse a Windows run directory that already existed without private permissions Hardening such a directory would make whatever it already held look trusted to the client, which checks only the directory's current permissions. The runtime now leaves it loose and serves no socket, so the client keeps refusing it as well. No released runtime creates this directory, so only a directory made outside opencodex is affected; removing it re-enables the socket. * test(link): start predecessor fixtures from a private run directory * test(link): cover run-directory creation under the config home and a directory loosened later; document the Windows trust boundary --- .../040_windows_control_socket.md | 64 +++ .../test-layout/layout-server-inbound.json | 1 + src/cli/link-local-control.ts | 6 +- src/lib/local-control-socket.ts | 187 ++++++- src/server/index/local-control-listener.ts | 117 ++++- structure/remote-link.md | 2 +- tests/fixtures/test-layout-expected.json | 2 +- .../local-control-socket-windows.test.ts | 476 ++++++++++++++++++ tests/server/local-control-socket.test.ts | 5 +- 9 files changed, 841 insertions(+), 19 deletions(-) create mode 100644 devlog/_plan/261121_fb2100_remote_link_auth/040_windows_control_socket.md create mode 100644 tests/server/local-control-socket-windows.test.ts diff --git a/devlog/_plan/261121_fb2100_remote_link_auth/040_windows_control_socket.md b/devlog/_plan/261121_fb2100_remote_link_auth/040_windows_control_socket.md new file mode 100644 index 00000000000..cefae82b971 --- /dev/null +++ b/devlog/_plan/261121_fb2100_remote_link_auth/040_windows_control_socket.md @@ -0,0 +1,64 @@ +# 040 #8998: `ocx link status` on a Windows hub with a non-loopback listener + +Branch `codex/fb2100-win-link-socket` from `origin/dev` a8f689f2c (after #9018 merged), second PR (roadmap unit 040). + +Problem: #8370 serves `GET /api/link/status` over a private AF_UNIX socket so the CLI's admin token has trusted +ingress on a hub whose public listener is not loopback. `localControlSocketSupported()` is false on win32, so a +Windows hub answers the CLI with `403` on every TCP listener. + +Measured on this Windows 11 host, Bun 1.3.14: + +| Behaviour | Result | +|---|---| +| `Bun.serve({ unix })` and `fetch(..., { unix })` with a path under 103 bytes | work (200) | +| `lstat` of the socket file and of a hard link to it | `EACCES` (a plain file in the same directory stats fine) | +| `existsSync` on the socket | `false`; `readdirSync` lists it | +| `linkSync` to the socket, then fetch through the link | works | +| unlink of either name while the server listens; rebind after unlink | works | +| `server.stop()` | unlinks its bound name once the stop completes; a killed process leaves it behind | +| `hardenSecretDir` + `verifyWindowsEntriesAcl(private-runtime-directory)` on the run directory | 410 ms + 273 ms once; a repeat harden is memoized (0 ms) | + +Design: keep #8370's protocol (private `.c.`, public hard link `control-.sock`, per-port lease under +the claim mutex) and replace only the parts that read POSIX identity: + +- `src/lib/local-control-socket.ts`: supported on win32. `isPrivateSocketDir` on win32 = a real directory (no + symlink or junction) whose DACL passes the `private-runtime-directory` policy. A socket entry on win32 = listed by + `readdir` and `lstat` refused with `EACCES` (an AF_UNIX reparse point); a readable regular file is not ours. + `isLocalControlPrivateSocketName(port, name)` matches exactly `.c.<8 hex>`, so the lease and claim files are + never cleanup candidates. +- `src/server/index/local-control-listener.ts`: `preparePrivateDir` on win32 creates the directory, refuses a + symlink/junction or non-directory, hardens it with `hardenSecretDir` (as `src/client/lifecycle-lock.ts` does for its + runtime directory) and refuses it unless the ACL check then passes. No chmod of the socket on win32. Publication and + orphan sweep use the win32 socket test. Ownership at release on win32 is "the lease still names this token" checked + inside the claim mutex (a successor can publish only after it holds the lease), instead of inode identity; + `abort()` keeps Bun's own unlink, as on POSIX. +- `src/cli/link-local-control.ts`: unchanged flow; `usableLocalControlSocket` now answers on win32 after the same + directory ACL check, so the token goes to the socket only in a private directory. +- Trusted path (audit round 1, blocker 1): one check, `windowsTrustedRunDir(dir)`, used by the server before it binds + and by the CLI before it sends the token. The canonical path (`realpathSync.native`) must spell the same path, so no + junction, symlink or other reparse point sits anywhere on it; then one ACL batch must pass: every ancestor of the + config home under `trusted-ancestry` (owned by the user or a kernel-equivalent principal, nobody else holding write, + delete or DACL rights), the config home under `write-private`, and the run directory under + `private-runtime-directory`. Once no other principal can write anywhere on the path, the path verified before + connecting cannot be swapped before the connect. Same-user processes and administrators are inside the trust + boundary, as for every other file in the config home. Any failure (unexpected error, timeout, unverifiable path) + answers "not trusted": the server serves no socket and the CLI keeps its TCP request. +- Failed publication (audit round 1, blocker 2): `acquireLease` takes a rollback that runs inside the claim mutex + before the lease is removed. On win32 it stops the bound listener and unlinks the private name this attempt bound; + the public link is the last, atomic step of publication, so a failed attempt never published it and never touches it. +- A win32 cleanup candidate must be listed, match the exact private-name format and refuse `lstat` with `EACCES`; + any other error leaves the entry alone, and an unlink error leaves it too. +- The start stays synchronous: the one-time cost (about 0.7 s) applies only to a Windows hub whose public listener is + not loopback, and an async start would add a new in-flight state to stop and abort. + +Tests: `tests/server/local-control-socket-windows.test.ts` (win32 only: TCP 403 vs socket 200, other routes 404, +`ocx link status` over the socket, files and lease removed on stop, a crashed predecessor's socket names replaced while a +decoy and the lease format survive, a loosened directory refused by the client, a loose pre-existing directory refused and left loose, +a config home under a parent other users can write refused by server and client while the token stays protected, a +failed publication that leaves no private name and no lease) and platform-neutral name-matcher cases. Registered in the +test layout. + +Verification: that file and `tests/server/local-control-socket.test.ts` on Windows, `bun run typecheck`, +`bun run test:changed`, `bun run structure:check`, and a real `ocx start` with `hostname: 0.0.0.0` plus +`ocx link status --json` on this host. Security review by gpt-6.1-terra. + diff --git a/scripts/test-layout/layout-server-inbound.json b/scripts/test-layout/layout-server-inbound.json index 13ec55a193e..3237bb35403 100644 --- a/scripts/test-layout/layout-server-inbound.json +++ b/scripts/test-layout/layout-server-inbound.json @@ -7,6 +7,7 @@ "claude-translated-hosted-advisor-choice.test.ts": "claude-integration", "management-provider-forward-advisor-tool.test.ts": "server", "local-control-socket.test.ts": "server", + "local-control-socket-windows.test.ts": "server", "config-concurrent-inbound-body.test.ts": "config", "inbound-body-admission.test.ts": "server", "inbound-body-budget.test.ts": "server", diff --git a/src/cli/link-local-control.ts b/src/cli/link-local-control.ts index 20a44700648..ca1925785b5 100644 --- a/src/cli/link-local-control.ts +++ b/src/cli/link-local-control.ts @@ -9,8 +9,10 @@ export interface LocalControlDeps { /** * Send one `ocx link status` read over the runtime's local control socket when it has one (#8184). * A hub whose public listener is not loopback refuses the admin token on its TCP listeners, and the - * socket is the ingress that may accept it. A runtime without the socket (Windows, a loopback bind, - * an older version), or one whose socket cannot be reached, is asked over TCP exactly as before. + * socket is the ingress that may accept it. Windows has it too (#8998), once its directory and the + * whole path to it pass the ACL and reparse checks in src/lib/local-control-socket.ts. A runtime + * without the socket (a loopback bind, an older version, a path that is not trusted), or one whose + * socket cannot be reached, is asked over TCP exactly as before. */ export async function viaLocalControlSocket( baseUrl: string, diff --git a/src/lib/local-control-socket.ts b/src/lib/local-control-socket.ts index e9492ef9cfa..b17f817c202 100644 --- a/src/lib/local-control-socket.ts +++ b/src/lib/local-control-socket.ts @@ -1,6 +1,8 @@ -import { lstatSync } from "node:fs"; -import { join } from "node:path"; +import { lstatSync, readdirSync, realpathSync, unlinkSync } from "node:fs"; +import { basename, dirname, join, resolve } from "node:path"; import { getConfigDir } from "../config/paths"; +import { resolveTrustedWindowsPowerShellExe } from "./windows-elevation"; +import { verifyWindowsEntriesAcl, WINDOWS_OWNER_ACL_TIMEOUT_MS, type WindowsAclEntry } from "./windows-owner-acl"; /** * The local control socket (#8184): a Unix-domain socket in a private directory under the @@ -8,6 +10,12 @@ import { getConfigDir } from "../config/paths"; * (Tailscale Serve on the hub management listener, a reverse proxy) can deliver a request to it, * so a request that arrives on it came from this machine through the filesystem. That is the * property the TCP loopback listeners cannot offer once a relay targets them. + * + * Windows (#8998) has AF_UNIX sockets too, with two differences this module absorbs: an AF_UNIX + * file is a reparse point that lstat refuses with EACCES, so neither its type nor its owner can be + * read; and the private directory is a DACL, not a mode. The directory therefore has to be proven + * private by its ACL, and the whole path to it by trusted ancestry with no reparse point on it, so + * that no other account can create, replace or redirect anything the CLI sends the token to. */ /** sun_path is 104 bytes on macOS and 108 on Linux, both including the terminating NUL. */ @@ -23,7 +31,7 @@ export function localControlSocketPathFits(path: string): boolean { } export function localControlSocketSupported(): boolean { - return process.platform !== "win32" && typeof process.getuid === "function"; + return process.platform === "win32" || typeof process.getuid === "function"; } export function localControlSocketDir(configDir: string = getConfigDir()): string { @@ -42,6 +50,17 @@ export function localControlSocketPath(port: number, configDir?: string): string * 16 bytes, `control-65535.sock` is 18), so a home that fits the public path fits this one too. */ const PRIVATE_SOCKET_TOKEN_CHARS = 8; +const PRIVATE_SOCKET_NAME = /^\.c([1-9]\d{0,4})\.[0-9a-f]{8}$/; + +/** + * Is this directory entry one runtime's private socket for this port? Exactly that name shape and + * nothing else, so the lease, its claim files or any other file in the directory are never cleanup + * candidates. + */ +export function isLocalControlPrivateSocketName(port: number, name: string): boolean { + const match = PRIVATE_SOCKET_NAME.exec(name); + return match !== null && match[1] === String(port); +} /** * The address Bun itself binds for one runtime. It is instance-specific, so a shutdown can only @@ -60,8 +79,159 @@ export function localControlLeasePath(port: number, configDir?: string): string return join(localControlSocketDir(configDir), `.c${port}.lease`); } -/** A real directory, owned by this user, that no other user can enter or list. */ +/** + * On Windows, is this an AF_UNIX socket entry? The directory lists it and lstat refuses it with + * EACCES, which is how an AF_UNIX reparse point reads; a file lstat can read is not one. This is an + * observation, not proof of the type: it is only trusted inside a directory proven private, where + * nothing but this account and the system can create entries. + */ +export function windowsSocketEntry(path: string): boolean { + return windowsSocketEntryState(path) === "socket"; +} + +/** + * The same observation with the doubt kept: "absent" only when the directory was read and does not + * list the name (or is itself gone), "other" for an entry lstat can read, "socket" as above, and + * "unknown" for any failure in between. Cleanup that must prove a name gone treats "unknown" as + * still present. + */ +export type WindowsSocketEntryState = "absent" | "socket" | "other" | "unknown"; + +export function windowsSocketEntryState(path: string): WindowsSocketEntryState { + let listed: boolean; + try { + listed = readdirSync(dirname(path)).includes(basename(path)); + } catch (error) { + return (error as { code?: unknown } | null)?.code === "ENOENT" ? "absent" : "unknown"; + } + if (!listed) return "absent"; + try { + lstatSync(path); + return "other"; + } catch (error) { + const code = (error as { code?: unknown } | null)?.code; + return code === "EACCES" ? "socket" : code === "ENOENT" ? "absent" : "unknown"; + } +} + +/** + * Remove a socket name this runtime published, or throw. A name proven absent is done, and so is an + * entry lstat can read: it is verifiably not a socket, so not one this runtime could still serve. A + * socket is unlinked and must then read absent. Anything that cannot be proven (an unreadable + * directory, an unexpected error, a failed unlink) throws, so the caller keeps its lease and retries + * instead of handing the port to a successor while the name may still exist. + */ +export function removeWindowsPrivateSocket( + path: string, + observe: (path: string) => WindowsSocketEntryState = windowsSocketEntryState, + unlink: (path: string) => void = unlinkSync, +): void { + const state = observe(path); + if (state === "absent" || state === "other") return; + if (state !== "socket") throw new Error("socket name could not be proven removed"); + unlink(path); + if (observe(path) !== "absent") throw new Error("socket name is still present after unlink"); +} + +/** + * One directory, as it is: the canonical path spells the same, lstat sees a directory and no link, + * and Windows reports no reparse point on it. Checked before anything changes the directory, so a + * pre-existing junction or other reparse point is refused before an ACL operation could follow it. + */ +export function windowsPlainDirectory(dir: string): boolean { + try { + const absolute = resolve(dir); + if (realpathSync.native(absolute).toLowerCase() !== absolute.toLowerCase()) return false; + const stat = lstatSync(absolute); + return stat.isDirectory() && !stat.isSymbolicLink() && windowsNoReparsePoint([absolute]); + } catch { + return false; + } +} + +/** The config home's ancestors, nearest first, up to the volume root. */ +function ancestorsOf(path: string): string[] { + const ancestors: string[] = []; + for (let current = dirname(path); ; current = dirname(current)) { + ancestors.push(current); + if (dirname(current) === current) return ancestors; + } +} + +/** + * The ACL entries the Windows path has to pass: the run directory private, the config home + * writable by this account alone, and every ancestor owned by this account or a kernel-equivalent + * principal with nobody else able to change it (src/lib/windows-owner-acl.ts). + */ +function windowsTrustEntries(runDir: string, includeRunDir: boolean): WindowsAclEntry[] { + const config = dirname(runDir); + return [ + ...(includeRunDir ? [{ path: runDir, directory: true, policy: "private-runtime-directory" as const }] : []), + { path: config, directory: true, policy: "write-private" as const }, + ...ancestorsOf(config).map(path => ({ path, directory: true, policy: "trusted-ancestry" as const })), + ]; +} + +// Constant script; the paths arrive as environment data and never become PowerShell source. +const REPARSE_SCRIPT = String.raw` +$ErrorActionPreference='Stop' +try { + $countText=[Environment]::GetEnvironmentVariable('OCX_LC_COUNT') + if ($countText -notmatch '^[1-9][0-9]?$') { exit 3 } + for ($i=0; $i -lt [int]$countText; $i++) { + $path=[Environment]::GetEnvironmentVariable(('OCX_LC_PATH_{0}' -f $i)) + if ([string]::IsNullOrEmpty($path)) { exit 3 } + $attributes=[System.IO.File]::GetAttributes($path) + if (($attributes -band [System.IO.FileAttributes]::Directory) -eq 0) { exit 1 } + if (($attributes -band [System.IO.FileAttributes]::ReparsePoint) -ne 0) { exit 1 } + } + exit 0 +} catch { exit 3 } +`; +const ENCODED_REPARSE_SCRIPT = Buffer.from(REPARSE_SCRIPT, "utf16le").toString("base64"); + +/** Every path a real directory without a reparse point, as Windows itself reports the attributes. */ +function windowsNoReparsePoint(paths: readonly string[]): boolean { + if (paths.length === 0 || paths.length > 99) return false; + const env: Record = { ...process.env, OCX_LC_COUNT: String(paths.length) }; + paths.forEach((path, index) => { env[`OCX_LC_PATH_${index}`] = path; }); + try { + const result = Bun.spawnSync([ + resolveTrustedWindowsPowerShellExe(), "-NoLogo", "-NoProfile", "-NonInteractive", + "-ExecutionPolicy", "Bypass", "-EncodedCommand", ENCODED_REPARSE_SCRIPT, + ], { env, stdin: "ignore", stdout: "ignore", stderr: "ignore", timeout: WINDOWS_OWNER_ACL_TIMEOUT_MS, windowsHide: true }); + return result.success && !result.exitedDueToTimeout && result.exitCode === 0; + } catch { + return false; + } +} + +/** + * The Windows path rule (#8998). The canonical path spells the same path and every component is + * a real directory, so no junction, symlink or other reparse point redirects it; and the ACLs + * leave no other account able to create, replace or rename anything on it, so the path checked + * now is the path a later connect uses. Any doubt, error or timeout answers false. + */ +export function windowsTrustedPath(runDir: string, includeRunDir = true): boolean { + try { + const absolute = resolve(runDir); + const entries = windowsTrustEntries(absolute, includeRunDir); + const checked = includeRunDir ? absolute : dirname(absolute); + if (realpathSync.native(checked).toLowerCase() !== checked.toLowerCase()) return false; + for (const entry of entries) { + const stat = lstatSync(entry.path); + if (!stat.isDirectory() || stat.isSymbolicLink()) return false; + } + return windowsNoReparsePoint(entries.map(entry => entry.path)) + && verifyWindowsEntriesAcl(entries, WINDOWS_OWNER_ACL_TIMEOUT_MS); + } catch { + return false; + } +} + +/** A real directory, owned by this user, that no other user can enter or list (Windows: see above). */ export function isPrivateSocketDir(dir: string): boolean { + if (process.platform === "win32") return windowsTrustedPath(dir); try { const stat = lstatSync(dir); return stat.isDirectory() && !stat.isSymbolicLink() @@ -78,6 +248,15 @@ export function isPrivateSocketDir(dir: string): boolean { export function usableLocalControlSocket(port: number, configDir?: string): string | null { if (!localControlSocketSupported() || !Number.isInteger(port) || port <= 0 || port > 65535) return null; const path = localControlSocketPath(port, configDir); + if (process.platform === "win32") { + // Trust boundary: the current user and administrators are trusted, as for every file in the + // config home. Windows cannot report an AF_UNIX file's owner, so endpoint ownership is not + // verified here; what is verified is that the run directory is private. The runtime creates + // it only under a write-private config home and refuses one that already existed loose. + // The cheap observation first: no listed socket means no PowerShell at all. + if (!localControlSocketPathFits(path) || !windowsSocketEntry(path)) return null; + return isPrivateSocketDir(localControlSocketDir(configDir)) && windowsSocketEntry(path) ? path : null; + } if (!localControlSocketPathFits(path) || !isPrivateSocketDir(localControlSocketDir(configDir))) return null; try { const stat = lstatSync(path); diff --git a/src/server/index/local-control-listener.ts b/src/server/index/local-control-listener.ts index 056f1b277f4..61c257a8722 100644 --- a/src/server/index/local-control-listener.ts +++ b/src/server/index/local-control-listener.ts @@ -20,6 +20,7 @@ import { getConfigDir } from "../../config/paths"; import { ConfigOwnershipLockError, registerOwnedConfigPath } from "../../lib/config-ownership"; import { assertNotRealHomeUnderTest } from "../../lib/test-home-guard"; import { + isLocalControlPrivateSocketName, isPrivateSocketDir, localControlLeasePath, localControlPrivateSocketPath, @@ -27,9 +28,16 @@ import { localControlSocketPath, localControlSocketPathFits, localControlSocketSupported, + removeWindowsPrivateSocket, + windowsPlainDirectory, + windowsSocketEntry, + windowsTrustedPath, } from "../../lib/local-control-socket"; +import { hardenSecretDir } from "../../lib/windows-secret-acl"; import type { OcxConfig } from "../../types"; +const WINDOWS = process.platform === "win32"; + /** * The one request the local control socket serves (#8184). `ocx link status` needs admin-token * authority on trusted loopback ingress, which a hub whose public listener is not loopback cannot @@ -68,6 +76,24 @@ export interface LocalControlListener { function preparePrivateDir(dir: string): void { assertNotRealHomeUnderTest(dirname(dir)); + if (WINDOWS) { + // Trust the path above the run directory before creating anything in it (#8998). + if (!windowsTrustedPath(dir, false)) throw new Error("socket directory path is not trusted"); + let created = true; + try { mkdirSync(dir); } catch (error) { if (!isCode(error, "EEXIST")) throw error; created = false; } + // Refuse a pre-existing junction or other reparse point before any ACL operation can follow it. + if (!windowsPlainDirectory(dir)) throw new Error("socket directory is not a plain directory"); + // A run directory that already existed without private permissions may hold a socket and lease + // someone else planted while it was open. Hardening it would make those entries look trusted to + // the client, which checks only the directory's current permissions, so refuse instead and leave + // it loose: the client then refuses it too. No released runtime creates this directory loose. + if (!created && !isPrivateSocketDir(dir)) { + throw new Error("socket directory already existed without private permissions; remove it to enable the control socket"); + } + hardenSecretDir(dir, { required: true, verifyExistingRuntimeDirectory: true }); + if (!isPrivateSocketDir(dir)) throw new Error("socket directory could not be made private"); + return; + } mkdirSync(dir, { recursive: true, mode: 0o700 }); const stat = lstatSync(dir); if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid!()) { @@ -80,6 +106,14 @@ function preparePrivateDir(dir: string): void { /** Inode identity as the kernel reports it. Bigint keeps every bit of a Windows file ID. */ interface FileIdentity { dev: bigint; ino: bigint } +/** + * Windows cannot read an AF_UNIX file's identity (lstat refuses it), so a socket this runtime + * published there carries this marker instead. What makes such a path this runtime's is the lease: + * every unlink of a marked path happens inside the claim mutex while the lease still names this + * runtime's token, and a successor can publish only after it holds the lease. + */ +const WINDOWS_SOCKET_IDENTITY: FileIdentity = Object.freeze({ dev: -1n, ino: -1n }); + /** * The per-port ownership record. `host` and `processStart` come from the shared owner evidence * (`src/codex/prompt-lock-owner.ts`), so a record from another machine, or from a pid that has @@ -97,7 +131,7 @@ type LeaseDecision = | { kind: "held" } | { kind: "unsafe" } | { kind: "contended" } - | { kind: "failed"; error: unknown }; + | { kind: "failed"; error: unknown; retained?: "socket" | "lease" }; const PUBLISH_ATTEMPTS = 4; /** `withLockClaim` is a try-lock; a contender retries a bounded number of times and then refuses. */ @@ -148,6 +182,7 @@ function registerRunDirectory(root: string, dir: string): void { } function identityOf(path: string): FileIdentity | null { + if (WINDOWS) return windowsSocketEntry(path) ? WINDOWS_SOCKET_IDENTITY : null; try { const stat = lstatSync(path, { bigint: true }); return { dev: stat.dev, ino: stat.ino }; @@ -157,6 +192,7 @@ function identityOf(path: string): FileIdentity | null { } function sameIdentity(path: string, identity: FileIdentity): boolean { + if (identity === WINDOWS_SOCKET_IDENTITY) return windowsSocketEntry(path); const current = identityOf(path); return current !== null && current.dev === identity.dev && current.ino === identity.ino; } @@ -192,11 +228,19 @@ function writeLease(path: string, lease: LocalControlLease): void { } } -/** Remove the record only when it is still this instance's; the caller holds the claim mutex. */ +/** + * Remove the record only when it is still this instance's; the caller holds the claim mutex. + * Only a record that is already gone counts as removed: any other unlink failure throws, so the + * caller keeps its retry state instead of reporting a release that left a live lease behind. + */ function removeOwnedLease(path: string, token: string): void { const current = readLease(path); if (current.kind !== "record" || current.lease.token !== token) return; - try { unlinkSync(path); } catch { /* already gone */ } + try { + unlinkSync(path); + } catch (error) { + if (!isCode(error, "ENOENT")) throw error; + } } /** @@ -208,11 +252,15 @@ function removeOrphanPrivateSockets(port: number, configDir: string | undefined) const dir = localControlSocketDir(configDir); let entries: string[]; try { entries = readdirSync(dir); } catch { return; } - const prefix = `.c${port}.`; for (const name of entries) { - if (!name.startsWith(prefix)) continue; + // The exact private-socket name, never a prefix: the lease shares the prefix. + if (!isLocalControlPrivateSocketName(port, name)) continue; const candidate = join(dir, name); try { + if (WINDOWS) { + if (windowsSocketEntry(candidate)) unlinkSync(candidate); + continue; + } const stat = lstatSync(candidate); if (stat.isSocket() && stat.uid === process.getuid!()) unlinkSync(candidate); } catch { /* raced with another cleanup */ } @@ -233,6 +281,13 @@ function publishPublicLink(target: string, privateTarget: string): void { if (!isCode(error, "EEXIST")) throw error; } let existing: BigIntStats; + if (WINDOWS) { + // A socket left there can only be a crashed predecessor's: this runtime holds the lease and + // the directory is private. Anything lstat can read is not a socket and is left alone. + if (!windowsSocketEntry(target)) throw new Error("socket path is occupied"); + unlinkSync(target); + continue; + } try { existing = lstatSync(target, { bigint: true }); } catch (error) { @@ -251,7 +306,7 @@ function publishPublicLink(target: string, privateTarget: string): void { * rather than a recheck: no other runtime can be between its own read and its own write, so a * record judged stale cannot be replaced by a live one before this runtime publishes. */ -function acquireLease(leasePath: string, token: string, publish: () => void): LeaseDecision { +function acquireLease(leasePath: string, token: string, publish: () => void, rollback: () => void = () => {}): LeaseDecision { for (let attempt = 0; attempt < LEASE_LOCK_ATTEMPTS; attempt += 1) { const outcome = withLockClaim(leasePath, token, ownerDefaults, (): LeaseDecision => { const current = readLease(leasePath); @@ -265,7 +320,12 @@ function acquireLease(leasePath: string, token: string, publish: () => void): Le try { publish(); } catch (error) { - removeOwnedLease(leasePath, token); + // Undo what this attempt bound while it still holds the lease. A rollback that fails keeps + // the lease, so no successor publishes over a name this attempt may still own. + try { rollback(); } catch { return { kind: "failed", error, retained: "socket" }; } + // The names are gone; a lease that cannot be deleted still names this runtime, so it is + // retained for the next stop() or start() exactly like a release that failed. + try { removeOwnedLease(leasePath, token); } catch { return { kind: "failed", error, retained: "lease" }; } return { kind: "failed", error }; } return { kind: "acquired" }; @@ -317,6 +377,19 @@ function releaseFailure(outcome: Exclude): function releaseOwnedSocket(state: OwnedSocket): ReleaseOutcome { try { const outcome = withLockClaim(state.leasePath, state.token, ownerDefaults, () => { + if (WINDOWS) { + // Without inode identity, the lease is the proof: unlink only while it still names us, and + // keep the lease (the release throws) unless both names are proven gone. + const current = readLease(state.leasePath); + // An unreadable record proves nothing about who owns the names: fail, keep the retry state. + if (current.kind === "unsafe") throw new Error("the control socket ownership record could not be read"); + // Absent, or a confirmed successor's token: nothing here is this runtime's any more. + if (current.kind !== "record" || current.lease.token !== state.token) return; + if (state.publicPath) removeWindowsPrivateSocket(state.publicPath); + if (state.privatePath) removeWindowsPrivateSocket(state.privatePath); + removeOwnedLease(state.leasePath, state.token); + return; + } if (state.publicPath && state.identity && sameIdentity(state.publicPath, state.identity)) unlinkSync(state.publicPath); if (state.privatePath && state.identity && sameIdentity(state.privatePath, state.identity)) unlinkSync(state.privatePath); removeOwnedLease(state.leasePath, state.token); @@ -424,15 +497,33 @@ export function createLocalControlListener(): LocalControlListener { }, }); // The private directory is the access boundary; the socket mode is a second fence. - chmodSync(privateTarget, 0o600); + // Windows has no mode to set: its boundary is the directory's verified ACL. + if (!WINDOWS) chmodSync(privateTarget, 0o600); const socketIdentity = identityOf(privateTarget); if (!socketIdentity) throw new Error("socket identity unavailable"); publishPublicLink(target, privateTarget); published = socketIdentity; }; + // Bun unlinks its bound name only when its stop completes, after this attempt gave the lease + // up. On Windows, where no inode identity guards a later cleanup, a failed publication removes + // the name itself, inside the claim mutex and before the lease goes. POSIX keeps Bun's cleanup. + const rollback = (): void => { + if (!WINDOWS) return; + // The name is removed here, not by the stop: unlinking a listening AF_UNIX name works on + // Windows, and the stop only completes after this attempt gave the lease up. A stop that + // fails or completes late leaves a listener with no name: a nameless AF_UNIX listener + // accepts no new connection, and a successor binds its own per-token name, so neither + // can collide with it. The failure is reported. + if (bound) { + void (bound as Server).stop(true).catch(error => { + console.warn(`[local-control] a failed publication's listener did not stop: ${messageOf(error)}`); + }); + } + removeWindowsPrivateSocket(privateTarget); + }; let decision: LeaseDecision; try { - decision = acquireLease(leaseFile, token, publish); + decision = acquireLease(leaseFile, token, publish, rollback); } catch (error) { if (bound) void (bound as Server).stop(true).catch(() => {}); console.warn(hardLinkUnsupported(error) ? HARD_LINK_WARNING : `[local-control] socket unavailable: ${messageOf(error)}`); @@ -440,6 +531,14 @@ export function createLocalControlListener(): LocalControlListener { } if (decision.kind === "failed") { if (bound) void (bound as Server).stop(true).catch(() => {}); + if (decision.retained === "socket") { + // The rollback could not remove what this attempt bound; keep the port owned and let the + // next stop() or start() finish the release, exactly as a release that failed would. + pendingRelease = { leasePath: leaseFile, token, publicPath: null, privatePath: privateTarget, identity: WINDOWS_SOCKET_IDENTITY }; + } else if (decision.retained === "lease") { + // The names are gone and only the record survived its unlink: retry just the record. + pendingRelease = { leasePath: leaseFile, token, publicPath: null, privatePath: null, identity: null }; + } // Publishing is where a hard-link-less filesystem actually fails, and that error is // returned rather than thrown, so this branch is the one that has to classify it. console.warn(hardLinkUnsupported(decision.error) ? HARD_LINK_WARNING : `[local-control] socket unavailable: ${messageOf(decision.error)}`); diff --git a/structure/remote-link.md b/structure/remote-link.md index 5bba97f4799..151eb9c6d9c 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -81,7 +81,7 @@ The **Child automation** panel reads `GET /api/link/children/policy` and writes The dashboard link routes (`GET /api/link/status`, `GET /api/link/diagnostics`, `GET /api/link/candidates`, `POST /api/link/probe`, `POST /api/link/confirm-host`, `POST /api/link/apply`, `POST /api/link/{id}/reconnect`, `DELETE /api/link/{id}`, `POST /api/link/children/operations` and `GET /api/link/children/jobs/{jobId}`) admit a paired GUI session, or, on a standalone runtime only, the current loopback-issued GUI session that reached the public listener bound to a loopback hostname. `POST /api/link/join` is stricter and requires the paired session because it durably redirects this machine's client traffic. The hub-link, hub-management and claude-intercept ingresses are never trusted loopback ingress, a stale session is refused, and a hub keeps the paired-only rule. The Tailscale identity refusal runs before either check. A loopback session is minted by the loopback dashboard bootstrap without a credential, so it proves possession, not user presence: any local process can fetch the bootstrap and replay its token and CSRF value, which is why it cannot authorize joining and why `src/client/machine-listener.ts` keeps durable machine changes on the connected listener away from that session. Caller-supplied explicit routes follow the stricter [explicit-route authority check](#explicit-route). Other link operations accept this casual-path trade, the same as `POST /api/github/star` in `src/server/management/sidebar-routes.ts`; it is not a secret-backed boundary like an operator-created pairing grant or the admin token. -The admin-token link routes require trusted loopback ingress. A runtime whose public listener is not bound to loopback has no TCP listener that qualifies, because the hub management listener is relayed by Tailscale Serve and must never confer that trust (#6913). `src/server/index/local-control-listener.ts` therefore opens a Unix socket at `/run/control-.sock` (`src/lib/local-control-socket.ts`) on macOS and Linux when the public bind is not loopback. Its ingress is `local-control`, the only non-TCP ingress, and `trustedLoopbackForIngress` treats it as trusted. The boundary is the filesystem: the directory is created or tightened to `0700`, must be a real directory owned by this user, and the socket is `0600`; a TCP relay or a forged header cannot produce the ingress, which is derived from the Bun server object. Before dispatch the listener admits only `GET /api/link/status` and answers 404 for anything else, and the request still needs the admin token. Two runtimes can share a home and a public port, so the public path is not the address Bun binds: it is a hard link to an instance-specific socket, and a per-port lease records the owner's host, pid and process start time from the shared owner evidence in `src/codex/prompt-lock-owner.ts`. Reading that record, deciding it is stale, and publishing the new one all happen inside the claim mutex in `src/codex/prompt-lock-claim.ts`, so a record judged dead cannot be replaced by a live one before this runtime publishes. A live owner is never displaced — a second runtime refuses the socket and leaves it serving. A record from another machine, or one that cannot be parsed, is refused rather than treated as absent. A lease whose process is provably gone is a crashed predecessor, so its dead public link and private socket are replaced; any other file at the path is left alone and no socket is served. The run directory is registered with config ownership, so uninstall removes it. A path longer than `sun_path` in bytes is refused before anything is created, because a length in code units admits a non-ASCII home the kernel cannot bind. On shutdown the runtime gives the record up first, before it awaits its own socket teardown and before the other optional listeners shut down, so a successor that starts while that shutdown is still running is not blocked by a departing incumbent; it removes the public link only when that link is still the inode it published, because Bun's own stop unlinks the path it was given. A release that cannot take the claim mutex is retried, and if it still cannot run it is reported and retained on the listener, so the next stop or start finishes it instead of leaving a live lease nobody serves. `src/cli/link-local-control.ts` sends `ocx link status` there when the directory is still private and the socket is this user's, falls back to TCP only on a transport failure, and leaves an explicit base URL untouched. Coverage: `tests/server/local-control-socket.test.ts`. +The admin-token link routes require trusted loopback ingress. A runtime whose public listener is not bound to loopback has no TCP listener that qualifies, because the hub management listener is relayed by Tailscale Serve and must never confer that trust (#6913). `src/server/index/local-control-listener.ts` therefore opens a Unix socket at `/run/control-.sock` (`src/lib/local-control-socket.ts`) on macOS, Linux and Windows when the public bind is not loopback. Its ingress is `local-control`, the only non-TCP ingress, and `trustedLoopbackForIngress` treats it as trusted. The boundary is the filesystem: the directory is created or tightened to `0700`, must be a real directory owned by this user, and the socket is `0600`; a TCP relay or a forged header cannot produce the ingress, which is derived from the Bun server object. Before dispatch the listener admits only `GET /api/link/status` and answers 404 for anything else, and the request still needs the admin token. Two runtimes can share a home and a public port, so the public path is not the address Bun binds: it is a hard link to an instance-specific socket, and a per-port lease records the owner's host, pid and process start time from the shared owner evidence in `src/codex/prompt-lock-owner.ts`. Reading that record, deciding it is stale, and publishing the new one all happen inside the claim mutex in `src/codex/prompt-lock-claim.ts`, so a record judged dead cannot be replaced by a live one before this runtime publishes. A live owner is never displaced — a second runtime refuses the socket and leaves it serving. A record from another machine, or one that cannot be parsed, is refused rather than treated as absent. A lease whose process is provably gone is a crashed predecessor, so its dead public link and private socket are replaced; any other file at the path is left alone and no socket is served. The run directory is registered with config ownership, so uninstall removes it. A path longer than `sun_path` in bytes is refused before anything is created, because a length in code units admits a non-ASCII home the kernel cannot bind. On shutdown the runtime gives the record up first, before it awaits its own socket teardown and before the other optional listeners shut down, so a successor that starts while that shutdown is still running is not blocked by a departing incumbent; it removes the public link only when that link is still the inode it published, because Bun's own stop unlinks the path it was given. A release that cannot take the claim mutex is retried, and if it still cannot run it is reported and retained on the listener, so the next stop or start finishes it instead of leaving a live lease nobody serves. `src/cli/link-local-control.ts` sends `ocx link status` there when the directory is still private and the socket is this user's, falls back to TCP only on a transport failure, and leaves an explicit base URL untouched. Windows has the socket too (#8998). There lstat refuses an AF_UNIX file with `EACCES`, so neither its type nor its owner can be read, and the directory boundary is a DACL. `windowsTrustedPath` therefore proves the path instead: the canonical path spells the same, every component is a real directory with no reparse point (lstat and the file attributes both checked), the run directory passes the `private-runtime-directory` ACL policy, the config home `write-private` and every ancestor `trusted-ancestry` (`src/lib/windows-owner-acl.ts`). The runtime checks the path above the run directory before it creates anything, creates and hardens the run directory with `hardenSecretDir`, and serves no socket unless the whole check then passes; a run directory that already exists without private permissions is refused and left as it is, because hardening it would make a socket or lease planted while it was open look trusted to the client, which then refuses the loose directory too; the CLI runs the same check before it sends the token and otherwise keeps TCP. No other account can change anything on such a path, so the path checked is the path connected. A Windows socket entry is one the directory lists and lstat refuses with `EACCES`; a file lstat can read is never treated as a socket. Without inode identity, a release unlinks the public link and the private name only inside the claim mutex while the lease still names this runtime's token, orphan cleanup matches the exact `.c.<8 hex>` name (never the lease), and a publication that fails removes the private name it bound before the lease goes, or keeps the lease and retries the release when it cannot. Only an already-absent lease counts as removed: a lease whose unlink fails fails the release, which is retained for the next stop or start. Same-user processes and administrators are inside the trust boundary, as for every other file in the config home. On Windows endpoint ownership is not verified, because an AF_UNIX file reports no owner there: the client trusts a socket in a run directory that is private when it looks, and the runtime keeps that sound by creating the directory only under a write-private config home, whose inheritable grants admit no other account, and by refusing a directory that already existed without private permissions. Coverage: `tests/server/local-control-socket.test.ts`, `tests/server/local-control-socket-windows.test.ts` (Windows hub cases; `OCX_TEST_WINDOWS_SOCKET_ROOT` names a trusted root where the default temp directory is shared). A successful join restarts this proxy (a 503 drain of up to a minute while running turns finish, then a closed listener) into the client runtime on the configured port. `GET /api/link/status` tells a GUI-session caller whether it may join: the response gains `joinAvailable`, true only for a paired dashboard session on a standalone runtime whose live port is its configured port, and `joinDenied`, which is `null` when allowed or the first failed gate (`pairing_required`, `standalone_required`, then `join_port_mismatch`). On a Child whose durable connection diverges from its startup snapshot, link and machine status instead return `503 client_state_changed`, as does readiness; this reports the divergence without stopping or reconstructing the relay. An admin-token caller gets the exact K16 document without either field, because `ocx link status` validates it key by key. The dashboard reads an absent availability field as false and an absent or unknown denial as generic unavailability; while unavailable the Child role card cannot be selected by pointer or keyboard. A pairing refusal says to pair this machine first and offers code entry only on the existing same-origin literal-loopback transport. A port refusal instead asks the operator to restart on the configured port; neither status reads nor displaying this guidance mint a grant or change pairing, keys, routing, or runtime state. Before **Connect as Child** the confirmation panel says that the restart briefly interrupts Codex and that Codex keeps its local address. The dashboard reads the standalone's pid from same-origin `/healthz`, sends the join, then reads `/healthz` once a second, skipping status polls meanwhile, and reloads only when it reports `role: "client"` under another pid, so the reloaded document carries the client role and a fresh session. It never gives up by itself: past the server's own handoff budget (60 s drain plus 70 s replacement readiness, plus a margin: 145 seconds) it says the restart is slow and keeps reading `/healthz` every 5 seconds until the Child answers or the page is left. diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 468acc03a6a..ec8cdf610d0 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1119,7 +1119,7 @@ "logs-model-tier-confirmation.test.ts": "gui", "logs-timezone.test.ts": "server", "loop-reasoning-replay.test.ts": "images", "loop.test.ts": "images", "loopback-companion-client-targets.test.ts": "server", "loopback-listener-admission.test.ts": "server", - "local-control-socket.test.ts": "server", "loopback-listener-integration.test.ts": "server", "macos-serial-lanes.test.ts": "ci-workflows", + "local-control-socket.test.ts": "server", "local-control-socket-windows.test.ts": "server", "loopback-listener-integration.test.ts": "server", "macos-serial-lanes.test.ts": "ci-workflows", "main-account-hard-lock-auth.test.ts": "codex-integration", "main-account-hard-lock-fallback-routing.test.ts": "codex-integration", "main-account-hard-lock-usage-limit.test.ts": "codex-integration", "main-account-hard-lock-default.test.ts": "codex-integration", "main-account-hard-lock-policy.test.ts": "codex-integration", diff --git a/tests/server/local-control-socket-windows.test.ts b/tests/server/local-control-socket-windows.test.ts new file mode 100644 index 00000000000..7dbabdac95f --- /dev/null +++ b/tests/server/local-control-socket-windows.test.ts @@ -0,0 +1,476 @@ +/** + * #8998: the #8184 local control socket on Windows. + * + * Windows has AF_UNIX sockets, but lstat refuses an AF_UNIX file with EACCES, so neither its type + * nor its owner can be read and the POSIX identity checks in tests/server/local-control-socket.test.ts + * do not apply. These cases start real hubs on Windows and prove the same contract: the admin + * token stays refused on TCP, the socket admits it for the one status read, the files go away on + * stop, a crashed predecessor's names are replaced, and the client sends the token only when the + * run directory and the whole path to it are trusted. + * + * The test root has to have trusted ancestry itself, which a shared temp directory may not have + * (the test preload also moves tmpdir() and homedir() into a sandbox under it): this file picks the + * first of OCX_TEST_WINDOWS_SOCKET_ROOT, tmpdir() and homedir() that passes, and skips the hub cases + * with a printed reason when none does rather than weakening the check. + */ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { spawnSync } from "node:child_process"; +import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs"; +import { homedir, tmpdir } from "node:os"; +import { join } from "node:path"; +import { saveConfig } from "../../src/config"; +import { startServer, waitForFailedStartRollback } from "../../src/server"; +import { runLinkCommand } from "../../src/cli/link"; +import { ownEvidence, ownerDefaults, ownerState } from "../../src/codex/prompt-lock-owner"; +import { + isLocalControlPrivateSocketName, + localControlLeasePath, + localControlPrivateSocketPath, + localControlSocketDir, + localControlSocketPath, + removeWindowsPrivateSocket, + usableLocalControlSocket, + windowsSocketEntryState, + windowsTrustedPath, + type WindowsSocketEntryState, +} from "../../src/lib/local-control-socket"; +import { createLocalControlListener, LocalControlReleaseError } from "../../src/server/index/local-control-listener"; +import { AuxiliaryListenerBindError, findAvailablePort, isAddrInUse } from "../../src/server/ports"; +import type { OcxConfig } from "../../src/types"; +import { SERVER_BUDGET_MS } from "../helpers/test-budget"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { hardenSecretDir } from "../../src/lib/windows-secret-acl"; + +const windows = process.platform === "win32"; +const ADMIN = "admin-secret"; +const STATUS = "/api/link/status?children=1"; +const previous = { + api: process.env.OPENCODEX_API_AUTH_TOKEN, + admin: process.env.OPENCODEX_ADMIN_AUTH_TOKEN, + home: process.env.OPENCODEX_HOME, +}; + +/** A root whose own path a Windows runtime would trust, or null. */ +function trustedRoot(): string | null { + if (!windows) return null; + const override = process.env.OCX_TEST_WINDOWS_SOCKET_ROOT?.trim(); + for (const base of [...(override ? [override] : []), tmpdir(), homedir()]) { + mkdirSync(base, { recursive: true }); + const probe = mkdtempSync(join(base, "ocx-lcw-")); + try { + mkdirSync(join(probe, "home", "run"), { recursive: true }); + if (windowsTrustedPath(join(probe, "home", "run"), false)) return base; + } finally { + removeTreeWithRetry(probe); + } + } + return null; +} +const ROOT = trustedRoot(); +if (windows && ROOT === null) { + console.warn("[local-control-socket-windows] no candidate root has trusted ancestry; set OCX_TEST_WINDOWS_SOCKET_ROOT to a private directory to run the hub cases"); +} +let testDir = ""; + +function hubConfig(managementPort: number, hostname = "0.0.0.0"): OcxConfig { + return { + port: 0, + hostname, + defaultProvider: "chatgpt", + providers: { chatgpt: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward" } }, + runtimeRole: "hub", + hub: { managementPublicOrigin: "https://hub.example.test", managementIngress: { enabled: true, port: managementPort } }, + remoteGui: { allowedTailscaleUsers: ["alice@example.test"] }, + } as unknown as OcxConfig; +} + +async function startHub(publicPort = 0) { + for (let draw = 1; ; draw += 1) { + const managementPort = await findAvailablePort(0, "127.0.0.1"); + saveConfig(hubConfig(managementPort)); + try { + const server = startServer(publicPort); + return { server, managementPort, publicPort: server.port! }; + } catch (error) { + await waitForFailedStartRollback(error); + if (!(error instanceof AuxiliaryListenerBindError && isAddrInUse(error.cause)) || draw >= 3) throw error; + } + } +} + +function overSocket(socket: string, path: string, init: RequestInit = {}): Promise { + return fetch("http://localhost" + path, { ...init, unix: socket } as RequestInit); +} + +/** A run directory as a previous runtime leaves it: created, then made private the way startup does. */ +function privateRunDir(dir: string): void { + hardenSecretDir(dir, { required: true, verifyExistingRuntimeDirectory: true }); +} + +/** What the run directory lists for this port: the public name, private names and the lease. */ +function portEntries(port: number): string[] { + try { + return readdirSync(localControlSocketDir()).filter(name => name === "control-" + port + ".sock" || name.startsWith(".c" + port + ".")) + .filter(name => !name.endsWith(".lock") && !name.endsWith(".tmp")).sort(); + } catch { + return []; + } +} + +/** Give Everyone modify rights on a directory, as a careless installer or a shared parent would. */ +function loosen(dir: string): void { + const result = spawnSync(join(process.env.SystemRoot ?? "C:\\Windows", "System32", "icacls.exe"), [dir, "/grant", "*S-1-1-0:(OI)(CI)M"], { encoding: "utf8" }); + expect(result.status).toBe(0); +} + +async function runQuietly(args: string[], deps: Parameters[1]) { + const out: string[] = []; + const err: string[] = []; + const [log, error] = [console.log, console.error]; + console.log = (...values: unknown[]) => { out.push(values.join(" ")); }; + console.error = (...values: unknown[]) => { err.push(values.join(" ")); }; + try { + return { code: await runLinkCommand(args, deps), out, err: err.join("\n") }; + } finally { + console.log = log; + console.error = error; + } +} + +function cliDeps(publicPort: number) { + return { + findLiveProxy: async () => ({ pid: process.pid, port: publicPort, hostname: "0.0.0.0", source: "runtime" as const, role: "hub" }), + readAdminToken: () => ADMIN, + }; +} + +describe("private socket names", () => { + test.each([ + [".c10100.abcdef12", true], [".c10100.0123abcd", true], + [".c10100.lease", false], [".c10100.lease.lock", false], [".c10100.abcdef1", false], [".c10100.abcdef123", false], + [".c10100.ABCDEF12", false], [".c101000.abcdef12", false], [".c1010.abcdef12", false], ["control-10100.sock", false], + [".c010100.abcdef12", false], ["x.c10100.abcdef12", false], + ] as const)("%s for port 10100 is %p", (name, expected) => { + expect(isLocalControlPrivateSocketName(10100, name)).toBe(expected); + }); +}); + +describe("removing a published socket name keeps the lease unless the name is proven gone", () => { + function remove(states: WindowsSocketEntryState[], unlinkFails = false) { + const unlinked: string[] = []; + const observe = () => states.shift() ?? "unknown"; + const unlink = (path: string) => { if (unlinkFails) throw new Error("EBUSY"); unlinked.push(path); }; + let error: unknown = null; + try { removeWindowsPrivateSocket("C:\\run\\.c10100.abcdef12", observe, unlink); } catch (caught) { error = caught; } + return { unlinked, error }; + } + + test("an absent name or a readable non-socket is left alone and does not block the release", () => { + for (const state of ["absent", "other"] as const) expect(remove([state])).toEqual({ unlinked: [], error: null }); + }); + + test("a socket is unlinked and must then read absent", () => { + expect(remove(["socket", "absent"])).toEqual({ unlinked: ["C:\\run\\.c10100.abcdef12"], error: null }); + expect(remove(["socket", "socket"]).error).toBeInstanceOf(Error); + expect(remove(["socket", "unknown"]).error).toBeInstanceOf(Error); + }); + + test("an unverifiable entry or a failed unlink throws, so the caller keeps its lease", () => { + const unknown = remove(["unknown"]); + expect(unknown.unlinked).toEqual([]); + expect(unknown.error).toBeInstanceOf(Error); + expect(remove(["socket"], true).error).toBeInstanceOf(Error); + }); +}); + +describe.skipIf(!windows || ROOT === null)("Windows hub with a non-loopback public listener (#8998)", () => { + beforeEach(() => { + testDir = mkdtempSync(join(ROOT!, "ocx-lcw-")); + process.env.OPENCODEX_HOME = join(testDir, "home"); + mkdirSync(process.env.OPENCODEX_HOME, { recursive: true }); + process.env.OPENCODEX_API_AUTH_TOKEN = "public-secret"; + process.env.OPENCODEX_ADMIN_AUTH_TOKEN = ADMIN; + }); + + afterEach(() => { + for (const [key, value] of [["OPENCODEX_API_AUTH_TOKEN", previous.api], ["OPENCODEX_ADMIN_AUTH_TOKEN", previous.admin], ["OPENCODEX_HOME", previous.home]] as const) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + if (testDir) removeTreeWithRetry(testDir); + testDir = ""; + }); + + test("refuses the admin token on TCP, admits it on the socket, and removes every file on stop", async () => { + const { server, managementPort, publicPort } = await startHub(); + const socket = localControlSocketPath(publicPort); + try { + for (const port of [managementPort, publicPort]) { + const response = await fetch("http://127.0.0.1:" + port + STATUS, { headers: { "x-opencodex-api-key": ADMIN } }); + expect(response.status).toBe(403); + } + const admitted = await overSocket(socket, STATUS, { headers: { "x-opencodex-api-key": ADMIN } }); + expect(admitted.status).toBe(200); + expect(Object.keys((await admitted.json()) as Record)).toEqual(expect.arrayContaining(["role", "listener", "links"])); + expect((await overSocket(socket, STATUS)).status).toBe(401); + for (const [method, path] of [["GET", "/api/config"], ["POST", "/api/link/issue"], ["GET", "/healthz"]] as const) { + expect((await overSocket(socket, path, { method, headers: { "x-opencodex-api-key": ADMIN } })).status).toBe(404); + } + expect(usableLocalControlSocket(publicPort)).toBe(socket); + expect(portEntries(publicPort).filter(name => isLocalControlPrivateSocketName(publicPort, name))).toHaveLength(1); + } finally { + await server.stop(true); + } + expect(portEntries(publicPort)).toEqual([]); + expect(usableLocalControlSocket(publicPort)).toBeNull(); + }, SERVER_BUDGET_MS); + + test("ocx link status reads the hub through the socket instead of meeting the 403", async () => { + const { server, publicPort } = await startHub(); + try { + const viaSocket = await runQuietly(["status", "--json"], cliDeps(publicPort)); + expect(viaSocket.err).toBe(""); + expect(viaSocket.code).toBe(0); + expect(Object.keys(JSON.parse(viaSocket.out.at(-1)!))).toEqual(expect.arrayContaining(["role", "listener", "links"])); + const viaTcp = await runQuietly(["status", "--json"], { ...cliDeps(publicPort), localControlSocket: () => null }); + expect(viaTcp.code).toBe(1); + expect(viaTcp.err).toContain("Link management request failed (403)"); + } finally { + await server.stop(true); + } + }, SERVER_BUDGET_MS); + + test("a crashed predecessor's socket names are replaced; the lease shape and other files are kept", async () => { + const publicPort = await findAvailablePort(0, "0.0.0.0"); + const dir = localControlSocketDir(); + mkdirSync(dir, { recursive: true }); + privateRunDir(dir); + // A real AF_UNIX file left by a runtime that was killed: only a completed stop unlinks it. + const stale = localControlPrivateSocketPath(publicPort, "0123456789abcdef"); + const crashed = Bun.spawn([process.execPath, "-e", + "Bun.serve({ unix: process.argv[1], fetch: () => new Response('stale') }); require('fs').writeFileSync(process.argv[1] + '-ready', '1'); setInterval(() => {}, 1000);", + stale], { stdout: "ignore", stderr: "ignore" }); + while (!readdirSync(dir).includes(".c" + publicPort + ".01234567-ready")) await Bun.sleep(10); + crashed.kill("SIGKILL"); + await crashed.exited; + unlinkSync(stale + "-ready"); + expect(readdirSync(dir)).toContain(".c" + publicPort + ".01234567"); + linkSync(stale, localControlSocketPath(publicPort)); + const deadPid = spawnSync(process.execPath, ["-e", "0"]).pid!; + const record = { ...ownEvidence(ownerDefaults), pid: deadPid, token: "0123456789abcdef" }; + expect(ownerState(record, ownerDefaults)).toBe("dead"); + writeFileSync(localControlLeasePath(publicPort), JSON.stringify(record)); + writeFileSync(join(dir, ".c" + publicPort + ".notes"), "keep me"); + const { server } = await startHub(publicPort); + try { + const entries = portEntries(publicPort); + expect(entries).not.toContain(".c" + publicPort + ".01234567"); + expect(entries).toContain(".c" + publicPort + ".notes"); + const lease = JSON.parse(readFileSync(localControlLeasePath(publicPort), "utf8")) as { token: string }; + expect(lease.token).not.toBe("0123456789abcdef"); + expect((await overSocket(localControlSocketPath(publicPort), STATUS, { headers: { "x-opencodex-api-key": ADMIN } })).status).toBe(200); + } finally { + await server.stop(true); + } + expect(portEntries(publicPort)).toEqual([".c" + publicPort + ".notes"]); + }, SERVER_BUDGET_MS); + + test("a readable file at the public path is left alone, and the failed attempt leaves no socket and no lease", async () => { + const publicPort = await findAvailablePort(0, "0.0.0.0"); + mkdirSync(localControlSocketDir(), { recursive: true }); + privateRunDir(localControlSocketDir()); + writeFileSync(localControlSocketPath(publicPort), "not a socket"); + const { server } = await startHub(publicPort); + try { + expect(portEntries(publicPort)).toEqual(["control-" + publicPort + ".sock"]); + expect(readFileSync(localControlSocketPath(publicPort), "utf8")).toBe("not a socket"); + expect(usableLocalControlSocket(publicPort)).toBeNull(); + } finally { + await server.stop(true); + } + }, SERVER_BUDGET_MS); + + test("a loose pre-existing run directory is refused and left loose, so no client trusts what it holds", async () => { + mkdirSync(localControlSocketDir(), { recursive: true }); + loosen(localControlSocketDir()); + expect(windowsTrustedPath(localControlSocketDir())).toBe(false); + const { server, publicPort } = await startHub(); + try { + expect(windowsTrustedPath(localControlSocketDir())).toBe(false); + expect(portEntries(publicPort)).toEqual([]); + expect(usableLocalControlSocket(publicPort)).toBeNull(); + } finally { + await server.stop(true); + } + }, SERVER_BUDGET_MS); + + test("the client refuses a run directory another account can write, and the CLI keeps TCP", async () => { + const { server, publicPort } = await startHub(); + try { + expect(usableLocalControlSocket(publicPort)).toBe(localControlSocketPath(publicPort)); + loosen(localControlSocketDir()); + expect(usableLocalControlSocket(publicPort)).toBeNull(); + const result = await runQuietly(["status", "--json"], cliDeps(publicPort)); + expect(result.code).toBe(1); + expect(result.err).toContain("Link management request failed (403)"); + } finally { + await server.stop(true); + } + }, SERVER_BUDGET_MS); + + test("a config home under a parent other accounts can write gets no socket, from server or client", async () => { + const shared = join(testDir, "shared"); + mkdirSync(shared); + loosen(shared); + process.env.OPENCODEX_HOME = join(shared, "home"); + mkdirSync(process.env.OPENCODEX_HOME); + const { server, publicPort } = await startHub(); + try { + expect(portEntries(publicPort)).toEqual([]); + expect(usableLocalControlSocket(publicPort)).toBeNull(); + const result = await runQuietly(["status", "--json"], cliDeps(publicPort)); + expect(result.code).toBe(1); + expect(result.err).toContain("Link management request failed (403)"); + } finally { + await server.stop(true); + } + }, SERVER_BUDGET_MS); + + test("a loopback public listener serves no socket and spawns no ACL check in the client", async () => { + const managementPort = await findAvailablePort(0, "127.0.0.1"); + saveConfig(hubConfig(managementPort, "127.0.0.1")); + const server = startServer(0); + try { + expect(portEntries(server.port!)).toEqual([]); + expect(usableLocalControlSocket(server.port!)).toBeNull(); + } finally { + await server.stop(true); + } + }, SERVER_BUDGET_MS); + + test("a pre-existing junction at the run directory is refused before any ACL operation follows it", async () => { + const target = join(testDir, "elsewhere"); + mkdirSync(target); + loosen(target); + const made = spawnSync("cmd.exe", ["/c", "mklink", "/J", localControlSocketDir(), target], { encoding: "utf8" }); + expect(made.status).toBe(0); + const before = spawnSync(join(process.env.SystemRoot ?? "C:\\Windows", "System32", "icacls.exe"), [target], { encoding: "utf8" }).stdout; + const { server, publicPort } = await startHub(); + try { + expect(readdirSync(target)).toEqual([]); + expect(usableLocalControlSocket(publicPort)).toBeNull(); + // Hardening never ran on the junction's target: its loose ACL is exactly as it was. + expect(spawnSync(join(process.env.SystemRoot ?? "C:\\Windows", "System32", "icacls.exe"), [target], { encoding: "utf8" }).stdout).toBe(before); + } finally { + await server.stop(true); + spawnSync("cmd.exe", ["/c", "rmdir", localControlSocketDir()]); + } + }, SERVER_BUDGET_MS); + + test("the socket entry observation tells a socket, a readable file, absence and a missing directory apart", async () => { + const { server, publicPort } = await startHub(); + try { + expect(windowsSocketEntryState(localControlSocketPath(publicPort))).toBe("socket"); + writeFileSync(join(localControlSocketDir(), "plain"), "x"); + expect(windowsSocketEntryState(join(localControlSocketDir(), "plain"))).toBe("other"); + expect(windowsSocketEntryState(join(localControlSocketDir(), "missing"))).toBe("absent"); + expect(windowsSocketEntryState(join(testDir, "no-such-dir", "x"))).toBe("absent"); + } finally { + await server.stop(true); + } + }, SERVER_BUDGET_MS); + + test("an unreadable ownership record fails the release and keeps it for the next stop", async () => { + const publicPort = await findAvailablePort(0, "0.0.0.0"); + const listener = createLocalControlListener(); + listener.start({ config: { hostname: "0.0.0.0" } as OcxConfig, publicPort, dispatch: async () => Response.json({ ok: true }) }); + expect(listener.socketPath()).toBe(localControlSocketPath(publicPort)); + const lease = localControlLeasePath(publicPort); + const record = readFileSync(lease, "utf8"); + writeFileSync(lease, "{not json"); + const failed = await listener.stop().then(() => null, (error: unknown) => error); + expect(failed).toBeInstanceOf(LocalControlReleaseError); + // Nothing was handed over: the public name is still there for the retained release. + expect(portEntries(publicPort)).toContain("control-" + publicPort + ".sock"); + writeFileSync(lease, record); + await listener.stop(); + expect(portEntries(publicPort)).toEqual([]); + }, SERVER_BUDGET_MS); + + test("a lease that cannot be deleted fails the stop, and the next start retries it before serving again", async () => { + const publicPort = await findAvailablePort(0, "0.0.0.0"); + const ctx = { config: { hostname: "0.0.0.0" } as OcxConfig, publicPort, dispatch: async () => Response.json({ ok: true }) }; + const listener = createLocalControlListener(); + listener.start(ctx); + expect(listener.socketPath()).toBe(localControlSocketPath(publicPort)); + const lease = localControlLeasePath(publicPort); + // Another process holds the record open without FILE_SHARE_DELETE: it stays readable, but no + // unlink can remove it until that handle closes. The path travels as a quoted literal: copying + // process.env into the child can carry both SYSTEMROOT and SystemRoot, which breaks the spawn. + const quoted = "'" + lease.replaceAll("'", "''") + "'"; + const holder = Bun.spawn(["powershell.exe", "-NoProfile", "-NonInteractive", "-Command", + "$ErrorActionPreference = 'Stop'; $f = [IO.File]::Open(" + quoted + ", 'Open', 'Read', 'Read'); [Console]::Out.WriteLine('held'); [Console]::Out.Flush(); [void][Console]::In.ReadLine(); $f.Close()"], + { stdin: "pipe", stdout: "pipe", stderr: "ignore" }); + try { + const reader = holder.stdout.getReader(); + let seen = ""; + while (!seen.includes("held")) { + const chunk = await reader.read(); + if (chunk.done) throw new Error("the lease holder exited before opening the record"); + seen += new TextDecoder().decode(chunk.value); + } + const failed = await listener.stop().then(() => null, (error: unknown) => error); + expect(failed).toBeInstanceOf(LocalControlReleaseError); + expect(readFileSync(lease, "utf8")).toContain("token"); + } finally { + holder.stdin.write("\n"); + await holder.stdin.end(); + await holder.exited; + } + // The retained release runs first, so this runtime's own stale record does not read as a live owner. + listener.start(ctx); + expect(listener.socketPath()).toBe(localControlSocketPath(publicPort)); + await listener.stop(); + expect(portEntries(publicPort)).toEqual([]); + }, SERVER_BUDGET_MS); + + test("a config home whose inheritable grants would let another account write gets no run directory", async () => { + // A new directory inherits its parent's grants before hardening runs, so the parent check + // has to refuse first: the run directory is never created where it could start out writable. + const grant = spawnSync(join(process.env.SystemRoot ?? "C:\\Windows", "System32", "icacls.exe"), + [process.env.OPENCODEX_HOME!, "/grant", "*S-1-1-0:(OI)(CI)(IO)M"], { encoding: "utf8" }); + expect(grant.status).toBe(0); + const publicPort = await findAvailablePort(0, "0.0.0.0"); + const listener = createLocalControlListener(); + listener.start({ config: { hostname: "0.0.0.0" } as OcxConfig, publicPort, dispatch: async () => Response.json({ ok: true }) }); + try { + expect(listener.socketPath()).toBeNull(); + expect(existsSync(localControlSocketDir())).toBe(false); + expect(usableLocalControlSocket(publicPort)).toBeNull(); + } finally { + await listener.stop(); + } + }, SERVER_BUDGET_MS); + + test("a run directory loosened after a runtime created it is refused at the next start and left loose", async () => { + const publicPort = await findAvailablePort(0, "0.0.0.0"); + const ctx = { config: { hostname: "0.0.0.0" } as OcxConfig, publicPort, dispatch: async () => Response.json({ ok: true }) }; + const first = createLocalControlListener(); + first.start(ctx); + expect(first.socketPath()).toBe(localControlSocketPath(publicPort)); + expect(windowsTrustedPath(localControlSocketDir())).toBe(true); + await first.stop(); + loosen(localControlSocketDir()); + const next = createLocalControlListener(); + next.start(ctx); + try { + expect(next.socketPath()).toBeNull(); + expect(windowsTrustedPath(localControlSocketDir())).toBe(false); + expect(portEntries(publicPort)).toEqual([]); + expect(usableLocalControlSocket(publicPort)).toBeNull(); + } finally { + await next.stop(); + } + }, SERVER_BUDGET_MS); +}); + diff --git a/tests/server/local-control-socket.test.ts b/tests/server/local-control-socket.test.ts index bfa11ec088e..3e25b24cc3a 100644 --- a/tests/server/local-control-socket.test.ts +++ b/tests/server/local-control-socket.test.ts @@ -275,8 +275,9 @@ describe("local control socket route table", () => { }); test("is wanted only when the public listener is not loopback", () => { - expect(localControlSocketWanted({ hostname: "0.0.0.0" })).toBe(unixSupported); - expect(localControlSocketWanted({ hostname: "10.0.0.5" })).toBe(unixSupported); + // Every platform, Windows included since #8998. + expect(localControlSocketWanted({ hostname: "0.0.0.0" })).toBe(true); + expect(localControlSocketWanted({ hostname: "10.0.0.5" })).toBe(true); for (const hostname of ["127.0.0.1", "localhost", "::1", undefined]) { expect(localControlSocketWanted({ hostname } as Pick)).toBe(false); } From d7746891a2a8d361e7756e9b3b6cea30d2e034c9 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Wed, 25 Nov 2026 14:12:13 +0900 Subject: [PATCH 29/60] fix(vision): apply caller model scope to the selected helper (#9061) Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN Co-authored-by: lidge-jun --- docs-site/src/content/docs/guides/sidecars.md | 2 + .../src/content/docs/ko/guides/sidecars.md | 2 + src/vision/plan.ts | 55 ++++++++++++------- structure/gui-and-management-api.md | 2 +- structure/runtime.md | 2 +- .../vision-anthropic-instance-sidecar.test.ts | 17 ++++++ tests/vision/vision-cache.test.ts | 53 ++++++++++++++++++ 7 files changed, 110 insertions(+), 23 deletions(-) diff --git a/docs-site/src/content/docs/guides/sidecars.md b/docs-site/src/content/docs/guides/sidecars.md index c428e3dd1aa..26a2eaac018 100644 --- a/docs-site/src/content/docs/guides/sidecars.md +++ b/docs-site/src/content/docs/guides/sidecars.md @@ -150,6 +150,8 @@ failures after response headers have started are delivered as `response.failed` ## Vision sidecar +A scoped API key must allow the provider and model that will describe the image, including a fallback helper. If the routed helper is denied, a text-only request that can continue proceeds with the image omitted. + Mistral's `zai-glm-5-3` is enrolled by the provider preset as text-only. With the vision sidecar enabled and available, OpenCodex describes attached images and sends their text descriptions to GLM. The Codex catalog advertises image diff --git a/docs-site/src/content/docs/ko/guides/sidecars.md b/docs-site/src/content/docs/ko/guides/sidecars.md index f84514a74c6..f67a28e47bb 100644 --- a/docs-site/src/content/docs/ko/guides/sidecars.md +++ b/docs-site/src/content/docs/ko/guides/sidecars.md @@ -77,6 +77,8 @@ stall은 전체 생성 timeout이 아닙니다. SSE가 시작되기 전 실패 ## 비전 사이드카 +사용 범위가 제한된 API 키는 이미지를 설명할 프로바이더와 모델을 허용해야 합니다. 대체 모델에도 같은 기준이 적용됩니다. 라우팅된 보조 모델의 권한이 거부되면, 이미지 없이 처리할 수 있는 텍스트 전용 요청은 이미지를 제외하고 계속합니다. + 라우팅 모델이 해당 프로바이더의 `noVisionModels`에 있거나 해당 모델이 `modelInputModalities`에서 텍스트 전용으로 선언되어 있고 요청에 이미지가 들어오면, opencodex는 사용 가능한 비전 사이드카 계획이 있을 때에만 메인 호출 **전에** 각 이미지를 설명한 텍스트로 바꿉니다. 사용 가능한 계획이 없으면 원본 이미지는 텍스트 전용 diff --git a/src/vision/plan.ts b/src/vision/plan.ts index be7880a6c91..48d459a1e0f 100644 --- a/src/vision/plan.ts +++ b/src/vision/plan.ts @@ -2,12 +2,13 @@ import type { OcxConfig, OcxContentPart, OcxParsedRequest, OcxProviderConfig } f import { modelRecordValue, type VisionReasoningEffort } from "../reasoning-effort"; import type { VisionSettings } from "./describe"; import type { ResolvedOpenAiForwardSidecar } from "../providers/openai-sidecar"; +import { OPENAI_CODEX_PROVIDER_ID } from "../providers/openai-tiers"; import type { CodexAuthPolicyConfig } from "../codex/auth-context"; import { isCodexReserveRequestEligible } from "../codex/loopback-target"; import { resolveDataPlaneAdmissionSecret, type DataPlaneAdmission } from "../server/auth-cors"; import type { CapturedAdmissionPolicy } from "../types/admission-policy"; import { previewRouteModel } from "../router"; -import { resolveAdmissionModelScope, routeAllowedByScope, type AdmissionModelScope } from "../server/admission-model-scope"; +import { intersectAdmissionModelScopes, resolveAdmissionModelScope, routeAllowedByScope, type AdmissionModelScope, type ScopedRoute } from "../server/admission-model-scope"; import { localChatCompletionDestination } from "../lib/local-chat-completion"; import { selfFetchAdmissionToken } from "../lib/local-destinations"; import { resolveWireProtocolOverride } from "../server/adapter-resolve"; @@ -87,10 +88,7 @@ function preferredVisionBackend(config: OcxConfig, parentProviderName?: string): /** Native model used by the OpenAI vision helper, including its bounded default. */ export function resolveOpenAiVisionModel(config: Pick): string { - const configured = config.visionSidecar?.model; - // Namespaced routed ids never reach the forward executor (see - // resolveEffectiveVisionModel). - return configured && !configured.includes("/") ? configured : DEFAULT_VISION_MODEL; + return resolveEffectiveVisionModel(config, "openai"); } /** Effective describer model for the backend `planVisionSidecar` selected. */ @@ -159,8 +157,23 @@ export function requiresVisionPreprocessing( return modelAcceptsImageInput(config, { provider: providerName, id: modelId }) === false; } -/** Check the destination and both admission scopes used by the routed Chat self-fetch. */ -function usableRoutedVisionModel(config: OcxConfig, callerScope?: AdmissionModelScope): string | undefined { +type RoutedVisionTarget = { kind: "usable"; model: string } | { kind: "denied" }; + +function routedVisionAuthorized(config: OcxConfig, route: ScopedRoute, callerScope?: AdmissionModelScope): boolean { + try { + if (!routeAllowedByScope(callerScope, route)) return false; + const destination = localChatCompletionDestination(config); + const token = selfFetchAdmissionToken(config, destination); + if (!token) return !destination.requiresAdmissionToken; + const host = resolveDataPlaneAdmissionSecret(token, config); + return host !== null && routeAllowedByScope(resolveAdmissionModelScope(config, host), route); + } catch { + return false; + } +} + +/** An unavailable target can fall back. An admission refusal ends helper selection. */ +function resolveRoutedVisionTarget(config: OcxConfig, callerScope?: AdmissionModelScope): RoutedVisionTarget | undefined { const cfg = config.visionSidecar; if (cfg?.backend !== "routed") return undefined; const routedModel = cfg.model; @@ -169,15 +182,10 @@ function usableRoutedVisionModel(config: OcxConfig, callerScope?: AdmissionModel try { const route = previewRouteModel(config, routedModel); if (route.routeKind !== "explicit-provider" && route.routeKind !== "explicit-account") return undefined; - if (!routeAllowedByScope(callerScope, route)) return undefined; + if (!routedVisionAuthorized(config, route, callerScope)) return { kind: "denied" }; const provider = resolveWireProtocolOverride(route.providerName, route.modelId, route.provider, "chat"); if (requiresVisionPreprocessing(config, provider, route.modelId, route.providerName)) return undefined; - const destination = localChatCompletionDestination(config); - const token = selfFetchAdmissionToken(config, destination); - if (!token) return destination.requiresAdmissionToken ? undefined : routedModel; - const hostAdmission = resolveDataPlaneAdmissionSecret(token, config); - return hostAdmission && routeAllowedByScope(resolveAdmissionModelScope(config, hostAdmission), route) - ? routedModel : undefined; + return { kind: "usable", model: routedModel }; } catch { return undefined; } @@ -194,8 +202,9 @@ export function shouldResolveOpenAiVisionSidecar( if (!requiresVisionPreprocessing(config, provider, modelId, providerName) || !messagesHaveImage(parsed)) return false; const cfg = config.visionSidecar ?? {}; if (cfg.enabled === false) return false; - if (usableRoutedVisionModel(config, admissionScope)) return false; - return preferredVisionBackend(config, providerName) === "openai"; + if (resolveRoutedVisionTarget(config, admissionScope)) return false; + return routeAllowedByScope(admissionScope, { providerName: OPENAI_CODEX_PROVIDER_ID, modelId: resolveOpenAiVisionModel(config) }) + && preferredVisionBackend(config, providerName) === "openai"; } export interface VisionPlan { @@ -243,12 +252,16 @@ export function planVisionSidecar( // fence: the target must not be provably blind, and must not itself be a // model this planner would re-enter for (belt; the terminal marker on the // loopback request is the braces). - const routedModel = usableRoutedVisionModel(config, options.admissionScope ?? options.advisorAdmissionPolicy?.modelScope); - if (routedModel) { + const scope = intersectAdmissionModelScopes(options.admissionScope, options.advisorAdmissionPolicy?.modelScope); + const routed = resolveRoutedVisionTarget(config, scope); + if (routed?.kind === "denied") return undefined; + if (routed) { + const routedModel = routed.model; return { backend: "routed", routedModel, - advisorAdmissionPolicy: options.advisorAdmissionPolicy, + advisorAdmissionPolicy: options.advisorAdmissionPolicy && scope + ? { ...options.advisorAdmissionPolicy, modelScope: scope } : options.advisorAdmissionPolicy, routedConfig: { port: config.port, ...(config.apiKeys ? { apiKeys: config.apiKeys } : {}), @@ -281,7 +294,7 @@ export function planVisionSidecar( const maxDescriptionsPerTurn = resolveMaxDescriptionsPerTurn(cfg.maxDescriptionsPerTurn); if (backend === "anthropic") { - if (!anthropicSidecar) return undefined; + if (!anthropicSidecar || !routeAllowedByScope(scope, { providerName: anthropicSidecar.providerName, modelId: model })) return undefined; return { backend, anthropicSidecar, @@ -294,7 +307,7 @@ export function planVisionSidecar( }; } - if (!openAiSidecar) return undefined; + if (!openAiSidecar || !routeAllowedByScope(scope, { providerName: openAiSidecar.providerName, modelId: model })) return undefined; return { backend, forwardSidecar: openAiSidecar, diff --git a/structure/gui-and-management-api.md b/structure/gui-and-management-api.md index 088754559c5..de6b9c66229 100644 --- a/structure/gui-and-management-api.md +++ b/structure/gui-and-management-api.md @@ -572,7 +572,7 @@ Pairing-grant source limiting applies only to invalid guesses from an allowed br ## Durable provider PATCH -Provider editor snapshots and management writes validate provider-wide `inputModalities` through `providerManagementConfigError` in `src/server/auth-cors.ts`, sharing the [config modality contract](config.md#explicit-per-model-capability-declarations). Malformed declarations are refused before persistence or catalog refresh; the field remains editor-owned rather than a credential or derived DTO field. `PUT /api/combos` shares this transaction for combo changes, rename references, disabled selectors and request-only Vision Sidecar enrollment; see `tests/routing/combo-vision-enrollment.test.ts`. +Provider editor snapshots and management writes validate provider-wide `inputModalities` through `providerManagementConfigError` in `src/server/auth-cors.ts`, sharing the [config modality contract](config.md#explicit-per-model-capability-declarations). The model catalog describes capability. The [runtime](runtime.md) separately checks the requesting key’s scope against the selected Vision helper. Malformed declarations are refused before persistence or catalog refresh; the field remains editor-owned rather than a credential or derived DTO field. `PUT /api/combos` shares this transaction for combo changes, rename references, disabled selectors and request-only Vision Sidecar enrollment; see `tests/routing/combo-vision-enrollment.test.ts`. `src/server/management/provider-routes.ts` commits every provider PATCH variant through `src/server/management/provider-patch-transaction.ts`, including standalone default-provider diff --git a/structure/runtime.md b/structure/runtime.md index b01e6e63df0..5acf4bab5ef 100644 --- a/structure/runtime.md +++ b/structure/runtime.md @@ -477,7 +477,7 @@ and Anthropic image wire handling remain unchanged. Canonical ChatGPT Codex forwarding uses the generated `openai-codex` capability bundle rather than the public `openai` bundle. This matters when the two backends differ: for example, the vendored metadata records `gpt-5.3-codex-spark` as text-only on `openai-codex` while the public OpenAI row lists image input. The native Chat fast path and web-search image verbalization consume the same effective-capability decision. -A routed `visionSidecar.model` must resolve to an explicit destination admitted by the caller scope and the self-fetch credential. The routed Chat wire must permit image input under the same capability predicate as the primary pipeline. Unknown image capability stays permissive after those checks. If a proven text-only main target has no usable sidecar plan, image parts are stripped before the upstream request rather than forwarded raw. `modelInputModalities` is symmetric evidence: `["text","image"]` proves image support while `["text"]` triggers preprocessing. Provider-wide fallback declarations follow the [validated modality contract](config.md#explicit-per-model-capability-declarations); malformed saved values restrict to text before runtime enrichment. Runtime provider hooks such as injected `fetch` functions are preserved without mutation during capability enrichment. +A routed `visionSidecar.model` must resolve to an explicit destination admitted by the caller scope and the self-fetch credential. An admission refusal ends helper selection. When the routed target is unavailable, a native fallback must also satisfy the caller scope for its actual provider instance and effective model. The routed Chat wire must permit image input under the same capability predicate as the primary pipeline. Unknown image capability stays permissive after those checks. If a proven text-only main target has no usable sidecar plan, image parts are stripped before the upstream request rather than forwarded raw. `modelInputModalities` is symmetric evidence: `["text","image"]` proves image support while `["text"]` triggers preprocessing. Provider-wide fallback declarations follow the [validated modality contract](config.md#explicit-per-model-capability-declarations); malformed saved values restrict to text before runtime enrichment. Runtime provider hooks such as injected `fetch` functions are preserved without mutation during capability enrichment. Routed vision helpers retain frozen caller policy and intersect host limits under the [Advisor admission contract](advisor.md#cross-provider-consultation). Regression coverage: `tests/vision/vision-cache.test.ts`, `tests/vision/vision-eligibility.test.ts`, `tests/vision/vision-routed.test.ts`, and `tests/adapters/openai/openai-chat-native-policy.test.ts`. diff --git a/tests/vision/vision-anthropic-instance-sidecar.test.ts b/tests/vision/vision-anthropic-instance-sidecar.test.ts index 6c25f84e7a3..9e989560d68 100644 --- a/tests/vision/vision-anthropic-instance-sidecar.test.ts +++ b/tests/vision/vision-anthropic-instance-sidecar.test.ts @@ -121,3 +121,20 @@ test("vision planner turns an unavailable selected pool into no plan instead of delete fixture.config.visionSidecar.anthropicInstance; expect(vision.planVisionSidecar(fixture.config, target, fixture.model, parsed, undefined, { providerName: "anthropic" })?.anthropicSidecar?.providerName).toBe("anthropic"); }); + +test("vision checks the selected Anthropic instance and effective model", async () => { + const { planVisionSidecar } = await import("../../src/vision"); + const { parseRequest } = await import("../../src/responses/parser"); + const target: OcxProviderConfig = { adapter: "openai-chat", baseUrl: "https://main.test/v1", inputModalities: ["text"] }; + fixture.config.visionSidecar = { backend: "anthropic", anthropicInstance: "anthropic2", model: fixture.model }; + const request = parseRequest({ model: "main/text", input: [{ role: "user", content: [ + { type: "input_image", image_url: "data:image/png;base64,YQ==" }, + ] }] }); + const select = (provider: string, model: string) => planVisionSidecar( + fixture.config, target, "text", request, undefined, + { providerName: "main", admissionScope: { providers: [provider], models: [model] } }, + ); + expect(select("anthropic", fixture.model)).toBeUndefined(); + expect(select("anthropic2", "another-model")).toBeUndefined(); + expect(select("anthropic2", `anthropic2/${fixture.model}`)?.anthropicSidecar?.providerName).toBe("anthropic2"); +}); diff --git a/tests/vision/vision-cache.test.ts b/tests/vision/vision-cache.test.ts index d62610115c9..7d85e313dd6 100644 --- a/tests/vision/vision-cache.test.ts +++ b/tests/vision/vision-cache.test.ts @@ -4,6 +4,7 @@ import * as oauthModule from "../../src/oauth"; mock.module("../../src/oauth", () => ({ ...oauthModule, getValidAccessToken: async () => "vision-cache-token" })); import { parseRequest } from "../../src/responses/parser"; +import { routeAllowedByScope } from "../../src/server/admission-model-scope"; import type { OcxConfig, OcxContentPart, OcxProviderConfig } from "../../src/types"; import { describeImagesInPlace, @@ -138,6 +139,58 @@ test("vision auth and planning agree on a routed describer and its legacy fallba expect(planVisionSidecar(cfg, textOnlyProvider, "text-model", request, plan().forwardSidecar)?.backend).toBe("openai"); }); +test("vision admission distinguishes an unavailable route from a refused route", () => { + const config: OcxConfig = { + port: 10100, defaultProvider: "main", + providers: { main: textOnlyProvider, helper: { adapter: "openai-chat", baseUrl: "https://helper.test/v1" } }, + visionSidecar: { backend: "routed", model: "helper/vision" }, + }; + const request = parsed([{ type: "input_image", image_url: DATA_A }]); + const scope = { providers: ["openai"], models: ["openai/gpt-5.6-luna"] }; + const forward = plan().forwardSidecar; + const resolveAuth = () => shouldResolveOpenAiVisionSidecar(config, textOnlyProvider, "text-model", request, "main", scope); + const makePlan = () => planVisionSidecar(config, textOnlyProvider, "text-model", request, forward, { admissionScope: scope }); + + expect(resolveAuth()).toBe(false); + expect(makePlan()).toBeUndefined(); + delete config.providers.helper; + expect(resolveAuth()).toBe(true); + expect(makePlan()?.settings.model).toBe("gpt-5.6-luna"); + scope.models = ["openai/another-model"]; + expect(resolveAuth()).toBe(false); + expect(makePlan()).toBeUndefined(); + scope.providers = ["main"]; + scope.models = []; + expect(resolveAuth()).toBe(false); + expect(makePlan()).toBeUndefined(); +}); + +test("routed vision honors the host credential and every inherited caller scope", () => { + const config: OcxConfig = { + port: 10100, defaultProvider: "main", + providers: { main: textOnlyProvider, helper: { adapter: "openai-chat", baseUrl: "https://helper.test/v1" } }, + visionSidecar: { backend: "routed", model: "helper/vision" }, + apiKeys: [{ id: "fixture", key: "fixture-secret", name: "Fixture", createdAt: "2026-01-01T00:00:00Z", allowedProviders: ["main"] }], + }; + config.providers.helper!.inputModalities = ["text"]; + const request = parsed([{ type: "input_image", image_url: DATA_A }]); + const forward = plan().forwardSidecar; + expect(shouldResolveOpenAiVisionSidecar(config, textOnlyProvider, "text-model", request)).toBe(false); + expect(planVisionSidecar(config, textOnlyProvider, "text-model", request, forward)).toBeUndefined(); + config.apiKeys![0]!.allowedProviders = ["helper"]; + config.providers.helper!.inputModalities = ["text", "image"]; + const advisorAdmissionPolicy = { + modelScope: { providers: ["main"], models: [] as string[] }, + allowMeteredComboTargets: false, meteredRequiresComboOptIn: false, fallbackPolicies: [], + }; + const options = { admissionScope: { providers: ["helper"], models: ["helper/vision"] }, advisorAdmissionPolicy }; + expect(planVisionSidecar(config, textOnlyProvider, "text-model", request, forward, options)).toBeUndefined(); + advisorAdmissionPolicy.modelScope.providers = ["helper"]; + const permitted = planVisionSidecar(config, textOnlyProvider, "text-model", request, forward, options); + expect(permitted?.backend).toBe("routed"); + expect(routeAllowedByScope(permitted?.advisorAdmissionPolicy?.modelScope, { providerName: "helper", modelId: "other" })).toBe(false); +}); + function parsed(parts: Array>) { return parseRequest({ model: "routed/blind", From eaf317bb0f046ef9c57de0f80e571dcd9a0157f1 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Wed, 25 Nov 2026 14:12:31 +0900 Subject: [PATCH 30/60] perf(m365): reuse parsed tool ranges in completed answers (#9068) * perf(m365): reuse parsed tool ranges in completed answers * fix(m365): check the untrimmed prefix before accepting a tool result * fix(m365): retain notes and line breaks between inline tool calls --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- .../src/content/docs/guides/m365-copilot.md | 2 + src/adapters/m365-copilot.ts | 9 +- src/adapters/m365-copilot/fenced.ts | 78 +++++--- src/adapters/m365-copilot/tools.ts | 171 +++++++++++------- structure/providers/m365-copilot.md | 2 + tests/providers/m365-copilot.test.ts | 151 +++++++++++++++- 6 files changed, 317 insertions(+), 96 deletions(-) diff --git a/docs-site/src/content/docs/guides/m365-copilot.md b/docs-site/src/content/docs/guides/m365-copilot.md index e23d611cc91..9e5e1877dc7 100644 --- a/docs-site/src/content/docs/guides/m365-copilot.md +++ b/docs-site/src/content/docs/guides/m365-copilot.md @@ -41,6 +41,8 @@ m365-copilot/Gpt_61_Sol_Reasoning Text streams and client-executed tools travel through OpenCodex's existing request interfaces. Tool calls are prompt-emulated: the model emits a fenced call, OpenCodex translates it into the client's tool format, and the client executes it under its own permissions. OpenCodex reuses a conversation only for the same Microsoft account, model, authenticated OpenCodex caller, resolved client conversation and tool set. A request without an authenticated caller or resolved conversation starts a fresh ChatHub conversation using the supplied history. Temporary chats keep their live conversation context without adding a persistent Copilot history entry. +OpenCodex reads tool calls from the completed answer. When it returns a named tool call, it preserves surrounding prose, including an identical example inside a documentation fence. + Every ChatHub turn also includes Microsoft's built-in `BingWebSearch` tool in the upstream request. It is sent regardless of whether client tools are enabled, and the model may use web search on its own; OpenCodex does not control that server-side capability. In a failover combo with fallback enabled, a Copilot quota refusal before output commits advances to the next eligible target. Empty thinking placeholders are ignored. The proxy can hold reasoning-only output briefly during preflight. Once reasoning, text or a tool call commits the stream, a subsequent refusal stays with that model. diff --git a/src/adapters/m365-copilot.ts b/src/adapters/m365-copilot.ts index f2c923661ba..f97c066d8b3 100644 --- a/src/adapters/m365-copilot.ts +++ b/src/adapters/m365-copilot.ts @@ -7,7 +7,7 @@ import { M365_COPILOT_BASE_URL } from "../providers/m365-copilot-models"; import { m365CopilotClaims } from "../oauth/m365-copilot"; import { SendBudgetExhaustedError, providerErrorDestinationLabel } from "../lib/upstream-retry"; import { estimateTokens } from "../lib/token-estimate"; -import { formatMessages, formatToolResponse, parseToolCalls, isProseDocument, fabricatedToolResponseAt, truncateAtFabricatedToolResponse, type Message, type ToolDef, type ToolChoice } from "./m365-copilot/tools"; +import { formatMessages, formatToolResponse, parseToolAnswer, type Message, type ToolDef, type ToolChoice } from "./m365-copilot/tools"; import { defaultFramingForModel } from "./m365-copilot/fenced"; import { createM365Conversation, runM365CopilotTurn, m365RequestSocketRoute, M365CopilotTurnError, type M365Conversation, type M365TurnOptions } from "./m365-copilot/transport"; import { m365ImageUrls, uploadM365Images, MAX_IMAGES } from "./m365-copilot/images"; @@ -103,10 +103,9 @@ export function createM365CopilotAdapter(provider: OcxProviderConfig, deps: { tu state.sent = messages.length; state.prefix = digest(JSON.stringify(messages)); state.accessed = Date.now(); state.sentImages = imageUrls.length; state.imagePrefix = digest(JSON.stringify(imageUrls)); if (toolMode) { - if (fabricatedToolResponseAt(answer, tools) >= 0) state.pendingNote = "Only tool calls returned to the client were executed. Any tool output you wrote yourself did not happen; the following is the real client output."; - const cleaned = truncateAtFabricatedToolResponse(answer, tools); - const result = parseToolCalls(cleaned, tools); - if (isProseDocument(result, cleaned, tools)) emit({ type: "text_delta", text: cleaned }); + const { accepted, result, truncated, document } = parseToolAnswer(answer, tools!); + if (truncated) state.pendingNote = "Only tool calls returned to the client were executed. Any tool output you wrote yourself did not happen; the following is the real client output."; + if (document) emit({ type: "text_delta", text: accepted }); else { // Validate every call before emitting anything: a malformed or undeclared call must not leave the client with partial output. const calls = result.toolCalls.map(call => { diff --git a/src/adapters/m365-copilot/fenced.ts b/src/adapters/m365-copilot/fenced.ts index c1ee5836fa3..185dc39c333 100644 --- a/src/adapters/m365-copilot/fenced.ts +++ b/src/adapters/m365-copilot/fenced.ts @@ -291,7 +291,7 @@ interface FenceBlock { start: number; end: number; } -function scanFences(text: string): FenceBlock[] { +function scanFences(text: string, includeBare = false): FenceBlock[] { const blocks: FenceBlock[] = []; let depth = 0; let open: { @@ -299,15 +299,16 @@ function scanFences(text: string): FenceBlock[] { start: number; bodyStart: number; } | null = null; - let offset = 0; - for (const raw of text.split("\n")) { + for (let offset = 0; offset <= text.length;) { + const newline = text.indexOf("\n", offset); + const lineEnd = newline < 0 ? text.length : newline; + const raw = text.slice(offset, lineEnd); const line = raw.endsWith("\r") ? raw.slice(0, -1) : raw; - const lineEnd = offset + raw.length; const opener = FENCE_OPEN.exec(line)?.[1]; if (depth === 0) { const midline = opener ? null : FENCE_OPEN_MIDLINE.exec(line); - if (opener || midline) { - open = { info: opener || midline![1], start: offset + (midline?.index ?? 0), bodyStart: lineEnd + 1 }; + if (opener || midline || (includeBare && opener === "")) { + open = { info: opener || midline?.[1] || "", start: offset + (midline?.index ?? 0), bodyStart: lineEnd + 1 }; depth = 1; } } @@ -669,6 +670,37 @@ function parseFencedInner(spec: FencedToolSpec, inner: string): Record): ToolFence } fences.push(fence); } - return fences; -} -export function parseFencedToolCalls(text: string, specs: Map): FencedParseResult { - const calls: ParsedToolCall[] = []; - let leftover = text; - for (const fence of toolFences(text, specs)) { - calls.push(makeCall(fence.name, fence.args)); - leftover = leftover.replace(text.slice(fence.start, fence.end), ""); - } - if (calls.length === 0) { + if (!fences.length) { const open = findUnclosedToolFence(text, specs); const args = open && parseFencedInner(open.spec, open.inner); - if (open && args) { - calls.push(makeCall(open.spec.name, args)); - leftover = text.slice(0, open.start); - } + if (open && args) fences.push({ start: open.start, end: open.end, name: open.spec.name, args, hadNativeCloser: true }); } - return { calls, leftover }; + return fences; +} +export function parseFencedToolCalls(text: string, specs: Map): FencedParseResult { + const fences = toolFences(text, specs); + const calls = fences.map(fence => makeCall(fence.name, fence.args)); + const documentRanges = fences.length === 2 || fences.length === 3 ? fences.map(({ start, end }) => ({ start, end })) : undefined; + return { calls, leftover: proseOutsideFences(text, fences), firstStart: fences[0]?.start, documentRanges }; +} +export function findToolFenceRanges(text: string, specs: Map): FenceRange[] { + return toolFences(text, specs).map(({ start, end }) => ({ start, end })); } export function findFirstToolFence(text: string, specs: Map): { start: number; end: number; } | null { const first = toolFences(text, specs)[0]; - if (first) - return { start: first.start, end: first.end }; - const open = findUnclosedToolFence(text, specs); - if (open && parseFencedInner(open.spec, open.inner)) - return { start: open.start, end: open.end }; - return null; + return first ? { start: first.start, end: first.end } : null; } diff --git a/src/adapters/m365-copilot/tools.ts b/src/adapters/m365-copilot/tools.ts index 2dd7c36dc80..de2e0cfc428 100644 --- a/src/adapters/m365-copilot/tools.ts +++ b/src/adapters/m365-copilot/tools.ts @@ -1,5 +1,5 @@ // Adapted from cramt/m365-copilot-proxy (65905e8), copyright 2026 Alexandra Østermark. MIT; see LICENSE. -import { buildSpecMap, currentFramingVariant, deriveFencedSpec, findFirstToolFence, formatFencedToolDefinitions, parseFencedToolCalls, renderFencedCall, transcriptStyleForVariant, } from "./fenced"; +import { buildSpecMap, currentFramingVariant, deriveFencedSpec, findToolFenceRanges, formatFencedToolDefinitions, parseFencedToolCalls, unwrapToolReplyFences, renderFencedCall, transcriptStyleForVariant, type FenceRange } from "./fenced"; export interface ToolFunction { name: string; description?: string; @@ -41,8 +41,39 @@ export type ToolChoice = "auto" | "none" | "required" | { name: string; }; } | undefined; -const TOOL_CALL_REGEX = /\{\s*"tool"\s*:\s*"[^"]+"\s*,\s*"arguments"\s*:\s*\{[\s\S]*?\}\s*\}/g; -const FENCED_TOOL_CALL_REGEX = /```tool_call\s*\n(\{[\s\S]*?\})\s*\n\s*```/g; +interface JsonEnvelope { start: number; end: number; valueStart: number; valueEnd: number } + +/** Keep the original inline and fenced grammars. Advance both boundaries once per envelope. */ +function jsonToolEnvelopes(text: string, fenced: boolean): JsonEnvelope[] { + const opener = fenced ? /```tool_call\s*\n(?=\{)/g : /\{\s*"tool"\s*:\s*"[^"]+"\s*,\s*"arguments"\s*:\s*\{/g; + const closer = fenced ? /\}[^\S\n]*\n\s*```/g : /\}\s*\}/g; + const ranges: JsonEnvelope[] = []; + let opening: RegExpExecArray | null; + while ((opening = opener.exec(text)) !== null) { + closer.lastIndex = opener.lastIndex; + const closing = closer.exec(text); + if (!closing) break; + ranges.push({ start: opening.index, end: closer.lastIndex, valueStart: fenced ? opener.lastIndex : opening.index, + valueEnd: fenced ? closing.index + 1 : closer.lastIndex }); + opener.lastIndex = closer.lastIndex; + } + return ranges; +} + +function proseOutsideEnvelopes(text: string, inline: JsonEnvelope[], fenced: JsonEnvelope[]): string { + if (!inline.length && !fenced.length) return text; + const prose: string[] = []; + let cursor = 0, i = 0, j = 0; + // An inline envelope can be inside a JSON fence. Both ranges refer to the original answer. + while (i < inline.length || j < fenced.length) { + const takeInline = j === fenced.length || (i < inline.length && inline[i]!.start < fenced[j]!.start); + const next = takeInline ? inline[i++]! : fenced[j++]!; + if (next.start > cursor) prose.push(text.slice(cursor, next.start)); + cursor = Math.max(cursor, next.end); + } + prose.push(text.slice(cursor)); + return prose.join(""); +} const CONFIDENCE_REGEX = /\{\s*"confidence"\s*:\s*-?[0-9.]+\s*\}/g; const FINAL_OBJECT_REGEX = /\{\s*"final"\s*:\s*"(?:[^"\\]|\\.)*"\s*\}/g; function cleanLooseText(text: string): string | null { @@ -180,51 +211,90 @@ export interface ParseResult { textContent: string | null; } const SELF_WRITTEN_RESULT = / 0 ? parseToolCalls(head, tools).hasToolCalls : ANY_FENCE.test(head); - return acted ? i : -1; + return precedingToolCall(text, tools?.length ? buildSpecMap(tools) : null)?.index ?? -1; +} +type ToolSpecs = ReturnType | null; +interface ToolInspection { result: ParseResult; firstFenceStart?: number; inline?: JsonEnvelope[]; documentRanges?: FenceRange[] } + +function precedingToolCall(text: string, specs: ToolSpecs) { + const index = text.search(SELF_WRITTEN_RESULT); + if (index < 0) return; + const raw = text.slice(0, index); + if (specs) { + const inspection = inspectToolCalls(raw, specs); + if (!inspection.result.hasToolCalls) return; + const head = raw.trimEnd(); + // The original prefix establishes eligibility. Only reuse ranges for the exact delivery text. + return { index, head, inspection: head.length === raw.length ? inspection : undefined }; + } + const open = ANY_FENCE_OPEN.exec(raw); + if (open && raw.indexOf("```", open.index + open[0].length) >= 0) return { index, head: raw.trimEnd(), inspection: undefined }; +} + +/** Classify the same source ranges that supplied the accepted calls. */ +export function parseToolAnswer(text: string, tools: ToolDef[]) { + const specs = buildSpecMap(tools); + const prefix = precedingToolCall(text, specs); + const accepted = prefix?.head ?? text; + const inspection = prefix?.inspection ?? inspectToolCalls(accepted, specs); + return { accepted, result: inspection.result, truncated: prefix !== undefined, document: proseDocument(inspection, accepted) }; } export function isProseDocument(parsed: ParseResult, text?: string, tools?: ToolDef[]): boolean { if (!parsed.hasToolCalls || parsed.toolCalls.length < 2) return false; - if (text !== undefined && tools && tools.length > 0) { - const first = findFirstToolFence(text, buildSpecMap(tools)); - if (first && !looksLikeDocumentPreamble(text.slice(0, first.start))) - return false; + const documentRanges = text !== undefined && tools?.length ? findToolFenceRanges(text, buildSpecMap(tools)) : undefined; + const inline = !documentRanges?.length && text !== undefined && parsed.toolCalls.length < 4 ? jsonToolEnvelopes(text, false) : undefined; + return proseDocument({ result: parsed, firstFenceStart: documentRanges?.[0]?.start, inline, documentRanges }, text); +} +function proseDocument({ result: parsed, firstFenceStart, inline, documentRanges }: ToolInspection, text?: string): boolean { + if (parsed.toolCalls.length < 2) return false; + if (text !== undefined && firstFenceStart !== undefined && !looksLikeDocumentPreamble(text.slice(0, firstFenceStart))) return false; + if (parsed.toolCalls.length >= 4) return true; + // Only two or three calls depend on the exact heading and length of the old prose. + // Preserve that decision without reparsing calls, their arguments or IDs. + let prose = parsed.textContent?.trim() ?? ""; + if (text !== undefined && (documentRanges?.length === 2 || documentRanges?.length === 3)) { + // Each original fence was removed at its first text match, which may have been in a document. + let legacy = text; + for (const range of documentRanges) legacy = legacy.replace(text.slice(range.start, range.end), ""); + prose = cleanLooseText(legacy) ?? ""; + } else if (text !== undefined && inline) { + // JSON cleanup removed inline envelopes first, then fenced envelopes from the remaining text. + const afterInline = proseOutsideEnvelopes(text, inline, []); + const fenced = afterInline.includes("```tool_call") ? jsonToolEnvelopes(afterInline, true) : []; + prose = proseOutsideEnvelopes(afterInline, [], fenced) + .replace(CONFIDENCE_REGEX, "").replace(FINAL_OBJECT_REGEX, "") + .replace(/```(?:json|tool_call)?\s*```/g, "").replace(/```(?:json|tool_call)?/g, "").trim(); } - const prose = parsed.textContent ? parsed.textContent.trim() : ""; - const hasMarkdownHeaders = /^#{1,6}\s/m.test(prose); - return parsed.toolCalls.length >= 4 || hasMarkdownHeaders || prose.length >= 300; + return /^#{1,6}\s/m.test(prose) || prose.length >= 300; } function looksLikeDocumentPreamble(preamble: string): boolean { return /^#{1,6}\s/m.test(preamble) || preamble.includes("```") || preamble.trim().length >= 200; } export function parseToolCalls(text: string, tools?: ToolDef[]): ParseResult { - const specMap = tools && tools.length > 0 ? buildSpecMap(tools) : null; + return inspectToolCalls(text, tools?.length ? buildSpecMap(tools) : null).result; +} +function inspectToolCalls(text: string, specMap: ToolSpecs): ToolInspection { if (specMap) { - const { calls, leftover } = parseFencedToolCalls(text, specMap); + const { calls, leftover, firstStart, documentRanges } = parseFencedToolCalls(text, specMap); if (calls.length > 0) { - return { hasToolCalls: true, toolCalls: calls, textContent: cleanLooseText(leftover) }; + return { firstFenceStart: firstStart, documentRanges, result: { hasToolCalls: true, toolCalls: calls, textContent: cleanLooseText(leftover) } }; } } const resolveName = (raw: unknown): string | undefined => typeof raw === "string" ? (specMap?.get(raw)?.name ?? raw) : undefined; const toolCalls: ParsedToolCall[] = []; - const jsonRegex = new RegExp(TOOL_CALL_REGEX.source, "g"); - let match: RegExpExecArray | null; - while ((match = jsonRegex.exec(text)) !== null) { + function readCall(range: JsonEnvelope, fenced: boolean, emit: boolean): boolean { try { - const parsed = JSON.parse(match[0]); - const name = resolveName(parsed.tool); - if (name) { + const parsed = JSON.parse(text.slice(range.valueStart, range.valueEnd)); + const name = resolveName(fenced ? parsed.tool || parsed.name : parsed.tool); + if (!name) return false; + if (emit) { toolCalls.push({ id: `call_${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`, type: "function", @@ -236,49 +306,24 @@ export function parseToolCalls(text: string, tools?: ToolDef[]): ParseResult { }, }); } + return true; } catch { - continue; - } - } - if (toolCalls.length === 0) { - const fencedRegex = new RegExp(FENCED_TOOL_CALL_REGEX.source, "g"); - while ((match = fencedRegex.exec(text)) !== null) { - try { - const parsed = JSON.parse(match[1]); - const name = resolveName(parsed.tool || parsed.name); - if (name) { - toolCalls.push({ - id: `call_${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`, - type: "function", - function: { - name, - arguments: typeof parsed.arguments === "string" - ? parsed.arguments - : JSON.stringify(parsed.arguments ?? {}), - }, - }); - } - } - catch { - continue; - } + return false; } } - if (toolCalls.length === 0) { - return { hasToolCalls: false, toolCalls: [], textContent: cleanLooseText(text) }; - } - let remaining = text - .replace(jsonRegex, "") - .replace(new RegExp(FENCED_TOOL_CALL_REGEX.source, "g"), "") + const inline = jsonToolEnvelopes(text, false); + const acceptedInline = inline.filter(range => readCall(range, false, true)); + const useFenced = acceptedInline.length === 0; + const acceptedFenced = jsonToolEnvelopes(text, true).filter(range => readCall(range, true, useFenced)); + if (!toolCalls.length) return { result: { hasToolCalls: false, toolCalls: [], textContent: cleanLooseText(text) } }; + const remaining = unwrapToolReplyFences(proseOutsideEnvelopes(text, acceptedInline, acceptedFenced) .replace(CONFIDENCE_REGEX, "") - .replace(FINAL_OBJECT_REGEX, "") - .replace(/```(?:json|tool_call)?\s*```/g, "") - .replace(/```(?:json|tool_call)?/g, "") - .trim(); - return { + .replace(FINAL_OBJECT_REGEX, "")).trim(); + const documentInline = acceptedInline.length !== inline.length || text.includes("`") ? inline : undefined; + return { inline: documentInline, result: { hasToolCalls: true, toolCalls, textContent: remaining || null, - }; + } }; } diff --git a/structure/providers/m365-copilot.md b/structure/providers/m365-copilot.md index 6a8331a70b6..a99b4ba7ef1 100644 --- a/structure/providers/m365-copilot.md +++ b/structure/providers/m365-copilot.md @@ -23,6 +23,8 @@ The transport validates and bounds SignalR frames, assembles text per bot messag `src/adapters/m365-copilot/fenced.ts` and `src/adapters/m365-copilot/tools.ts` retain only the selected MIT tool grammar and baseline/relay/relay-batch framing. Tool names must belong to the declared catalog, custom/namespace identities are restored, and client results continue the same eligible conversation. Request history that is not an extension starts a fresh conversation. Copilot-generated speculative tool output is not treated as a real client result. The client retains execution ownership. The source notice is in `src/adapters/m365-copilot/LICENSE`. +The adapter classifies tool calls after the ChatHub turn completes. Document classification and client delivery share the accepted parse. The display removes recognized calls by their source ranges. A `tool_call` wrapper can contain multiple inline calls and prose; the prose remains in the response. + `tests/providers/m365-copilot-security.test.ts` checks retargeted OAuth rows and runtime wire pins, and exercises Bun's real WebSocket constructor against a refusing loopback proxy while asserting that the loopback destination receives no direct connection. Both plain and TLS WebSocket attempts use HTTP CONNECT. Explicit and inherited SOCKS routes fail with a configuration error before dialing; the ChatHub socket supports HTTP(S) proxies only. `tests/providers/m365-copilot-executor.test.ts` checks adapter-level request-executor refusal with zero destination connections and zero upload-admission calls. It also exercises successful native turns with no executor and with the built-in request executor, rejects HTTP-only or mismatched authority, and checks the captured route and bypass list. diff --git a/tests/providers/m365-copilot.test.ts b/tests/providers/m365-copilot.test.ts index 05802853981..552975ff9ba 100644 --- a/tests/providers/m365-copilot.test.ts +++ b/tests/providers/m365-copilot.test.ts @@ -11,7 +11,7 @@ import { getProviderRegistryEntry } from "../../src/providers/registry"; import { deriveProviderPresets } from "../../src/providers/derive"; import { isPublicOAuthProvider } from "../../src/oauth"; import { providerSupportsLiveModelDiscovery } from "../../src/providers/static-model-discovery"; -import { parseToolCalls } from "../../src/adapters/m365-copilot/tools"; +import { parseToolAnswer, parseToolCalls } from "../../src/adapters/m365-copilot/tools"; import { createTranslatorBudget } from "../../src/lib/translator-budget"; import type { AdapterEvent, OcxParsedRequest } from "../../src/types"; @@ -156,6 +156,143 @@ describe("Microsoft 365 Copilot registration and authentication", () => { }); describe("Microsoft 365 Copilot native transport", () => { + const fixtureTools = [{ function: { name: "lookup", parameters: { properties: { query: { type: "string" } } } } }]; + const block = (name: string, body: string) => ["```" + name, body, "```"].join("\n"); + + test("reuses the call IDs when the result marker follows the exact delivery text", () => { + const text = [block("lookup", "one"), block("lookup", "two")].join("\n"); + const ids = spyOn(crypto, "randomUUID"); + try { + const answer = parseToolAnswer(text + "example", fixtureTools); + expect(answer).toMatchObject({ accepted: text, document: false, truncated: true }); + expect(answer.result.toolCalls.map(call => JSON.parse(call.function.arguments))).toEqual([{ query: "one" }, { query: "two" }]); + expect(new Set(answer.result.toolCalls.map(call => call.id)).size).toBe(2); + expect(ids).toHaveBeenCalledTimes(2); + } finally { ids.mockRestore(); } + }); + + test("checks the original prefix before trimming text for delivery", () => { + const first = block("lookup", "one"), second = block("lookup", "two"); + const marker = "example"; + const prose = first + "\u00a0" + marker; + const untouched = parseToolAnswer(prose, fixtureTools); + expect(untouched).toMatchObject({ accepted: prose, truncated: false }); + expect(untouched.result.toolCalls).toHaveLength(0); + + const accepted = first + "\n" + second; + const both = parseToolAnswer(accepted + "\u00a0" + marker, fixtureTools); + expect(both).toMatchObject({ accepted, truncated: true }); + expect(both.result.toolCalls.map(call => JSON.parse(call.function.arguments))).toEqual([{ query: "one" }, { query: "two" }]); + }); + + test("keeps an identical tool example nested in a document fence", () => { + const call = block("lookup", "sample"); + const example = block("markdown", call); + const answer = parseToolAnswer([example, "Then", call].join("\n"), fixtureTools); + expect(answer.result.toolCalls).toHaveLength(1); + expect(answer.result.textContent).toBe(example + "\nThen"); + const document = ["# Examples", call, call].join("\r\n"); + expect(parseToolAnswer(document, fixtureTools)).toMatchObject({ accepted: document, document: true, truncated: false }); + }); + + test("preserves nested JSON in fenced calls and inline call precedence", () => { + const args = { fields: [{ label: "one", tags: ["a"] }], text: "two" }; + const fence = block("tool_call", JSON.stringify({ name: "lookup", arguments: args })); + const fenced = parseToolAnswer(fence, fixtureTools); + expect(JSON.parse(fenced.result.toolCalls[0]!.function.arguments)).toEqual(args); + const toolFence = block("tool_call", JSON.stringify({ tool: "lookup", arguments: { field: { key: "blue" } } })); + const nested = parseToolAnswer(["Before", toolFence, "After"].join("\n"), fixtureTools); + expect(nested.result.textContent).toBe("Before\n\nAfter"); + expect(JSON.parse(nested.result.toolCalls[0]!.function.arguments)).toEqual({ field: { key: "blue" } }); + const inline = JSON.stringify({ tool: "lookup", arguments: { query: "inline" } }); + const mixed = parseToolAnswer([inline, toolFence, fence].join("\n"), fixtureTools); + expect(mixed.result.toolCalls.map(call => JSON.parse(call.function.arguments))).toEqual([{ query: "inline" }]); + expect(mixed.result.textContent).toBeNull(); + const documentation = block("sql", "SELECT 1"); + expect(parseToolAnswer([documentation, block("json", inline)].join("\n"), fixtureTools).result.textContent).toBe(documentation); + }); + + test("retains YAML header values and separates repeated named fences by source position", () => { + const tools = [{ function: { name: "lookup", parameters: { properties: { options: { type: "object" }, label: { type: "string" } } } } }]; + const fence = block("lookup", "options:\n tags:\n - blue\n - green\nlabel: summary"); + const answer = parseToolAnswer([fence, "Next", fence].join("\n"), tools); + expect(answer.document).toBe(false); + expect(answer.result.textContent).toBe("Next"); + expect(answer.result.toolCalls.map(call => JSON.parse(call.function.arguments))).toEqual( + Array(2).fill({ options: { tags: ["blue", "green"] }, label: "summary" }), + ); + }); + + test("keeps notes inside a tool_call wrapper without emitting the wrapper as a call", () => { + const call = (query: string) => JSON.stringify({ tool: "lookup", arguments: { query } }); + const one = call("one"), two = call("two"); + for (const [body, expected] of [ + [[one, "Keep this note.", two].join("\n"), "Keep this note."], + [["Opening note.", one, two, "Closing note."].join("\r\n"), "Opening note.\r\n\r\n\r\nClosing note."], + ] as const) { + const answer = parseToolAnswer(block("tool_call", body), fixtureTools); + expect(answer.result.toolCalls.map(tool => JSON.parse(tool.function.arguments).query)).toEqual(["one", "two"]); + expect(answer.result.textContent).toBe(expected); + expect(answer.document).toBe(false); + } + }); + + test("preserves unaccepted JSON text alongside real calls without changing eligibility", () => { + const call = JSON.stringify({ tool: "lookup", arguments: { query: "one" } }); + const example = '{"tool":"lookup","arguments":{"query":"' + "a".repeat(300) + '",}}'; + const answer = parseToolAnswer([call, example, call].join("\n"), fixtureTools); + expect(answer.result.textContent).toBe(example); + expect(answer.result.toolCalls).toHaveLength(2); + expect(answer.document).toBe(false); + const note = '{"memo":"Keep this note."}'; + expect(parseToolAnswer([call, block("tool_call", note)].join("\n"), fixtureTools).result.textContent).toBe(note); + }); + + test("stripping a mixed tool_call wrapper keeps its line endings and indentation", () => { + const call = JSON.stringify({ tool: "lookup", arguments: { query: "one" } }); + for (const eol of ["\n", "\r\n"]) { + const answer = ["Before", " ```tool_call ", call, " Keep the note.", call, " ``` ", "After"].join(eol); + const expected = ["Before", " ", "", " Keep the note.", "", " ", "After"].join(eol); + expect(parseToolAnswer(answer, fixtureTools).result.textContent).toBe(expected); + } + }); + + test("JSON call eligibility keeps its document threshold when Markdown display changes", () => { + const call = JSON.stringify({ tool: "lookup", arguments: { query: "one" } }); + const prose = "a".repeat(289) + "\n" + block("sql", "q"); + const actionable = parseToolAnswer([prose, call, call].join("\n"), fixtureTools); + expect(actionable.result.textContent).toBe(prose); + expect(prose.length).toBeGreaterThanOrEqual(300); + expect(actionable.document).toBe(false); + + const intro = "a".repeat(299); + const example = block("tool_call", JSON.stringify({ tool: "lookup", arguments: { options: { label: "blue" } } })); + const document = parseToolAnswer([intro, call, call, example].join("\n"), fixtureTools); + expect(document.result.textContent).toBe(intro); + expect(document.document).toBe(true); + }); + + test("a named fence repeated in documentation keeps the original document decision", () => { + const first = block("lookup", "one"); + const example = block("markdown", first); + const document = [example, "a".repeat(265), first, block("lookup", "two")].join("\n"); + const answer = parseToolAnswer(document, fixtureTools); + expect(answer.result.textContent).toBe(example + "\n" + "a".repeat(265)); + expect(answer.result.textContent?.length).toBe(299); + expect(answer.document).toBe(true); + const headingExample = ["```markdown", first + "# Notes", "```", "```", first, block("lookup", "two")].join("\n"); + const heading = parseToolAnswer(headingExample, fixtureTools); + expect(heading.result.toolCalls).toHaveLength(2); + expect(heading.result.textContent).not.toMatch(/^#{1,6}\s/m); + expect(heading.document).toBe(true); + }); + + test("a result marker in plain prose does not truncate a later call", () => { + const answer = parseToolAnswer("About formatting\n" + block("lookup", "test"), fixtureTools); + expect(answer.truncated).toBe(false); + expect(answer.result.textContent).toBe("About formatting"); + }); + test("invalid tool JSON remains text instead of becoming a client execution", () => { const malformed = '{"tool":"read_file","arguments":invalid}'; const result = parseToolCalls(malformed); @@ -294,6 +431,18 @@ describe("Microsoft 365 Copilot adapter", () => { expect(events.find(event => event.type === "error")).toMatchObject({ type: "error", message: "Microsoft 365 Copilot returned invalid tool arguments" }); } finally { budget.dispose(); } }); + test("an undeclared second call prevents all client output in the batch", async () => { + const answer = ["Notes", JSON.stringify({ tool: "read_file", arguments: { path: "sample.txt" } }), + JSON.stringify({ tool: "other", arguments: {} })].join("\n"); + const adapter = createM365CopilotAdapter(provider(), { turn: async () => answer }); + const events: AdapterEvent[] = []; + const budget = createTranslatorBudget(); + try { + await adapter.runTurn!(request(), { headers: new Headers(), translatorBudget: budget }, event => events.push(event)); + expect(events.some(event => event.type === "text_delta" || event.type === "tool_call_start")).toBe(false); + expect(events.find(event => event.type === "error")).toMatchObject({ message: "Microsoft 365 Copilot returned an undeclared tool" }); + } finally { budget.dispose(); } + }); test("isolates a shared conversation prefix by authenticated caller and resolved conversation", async () => { const ids: string[] = []; const adapter = createM365CopilotAdapter(provider(), { turn: async options => { From 414faafffc5b7ce0b4d02e2d4e17aec5bead8dc7 Mon Sep 17 00:00:00 2001 From: Enes Kartal <43950508+EnesKartal@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:16:11 +0300 Subject: [PATCH 31/60] fix(google): sanitize Claude Code 429 trigger phrases for gemini-4-neon (#9081) * fix(google): sanitize Claude Code 429 trigger phrases for gemini-4-neon * Cover and document Google Claude prompt filtering * docs: explain Antigravity Gemini prompt rewrites * test(google): assert full Claude Code trigger rewrites; document exact-paragraph opener removal --------- Co-authored-by: JUN Co-authored-by: lidge-jun --- .../src/content/docs/reference/adapters.md | 5 +++ src/adapters/google.ts | 36 ++++++++++++++----- structure/providers/google.md | 11 ++++++ tests/adapters/google/google-adapter.test.ts | 27 ++++++++++++++ 4 files changed, 71 insertions(+), 8 deletions(-) diff --git a/docs-site/src/content/docs/reference/adapters.md b/docs-site/src/content/docs/reference/adapters.md index 3c097545e45..5753c85936d 100644 --- a/docs-site/src/content/docs/reference/adapters.md +++ b/docs-site/src/content/docs/reference/adapters.md @@ -545,6 +545,11 @@ Use `liveModels: false` for a static catalog; Settings can switch between the tw multi-regions, and `-aiplatform.googleapis.com` for a region such as `us-central1`. - Vertex AI and Antigravity retry a `429` only when the response carries retry evidence, such as a valid `Retry-After` header, and surface hard quota exhaustion immediately. +- For Cloud Code Assist requests routed to `gemini-3.7-flash`, `gemini-3.8-flash`, or + `gemini-4-neon`, the proxy removes the three Claude Code / Claude Agent SDK identity-opener + paragraphs when each stands alone as its own paragraph (an opener that shares a paragraph with + other text stays in the prompt), and rewords two trigger sentences in the system prompt. These + generations otherwise respond with `429 RESOURCE_EXHAUSTED` to those phrases. - The shared tool-catalog guidance uses wording verified with Antigravity Gemini 3.8 Flash to avoid a prompt-triggered `429 RESOURCE_EXHAUSTED`. The available tools, argument constraints, and Codex code-mode helper rules stay the same. This does not suppress real quota errors. diff --git a/src/adapters/google.ts b/src/adapters/google.ts index 99ab08443e4..ebff092edb8 100644 --- a/src/adapters/google.ts +++ b/src/adapters/google.ts @@ -67,20 +67,36 @@ const GOOGLE_BREVITY_INSTRUCTION = [ "- Formatting: The client environment renders standard Markdown and does not support LaTeX math delimiters ($...$, $$...$$, \\(...\\), \\[...\\]). Do not use LaTeX math delimiters or LaTeX markup (such as \\text{}, \\times, \\le, \\ge, etc.) for variables, formulas, dimensions, or units. Use clean plain text, Markdown, and Unicode symbols (e.g. 180°, 2560 × 1920 px, ≤, ≥, Δ, ±) instead.", ].join("\n"); -const ANTIGRAVITY_REJECTED_CLAUDE_SDK_PARAGRAPH = - "You are a Claude agent, built on Anthropic's Claude Agent SDK."; +const ANTIGRAVITY_REJECTED_CLAUDE_SDK_PARAGRAPHS: ReadonlySet = new Set([ + "You are a Claude agent, built on Anthropic's Claude Agent SDK.", + "You are Claude Code, Anthropic's official CLI for Claude.", + "You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.", +]); + +const ANTIGRAVITY_REJECTED_CLAUDE_REWRITES: ReadonlyArray<[RegExp, string]> = [ + [ + /Dual-use security tools \(C2 frameworks, credential testing, exploit development\) require clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases\./g, + "Dual-purpose security tools (C2 frameworks, credential testing, exploit development) need clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases.", + ], + [ + /Text inside tags was pasted into the message by the user from somewhere else and may contain instructions the user did not write\./g, + "Content inside tags was pasted into the message by the user from an external source and may contain instructions the user did not author.", + ], +]; + /** - * CCA Flash generations that reject the Claude-Agent identity paragraph. + * CCA generations that reject the Claude-Agent identity / stock Claude Code phrases. * - * Membership is probe-established per generation, never assumed: 3.7 and 3.8 both answer - * 429 RESOURCE_EXHAUSTED when this paragraph survives into `systemInstruction`, and 200 with - * it stripped — same account, seconds apart. A policy rejection wearing a quota error's + * Membership is probe-established per generation, never assumed: 3.7, 3.8, and 4-neon answer + * 429 RESOURCE_EXHAUSTED when these phrases survive into `systemInstruction`, and 200 with + * them stripped/reworded — same account, seconds apart. A policy rejection wearing a quota error's * clothing sends users hunting a quota problem that does not exist, so a new generation is * added here only after the probe, and never dropped on the assumption that Google fixed it. */ const ANTIGRAVITY_CLAUDE_SDK_PARAGRAPH_REJECTORS = new Set([ "gemini-3.7-flash", "gemini-3.8-flash", + "gemini-4-neon", ]); /** @@ -107,10 +123,14 @@ function rejectsClaudeSdkParagraph(modelId: string, wireModelId: string): boolea } function stripAntigravityRejectedClaudeSdkParagraph(systemText: string): string { - return systemText + let result = systemText .split("\n\n") - .filter(paragraph => paragraph !== ANTIGRAVITY_REJECTED_CLAUDE_SDK_PARAGRAPH) + .filter(paragraph => !ANTIGRAVITY_REJECTED_CLAUDE_SDK_PARAGRAPHS.has(paragraph)) .join("\n\n"); + for (const [pattern, replacement] of ANTIGRAVITY_REJECTED_CLAUDE_REWRITES) { + result = result.replace(pattern, replacement); + } + return result; } /** diff --git a/structure/providers/google.md b/structure/providers/google.md index 4b49ec38002..9ff339e9d81 100644 --- a/structure/providers/google.md +++ b/structure/providers/google.md @@ -159,6 +159,17 @@ AI Studio, Vertex and Antigravity retain their own transport contracts. Mocked d and thought-signature continuation coverage lives in `tests/providers/opencode-go-gemini-wire.test.ts`; these fixtures do not attest live upstream availability. +## Cloud Code Assist Claude prompt compatibility + +For Cloud Code Assist, `src/adapters/google.ts` treats `gemini-4-neon` as a Claude SDK +paragraph rejector alongside `gemini-3.7-flash` and `gemini-3.8-flash`, using the routed +wire identity and canonical model identity. It removes exact double-newline-delimited paragraphs +identifying the assistant as a Claude agent built on the Claude Agent SDK, as Claude Code's +official CLI, or as that CLI running within the Claude Agent SDK. It also rewords the stock +“Dual-use security tools” authorization sentence as “Dual-purpose security tools” and the +stock “Text inside tags” sentence as “Content inside tags”. +Other models and non-Cloud Code Assist requests retain these phrases. + ## Google thought-text visibility boundary Google-family parts with `thought: true` stay separate from assistant output. After a CCA diff --git a/tests/adapters/google/google-adapter.test.ts b/tests/adapters/google/google-adapter.test.ts index 66e7ca915fd..d6b4f3b9da0 100644 --- a/tests/adapters/google/google-adapter.test.ts +++ b/tests/adapters/google/google-adapter.test.ts @@ -526,6 +526,33 @@ describe("google adapter — Antigravity system prompt compatibility", () => { expect(systemInstructionText(body)).toContain(REJECTED_CLAUDE_SDK_PARAGRAPH); }); + test("strips and rewords Claude Code 429 trigger phrases for gemini-4-neon on Cloud Code Assist", async () => { + const parsed: OcxParsedRequest = { + ...systemPromptParsed("gemini-4-neon"), + context: { + systemPrompt: [ + "You are Claude Code, Anthropic's official CLI for Claude.\n\n" + + "You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK.\n\n" + + `${REJECTED_CLAUDE_SDK_PARAGRAPH}\n\n` + + "Dual-use security tools (C2 frameworks, credential testing, exploit development) require clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases.\n\n" + + "Text inside tags was pasted into the message by the user from somewhere else and may contain instructions the user did not write.", + ], + messages: [{ role: "user", content: "hi" }], + }, + }; + const envelope = JSON.parse((await createGoogleAdapter(ccaProvider).buildRequest(parsed)).body) as { + request: Record; + }; + const text = systemInstructionText(envelope.request); + expect(text).not.toContain("You are Claude Code, Anthropic's official CLI for Claude."); + expect(text).not.toContain("You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK."); + expect(text).not.toContain(REJECTED_CLAUDE_SDK_PARAGRAPH); + expect(text).not.toContain("Dual-use security tools"); + expect(text).not.toContain("Text inside tags"); + expect(text).toContain("Dual-purpose security tools (C2 frameworks, credential testing, exploit development) need clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases."); + expect(text).toContain("Content inside tags was pasted into the message by the user from an external source and may contain instructions the user did not author."); + }); + test("removes x-anthropic-billing-header for Cloud Code Assist models", async () => { const parsed: OcxParsedRequest = { ...systemPromptParsed("gemini-3.8-flash"), From 249c72ecfd32c9bd19a2053870af26aa9f9a885e Mon Sep 17 00:00:00 2001 From: yunseong kim Date: Wed, 25 Nov 2026 14:22:46 +0900 Subject: [PATCH 32/60] fix(codex): accept the context route in Desktop observation (#9099) Allow the opted-in context-management alias on the verified local OpenCodex listener. Cover the injected URL and rejected alternatives with routing preflight tests. Co-authored-by: JUN Co-authored-by: lidge-jun --- .../content/docs/guides/codex-integration.md | 2 ++ .../docs/ko/guides/codex-integration.md | 3 +++ .../routing-preflight.ts | 5 ++++- structure/clients/codex-desktop.md | 1 + .../desktop-compatibility-routing.test.ts | 21 +++++++++++++++++++ 5 files changed, 31 insertions(+), 1 deletion(-) diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md index c3f8cd44ed5..47eec96a7b0 100644 --- a/docs-site/src/content/docs/guides/codex-integration.md +++ b/docs-site/src/content/docs/guides/codex-integration.md @@ -1224,6 +1224,8 @@ Certificates are restricted to TLS server authentication. If status shows `renew stop the service and close Codex, then renew the older certificate before starting again. The native API URL must match the proxy's actual listener address and port. IPv4 and IPv6 loopback addresses are not interchangeable here; ambiguous `localhost` aliases are refused. +When experimental context management is enabled, the managed `/backend-api/codex` base path +also qualifies on that listener. Codex's automatic MCP connection refresh and configuration formatting do not invalidate observation. Model, authentication, profile and routing changes still require a fresh observation context; the service does not silently adopt those changes during a trial. diff --git a/docs-site/src/content/docs/ko/guides/codex-integration.md b/docs-site/src/content/docs/ko/guides/codex-integration.md index 3cfa116ec0b..9571420e8ad 100644 --- a/docs-site/src/content/docs/ko/guides/codex-integration.md +++ b/docs-site/src/content/docs/ko/guides/codex-integration.md @@ -77,6 +77,9 @@ context_management.experimental_mode = true 시작하세요. 이 기능은 명시적으로 켜야 하며, 사용자 소유 URL과 원격 사용자 지정 provider 주입은 변경하지 않습니다. 컨텍스트 창이나 압축 한도를 덮어쓰지 않습니다. +Windows 데스크톱 호환의 관찰 모드는 이 경로가 현재 OpenCodex 프록시의 주소와 포트를 +가리키면 실험적 컨텍스트 관리를 켠 상태에서도 시작할 수 있습니다. + 이 backend 접두사는 Responses WebSocket 업그레이드를 포함한 기존 데이터 경로의 별칭입니다. 원래 `/v1` 경로와 realtime sideband 오버라이드도 유지됩니다. 열 개의 네이티브 `alpha/history/v2/*`, `alpha/notes/v2/*` POST 엔드포인트는 `openai-responses` 어댑터와 정식 diff --git a/src/codex/desktop-compatibility/routing-preflight.ts b/src/codex/desktop-compatibility/routing-preflight.ts index 97b66a54fb2..5a588df9750 100644 --- a/src/codex/desktop-compatibility/routing-preflight.ts +++ b/src/codex/desktop-compatibility/routing-preflight.ts @@ -2,6 +2,7 @@ import { lstatSync, readFileSync } from "node:fs"; import { createHash } from "node:crypto"; import { join } from "node:path"; import type { OcxConfig } from "../../types"; +import { CONTEXT_BACKEND_PREFIX, contextExperimentalEnabled } from "../context-compat"; import { nativeCompatibilityOwner, type NativeCompatibilityOwner } from "./routing-binding"; const record = (value: unknown): value is Record => !!value && typeof value === "object" && !Array.isArray(value); @@ -39,7 +40,9 @@ export function matchesNativeCompatibilityRouting(text: string, owner: NativeCom if (typeof effective.openai_base_url !== "string") return false; const url = new URL(effective.openai_base_url); if (url.protocol !== "http:" || !["127.0.0.1", "[::1]"].includes(url.hostname) || url.username || url.password - || url.search || url.hash || !["/v1", "/v1/"].includes(url.pathname) || !url.port) return false; + || url.search || url.hash || !url.port) return false; + const basePath = url.pathname.replace(/\/$/, ""); + if (basePath !== "/v1" && (basePath !== CONTEXT_BACKEND_PREFIX || !contextExperimentalEnabled(text))) return false; const port = Number(url.port), matchesPort = (value: number | undefined) => Number.isInteger(value) && Number(value) > 0 && value === port; // The companion always binds IPv4. localhost can resolve to another address family. if (matchesPort(owner.loopbackPort) && url.hostname === "127.0.0.1") return true; diff --git a/structure/clients/codex-desktop.md b/structure/clients/codex-desktop.md index 89b204d5657..9ec63e172ff 100644 --- a/structure/clients/codex-desktop.md +++ b/structure/clients/codex-desktop.md @@ -168,6 +168,7 @@ described in the [transport inventory](../transports/inventory.md#native-desktop Invalid proxy routes refuse rather than falling back to direct egress. Native routing verification binds both the actual listener address family and port; the companion is IPv4-only. Ambiguous localhost aliases cannot qualify, and listener identity changes revoke observation. +It accepts the native `/v1` base path and the `/backend-api/codex` alias when experimental context management is enabled. `relay-listener.ts` forwards HTTP with the existing upstream-header filter, cookies and streaming bodies, and pipes upgraded TLS sockets without decoding their frames. The diff --git a/tests/clients/desktop-compatibility-routing.test.ts b/tests/clients/desktop-compatibility-routing.test.ts index 8eaaaf69706..5c8d07e9035 100644 --- a/tests/clients/desktop-compatibility-routing.test.ts +++ b/tests/clients/desktop-compatibility-routing.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, expect, test } from "bun:test"; import { mkdtempSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { contextCompatibleBaseLine } from "../../src/codex/context-compat"; import { createNativeRoutingVerifier, matchesNativeCompatibilityRouting } from "../../src/codex/desktop-compatibility/routing-preflight"; import { bindNativeCompatibilityOwner, nativeCompatibilityOwner, type NativeCompatibilityOwner } from "../../src/codex/desktop-compatibility/routing-binding"; import { removeTreeWithRetry } from "../helpers/remove-tree"; @@ -56,6 +57,26 @@ test("the actual bound listener and companion port are accepted, not a stale con expect(matchesNativeCompatibilityRouting(text, { ...owner, config: { ...owner.config, codexDesktopAuthless: true } })).toBe(false); expect(matchesNativeCompatibilityRouting(text, { ...owner, config: { ...owner.config, runtimeRole: "client" } })).toBe(false); }); +test("the injected context-management base URL qualifies on the active listener", () => { + const baseLine = 'openai_base_url = "http://127.0.0.1:12001/v1"'; + const optedIn = text + '[features.context_management]\nexperimental_mode = true\n'; + const injected = optedIn.replace(baseLine, contextCompatibleBaseLine(optedIn, baseLine)); + expect(injected).toContain('openai_base_url = "http://127.0.0.1:12001/backend-api/codex"'); + expect(matchesNativeCompatibilityRouting(injected, owner)).toBe(true); + expect(matchesNativeCompatibilityRouting(injected.replace('/codex"', '/codex/"'), owner)).toBe(true); +}); + +test("the context-management alias still requires opt-in and a valid local route", () => { + const alias = text.replace("/v1", "/backend-api/codex"); + const optedIn = alias + '[features]\ncontext_management = true\n'; + expect(matchesNativeCompatibilityRouting(optedIn, owner)).toBe(true); + for (const candidate of [alias, optedIn.replace("= true", "= false"), + optedIn.replace(":12001", ":10100"), optedIn.replace("127.0.0.1", "example.test"), + optedIn.replace("/codex", "/codex/extra"), optedIn.replace("/codex", "/codex?x=1")]) { + expect(matchesNativeCompatibilityRouting(candidate, owner)).toBe(false); + } +}); + test("foreign providers, destinations, credentials and unknown profiles cannot qualify", () => { for (const candidate of [text.replace('"openai"', '"custom"'), text.replace("127.0.0.1", "example.test"), text.replace("http://", "https://"), text.replace("127.0.0.1", "user:pass@127.0.0.1"), text.replace("/v1", "/v1?x=1"), From 7ef7c5811815859625d1520d2c99cdc1064a7630 Mon Sep 17 00:00:00 2001 From: Enes Kartal <43950508+EnesKartal@users.noreply.github.com> Date: Wed, 25 Nov 2026 08:23:43 +0300 Subject: [PATCH 33/60] fix(devin): rewrite official Claude Code CLI opener for Cognition (#9080) * fix(devin): rewrite official Claude Code CLI opener for Cognition * docs: document Devin Claude Code rewrite --------- Co-authored-by: JUN Co-authored-by: lidge-jun --- src/adapters/devin/cloud-direct/chat.ts | 4 ++++ structure/providers-and-adapters.md | 2 +- tests/providers/devin-adapter.test.ts | 6 ++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/adapters/devin/cloud-direct/chat.ts b/src/adapters/devin/cloud-direct/chat.ts index e6edceb6500..9bc41d4df77 100644 --- a/src/adapters/devin/cloud-direct/chat.ts +++ b/src/adapters/devin/cloud-direct/chat.ts @@ -715,6 +715,10 @@ const COGNITION_BLOCKLIST_REWRITES: ReadonlyArray<[RegExp, string]> = [ ], // #8558: Claude Code system prompt. Matched like the Codex entries: // case-insensitive, flexible whitespace, optional commas. + [ + /\bYou\s+are\s+Claude\s+Code,?\s+Anthropic['’]?s\s+official\s+CLI\s+for\s+Claude\b/gi, + "You are Claude Code, a CLI for Claude built by Anthropic", + ], [ /\bYou\s+are\s+a\s+Claude\s+agent,?\s+built\s+on\s+Anthropic['’]?s\s+Claude\s+Agent\s+SDK\b/gi, "You are a Claude agent, built on Anthropic's Claude Agent Toolkit", diff --git a/structure/providers-and-adapters.md b/structure/providers-and-adapters.md index 310aba504d9..a099f8c4b71 100644 --- a/structure/providers-and-adapters.md +++ b/structure/providers-and-adapters.md @@ -213,7 +213,7 @@ rewrite rules and the routed-id settlement. | `src/adapters/azure.ts` | Azure OpenAI bridge; optional `minMaxOutputTokens` raises only smaller explicit positive integer output budgets. Unset preserves caller caps. Serialization and pre-admission spend estimates share `effectiveAzureOutputBudget`; see the [spend contract](transports/responses-spend.md#durable-spend-reservations). | | `src/adapters/cursor.ts`, `src/adapters/cursor/` | Cursor protobuf transport: discovery, request builder, event decoding, MCP, thread continuity, native-exec policy. | | `src/adapters/zed.ts`, `src/providers/zed.ts`, `src/oauth/zed.ts` | Zed Hosted AI native-app RSA login, account-scoped short-lived LLM-token exchange, bounded live model discovery, and provider-envelope translation through the existing Anthropic, Google, Responses, and Chat builders. Buffered delivery retains events under the shared translator budget and cancels delegated streams on early exit. The Responses delegate applies destination compatibility, strips OpenAI-private fields and unsupported built-in tools, reconciles removed tool choices through the shared hosted-tool policy, and maps OpenAI `developer` messages to Zed-supported `system` messages before wrapping the request. `src/adapters/zed-openai-stream.ts` translates the OpenAI stream: the current turn's `additional_tools` are promoted on a detached copy before replay repair, interleaved function and custom calls stay buffered until the oldest open call's authoritative item end or successful response terminal because adapter deltas are unkeyed, and end of stream or an incomplete response flushes only arguments that already arrived, marking unfinished calls incomplete. Text and reasoning wait behind an open call; invisible heartbeats report buffered progress. Item aliases share one execution identity and conflicting reuse fails closed. Missing tool names fail the turn, and no output follows a terminal error. Per-item reasoning and done-only text fallback suppress completed replays. A completed compaction item keeps its ciphertext on the done event and transfers that retained lease. Arguments, full snapshots, dedupe identities, queued events, text and opaque usage are budgeted and released on failure or cancellation; typed and untyped native error envelopes scrub every diagnostic string, including code/type, with the captured credential scrubber and discard diagnostic metadata before delegation. Untyped error envelopes terminate the OpenAI relay. Argument-done frames confirm bytes only; item status or successful response completion authorizes executable closure. Authoritative custom snapshots and every later delta agree byte-for-byte regardless of emission order; extensions or contradictions close outstanding calls incomplete and fail the turn. Function arguments compare ordered lexical JSON tokens for complete snapshots and replay fingerprints: whitespace outside strings is ignored, strings compare decoded Unicode units, number literals remain exact, and object-key order (including duplicate members) stays significant; compatible whitespace-adjusted prefixes append only a validated suffix and preserve delivered bytes. `src/adapters/zed-tool-arguments.ts` owns lexical reconciliation and domain-separated replay fingerprints. `src/adapters/zed-json-tokens.ts` scans JSON iteratively with a 65,536-container nesting limit, reporting a clear limit failure above it. Late fragments scan only new source units against retained authoritative tokens, including calls held behind another call; `tests/providers/zed-argument-consistency.test.ts` covers late, buffered and JSON/SSE cases. Failed terminals close outstanding calls incomplete and replay queued text/reasoning before the original error. Diagnostic usage retains only finite nonnegative numeric token counters through `src/adapters/zed-diagnostic-usage.ts`, including nested cache/reasoning counters; opaque extensions are discarded. `tests/providers/zed-failure-relay.test.ts` covers JSON/SSE failure projection and completion conflicts. `src/adapters/zed-additional-tools.ts` owns tool promotion, while `src/adapters/openai-responses/usage.ts` shares usage projection with Responses compaction. `tests/providers/zed-openai-contract.test.ts` covers the relay and client-boundary regressions. Experimental and unofficial; the Zed terms risk is intentionally surfaced in user docs and release review. Zed account and token preparation use the support executor, and completions use the guarded inference executor. | -| `src/adapters/devin.ts`, `src/adapters/devin/cloud-direct/` | Devin runTurn transport over Cognition Connect-RPC. Assistant reasoning replays as ChatMessagePrompt #11 thinking, #12 signature and #18 signature type (`src/adapters/devin/reasoning-signature.ts`): the #10/#21 pair arrives after the visible answer and becomes its own signature-only reasoning item, so a single unsigned thinking block plus exactly one signature-only block is replayed as one signed prompt, and a signature-only turn (GPT, Gemini) is replayed rather than dropped. An Anthropic signature is replayed, but because the streamed thinking is a summary the signature may not cover, a turn Cognition refuses with `invalid_argument` before any visible output (reasoning alone does not count) is retried once with Anthropic signatures withheld and the thinking text kept. `GetChatMessage` uses the Responses provider executor and shared physical-send budget; catalog, JWT, and `src/web-search/devin-executor.ts` native search support RPCs remain outside inference-send accounting. Provider-stated pre-output 429 reset delays are surfaced immediately by default, releasing shared active-turn capacity. A positive `OPENCODEX_DEVIN_STATED_RESET_WAIT_MS` explicitly enables bounded waiting and up to two replays on standalone turns, which hold that capacity until completion or cancellation. Combo children bypass that wait and surface a pre-output 429 so the next target can run. During an opted-in standalone wait, safe heartbeats commit the response preflight and keep the stream's stall watchdog fed. Invalid values fail closed to the immediate-refusal behavior. A recorded tenant host is used only for the stored account whose credential owns the transmitted key, searched in the configured provider id and then its deprecated alias; a configured, forwarded, or unmatched key uses the configured base URL or the US default. Native search previews the current route by effective adapter without mutating combo selection state, pins one admitted active-account snapshot for the request, and calls `GetWebSearchResults`, so it starts no CLI or second model. The wire model UID comes from the catalog's family metadata (`ClientModelConfig` #23/#30/#31): a family id with no effort anchors on the family's default member and selects the nearest enabled rung, rounding up first; an effort moves only the effort axis, to the lowest rung at or above it (else the highest below) while Fast Mode, 1M Context and the other axes stay at the anchor's values unless the caller asked for `fast` or a `1m` value; not lowering a requested effort outranks keeping those axes (an unranked member counts as lower), a disabled row the caller named is kept when the request still selects it so the preflight names that refusal, and resolution never leaves the family. Rows without family metadata fall back to suffix resolution, whose variant scan matches the collapsed base rather than a string prefix. With no caller or configured output cap, the selected row's catalog `maxOutputTokens` fills CompletionConfiguration #2; #3 is `max_newlines` and is sent at a fixed value, never a context window. The leading system text is sent as `GetChatMessage` #2, a failed tool result sets ChatMessagePrompt #9 and keeps an in-band `ERROR:` marker, and Gemini uids have JSON-Schema type arrays expressed as type-only `anyOf` branches in tool parameters. Shared constraints remain on the surrounding node, so nested schemas have one wire representation while outer enum/const, boolean constraints (including `not`, `oneOf`, and `allOf`) on null, and existing null-branch restrictions retain their conjunctive meaning. A null-only type keeps its null constraint even when an outer enum/const excludes null, preserving an unsatisfiable schema without producing an empty anyOf. Schema resource identifiers, anchors, definition maps, and existing anyOf branches remain on their original node. The type constraint is appended to existing allOf entries without shifting their indices, so JSON Pointer targets and reference scopes remain unchanged. Claude uids (`claude-*`, `MODEL_CLAUDE_*`) whose tool parameters have a root `oneOf`, `anyOf` or `allOf` get the same root flattening as Claude Chat gateways (`flattenClaudeRootToolParameters` in `src/adapters/openai-chat/tool-schema.ts`), because Cognition refuses a root composition for Claude with `invalid_argument`; every other Claude schema is sent unchanged. A pre-output `invalid_argument` on a history whose word-piece estimate, using the sanitized and truncated tool descriptions actually sent on the wire, reaches 95% of the selected UID's catalog input window, capped by configured provider and model limits (512 KiB of text only when no window is known) is surfaced as `context_length_exceeded` so Codex compacts; a small request with the same code stays a plain 400. Known limit: a malformed schema on a history already at or above that 95% threshold is also reported as overflow because the upstream returns the same `invalid_argument`. The `COGNITION_BLOCKLIST_REWRITES` sanitizer always rewrites known triggers on instruction surfaces — tool descriptions and the #2 system prompt. Data sanitization is off by default and enables only when `OPENCODEX_DEVIN_SANITIZE_DATA_SURFACES` is exactly `"1"`: it also rewrites joined message text (#3), tool-call `arguments_json` (#6.3), image captions (#10.3), and replayed thinking (#11). Other values leave those data fields outside the sanitizer; a trigger there can still surface as upstream `permission_denied`. Tool names, tool-call IDs, and image bytes remain untouched. If sanitized thinking differs from the original, the prompt replays the rewritten #11 text unsigned and omits both its original #12 signature and #18 signature type; otherwise those signature fields remain byte-exact, including signature-only replay and changes confined to other data fields. The opt-in changes literal history and can weaken signed reasoning continuity for rewritten turns; it does not guarantee upstream acceptance. | +| `src/adapters/devin.ts`, `src/adapters/devin/cloud-direct/` | Devin runTurn transport over Cognition Connect-RPC. Assistant reasoning replays as ChatMessagePrompt #11 thinking, #12 signature and #18 signature type (`src/adapters/devin/reasoning-signature.ts`): the #10/#21 pair arrives after the visible answer and becomes its own signature-only reasoning item, so a single unsigned thinking block plus exactly one signature-only block is replayed as one signed prompt, and a signature-only turn (GPT, Gemini) is replayed rather than dropped. An Anthropic signature is replayed, but because the streamed thinking is a summary the signature may not cover, a turn Cognition refuses with `invalid_argument` before any visible output (reasoning alone does not count) is retried once with Anthropic signatures withheld and the thinking text kept. `GetChatMessage` uses the Responses provider executor and shared physical-send budget; catalog, JWT, and `src/web-search/devin-executor.ts` native search support RPCs remain outside inference-send accounting. Provider-stated pre-output 429 reset delays are surfaced immediately by default, releasing shared active-turn capacity. A positive `OPENCODEX_DEVIN_STATED_RESET_WAIT_MS` explicitly enables bounded waiting and up to two replays on standalone turns, which hold that capacity until completion or cancellation. Combo children bypass that wait and surface a pre-output 429 so the next target can run. During an opted-in standalone wait, safe heartbeats commit the response preflight and keep the stream's stall watchdog fed. Invalid values fail closed to the immediate-refusal behavior. A recorded tenant host is used only for the stored account whose credential owns the transmitted key, searched in the configured provider id and then its deprecated alias; a configured, forwarded, or unmatched key uses the configured base URL or the US default. Native search previews the current route by effective adapter without mutating combo selection state, pins one admitted active-account snapshot for the request, and calls `GetWebSearchResults`, so it starts no CLI or second model. The wire model UID comes from the catalog's family metadata (`ClientModelConfig` #23/#30/#31): a family id with no effort anchors on the family's default member and selects the nearest enabled rung, rounding up first; an effort moves only the effort axis, to the lowest rung at or above it (else the highest below) while Fast Mode, 1M Context and the other axes stay at the anchor's values unless the caller asked for `fast` or a `1m` value; not lowering a requested effort outranks keeping those axes (an unranked member counts as lower), a disabled row the caller named is kept when the request still selects it so the preflight names that refusal, and resolution never leaves the family. Rows without family metadata fall back to suffix resolution, whose variant scan matches the collapsed base rather than a string prefix. With no caller or configured output cap, the selected row's catalog `maxOutputTokens` fills CompletionConfiguration #2; #3 is `max_newlines` and is sent at a fixed value, never a context window. The leading system text is sent as `GetChatMessage` #2, a failed tool result sets ChatMessagePrompt #9 and keeps an in-band `ERROR:` marker, and Gemini uids have JSON-Schema type arrays expressed as type-only `anyOf` branches in tool parameters. Shared constraints remain on the surrounding node, so nested schemas have one wire representation while outer enum/const, boolean constraints (including `not`, `oneOf`, and `allOf`) on null, and existing null-branch restrictions retain their conjunctive meaning. A null-only type keeps its null constraint even when an outer enum/const excludes null, preserving an unsatisfiable schema without producing an empty anyOf. Schema resource identifiers, anchors, definition maps, and existing anyOf branches remain on their original node. The type constraint is appended to existing allOf entries without shifting their indices, so JSON Pointer targets and reference scopes remain unchanged. Claude uids (`claude-*`, `MODEL_CLAUDE_*`) whose tool parameters have a root `oneOf`, `anyOf` or `allOf` get the same root flattening as Claude Chat gateways (`flattenClaudeRootToolParameters` in `src/adapters/openai-chat/tool-schema.ts`), because Cognition refuses a root composition for Claude with `invalid_argument`; every other Claude schema is sent unchanged. A pre-output `invalid_argument` on a history whose word-piece estimate, using the sanitized and truncated tool descriptions actually sent on the wire, reaches 95% of the selected UID's catalog input window, capped by configured provider and model limits (512 KiB of text only when no window is known) is surfaced as `context_length_exceeded` so Codex compacts; a small request with the same code stays a plain 400. Known limit: a malformed schema on a history already at or above that 95% threshold is also reported as overflow because the upstream returns the same `invalid_argument`. The `COGNITION_BLOCKLIST_REWRITES` sanitizer always rewrites known triggers on instruction surfaces — tool descriptions and the #2 system prompt. This includes “You are Claude Code, Anthropic's official CLI for Claude”, rewritten as “You are Claude Code, a CLI for Claude built by Anthropic” with case-insensitive matching and flexible whitespace. Data sanitization is off by default and enables only when `OPENCODEX_DEVIN_SANITIZE_DATA_SURFACES` is exactly `"1"`: it also rewrites joined message text (#3), tool-call `arguments_json` (#6.3), image captions (#10.3), and replayed thinking (#11). Other values leave those data fields outside the sanitizer; a trigger there can still surface as upstream `permission_denied`. Tool names, tool-call IDs, and image bytes remain untouched. If sanitized thinking differs from the original, the prompt replays the rewritten #11 text unsigned and omits both its original #12 signature and #18 signature type; otherwise those signature fields remain byte-exact, including signature-only replay and changes confined to other data fields. The opt-in changes literal history and can weaken signed reasoning continuity for rewritten turns; it does not guarantee upstream acceptance. | | `src/adapters/kiro.ts` and `src/adapters/kiro/` | Kiro event/tool/thinking/truncation/retry handling, including an egress-aware completion fallback, fixed public HTTP 5xx text, and closed-set status/code diagnostics. The original path is a facade over leaves for wire identity, reasoning, conversation state, token estimation, payload assembly, streaming, and the adapter. | | `src/adapters/mimo-free.ts` | Mimo Free transport (client identity + JWT). Concurrent requests share one JWT bootstrap bound only to its timeout; each request stops waiting on its own abort without cancelling the others. Its registry entry is `deprecated`: existing saved providers keep the adapter and their stored configuration, while new-provider discovery (presets, the init menu, the featured list, and key logins) excludes it and `provider add` warns before creating one. | | `src/adapters/command-code.ts`, `src/adapters/command-code-tool-text.ts`, `src/adapters/command-code-restored-schema.ts` | Command Code OAuth NDJSON translation. For every `xiaomi/mimo-` model, text, native calls, reasoning, and terminal decisions share one byte-bounded queue with linear queue visits. Markup is deduplicated against matching native calls; text-only restoration requires one contiguous bare text block, a clean finish, a declared tool, and arguments validated against supported schema constraints. A parameter-free (freeform) block may omit `` but must end with ``; parameter blocks keep the canonical close. Markup appended after prose, including a marker in a later delta of the same text block, is held as a tail that can never mint a call: possible trailing marker prefixes stay in the same byte-accounted probe across deltas and release as text on a mismatch, boundary or end; a same-content native call strips a completed envelope as an echo, and anything else releases as presentation text so quoted examples stay inert. A tail waits only while a native input it could echo is open, counting the first later input of its own tool, so it is released as soon as those close without a match. Native, reasoning, and other intervening events interrupt a still-probing block but leave a held block held in arrival order, and the queued byte bound still flushes an unresolved envelope as text. An envelope the strict parser rejects but that opens with ``, closes with ``, and names a declared function is dropped when a native call for that same function arrives and on a clean finish; markup that parses but fits no supported schema is still released as text. Regex patterns, other unsupported constraints, and abnormal finishes fail closed. `tests/providers/command-code-tool-text-prose-split.test.ts` covers the prose boundary, the interleaved-event hold, and both drop paths. On OAuth rows the native fetch path normalizes only a 400 whose JSON is `success: false`, `error.code: "BAD_REQUEST"`, and message begins `You have insufficient credits to make this request.` to 429, adding `x-opencodex-refusal: insufficient-credits` and preserving the upstream status in `x-opencodex-upstream-status: 400`; ordinary 400s, other statuses, malformed or oversized bodies, and malformed UTF-8 stay untouched. Key and forward rows keep the 400, because a canonical key row has a same-key 429 retry ladder (`rateLimitRetryPolicyFor`) that would replay a credential with no credits left. A genuine upstream 429 keeps its own `Retry-After` and a 402 stays a 402 even when its body repeats the credit wording; `tests/providers/command-code-credit-failover.test.ts` pins that boundary and `tests/providers/command-code-credit-rotation.test.ts` drives the refusal through dispatch to the sibling account. On every auth mode a 403 whose JSON is `success: false`, `error.code: "FORBIDDEN"`, and message begins `MODEL_NOT_IN_PLAN` (then `:` or the end) becomes a 400 `invalid_request_error` with code `model_not_in_plan`, fixed copy naming the model, `x-opencodex-refusal: model-not-in-plan` and `x-opencodex-upstream-status: 403` (#7684): Codex reconnects on any 403 through its retry budget but ends the turn on a 400. The upstream detail is never quoted, so its free text cannot reach logs or steer the quota and reasoning-effort classifiers, and the effort repair skips the refusal. `isModelNotInPlanRefusal` in `src/lib/errors.ts` trusts the code only on a response object the adapter marked in memory, since an upstream can forge both the code and the diagnostic header; `formatErrorResponse` keeps it as the wire code, only the verifying boundaries (`formatUpstreamFailureResponse` in `src/bridge/errors.ts`, called by `adapter-dispatch.ts`, and `consumeComboFailure`) mark the envelope in memory (carried across the `src/server/responses/core-lifetime.ts` wrappers), `consumeComboFailure` drops an unmarked echo in any spelling failover folds into that code, and `comboFailureDecision` in `src/combos/failover.ts` hops past the refusal only with that caller-supplied provenance (combo or policy fallback; never a bare, passthrough or streamed code) while `comboFailureCooldownScope` cools only that target. The web-search and image sidecar loops keep a verified refusal's fixed copy without a wire-model name, code and mark in their own error envelope (`verifiedPlanRefusalMessage`), and `src/server/responses/sidecar-execution.ts` carries the mark across its stream wrappers; a later iteration's refusal inside an already committed 200 stream ends as `invalid_prompt` (`MODEL_NOT_IN_PLAN_STREAM_CODE`) with `retryable: false` and the same copy, because Codex reconnects on any other `response.failed` code. No account, key or provider cooldown is recorded. `tests/providers/command-code-plan-denial.test.ts` covers lookalikes, malformed bodies, abort, the Responses, Chat and Messages inbound paths, combo and policy hops, and an unmarked echo. | diff --git a/tests/providers/devin-adapter.test.ts b/tests/providers/devin-adapter.test.ts index e9092a30c68..468b3d6300e 100644 --- a/tests/providers/devin-adapter.test.ts +++ b/tests/providers/devin-adapter.test.ts @@ -473,6 +473,12 @@ describe("devin adapter", () => { expect(sanitizeTextForCognitionForTests(agentSdk)) .toBe("You are a Claude agent, built on Anthropic's Claude Agent Toolkit."); + const officialCli = "You are Claude Code, Anthropic's official CLI for Claude."; + expect(sanitizeTextForCognitionForTests(officialCli)) + .toBe("You are Claude Code, a CLI for Claude built by Anthropic."); + expect(sanitizeTextForCognitionForTests(officialCli.toLowerCase())) + .toContain("a CLI for Claude built by Anthropic"); + const dualUse = "Dual-use security tools (C2 frameworks, credential testing, exploit development) require clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases."; expect(sanitizeTextForCognitionForTests(dualUse)) .toBe("Dual-purpose security tools (C2 frameworks, credential testing, exploit development) need clear authorization context: pentesting engagements, CTF competitions, security research, or defensive use cases."); From 8a212aec8fe53f68130371ae1b814436efdf825d Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 14:27:29 +0900 Subject: [PATCH 34/60] feat(oauth): per-account diagnostics with eligibility, refresh outcome and cooldown (#9109) * wip: G-016 account diagnostics * wip: G-016 route wiring and docs * feat(oauth): per-account diagnostics route with refresh outcomes (G-016) * fix(oauth): diagnostics read passively, per quota family, with scoped bounded refresh outcomes * wip: G-016 round 3 * fix(oauth): fence refresh outcomes to the login, snapshot leases, defer roster generation reads * fix(oauth): attribute refresh outcomes to the dispatched account snapshot * docs(es): document the account diagnostics route --------- Co-authored-by: r2b --- .../docs/es/reference/management-api.md | 1 + .../content/docs/reference/management-api.md | 1 + .../test-layout/layout-server-inbound.json | 1 + src/oauth/generic-account-failover.ts | 6 + src/oauth/index.ts | 7 +- src/oauth/kiro-account-load.ts | 9 + src/oauth/refresh-outcomes.ts | 100 ++++++ src/oauth/store.ts | 5 +- src/providers/antigravity-account-roster.ts | 38 ++- src/server/management-api.ts | 8 + .../management/account-diagnostics-routes.ts | 135 ++++++++ src/server/management/route-registry.ts | 1 + structure/providers/generic-account-pool.md | 8 + tests/fixtures/test-layout-expected.json | 2 +- .../server/account-diagnostics-routes.test.ts | 289 ++++++++++++++++++ 15 files changed, 602 insertions(+), 9 deletions(-) create mode 100644 src/oauth/refresh-outcomes.ts create mode 100644 src/server/management/account-diagnostics-routes.ts create mode 100644 tests/server/account-diagnostics-routes.test.ts diff --git a/docs-site/src/content/docs/es/reference/management-api.md b/docs-site/src/content/docs/es/reference/management-api.md index eda90539e8a..9420a98d3c8 100644 --- a/docs-site/src/content/docs/es/reference/management-api.md +++ b/docs-site/src/content/docs/es/reference/management-api.md @@ -465,6 +465,7 @@ OAuth filas de cuenta siempre incluyen `plan`: una etiqueta de suscripción vali | `GET /api/oauth/status` | Sondea el flujo OAuth de un proveedor; para xAI, `flowId` selecciona el intento de dispositivo y su omisión conserva el sondeo del proveedor. Un flujo fallido devuelve un `error` público fijo y un `errorCode` legible por máquina del mismo vocabulario que la respuesta al pegar código, incluido `oauth_authentication_failed` para una denegación de xAI o una redirección rechazada y `provider_unreachable` para un fallo de servidor xAI | 400 proveedor desconocido | | `POST /api/oauth/logout` | Eliminar la credencial de proveedor seleccionada | 400 proveedor desconocido; `oauth_mutation_busy` | | `GET /api/oauth/accounts` | Lista las cuentas enmascaradas. Las filas de Anthropic y OAuth genéricas incluyen `paused`. Las cuentas pausadas automáticamente pueden incluir `pauseDetails` (motivo y marca de tiempo) y el campo `pauseEvidence` al mismo nivel, con `statusCode` y un `message` opcional de hasta 300 caracteres con los datos sensibles ocultos. Una respuesta directa de Cloud Code Assist que confirme una suspensión puede incluir en `pauseEvidence` una `appealUrl` de Google validada y un `appealText` opcional en texto plano. Al reanudar se borran ambos campos. Las filas de Kiro incluyen `autoSelectable` y un `skipReason` de un conjunto cerrado cuando se excluyen de la selección automática; una única cuenta activa todavía puede enviar solicitudes. La consulta de cuota sigue siendo opcional. | 400 proveedor no válido | +| `GET /api/oauth/accounts/diagnostics?provider=` | Diagnóstico por cuenta de un inicio de sesión OAuth: `active`, `paused`, `needsReauth`, `eligible`, `eligibleModels` (modelos conocidos que la cuenta puede servir ahora; `null` si no se conoce ninguna lista de modelos), `lastRefresh` (`{ at, ok, reason?, status? }` de la última renovación de token en este proceso, o `null`), `cooldownUntil`, `inFlight` y, para Kiro con `maxConcurrentPerAccount`, `atCapacity`. Con una lista de modelos conocida, `eligible` significa que al menos un modelo es elegible. Las filas solo llevan el identificador de la cuenta, nunca un correo, una etiqueta ni una credencial. Solo lectura. | 400 proveedor no válido | | `DELETE /api/oauth/accounts` | Eliminar una cuenta | 400 proveedor/identificador no válido; 404 falta la cuenta; `oauth_mutation_busy` | | `PUT /api/oauth/accounts/active` | Selecciona la cuenta OAuth activa | 400 proveedor/cuenta inválidos; 404 cuenta ausente; 409 cuenta pausada; `oauth_mutation_busy`; 503 `affinity_reset_not_persisted` en Anthropic con `selectionCommitted: true`, `retryable: true`: el cambio se guardó; repite la misma solicitud aunque ya esté activa | | `PUT /api/oauth/accounts/pause` | Pausa o reanuda una cuenta Anthropic o genérica OAuth. Cuerpo `{ provider, accountId, paused }`; pausar la activa selecciona la siguiente utilizable cuando existe. Es durable e independiente del pool; reanudar conserva salud y credenciales | 400 proveedor o cuerpo inválidos; 404 cuenta ausente; `oauth_mutation_busy`; 503 `affinity_reset_not_persisted` en Anthropic con `pauseCommitted: true`, `retryable: true`: conserva cuenta y pausa, añade `retryAffinityReset: true` y reintenta confirmar el reset incluso después de reiniciar | diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index e726ef347e2..3e4cdd3ce47 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -729,6 +729,7 @@ Labels are read on login/import or refresh, never inferred from quota percentage | `GET /api/oauth/status` | Poll one provider's OAuth flow; for xAI, `flowId` selects the device attempt, while omitting it retains provider-wide polling. A failed flow reports a fixed public `error` and a machine-readable `errorCode` from the same vocabulary as the paste response, including `oauth_authentication_failed` for xAI denial or a refused redirect and `provider_unreachable` for an xAI server failure | 400 unknown provider | | `POST /api/oauth/logout` | Remove the selected provider credential | 400 unknown provider; `oauth_mutation_busy` | | `GET /api/oauth/accounts` | List masked accounts. Anthropic and generic OAuth rows include `paused`. Automatically paused rows can include `pauseDetails` (reason and timestamp) and a sibling `pauseEvidence` with `statusCode` and an optional redacted `message` of up to 300 characters. A conclusive first-party Cloud Code Assist ban can also include a validated Google `appealUrl` and optional plain `appealText` inside `pauseEvidence`. Resuming clears both fields. Kiro rows include `autoSelectable` and a closed `skipReason` when excluded from automatic selection; an active singleton may still send. Quota remains opt-in. | 400 invalid provider | +| `GET /api/oauth/accounts/diagnostics?provider=` | Per-account diagnostics for one OAuth login: `active`, `paused`, `needsReauth`, `eligible`, `eligibleModels` (known models the account may serve now; `null` when no model list is known), `lastRefresh` (`{ at, ok, reason?, status? }` from the last upstream token refresh in this process, or `null`), `cooldownUntil`, `inFlight` and, for Kiro with `maxConcurrentPerAccount`, `atCapacity`. With a known model list, `eligible` means at least one model is eligible. Rows carry the account id only, never an email, label or credential. Read-only. | 400 invalid provider | | `DELETE /api/oauth/accounts` | Remove one account | 400 invalid provider/id; 404 account missing; `oauth_mutation_busy` | | `PUT /api/oauth/accounts/active` | Select the active OAuth account | 400 invalid provider/account; 404 account missing; 409 account paused; `oauth_mutation_busy`; 503 `affinity_reset_not_persisted` (Anthropic: `selectionCommitted: true`, `retryable: true`; account change saved; resend the same request even if already active) | | `PUT /api/oauth/accounts/pause` | Pause or resume one Anthropic or generic OAuth account. Body `{ provider, accountId, paused }`; pausing the active account selects the next usable account when available. Pause is durable and independent of pool enablement; resume preserves health and credentials. | 400 unsupported provider or invalid body; 404 account missing; `oauth_mutation_busy`; 503 `affinity_reset_not_persisted` (Anthropic: `pauseCommitted: true`, `retryable: true`; pause state saved; preserve the account and pause state, add `retryAffinityReset: true`, and retry to confirm the reset even after a server restart) | diff --git a/scripts/test-layout/layout-server-inbound.json b/scripts/test-layout/layout-server-inbound.json index 3237bb35403..b77830002b7 100644 --- a/scripts/test-layout/layout-server-inbound.json +++ b/scripts/test-layout/layout-server-inbound.json @@ -1,4 +1,5 @@ { + "account-diagnostics-routes.test.ts": "server", "explicit-proxy-no-proxy.test.ts": "lib", "gemini-native.test.ts": "server", "gemini-native-wire.test.ts": "server", diff --git a/src/oauth/generic-account-failover.ts b/src/oauth/generic-account-failover.ts index fd768d91d2a..64aaf5d452c 100644 --- a/src/oauth/generic-account-failover.ts +++ b/src/oauth/generic-account-failover.ts @@ -153,6 +153,12 @@ function isCooled(provider: string, accountId: string, now: number, family?: Quo export type KiroSkipReason = "paused" | "needs_reauth" | "suspended" | "cooldown" | "quota_exhausted"; +/** Account-wide cooldown expiry for diagnostics, or null when the account is not cooled. */ +export function genericAccountCooldownUntil(provider: string, accountId: string, now = Date.now()): number | null { + if (!isCooled(provider, accountId, now)) return null; + return health.get(healthKey(provider, accountId))?.cooldownUntil ?? null; +} + /** Eligibility for automatic alternatives; an active singleton can still send. */ export function kiroAutoSelection( account: ProviderAccount, now = Date.now(), diff --git a/src/oauth/index.ts b/src/oauth/index.ts index 60915e61189..e8e3f305521 100644 --- a/src/oauth/index.ts +++ b/src/oauth/index.ts @@ -60,6 +60,7 @@ import { loginOrcaRouter, orcaRouterInferenceBaseUrl, refreshOrcaRouterKey } fro import { ANTIGRAVITY_DISCOVERY_UA } from "../adapters/google-antigravity-wire"; import { deriveOAuthDefaultModel, deriveOAuthProviderConfig } from "../providers/derive"; import { isOAuthCredentialSiblingOf, oauthCredentialSlot } from "./credential-siblings"; +import { observeOAuthRefresh } from "./refresh-outcomes"; import { apiKeyPoolEntryId, sanitizeApiKeyValue } from "../providers/api-keys"; import { preservableApiKeyPool } from "./api-key-pool-preserve"; import { effectiveGoogleMode, getProviderRegistryEntry, mergeRegistryStaticHeaders, providerMatchesRegistryTransport, withoutRegistryStaticHeaderCopies } from "../providers/registry"; @@ -829,7 +830,7 @@ function merged(fresh: OAuthCredentials, previous: OAuthCredentials): OAuthCrede ...(fresh.m365 === undefined && previous.m365 && fresh.accountId?.toLowerCase() === previous.accountId?.toLowerCase() ? { m365: previous.m365 } : {}), }; } -export async function refreshXaiAccountWithLock(provider:string,accountId:string,def:OAuthProviderDef,callerCredential:OAuthCredentials,deps:XaiRefreshDeps={}):Promise{const writerGeneration=captureConfigGeneration();const now=deps.now??Date.now;const guard=await(deps.intentLock??createOAuthRefreshIntentLock(provider,accountId)).acquire();try{const row=getAccountCredentialWithStatus(provider,accountId);if(!row)throw new OAuthLoginRequiredError(provider);if(row.paused)throw new OAuthAccountPausedError();if(deps.requireUsableAccount&&row.needsReauth)throw new OAuthAccountUnusableError(provider);const stored=row.credential;const active=getAccountSet(provider)?.activeAccountId===accountId,candidate=authoritative(stored,active,now);if(credentialGeneration(candidate)!==credentialGeneration(callerCredential)&&candidate.expires>now()+REFRESH_SKEW_MS){if(credentialGeneration(candidate)!==credentialGeneration(stored)){const o=await mergeAccountCredential(provider,accountId,candidate,{expectedGeneration:credentialGeneration(stored),afterPrePersistRead:deps.afterPrePersistRead});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}}return candidate.access;}if(cached(provider,accountId,candidate,now))throw new OAuthLoginRequiredError(provider);const generation=credentialGeneration(candidate);try{const fresh=merged(await def.refresh(candidate.refresh,deps.signal),candidate);const o=await mergeAccountCredential(provider,accountId,fresh,{expectedGeneration:generation,afterPrePersistRead:deps.afterPrePersistRead,keepReauthMarkedAfterDispatch:!row.needsReauth});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));if(candidate.source==="local-cli")console.warn(XAI_LOCAL_CLI_DETACH_WARNING);return fresh.access;}catch(error){if(error instanceof OAuthMutationBusyError){permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));throw error;}if(!terminal(error))throw error;const failedAt=now();permanentRefreshFailures.set(verdictKey(provider,accountId,candidate),failedAt+XAI_PERMANENT_FAILURE_TTL_MS);sweepExpiredOnWrite(failedAt);await markAccountNeedsReauthIfGeneration(provider,accountId,generation,writerGeneration);throw new OAuthLoginRequiredError(provider);}}finally{guard.release();}} +export async function refreshXaiAccountWithLock(provider:string,accountId:string,def:OAuthProviderDef,callerCredential:OAuthCredentials,deps:XaiRefreshDeps={}):Promise{const writerGeneration=captureConfigGeneration();const now=deps.now??Date.now;const guard=await(deps.intentLock??createOAuthRefreshIntentLock(provider,accountId)).acquire();try{const row=getAccountCredentialWithStatus(provider,accountId);if(!row)throw new OAuthLoginRequiredError(provider);if(row.paused)throw new OAuthAccountPausedError();if(deps.requireUsableAccount&&row.needsReauth)throw new OAuthAccountUnusableError(provider);const stored=row.credential;const active=getAccountSet(provider)?.activeAccountId===accountId,candidate=authoritative(stored,active,now);if(credentialGeneration(candidate)!==credentialGeneration(callerCredential)&&candidate.expires>now()+REFRESH_SKEW_MS){if(credentialGeneration(candidate)!==credentialGeneration(stored)){const o=await mergeAccountCredential(provider,accountId,candidate,{expectedGeneration:credentialGeneration(stored),afterPrePersistRead:deps.afterPrePersistRead});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}}return candidate.access;}if(cached(provider,accountId,candidate,now))throw new OAuthLoginRequiredError(provider);const generation=credentialGeneration(candidate);try{const fresh=merged(await observeOAuthRefresh(provider,accountId,()=>def.refresh(candidate.refresh,deps.signal),row),candidate);const o=await mergeAccountCredential(provider,accountId,fresh,{expectedGeneration:generation,afterPrePersistRead:deps.afterPrePersistRead,keepReauthMarkedAfterDispatch:!row.needsReauth});if(o.superseded){if(o.stored.expires>now()+REFRESH_SKEW_MS)return o.stored.access;throw new OAuthLoginRequiredError(provider);}permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));if(candidate.source==="local-cli")console.warn(XAI_LOCAL_CLI_DETACH_WARNING);return fresh.access;}catch(error){if(error instanceof OAuthMutationBusyError){permanentRefreshFailures.delete(verdictKey(provider,accountId,candidate));throw error;}if(!terminal(error))throw error;const failedAt=now();permanentRefreshFailures.set(verdictKey(provider,accountId,candidate),failedAt+XAI_PERMANENT_FAILURE_TTL_MS);sweepExpiredOnWrite(failedAt);await markAccountNeedsReauthIfGeneration(provider,accountId,generation,writerGeneration);throw new OAuthLoginRequiredError(provider);}}finally{guard.release();}} /** @@ -969,7 +970,7 @@ export async function refreshAnthropicAccountWithLock( // the outcome. refreshMayHaveReachedProvider = true; if (deps.flight) deps.flight.dispatched = true; - const fresh = merged(await def.refresh(stored.refresh, deps.signal), stored); + const fresh = merged(await observeOAuthRefresh(provider, accountId, () => def.refresh(stored.refresh, deps.signal), account), stored); const outcome = await mergeAccountCredential(provider, accountId, fresh, { expectedGeneration: generation, afterPrePersistRead: deps.afterPrePersistRead, @@ -1045,7 +1046,7 @@ export async function refreshGenericAccountWithLock( const generation = credentialGeneration(stored); try { if (deps.authorityCurrent && !deps.authorityCurrent()) throw new OAuthDiscoveryRefreshCancelledError(); - const refreshed = await def.refresh(stored.refresh, deps.signal, stored, accountId); + const refreshed = await observeOAuthRefresh(provider, accountId, () => def.refresh(stored.refresh, deps.signal, stored, accountId), row); const fresh = merged(refreshed, stored); const outcome = await mergeAccountCredential(provider, accountId, fresh, { expectedGeneration: generation, diff --git a/src/oauth/kiro-account-load.ts b/src/oauth/kiro-account-load.ts index 464b2cf469d..224bbb15094 100644 --- a/src/oauth/kiro-account-load.ts +++ b/src/oauth/kiro-account-load.ts @@ -71,6 +71,15 @@ export function accountInFlight(provider: string, accountId: string): number { return reclaim(keyOf(provider, accountId), Date.now())?.records.size ?? 0; } +/** Leases still within their lifetime, read without reclaiming expired ones or admitting a waiter. */ +export function accountInFlightSnapshot(provider: string, accountId: string, now = Date.now()): number { + const state = accounts.get(keyOf(provider, accountId)); + if (!state) return 0; + let live = 0; + for (const record of state.records.values()) if (now - record.acquiredAt < KIRO_LEASE_MAX_MS) live += 1; + return live; +} + /** A null result means the deadline expired or the caller aborted. */ export async function acquireAccountLease( provider: string, accountId: string, opts: AccountLeaseOptions = {}, diff --git a/src/oauth/refresh-outcomes.ts b/src/oauth/refresh-outcomes.ts new file mode 100644 index 00000000000..43ed9095a8d --- /dev/null +++ b/src/oauth/refresh-outcomes.ts @@ -0,0 +1,100 @@ +/** + * Last upstream token-refresh result per OAuth account, for the account diagnostics route. + * + * Process-local and keyed by config home, login slot, account id and login incarnation (the account's + * `loginId`, which every login mints anew). The refresh path passes the account row it read the + * dispatched credential from, and the home and incarnation are taken from that moment, so a login that + * replaces the account before or during the refresh never inherits the old credential's result. A restart, or a server for another home, starts with no result, which the + * route reports as `lastRefresh: null`. At most `MAX_OAUTH_REFRESH_OUTCOMES` entries are kept, least + * recently written first out. A failure is reduced to a + * fixed reason (and an HTTP status when the error carries one); no error text, token or email is kept. + */ +import { getConfigDir } from "../config/paths"; +import { oauthCredentialSlot } from "./credential-siblings"; +import type { ProviderAccount } from "./types"; + +export type OAuthRefreshFailureReason = "rejected" | "upstream_error" | "network" | "timeout" | "aborted" | "error"; +export interface OAuthRefreshOutcome { + at: number; + ok: boolean; + reason?: OAuthRefreshFailureReason; + status?: number; +} + +export const MAX_OAUTH_REFRESH_OUTCOMES = 1024; +const outcomes = new Map(); +// Rows that share one login (Kimi and Kimi (Responses)) share one refresh result. +const key = (provider: string, accountId: string, incarnation: string, home = getConfigDir()) => + `${home}\0${oauthCredentialSlot(provider)}\0${accountId}\0${incarnation}`; + +/** Which login of this account a result belongs to: its `loginId`, else (legacy rows) its `addedAt`. */ +export function oauthLoginIncarnation(account: Pick | undefined): string { + if (typeof account?.loginId === "string" && account.loginId) return `login:${account.loginId}`; + return typeof account?.addedAt === "number" ? `added:${account.addedAt}` : ""; +} + +function errorStatus(error: unknown): number | undefined { + if (!error || typeof error !== "object") return undefined; + const record = error as { status?: unknown; statusCode?: unknown; httpStatus?: unknown }; + // Provider token errors spell it differently (`AnthropicTokenError` and `KiroTokenRefreshError` use httpStatus). + for (const status of [record.status, record.statusCode, record.httpStatus]) { + if (typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599) return status; + } + return undefined; +} + +/** A fixed reason for a refresh failure; the error's own text never leaves this function. */ +export function classifyOAuthRefreshFailure(error: unknown): Pick { + const status = errorStatus(error); + if (status !== undefined) return { reason: status >= 500 ? "upstream_error" : "rejected", status }; + const name = error && typeof error === "object" ? String((error as { name?: unknown }).name ?? "") : ""; + const code = error && typeof error === "object" ? String((error as { code?: unknown }).code ?? "") : ""; + if (name === "TimeoutError" || code === "ETIMEDOUT") return { reason: "timeout" }; + if (name === "AbortError") return { reason: "aborted" }; + if (/^(ECONN|ENOTFOUND|EAI_|ENETUNREACH|EHOSTUNREACH|ConnectionRefused|FailedToOpenSocket)/.test(code)) return { reason: "network" }; + return { reason: "error" }; +} + +export function recordOAuthRefreshOutcome( + provider: string, accountId: string, outcome: OAuthRefreshOutcome, incarnation: string, home = getConfigDir(), +): void { + const entry = key(provider, accountId, incarnation, home); + outcomes.delete(entry); + outcomes.set(entry, outcome); + while (outcomes.size > MAX_OAUTH_REFRESH_OUTCOMES) outcomes.delete(outcomes.keys().next().value!); +} + +/** + * Await one upstream refresh call and record its result; the call's value or error passes through + * unchanged. `account` is the row the dispatched credential was read from: its login incarnation and + * the current config home are fixed here, before the call, whatever happens to the account meanwhile. + */ +export async function observeOAuthRefresh( + provider: string, accountId: string, refresh: () => Promise, + account: Pick | undefined, +): Promise { + const incarnation = oauthLoginIncarnation(account); + const home = getConfigDir(); + try { + const value = await refresh(); + recordOAuthRefreshOutcome(provider, accountId, { at: Date.now(), ok: true }, incarnation, home); + return value; + } catch (error) { + recordOAuthRefreshOutcome(provider, accountId, { at: Date.now(), ok: false, ...classifyOAuthRefreshFailure(error) }, incarnation, home); + throw error; + } +} + +/** The last result for this login of the account in the current config home. */ +export function lastOAuthRefreshOutcome(provider: string, accountId: string, incarnation: string): OAuthRefreshOutcome | null { + return outcomes.get(key(provider, accountId, incarnation)) ?? null; +} + +/** Tests only. */ +export function clearOAuthRefreshOutcomes(): void { + outcomes.clear(); +} + +export function oauthRefreshOutcomeCountForTests(): number { + return outcomes.size; +} diff --git a/src/oauth/store.ts b/src/oauth/store.ts index e300ce52bd6..ffb5d245b5b 100644 --- a/src/oauth/store.ts +++ b/src/oauth/store.ts @@ -1402,7 +1402,7 @@ export function getAccountCredential(provider: string, accountId: string): OAuth export function getAccountCredentialWithStatus( provider: string, accountId: string, -): { credential: OAuthCredentials; needsReauth: boolean; paused: boolean } | null { +): { credential: OAuthCredentials; needsReauth: boolean; paused: boolean; loginId?: string; addedAt?: number } | null { provider = oauthCredentialSlot(provider); const account = loadAuthStore()[provider]?.accounts.find(a => a.id === accountId); if (!account?.credential) return null; @@ -1410,6 +1410,9 @@ export function getAccountCredentialWithStatus( credential: account.credential, needsReauth: account.needsReauth === true, paused: account.paused === true, + // The login incarnation of this same snapshot, for results attributed to the credential read here. + ...(account.loginId !== undefined ? { loginId: account.loginId } : {}), + ...(account.addedAt !== undefined ? { addedAt: account.addedAt } : {}), }; } diff --git a/src/providers/antigravity-account-roster.ts b/src/providers/antigravity-account-roster.ts index baa1c782b58..381a04b2d37 100644 --- a/src/providers/antigravity-account-roster.ts +++ b/src/providers/antigravity-account-roster.ts @@ -113,12 +113,28 @@ export function recordAntigravityAccountRoster( } function freshRoster(providerName: string, accountId: string, now: number): AccountRoster | undefined { + return freshRosterWith(providerName, accountId, now, () => accountGeneration(providerName, accountId)); +} + +/** The credential generation is read only when a roster exists and is within its TTL. */ +function freshRosterWith( + providerName: string, accountId: string, now: number, generationOf: () => string | undefined, +): AccountRoster | undefined { const roster = rosters.get(rosterKey(providerName, accountId)); - if (!roster || now - roster.observedAt > ANTIGRAVITY_ACCOUNT_ROSTER_TTL_MS - || roster.generation !== accountGeneration(providerName, accountId)) return undefined; + if (!roster || now - roster.observedAt > ANTIGRAVITY_ACCOUNT_ROSTER_TTL_MS || roster.generation !== generationOf()) return undefined; return roster; } +/** One credential-generation read per account, deferred until some evidence needs it. */ +function lazyGeneration(providerName: string, accountId: string): () => string | undefined { + let loaded = false; + let generation: string | undefined; + return () => { + if (!loaded) { generation = accountGeneration(providerName, accountId); loaded = true; } + return generation; + }; +} + /** The picker ids one account's last discovery returned, or `undefined` when unknown. */ export function antigravityAccountRosterModelIds( providerName: string, @@ -138,14 +154,28 @@ export function antigravityAccountSupportsModel( accountId: string, modelId: string, now = Date.now(), +): boolean | undefined { + return supportsModel(providerName, accountId, modelId, now, lazyGeneration(providerName, accountId)); +} + +/** The same answer for many models of one account, reading its credential generation once. */ +export function antigravityAccountModelSupport( + providerName: string, accountId: string, modelIds: readonly string[], now = Date.now(), +): Map { + const generationOf = lazyGeneration(providerName, accountId); + return new Map(modelIds.map(id => [id, supportsModel(providerName, accountId, id, now, generationOf)] as const)); +} + +function supportsModel( + providerName: string, accountId: string, modelId: string, now: number, generationOf: () => string | undefined, ): boolean | undefined { const id = modelId.trim(); if (!id) return undefined; const key = rosterKey(providerName, accountId); const canonicalId = denialModelId(id); const denial = modelDenials.get(key)?.get(canonicalId); - const roster = freshRoster(providerName, accountId, now); - if (denial && denial.generation === accountGeneration(providerName, accountId) + const roster = freshRosterWith(providerName, accountId, now, generationOf); + if (denial && denial.generation === generationOf() && now - denial.deniedAt <= ANTIGRAVITY_MODEL_DENIAL_TTL_MS && (!roster || denial.order >= roster.order)) return false; if (!roster) return undefined; diff --git a/src/server/management-api.ts b/src/server/management-api.ts index 8490fe20b0d..7b88553969d 100644 --- a/src/server/management-api.ts +++ b/src/server/management-api.ts @@ -176,6 +176,13 @@ async function handleFallbackRoutesOnDemand(ctx: ManagementContext): Promise { + if (!pathInManagementNamespace(ctx.url.pathname, "/api/oauth/accounts/diagnostics", false)) return null; + const { handleAccountDiagnosticsRoutes } = await import("./management/account-diagnostics-routes"); + return handleAccountDiagnosticsRoutes(ctx); +} + async function handleRouteToRoutesOnDemand(ctx: ManagementContext): Promise { if (!pathInManagementNamespace(ctx.url.pathname, "/api/route-to")) return null; const { handleRouteToRoutes } = await import("./management/route-to-routes"); @@ -389,6 +396,7 @@ export async function handleManagementAPI( ?? (await handleLowQuotaRoutesOnDemand(ctx)) ?? (await handleQuotaPoolRoutesOnDemand(ctx)) ?? (await handleFallbackRoutesOnDemand(ctx)) + ?? (await handleAccountDiagnosticsRoutesOnDemand(ctx)) ?? (await handleRouteToRoutesOnDemand(ctx)) ?? (await handleWorkflowBudgetRoutesOnDemand(ctx)) ?? (await handleCodexAgentRoleRoutesOnDemand(ctx)) diff --git a/src/server/management/account-diagnostics-routes.ts b/src/server/management/account-diagnostics-routes.ts new file mode 100644 index 00000000000..7b5da429308 --- /dev/null +++ b/src/server/management/account-diagnostics-routes.ts @@ -0,0 +1,135 @@ +/** + * `GET /api/oauth/accounts/diagnostics?provider=`: why each account of one OAuth login can or + * cannot serve traffic right now. + * + * A passive read (`runPassiveReadSync`) assembled from state routing already keeps: account + * eligibility (the readers selection uses, once per quota family), the account-wide cooldown, the + * last upstream refresh result (`oauth/refresh-outcomes.ts`) and in-flight leases. Rows carry the + * account id only: no email, label, organization or credential field. + */ +import { isPublicOAuthProvider, OAUTH_PROVIDERS } from "../../oauth"; +import { oauthCredentialSlot } from "../../oauth/credential-siblings"; +import { getAccountSet, accountNeedsReauthForStatus } from "../../oauth/store"; +import { lastOAuthRefreshOutcome, oauthLoginIncarnation } from "../../oauth/refresh-outcomes"; +import { eligibleFailoverAccounts, genericAccountCooldownUntil, isGenericFailoverProvider } from "../../oauth/generic-account-failover"; +import { classifyModelFamilyForQuota } from "../../oauth/account-quota-rank"; +import { anthropicModelFamily } from "../../oauth/anthropic-model-family"; +import { accountInFlightSnapshot } from "../../oauth/kiro-account-load"; +import { anthropicRoutingFor } from "../../oauth/anthropic-routing"; +import { antigravityAccountModelSupport } from "../../providers/antigravity-account-roster"; +import { configuredAnthropicInstance, isAnthropicOAuthInstance, type AnthropicInstanceId } from "../../providers/anthropic-instance"; +import { getStaleCached } from "../../codex/model-cache"; +import { runPassiveReadSync } from "../../lib/passive-read"; +import { jsonResponse } from "../auth-cors"; +import type { ManagementContext } from "./context"; + +export interface AccountDiagnosticsRow { + id: string; + active: boolean; + paused: boolean; + needsReauth: boolean; + /** Whether automatic selection may pick this account right now (for some known model, when models are known). */ + eligible: boolean; + /** Known models this account may serve right now; null when the provider's model list is unknown. */ + eligibleModels: string[] | null; + lastRefresh: { at: number; ok: boolean; reason?: string; status?: number } | null; + cooldownUntil: number | null; + inFlight: number; + /** Kiro only: the account holds as many leases as `maxConcurrentPerAccount` allows. */ + atCapacity?: boolean; +} + +type Config = ManagementContext["config"]; + +function providerConfig(provider: string, config: Config) { + if (provider === "anthropic2" && !configuredAnthropicInstance(config, provider)) return undefined; + const configured = config.providers[provider]; + if (configured) return configured; + const definition = OAUTH_PROVIDERS[provider]; + return definition?.resolveProviderConfig?.(config) ?? definition?.providerConfig; +} + +/** Known model ids for the provider: the discovered catalog, else the configured list. */ +function knownModels(provider: string, config: Config): string[] | null { + const discovered = getStaleCached(provider)?.map(model => model.id).filter(id => typeof id === "string" && id.length > 0); + if (discovered?.length) return [...new Set(discovered)]; + const configured = config.providers[provider]?.models?.filter(id => typeof id === "string" && id.length > 0); + return configured?.length ? [...new Set(configured)] : null; +} + +function kiroCap(config: Config): number | undefined { + const cap = config.providers?.kiro?.oauthAccountFailover?.maxConcurrentPerAccount; + return typeof cap === "number" && Number.isInteger(cap) && cap >= 1 && cap <= 100 ? cap : undefined; +} + +export function buildAccountDiagnostics( + provider: string, config: Config, now = Date.now(), +): { provider: string; activeAccountId: string | null; models: string[] | null; accounts: AccountDiagnosticsRow[] } { + return runPassiveReadSync(() => { + const set = getAccountSet(provider); + const accounts = set?.accounts ?? []; + const models = knownModels(provider, config); + const effective = providerConfig(provider, config); + const anthropic = isAnthropicOAuthInstance(provider) && effective?.authMode === "oauth" + ? anthropicRoutingFor(provider as AnthropicInstanceId) : undefined; + const generic = !anthropic && effective !== undefined && isGenericFailoverProvider(provider, effective); + + // Eligibility varies only by quota family, so each reader runs once per family a known model has. + const familyOf = (model?: string): string => (anthropic ? anthropicModelFamily(model) : classifyModelFamilyForQuota(provider, model)) ?? ""; + const byFamily = new Map | undefined>(); + const eligibleFor = (model?: string): Set | undefined => { + const family = familyOf(model); + if (!byFamily.has(family)) { + byFamily.set(family, anthropic ? new Set(anthropic.getEligibleAnthropicAccounts(now, model)) + : generic ? new Set(eligibleFailoverAccounts(provider, now, classifyModelFamilyForQuota(provider, model))) : undefined); + } + return byFamily.get(family); + }; + const anyModel = eligibleFor(); + const cap = provider === "kiro" ? kiroCap(config) : undefined; + + const rows = accounts.map((account): AccountDiagnosticsRow => { + const paused = account.paused === true; + const needsReauth = accountNeedsReauthForStatus(provider, account, now); + // A snapshot: reclaiming an expired lease here would hand its slot to a queued request. + const inFlight = accountInFlightSnapshot(provider, account.id, now); + const atCapacity = cap !== undefined && inFlight >= cap; + const selectable = !atCapacity && (anyModel ? anyModel.has(account.id) : !paused && !needsReauth); + // Antigravity gates models per account from its discovered roster (#7500). + const roster = provider === "google-antigravity" && models ? antigravityAccountModelSupport(provider, account.id, models, now) : undefined; + const eligibleModels = models === null ? null : models.filter(model => { + if (atCapacity) return false; + const ids = eligibleFor(model); + if (ids ? !ids.has(account.id) : !selectable) return false; + return roster?.get(model) !== false; + }); + const cooldownUntil = anthropic + ? anthropic.getAnthropicAccountHealthSnapshot(account.id, now)?.cooldownUntil ?? null + : genericAccountCooldownUntil(provider, account.id, now); + const refresh = lastOAuthRefreshOutcome(provider, account.id, oauthLoginIncarnation(account)); + return { + id: account.id, + active: set?.activeAccountId === account.id, + paused, + needsReauth, + eligible: eligibleModels === null ? selectable : eligibleModels.length > 0, + eligibleModels, + lastRefresh: refresh ? { ...refresh } : null, + cooldownUntil, + inFlight, + ...(cap !== undefined ? { atCapacity } : {}), + }; + }); + return { provider, activeAccountId: set?.activeAccountId ?? null, models, accounts: rows }; + }); +} + +export function handleAccountDiagnosticsRoutes(ctx: Pick): Response | null { + const { req, url, config } = ctx; + if (url.pathname !== "/api/oauth/accounts/diagnostics" || req.method !== "GET") return null; + const provider = oauthCredentialSlot((url.searchParams.get("provider") ?? "").trim().toLowerCase()); + if (!isPublicOAuthProvider(provider)) return jsonResponse({ error: "unknown oauth provider" }, 400); + const response = jsonResponse(buildAccountDiagnostics(provider, config), 200, req, config); + response.headers.set("cache-control", "no-store"); + return response; +} diff --git a/src/server/management/route-registry.ts b/src/server/management/route-registry.ts index c7ebbef4264..77158b0fec2 100644 --- a/src/server/management/route-registry.ts +++ b/src/server/management/route-registry.ts @@ -400,6 +400,7 @@ export const MANAGEMENT_ROUTES: readonly ManagementRoute[] = [ { method: "GET", path: "/api/provider-quotas", module: "server/management/provider-routes", mutates: false }, { method: "GET", path: "/api/quota-pool", module: "server/management/quota-pool-routes", mutates: false, exempt: { reason: "deferred-verb", why: "The ocx.quota-pool/1 read is a machine contract GOAT consumes over management and the link relay; the CLI shows the same caches through ocx provider quota and ocx account.", owner: "ocx-1 quota pool", ownerDoc: "structure/quota-pool.md" } }, { method: "GET", path: "/api/fallback", module: "server/management/fallback-routes", mutates: false }, + { method: "GET", path: "/api/oauth/accounts/diagnostics", module: "server/management/account-diagnostics-routes", mutates: false, exempt: { reason: "deferred-verb", why: "Per-account eligibility, refresh, cooldown and lease diagnostics are a read-only operator view with no CLI verb yet; ocx account shows the account list.", owner: "catch-up 040a account diagnostics", ownerDoc: "structure/providers/generic-account-pool.md" } }, { method: "GET", path: "/api/route-to", module: "server/management/route-to-routes", mutates: false }, { method: "PUT", path: "/api/route-to", module: "server/management/route-to-routes", mutates: true }, { method: "POST", path: "/api/route-to/sync", module: "server/management/route-to-routes", mutates: true }, diff --git a/structure/providers/generic-account-pool.md b/structure/providers/generic-account-pool.md index 8b6368c1010..70137c3028d 100644 --- a/structure/providers/generic-account-pool.md +++ b/structure/providers/generic-account-pool.md @@ -50,3 +50,11 @@ account has an eligible sibling before cooling the whole target. This probe reco account's cooldown but passes `commit: false`, so it only peeks at a round-robin pool. An unsent sibling does not consume a sticky turn. Dispatching callers retain the default committed pick. `tests/oauth/generic-oauth-combo-account-cooldown.test.ts` covers this distinction. + +## Account diagnostics + +`GET /api/oauth/accounts/diagnostics?provider=` (`src/server/management/account-diagnostics-routes.ts`, loaded on demand by `src/server/management-api.ts`) explains why each account of one OAuth login can or cannot serve now. It runs inside `runPassiveReadSync`, so the credential-store read neither hardens, publishes nor backs up anything. Each row carries the account id, `active`, `paused`, `needsReauth`, `eligible`, `eligibleModels`, `lastRefresh`, `cooldownUntil`, `inFlight` and, for Kiro with `maxConcurrentPerAccount`, `atCapacity`; never an email, label, organization or credential field. + +Eligibility reuses the selection readers, once per quota family a known model has: Anthropic instances ask their routing (`getEligibleAnthropicAccounts`, grouped by `anthropicModelFamily`), generic pools ask `eligibleFailoverAccounts` with the model's quota family, and Antigravity additionally drops a model its account roster is known to omit (`antigravityAccountModelSupport` reads the credential generation at most once per account, and not at all without roster or denial evidence). A Kiro account holding as many leases as `maxConcurrentPerAccount` is not eligible. Other OAuth providers count an account eligible when it is neither paused nor flagged for reauthentication. The model list is the discovered catalog, else the configured `models`; with neither, `eligibleModels` is `null`. With a known list, `eligible` means at least one model is eligible. `cooldownUntil` is the account-wide hold (`genericAccountCooldownUntil` or the Anthropic health snapshot); family-scoped holds show up as models missing from `eligibleModels`. + +`lastRefresh` comes from `src/oauth/refresh-outcomes.ts`. The generic, xAI and Anthropic refresh paths in `src/oauth/index.ts` wrap their upstream refresh call in `observeOAuthRefresh`, which records the time and outcome per config home, login slot, account and login incarnation (the `loginId`, else `addedAt` for legacy rows, taken from the same account row the dispatched credential was read from, with the config home fixed at that moment), keeping at most 1024 entries. A login that replaces the account before, during or after the refresh therefore never inherits the old credential's result. A failure is reduced to a fixed reason (`rejected`, `upstream_error`, `network`, `timeout`, `aborted`, `error`) plus an HTTP status read from `status`, `statusCode` or `httpStatus`; no error text is kept. The record is process-local, so a restart reports `null`. `tests/server/account-diagnostics-routes.test.ts` covers the row fields, cooldown and family exclusion, the Antigravity roster and Kiro capacity cases, refresh recording through `refreshGenericAccountWithLock`, the scoping and bound, the passive read, and the absence of credential fields. diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index ec8cdf610d0..647aad825c5 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1,4 +1,4 @@ -{ "explicit-proxy-no-proxy.test.ts": "lib", "gemini-native.test.ts": "server", "gemini-native-wire.test.ts": "server", "gemini-native-routes.test.ts": "server", "provider-upstream-deadlines.test.ts": "responses", "web-search-local-deadline-provenance.test.ts": "web-search", "responses-combo-unavailable-cause.test.ts": "responses", "responses-native-sse-stall.test.ts": "responses", "client-restart-sync-fence.test.ts": "clients", "service-scheduler-restart-respawn-refusal.test.ts": "service", "route-to-home-sync-review.test.ts": "routing", "route-intent-connect-post-commit.test.ts": "clients", "route-intent-file-originals.test.ts": "clients", "route-to-child-defaults.test.ts": "routing", "route-to-home-live-flags.test.ts": "routing", "route-to-home-native-truth.test.ts": "routing", "route-to-home-decisions.test.ts": "routing", "route-to-ephemeral.test.ts": "server", "link-pinned-sync-overwrite.test.ts": "clients", "cli-sync-fanout-ephemeral.test.ts": "cli", "route-intent-home-consent.test.ts": "clients", "management-route-intent-native-errors.test.ts": "server", "route-intent-offline-mode-switch.test.ts": "clients", "route-intent-parity-withdrawal.test.ts": "clients", "service-scheduler-restart-cleanup.test.ts": "service", "route-to-retirement-review.test.ts": "server", "route-to-policy-review.test.ts": "server", "management-route-intent-native-review.test.ts": "server", "route-to-home-off-review.test.ts": "routing", "codex-journal-provider-reserialization.test.ts": "codex-integration", "route-intent-parity-fallback.test.ts": "clients", "route-intent-native-originals.test.ts": "clients", "route-intent-native-review.test.ts": "clients", "route-intent-connected-capabilities.test.ts": "clients", "route-intent-connected-review.test.ts": "clients", "route-intent-connect-recovery.test.ts": "clients", "client-disconnect-field-snapshot.test.ts": "clients", "cli-route-to-confirmation.test.ts": "cli", "route-intent-runtime-stop.test.ts": "clients", "route-intent-codex-connect-disabled.test.ts": "clients", "route-intent-codex-transitions.test.ts": "clients", "route-to-live-settings.test.ts": "server", "route-intent-claude-surface.test.ts": "clients", "route-intent-local-receipt.test.ts": "clients", "route-intent-scheduler.test.ts": "clients", "route-intent-watch-client.test.ts": "clients", "route-intent-watch-boundary.test.ts": "server", "route-intent-watch-waiters.test.ts": "server", "home-route-intent-upgrade.test.ts": "clients", "route-intent-overwrite.test.ts": "clients", "codex-disconnect-owned-recovery.test.ts": "codex-integration", "service-restart-registration-guard.test.ts": "service", "client-disconnect-config-recovery.test.ts": "clients", "route-intent-aside.test.ts": "clients", "route-intent-connected.test.ts": "clients", "cli-link-route-intent.test.ts": "cli", "cli-route-to-aliases.test.ts": "cli", "cli-route-to.test.ts": "cli", "client-disconnect-edited-codex.test.ts": "clients", "codex-disconnect-fields.test.ts": "codex-integration", "link-home-route-intent.test.ts": "clients", "link-route-intent.test.ts": "server", "route-intent-desktop.test.ts": "clients", "route-intent-materializer.test.ts": "clients", "route-intent-parity.test.ts": "clients", "route-intent-reporter.test.ts": "clients", "route-intent-state.test.ts": "clients", "route-intent.test.ts": "clients", "route-to-routes.test.ts": "server", "route-to-sync-child.test.ts": "routing", "service-disconnected-client-restart.test.ts": "service", "responses-forward-client-headers-live.test.ts": "responses", "pool-retry-client-metadata.test.ts": "responses", "responses-websocket-workflow-ceiling.test.ts": "responses", "responses-workflow-send-ceiling.test.ts": "responses", "kimi-monthly-quota.test.ts": "providers", "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "lmstudio-system-policy.test.ts": "config", "openai-chat-single-system.test.ts": "adapters/openai", "update-reclaim-authorizer.test.ts": "update", "update-capability-policy.test.ts": "update", "update-service-home.test.ts": "update", "update-service-home-policy.test.ts": "update", "update-home-recovery.test.ts": "update", "update-recovery-authority.test.ts": "update", "update-recovery-boundaries.test.ts": "update", "update-home-launcher.test.ts": "update", "update-home-worker.test.ts": "update", "update-mutation-boundaries.test.ts": "update", "update-mutation-guard.test.ts": "update", "update-guarded-ops.test.ts": "update", "update-effect-authority.test.ts": "update", "update-windows-wrapper-authority.test.ts": "update", "update-mutation-scanner.test.ts": "update", "refreshed-upstream-deadlines.test.ts": "responses", "local-upstream-deadlines.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "provider-input-modalities.test.ts": "providers", "turn-membership.test.ts": "responses", "turn-membership-ingress.test.ts": "responses", "workbuddy-quota.test.ts": "providers", "workbuddy-login.test.ts": "oauth", "workbuddy-adapter.test.ts": "adapters", "workbuddy-provider.test.ts": "providers", "link-tunnel-history.test.ts": "clients", "link-readiness.test.ts": "clients", "link-tunnel-status.test.ts": "clients", "link-diagnostics.test.ts": "clients", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "responses-chat-raw-summary.test.ts": "responses", "responses-phase-inference.test.ts": "responses", "cli-message-mcp-resume.test.ts": "cli", "messaging-mcp-resume.test.ts": "codex-integration", "link-diagnostics-read.test.ts": "clients", "cli-link-diagnostics.test.ts": "cli", "link-diagnostics-route.test.ts": "server", "provider-passive-wire-model.test.ts": "providers", "passive-key-observation.test.ts": "providers", "responses-passive-key-limits.test.ts": "responses", "passive-key-limits.test.ts": "providers", "terminal-safe-text.test.ts": "lib", +{ "account-diagnostics-routes.test.ts": "server", "explicit-proxy-no-proxy.test.ts": "lib", "gemini-native.test.ts": "server", "gemini-native-wire.test.ts": "server", "gemini-native-routes.test.ts": "server", "provider-upstream-deadlines.test.ts": "responses", "web-search-local-deadline-provenance.test.ts": "web-search", "responses-combo-unavailable-cause.test.ts": "responses", "responses-native-sse-stall.test.ts": "responses", "client-restart-sync-fence.test.ts": "clients", "service-scheduler-restart-respawn-refusal.test.ts": "service", "route-to-home-sync-review.test.ts": "routing", "route-intent-connect-post-commit.test.ts": "clients", "route-intent-file-originals.test.ts": "clients", "route-to-child-defaults.test.ts": "routing", "route-to-home-live-flags.test.ts": "routing", "route-to-home-native-truth.test.ts": "routing", "route-to-home-decisions.test.ts": "routing", "route-to-ephemeral.test.ts": "server", "link-pinned-sync-overwrite.test.ts": "clients", "cli-sync-fanout-ephemeral.test.ts": "cli", "route-intent-home-consent.test.ts": "clients", "management-route-intent-native-errors.test.ts": "server", "route-intent-offline-mode-switch.test.ts": "clients", "route-intent-parity-withdrawal.test.ts": "clients", "service-scheduler-restart-cleanup.test.ts": "service", "route-to-retirement-review.test.ts": "server", "route-to-policy-review.test.ts": "server", "management-route-intent-native-review.test.ts": "server", "route-to-home-off-review.test.ts": "routing", "codex-journal-provider-reserialization.test.ts": "codex-integration", "route-intent-parity-fallback.test.ts": "clients", "route-intent-native-originals.test.ts": "clients", "route-intent-native-review.test.ts": "clients", "route-intent-connected-capabilities.test.ts": "clients", "route-intent-connected-review.test.ts": "clients", "route-intent-connect-recovery.test.ts": "clients", "client-disconnect-field-snapshot.test.ts": "clients", "cli-route-to-confirmation.test.ts": "cli", "route-intent-runtime-stop.test.ts": "clients", "route-intent-codex-connect-disabled.test.ts": "clients", "route-intent-codex-transitions.test.ts": "clients", "route-to-live-settings.test.ts": "server", "route-intent-claude-surface.test.ts": "clients", "route-intent-local-receipt.test.ts": "clients", "route-intent-scheduler.test.ts": "clients", "route-intent-watch-client.test.ts": "clients", "route-intent-watch-boundary.test.ts": "server", "route-intent-watch-waiters.test.ts": "server", "home-route-intent-upgrade.test.ts": "clients", "route-intent-overwrite.test.ts": "clients", "codex-disconnect-owned-recovery.test.ts": "codex-integration", "service-restart-registration-guard.test.ts": "service", "client-disconnect-config-recovery.test.ts": "clients", "route-intent-aside.test.ts": "clients", "route-intent-connected.test.ts": "clients", "cli-link-route-intent.test.ts": "cli", "cli-route-to-aliases.test.ts": "cli", "cli-route-to.test.ts": "cli", "client-disconnect-edited-codex.test.ts": "clients", "codex-disconnect-fields.test.ts": "codex-integration", "link-home-route-intent.test.ts": "clients", "link-route-intent.test.ts": "server", "route-intent-desktop.test.ts": "clients", "route-intent-materializer.test.ts": "clients", "route-intent-parity.test.ts": "clients", "route-intent-reporter.test.ts": "clients", "route-intent-state.test.ts": "clients", "route-intent.test.ts": "clients", "route-to-routes.test.ts": "server", "route-to-sync-child.test.ts": "routing", "service-disconnected-client-restart.test.ts": "service", "responses-forward-client-headers-live.test.ts": "responses", "pool-retry-client-metadata.test.ts": "responses", "responses-websocket-workflow-ceiling.test.ts": "responses", "responses-workflow-send-ceiling.test.ts": "responses", "kimi-monthly-quota.test.ts": "providers", "sync-fanout.test.ts": "cli", "sync-command-fanout.test.ts": "cli", "link-pinned-sync-argv.test.ts": "clients", "sync-link-status.test.ts": "cli", "sync-fanout-process.test.ts": "cli", "codex-installation-acl.test.ts": "codex-integration", "codex-installation-id.test.ts": "codex-integration", "codex-installation-wire.test.ts": "codex-integration", "codex-installation-failover.test.ts": "responses", "lmstudio-system-policy.test.ts": "config", "openai-chat-single-system.test.ts": "adapters/openai", "update-reclaim-authorizer.test.ts": "update", "update-capability-policy.test.ts": "update", "update-service-home.test.ts": "update", "update-service-home-policy.test.ts": "update", "update-home-recovery.test.ts": "update", "update-recovery-authority.test.ts": "update", "update-recovery-boundaries.test.ts": "update", "update-home-launcher.test.ts": "update", "update-home-worker.test.ts": "update", "update-mutation-boundaries.test.ts": "update", "update-mutation-guard.test.ts": "update", "update-guarded-ops.test.ts": "update", "update-effect-authority.test.ts": "update", "update-windows-wrapper-authority.test.ts": "update", "update-mutation-scanner.test.ts": "update", "refreshed-upstream-deadlines.test.ts": "responses", "local-upstream-deadlines.test.ts": "responses", "service-desktop-recovery.test.ts": "service", "provider-input-modalities.test.ts": "providers", "turn-membership.test.ts": "responses", "turn-membership-ingress.test.ts": "responses", "workbuddy-quota.test.ts": "providers", "workbuddy-login.test.ts": "oauth", "workbuddy-adapter.test.ts": "adapters", "workbuddy-provider.test.ts": "providers", "link-tunnel-history.test.ts": "clients", "link-readiness.test.ts": "clients", "link-tunnel-status.test.ts": "clients", "link-diagnostics.test.ts": "clients", "combo-description.test.ts": "routing", "combo-description-catalog.test.ts": "codex-integration", "catalog-auto-review-override.test.ts": "codex-integration", "management-auto-review-settings.test.ts": "server", "management-auto-review-auth.test.ts": "server", "prefer-model-alias-ids.test.ts": "server", "responses-mimo-envelope.test.ts": "responses", "responses-call-id-linkage.test.ts": "responses", "responses-chat-raw-summary.test.ts": "responses", "responses-phase-inference.test.ts": "responses", "cli-message-mcp-resume.test.ts": "cli", "messaging-mcp-resume.test.ts": "codex-integration", "link-diagnostics-read.test.ts": "clients", "cli-link-diagnostics.test.ts": "cli", "link-diagnostics-route.test.ts": "server", "provider-passive-wire-model.test.ts": "providers", "passive-key-observation.test.ts": "providers", "responses-passive-key-limits.test.ts": "responses", "passive-key-limits.test.ts": "providers", "terminal-safe-text.test.ts": "lib", "codex-ws-recovery-budget.test.ts": "responses", "codex-ws-cache-miss.test.ts": "responses", "codex-ws-incremental.test.ts": "responses", diff --git a/tests/server/account-diagnostics-routes.test.ts b/tests/server/account-diagnostics-routes.test.ts new file mode 100644 index 00000000000..bde7f0925fd --- /dev/null +++ b/tests/server/account-diagnostics-routes.test.ts @@ -0,0 +1,289 @@ +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; +import { chmodSync, mkdtempSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { OAUTH_PROVIDERS, getValidAccessTokenForAccount } from "../../src/oauth"; +import { clearGenericFailoverHealth, rotateGenericOAuthAccountOn429 } from "../../src/oauth/generic-account-failover"; +import { getAccountSet, markAccountNeedsReauth, saveAccountCredential, saveCredential } from "../../src/oauth/store"; +import { refreshGenericAccountWithLock } from "../../src/oauth"; +import { readFileSync, writeFileSync } from "node:fs"; +const incarnationOf = (provider: string, id: string) => oauthLoginIncarnation(getAccountSet(provider)!.accounts.find(row => row.id === id)); +import { + classifyOAuthRefreshFailure, + clearOAuthRefreshOutcomes, + lastOAuthRefreshOutcome, + MAX_OAUTH_REFRESH_OUTCOMES, + oauthLoginIncarnation, + oauthRefreshOutcomeCountForTests, + observeOAuthRefresh, + recordOAuthRefreshOutcome, +} from "../../src/oauth/refresh-outcomes"; +import { AnthropicTokenError } from "../../src/oauth/anthropic"; +import { KiroTokenRefreshError } from "../../src/oauth/kiro"; +import { acquireAccountLease, accountInFlightSnapshot, KIRO_LEASE_MAX_MS } from "../../src/oauth/kiro-account-load"; +import { antigravityAccountModelSupport, antigravityAccountSupportsModel, clearAntigravityAccountRosters, recordAntigravityAccountRoster } from "../../src/providers/antigravity-account-roster"; +import * as store from "../../src/oauth/store"; +import { join as joinPath } from "node:path"; +import { clearModelCache, setCached } from "../../src/codex/model-cache"; +import { + buildAccountDiagnostics, + handleAccountDiagnosticsRoutes, +} from "../../src/server/management/account-diagnostics-routes"; +import type { CatalogModel } from "../../src/codex/catalog/parsing"; +import type { OcxConfig, OcxProviderConfig } from "../../src/types"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const previousHome = process.env.OPENCODEX_HOME; +const originalKimiRefresh = OAUTH_PROVIDERS.kimi!.refresh; +let home: string; + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "ocx-account-diagnostics-")); + process.env.OPENCODEX_HOME = home; + clearGenericFailoverHealth(); + clearOAuthRefreshOutcomes(); +}); +afterEach(() => { + OAUTH_PROVIDERS.kimi!.refresh = originalKimiRefresh; + clearGenericFailoverHealth(); + clearOAuthRefreshOutcomes(); + clearModelCache("xai"); + clearModelCache("google-antigravity"); + clearAntigravityAccountRosters(); + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previousHome; + removeTreeWithRetry(home); +}); + +const oauthProvider = (adapter: string, baseUrl: string, models?: string[]) => + ({ adapter, baseUrl, authMode: "oauth", ...(models ? { models } : {}) }) as unknown as OcxProviderConfig; + +function config(providers: Record): OcxConfig { + return { port: 0, defaultProvider: Object.keys(providers)[0], providers, oauthAccountFailover: { enabled: true } } as unknown as OcxConfig; +} + +async function seed(provider: string, count: number): Promise { + for (let i = 0; i < count; i += 1) { + await saveCredential(provider, { + access: `secret-access-${i}`, refresh: `secret-refresh-${i}`, expires: Date.now() + 3_600_000, + accountId: `uuid-${provider}-${i}`, email: `user${i}@example.com`, + } as never, { addAccount: true }); + } + return getAccountSet(provider)!.accounts.map(account => account.id); +} + +test("a refresh failure is reduced to a fixed reason and status, never its message", async () => { + const rejected = Object.assign(new Error("invalid_grant for secret-refresh-0"), { status: 401 }); + await expect(observeOAuthRefresh("xai", "acct", () => Promise.reject(rejected), undefined)).rejects.toBe(rejected); + expect(lastOAuthRefreshOutcome("xai", "acct", "")).toMatchObject({ ok: false, reason: "rejected", status: 401 }); + expect(JSON.stringify(lastOAuthRefreshOutcome("xai", "acct", ""))).not.toContain("secret"); + + await expect(observeOAuthRefresh("xai", "acct", () => Promise.resolve("token"), undefined)).resolves.toBe("token"); + expect(lastOAuthRefreshOutcome("xai", "acct", "")).toMatchObject({ ok: true }); + expect(lastOAuthRefreshOutcome("xai", "acct", "")?.reason).toBeUndefined(); + + expect(classifyOAuthRefreshFailure(Object.assign(new Error("x"), { status: 503 }))).toEqual({ reason: "upstream_error", status: 503 }); + expect(classifyOAuthRefreshFailure(Object.assign(new Error("x"), { code: "ECONNREFUSED" }))).toEqual({ reason: "network" }); + expect(classifyOAuthRefreshFailure(new DOMException("t", "TimeoutError"))).toEqual({ reason: "timeout" }); + expect(classifyOAuthRefreshFailure(new DOMException("a", "AbortError"))).toEqual({ reason: "aborted" }); + expect(classifyOAuthRefreshFailure("boom")).toEqual({ reason: "error" }); + // A synchronous throw from the refresh call is recorded too. + await expect(observeOAuthRefresh("xai", "sync", () => { throw new Error("sync"); }, undefined)).rejects.toThrow("sync"); + expect(lastOAuthRefreshOutcome("xai", "sync", "")).toMatchObject({ ok: false, reason: "error" }); +}); + +test("a real generic refresh records its outcome for the account", async () => { + await saveCredential("kimi", { access: "kimi-old", refresh: "rt-old", expires: Date.now() - 1, accountId: "kimi-acct" } as never); + const accountId = getAccountSet("kimi")!.activeAccountId!; + OAUTH_PROVIDERS.kimi!.refresh = async () => ({ access: "kimi-fresh", refresh: "rt-new", expires: Date.now() + 3_600_000 }); + await expect(getValidAccessTokenForAccount("kimi", accountId)).resolves.toBe("kimi-fresh"); + expect(lastOAuthRefreshOutcome("kimi", accountId, oauthLoginIncarnation(getAccountSet("kimi")!.accounts[0]))).toMatchObject({ ok: true }); +}); + +test("rows show cooldown, refresh result, reauth and eligibility without any credential field", async () => { + const cfg = config({ xai: oauthProvider("openai-chat", "https://api.x.ai/v1", ["grok-a", "grok-b"]) }); + const [cooled, failing, flagged] = await seed("xai", 3); + const now = Date.now(); + rotateGenericOAuthAccountOn429(cfg, "xai", cooled!, "120", now); + recordOAuthRefreshOutcome("xai", failing!, { at: now, ok: false, reason: "rejected", status: 400 }, incarnationOf("xai", failing!)); + await markAccountNeedsReauth("xai", flagged!, true); + + const view = buildAccountDiagnostics("xai", cfg, now); + expect(view.models).toEqual(["grok-a", "grok-b"]); + const row = (id: string) => view.accounts.find(account => account.id === id)!; + expect(row(cooled!)).toMatchObject({ eligible: false, eligibleModels: [], cooldownUntil: now + 120_000, inFlight: 0, lastRefresh: null }); + expect(row(failing!)).toMatchObject({ eligible: true, eligibleModels: ["grok-a", "grok-b"], cooldownUntil: null, + lastRefresh: { at: now, ok: false, reason: "rejected", status: 400 } }); + expect(row(flagged!)).toMatchObject({ eligible: false, needsReauth: true, eligibleModels: [] }); + + const body = JSON.stringify(view); + for (const forbidden of ["secret-access", "secret-refresh", "@example.com", "email", "organization"]) expect(body).not.toContain(forbidden); +}); + +test("a family-scoped cooldown removes only that family's models", async () => { + const cfg = config({ "google-antigravity": oauthProvider("google", "https://cloudcode-pa.googleapis.com") }); + setCached("google-antigravity", [{ id: "gemini-3-pro" }, { id: "claude-sonnet-4-6" }] as CatalogModel[]); + const [first, second] = await seed("google-antigravity", 2); + const now = Date.now(); + rotateGenericOAuthAccountOn429(cfg, "google-antigravity", first!, "300", now, "gemini-3-pro"); + const view = buildAccountDiagnostics("google-antigravity", cfg, now); + const row = (id: string) => view.accounts.find(account => account.id === id)!; + expect(row(first!)).toMatchObject({ eligible: true, eligibleModels: ["claude-sonnet-4-6"], cooldownUntil: null }); + expect(row(second!).eligibleModels).toEqual(["gemini-3-pro", "claude-sonnet-4-6"]); +}); + +test("an unknown model list is reported as null rather than empty", async () => { + const cfg = config({ xai: oauthProvider("openai-chat", "https://api.x.ai/v1") }); + await seed("xai", 1); + expect(buildAccountDiagnostics("xai", cfg).accounts[0]!.eligibleModels).toBeNull(); +}); + +test("the route answers GET for a known OAuth provider and refuses an unknown one", async () => { + const cfg = config({ xai: oauthProvider("openai-chat", "https://api.x.ai/v1", ["grok-a"]) }); + await seed("xai", 1); + const call = (query: string, method = "GET") => { + const url = new URL(`http://127.0.0.1/api/oauth/accounts/diagnostics${query}`); + return handleAccountDiagnosticsRoutes({ req: new Request(url, { method }), url, config: cfg }); + }; + const ok = call("?provider=xai")!; + expect(ok.status).toBe(200); + expect(ok.headers.get("cache-control")).toBe("no-store"); + expect((await ok.json() as { accounts: unknown[] }).accounts).toHaveLength(1); + expect(call("?provider=not-a-provider")!.status).toBe(400); + expect(call("?provider=xai", "POST")).toBeNull(); +}); + +test("provider token errors keep their HTTP status", () => { + expect(classifyOAuthRefreshFailure(new AnthropicTokenError("denied", 401, "invalid_grant"))).toEqual({ reason: "rejected", status: 401 }); + expect(classifyOAuthRefreshFailure(new AnthropicTokenError("unreachable", undefined, undefined, true))).toEqual({ reason: "error" }); + expect(classifyOAuthRefreshFailure(new KiroTokenRefreshError(503))).toEqual({ reason: "upstream_error", status: 503 }); +}); + +test("refresh results are fenced to the login, the config home and a bounded size", async () => { + const cfg = config({ xai: oauthProvider("openai-chat", "https://api.x.ai/v1", ["grok-a"]) }); + const [id] = await seed("xai", 1); + recordOAuthRefreshOutcome("xai", id!, { at: Date.now(), ok: true }, incarnationOf("xai", id!)); + expect(buildAccountDiagnostics("xai", cfg).accounts[0]!.lastRefresh).toMatchObject({ ok: true }); + + // An in-place login mints a new loginId: the previous login's result is not this login's. + const credential = getAccountSet("xai")!.accounts[0]!.credential; + await saveAccountCredential("xai", id!, credential, { rotateLoginId: true }); + expect(buildAccountDiagnostics("xai", cfg).accounts[0]!.lastRefresh).toBeNull(); + + const other = mkdtempSync(joinPath(tmpdir(), "ocx-account-diagnostics-other-")); + try { + process.env.OPENCODEX_HOME = other; + expect(lastOAuthRefreshOutcome("xai", id!, "login:any")).toBeNull(); + } finally { + process.env.OPENCODEX_HOME = home; + removeTreeWithRetry(other); + } + + for (let i = 0; i < MAX_OAUTH_REFRESH_OUTCOMES + 10; i += 1) recordOAuthRefreshOutcome("xai", `churn-${i}`, { at: i, ok: true }, ""); + expect(oauthRefreshOutcomeCountForTests()).toBe(MAX_OAUTH_REFRESH_OUTCOMES); + expect(lastOAuthRefreshOutcome("xai", "churn-0", "")).toBeNull(); +}); + +test("a refresh that finishes after its login was replaced does not report on the new login", async () => { + const cfg = config({ xai: oauthProvider("openai-chat", "https://api.x.ai/v1", ["grok-a"]) }); + const [id] = await seed("xai", 1); + let finish!: (value: string) => void; + const inFlight = observeOAuthRefresh("xai", id!, () => new Promise(resolve => { finish = resolve; }), getAccountSet("xai")!.accounts[0]); + const credential = getAccountSet("xai")!.accounts[0]!.credential; + await saveAccountCredential("xai", id!, credential, { rotateLoginId: true }); + finish("token"); + await inFlight; + expect(buildAccountDiagnostics("xai", cfg).accounts[0]!.lastRefresh).toBeNull(); +}); + +test("an expired lease with a queued waiter is counted out without admitting the waiter", async () => { + const [id] = await seed("kiro", 1); + const lease = await acquireAccountLease("kiro", id!, { maxConcurrentPerAccount: 1 }); + let admitted = false; + const waiter = acquireAccountLease("kiro", id!, { maxConcurrentPerAccount: 1, waitMs: 5_000 }).then(next => { admitted = true; return next; }); + const later = Date.now() + KIRO_LEASE_MAX_MS + 1; + expect(accountInFlightSnapshot("kiro", id!, later)).toBe(0); + const kiro = { ...oauthProvider("kiro", "https://q.us-east-1.amazonaws.com", ["claude-sonnet-4-6"]), + oauthAccountFailover: { enabled: true, maxConcurrentPerAccount: 1 } } as unknown as OcxProviderConfig; + expect(buildAccountDiagnostics("kiro", config({ kiro }), later).accounts[0]!.inFlight).toBe(0); + await Bun.sleep(20); + expect(admitted).toBe(false); + lease?.release(); + (await waiter)?.release(); + expect(admitted).toBe(true); +}); + +test("an Antigravity account without roster or denial evidence costs no credential read", async () => { + const [id] = await seed("google-antigravity", 1); + const loads = spyOn(store, "getAccountCredentialWithStatus"); + try { + expect(antigravityAccountSupportsModel("google-antigravity", id!, "gemini-3-pro")).toBeUndefined(); + expect([...antigravityAccountModelSupport("google-antigravity", id!, ["gemini-3-pro", "claude-sonnet-4-6"]).values()]).toEqual([undefined, undefined]); + expect(loads).toHaveBeenCalledTimes(0); + recordAntigravityAccountRoster("google-antigravity", id!, [{ id: "gemini-3-pro", wireModelId: "gemini-3-pro" }]); + loads.mockClear(); + expect([...antigravityAccountModelSupport("google-antigravity", id!, ["gemini-3-pro", "claude-sonnet-4-6"]).values()]).toEqual([true, false]); + expect(loads).toHaveBeenCalledTimes(1); + } finally { + loads.mockRestore(); + } +}); + +test("an Antigravity account whose roster omits every known model is not eligible", async () => { + const cfg = config({ "google-antigravity": oauthProvider("google", "https://cloudcode-pa.googleapis.com") }); + setCached("google-antigravity", [{ id: "gemini-3-pro" }, { id: "claude-sonnet-4-6" }] as CatalogModel[]); + const [narrow, wide] = await seed("google-antigravity", 2); + recordAntigravityAccountRoster("google-antigravity", narrow!, [{ id: "gemini-2-flash", wireModelId: "gemini-2-flash" }]); + const view = buildAccountDiagnostics("google-antigravity", cfg); + const row = (id: string) => view.accounts.find(account => account.id === id)!; + expect(row(narrow!)).toMatchObject({ eligible: false, eligibleModels: [] }); + expect(row(wide!)).toMatchObject({ eligible: true, eligibleModels: ["gemini-3-pro", "claude-sonnet-4-6"] }); +}); + +test("a Kiro account at its concurrency cap is reported at capacity and not eligible", async () => { + const kiro = { ...oauthProvider("kiro", "https://q.us-east-1.amazonaws.com", ["claude-sonnet-4-6"]), + oauthAccountFailover: { enabled: true, maxConcurrentPerAccount: 1 } } as unknown as OcxProviderConfig; + const cfg = config({ kiro }); + const [busy, idle] = await seed("kiro", 2); + const lease = await acquireAccountLease("kiro", busy!, { maxConcurrentPerAccount: 1 }); + try { + const view = buildAccountDiagnostics("kiro", cfg); + const row = (id: string) => view.accounts.find(account => account.id === id)!; + expect(row(busy!)).toMatchObject({ inFlight: 1, atCapacity: true, eligible: false, eligibleModels: [] }); + expect(row(idle!)).toMatchObject({ inFlight: 0, atCapacity: false }); + } finally { + lease?.release(); + } +}); + +test.skipIf(process.platform === "win32")("the diagnostics read does not harden or rewrite the credential store", async () => { + const cfg = config({ xai: oauthProvider("openai-chat", "https://api.x.ai/v1", ["grok-a"]) }); + await seed("xai", 1); + const authPath = joinPath(home, "auth.json"); + chmodSync(authPath, 0o644); + const before = statSync(authPath); + buildAccountDiagnostics("xai", cfg); + const after = statSync(authPath); + expect(after.mode & 0o777).toBe(0o644); + expect(after.mtimeMs).toBe(before.mtimeMs); +}); + +test("a login replaced between the credential read and the refresh call does not inherit the result", async () => { + await saveCredential("kimi", { access: "kimi-old", refresh: "rt-old", expires: Date.now() - 1, accountId: "kimi-acct" } as never); + const accountId = getAccountSet("kimi")!.activeAccountId!; + const before = incarnationOf("kimi", accountId); + const stored = getAccountSet("kimi")!.accounts[0]!.credential; + const def = { ...OAUTH_PROVIDERS.kimi!, refresh: async () => ({ access: "kimi-fresh", refresh: "rt-new", expires: Date.now() + 3_600_000 }) }; + const authPath = joinPath(home, "auth.json"); + // Another process logs in again after this refresh read its credential and before it dispatches. + const replaceLogin = () => { + const authStore = JSON.parse(readFileSync(authPath, "utf8")); + authStore.kimi.accounts.find((row: { id: string }) => row.id === accountId).loginId = crypto.randomUUID(); + writeFileSync(authPath, JSON.stringify(authStore)); + return true; + }; + await refreshGenericAccountWithLock("kimi", accountId, def, stored, { authorityCurrent: replaceLogin }).catch(() => undefined); + const after = incarnationOf("kimi", accountId); + expect(after).not.toBe(before); + expect(lastOAuthRefreshOutcome("kimi", accountId, after)).toBeNull(); + expect(lastOAuthRefreshOutcome("kimi", accountId, before)).toMatchObject({ ok: true }); +}); From d2e308d9ce2105a2dbda45e2036b06f018e1ebfc Mon Sep 17 00:00:00 2001 From: sunseol Date: Wed, 25 Nov 2026 14:37:28 +0900 Subject: [PATCH 35/60] fix(zai): degrade unsupported original image detail on Z.AI Responses (#9048) (#9049) Z.AI's Responses endpoint rejects input_image detail "original" with HTTP 400 / code 1210 "Invalid API parameter". codex-rs sends that value from view_image and screenshot tool results, and the image stays in history, so every later turn of the thread failed the same way. Add an exact-destination projection for https://api.z.ai/api/v1/responses that degrades "original" to "high" (the codex default) in message content and array-valued tool outputs, applied in the passthrough right after the OpenGateway projection. Other destinations and the source body are untouched; existing threads recover on their next send. Co-authored-by: JUN --- scripts/test-layout/layout-adapters.json | 3 +- src/adapters/openai-responses/passthrough.ts | 2 + src/adapters/openai-responses/zai-input.ts | 51 ++++++++ structure/INDEX.md | 4 +- structure/manifest.json | 10 ++ structure/providers/zai-image-detail.md | 27 ++++ tests/adapters/openai/zai-input.test.ts | 128 +++++++++++++++++++ tests/fixtures/test-layout-expected.json | 1 + 8 files changed, 224 insertions(+), 2 deletions(-) create mode 100644 src/adapters/openai-responses/zai-input.ts create mode 100644 structure/providers/zai-image-detail.md create mode 100644 tests/adapters/openai/zai-input.test.ts diff --git a/scripts/test-layout/layout-adapters.json b/scripts/test-layout/layout-adapters.json index e95629b7ea1..9da034cb408 100644 --- a/scripts/test-layout/layout-adapters.json +++ b/scripts/test-layout/layout-adapters.json @@ -48,5 +48,6 @@ "google-error-details.test.ts": "adapters/google", "google-retry-structured.test.ts": "adapters/google", "google-finish-fidelity.test.ts": "adapters/google", - "google-request-fidelity.test.ts": "adapters/google" + "google-request-fidelity.test.ts": "adapters/google", + "zai-input.test.ts": "adapters/openai" } diff --git a/src/adapters/openai-responses/passthrough.ts b/src/adapters/openai-responses/passthrough.ts index 5e94982ad68..157d90e3457 100644 --- a/src/adapters/openai-responses/passthrough.ts +++ b/src/adapters/openai-responses/passthrough.ts @@ -60,6 +60,7 @@ import { normalizeMuseToolChoice } from "./muse-tool-choice"; import { declaresHostedWebSearch, projectHostedSearchHistory, renderCompactionSearchHistoryItems } from "./compaction-search-history"; import { isKimiCodingResponsesHttpsUrl, stripKimiEmptyAssistantMessages } from "./empty-assistant"; import { normalizeOpenGatewayResponsesInput } from "./opengateway-input"; +import { normalizeZaiResponsesInput } from "./zai-input"; /** * Identifies DeepSeek's strict Responses replay contract: tool-bearing continuations need @@ -540,6 +541,7 @@ export function createResponsesPassthroughAdapter(provider: OcxProviderConfig): finalBody = projectHostedSearchHistory(finalBody); } finalBody = normalizeOpenGatewayResponsesInput(finalBody, url); + finalBody = normalizeZaiResponsesInput(finalBody, url); observeOutbound(parsed._rawBody, finalBody, headers); if (!isCanonicalOpenAiForwardProvider(provider)) { validateFinalCustomToolCompatibility(finalBody, provider.supportsResponsesCustomTools); diff --git a/src/adapters/openai-responses/zai-input.ts b/src/adapters/openai-responses/zai-input.ts new file mode 100644 index 00000000000..bf0fa13b500 --- /dev/null +++ b/src/adapters/openai-responses/zai-input.ts @@ -0,0 +1,51 @@ +import { isPlainObject } from "./internal"; + +const ZAI_RESPONSES_URL = "https://api.z.ai/api/v1/responses"; + +function degradeOriginalDetail(part: unknown): unknown { + return isPlainObject(part) && part.type === "input_image" && part.detail === "original" + ? { ...part, detail: "high" } + : part; +} + +/** Returns the same array when no part changes, so unchanged items keep their identity. */ +function degradeParts(parts: unknown[]): unknown[] { + let changed = false; + const next = parts.map(part => { + const projected = degradeOriginalDetail(part); + if (projected !== part) changed = true; + return projected; + }); + return changed ? next : parts; +} + +/** + * Z.AI's Responses endpoint accepts image detail auto|low|high only. codex-rs sends + * `detail: "original"` when the catalog row advertises `supports_image_detail_original`, + * and Z.AI answers the whole request with HTTP 400 "Invalid API parameter". Because the + * image stays in history, every later turn of the thread fails the same way. Message content + * and every array-valued tool output (`function_call_output`, `custom_tool_call_output`, ...) + * degrade "original" to "high", the codex default. Image bytes, part order and every other + * field are unchanged; other destinations and the source body are untouched. + */ +export function normalizeZaiResponsesInput(body: unknown, url: string): unknown { + // Exact-URL boundary, the same shape as the OpenGateway projection: a query-routed or + // lookalike destination is a different upstream. + if (url !== ZAI_RESPONSES_URL || !isPlainObject(body) || !Array.isArray(body.input)) return body; + let changed = false; + const input = body.input.map(item => { + if (!isPlainObject(item)) return item; + let next = item; + if (Array.isArray(item.content)) { + const content = degradeParts(item.content); + if (content !== item.content) next = { ...next, content }; + } + if (Array.isArray(item.output)) { + const output = degradeParts(item.output); + if (output !== item.output) next = { ...next, output }; + } + if (next !== item) changed = true; + return next; + }); + return changed ? { ...body, input } : body; +} diff --git a/structure/INDEX.md b/structure/INDEX.md index 9ac2f198c92..ecd299a0e70 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -104,6 +104,7 @@ Per-vendor contracts and the adapter authority that constructs them. | [`providers-and-adapters.md`](providers-and-adapters.md) | Provider and adapter selection, the adapter inventory, live model discovery, and the hosted-search continuation bridge. | | [`providers/step-cli-transport.md`](providers/step-cli-transport.md) | StepCode as a Step Plan transport: its own framed stdio wire, one process per conversation, inline SDK tools instead of an MCP catalog, and the bounded tool-result window. | | [`providers/opengateway.md`](providers/opengateway.md) | Preset discovery, paired Responses tool-result projection and bounded empty-completion recovery. | +| [`providers/zai-image-detail.md`](providers/zai-image-detail.md) | Exact-destination Responses projection that degrades unsupported original image detail to high for Z.AI. | | [`providers/aimlapi.md`](providers/aimlapi.md) | Type-filtered Chat discovery, seeded models and attribution headers bound to the preset destination. | | [`providers/jev-decision.md`](providers/jev-decision.md) | JEV Combo decision methods (TypeSafe, self-hosted System One rows, opencodex models), the decision request path, dashboard surfaces, and the content-free statistics projection. | | [`providers/anthropic-output-caps.md`](providers/anthropic-output-caps.md) | Routed omitted-output caps for adapter:anthropic rows keyed by Claude model id, precedence and unknown-id fallback. | @@ -252,10 +253,11 @@ A source area can be described by more than one doc, because these docs are orga | `src/adapters/openai-chat/serialized-tool-call-content.ts` | [`providers/completed-tool-blocks.md`](providers/completed-tool-blocks.md) | | `src/adapters/openai-responses/` | [`transports/response-citations.md`](transports/response-citations.md) | | `src/adapters/openai-responses/opengateway-input.ts` | [`providers/opengateway.md`](providers/opengateway.md) | -| `src/adapters/openai-responses/passthrough.ts` | [`transports/responses-citations.md`](transports/responses-citations.md)
    [`providers/opengateway.md`](providers/opengateway.md)
    [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | +| `src/adapters/openai-responses/passthrough.ts` | [`transports/responses-citations.md`](transports/responses-citations.md)
    [`providers/opengateway.md`](providers/opengateway.md)
    [`providers/zai-image-detail.md`](providers/zai-image-detail.md)
    [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | | `src/adapters/openai-responses/request-strips.ts` | [`transports/responses-citations.md`](transports/responses-citations.md) | | `src/adapters/openai-responses/tool-schema.ts` | [`providers/hosted-tool-denials.md`](providers/hosted-tool-denials.md) | | `src/adapters/openai-responses/transport.ts` | [`providers/codex-installation-identity.md`](providers/codex-installation-identity.md) | +| `src/adapters/openai-responses/zai-input.ts` | [`providers/zai-image-detail.md`](providers/zai-image-detail.md) | | `src/adapters/step-cli/` | [`providers/step-cli-transport.md`](providers/step-cli-transport.md) | | `src/adapters/unique-tool-call-ids.ts` | [`providers/completed-tool-blocks.md`](providers/completed-tool-blocks.md) | | `src/adapters/workbuddy-schema.ts` | [`providers/workbuddy.md`](providers/workbuddy.md) | diff --git a/structure/manifest.json b/structure/manifest.json index 71cffd1094e..2e14b6b2bf2 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -751,6 +751,16 @@ "src/codex/catalog/routed-gather.ts" ] }, + { + "path": "providers/zai-image-detail.md", + "tier": 4, + "title": "Z.AI Image Detail", + "scope": "Exact-destination Responses projection that degrades unsupported original image detail to high for Z.AI.", + "documents": [ + "src/adapters/openai-responses/zai-input.ts", + "src/adapters/openai-responses/passthrough.ts" + ] + }, { "path": "providers/aimlapi.md", "tier": 4, diff --git a/structure/providers/zai-image-detail.md b/structure/providers/zai-image-detail.md new file mode 100644 index 00000000000..74e9e90a186 --- /dev/null +++ b/structure/providers/zai-image-detail.md @@ -0,0 +1,27 @@ +# Z.AI Image Detail + +## Responses image detail projection + +Z.AI's Responses endpoint accepts `input_image.detail` values `auto`, `low` and `high`. codex-rs +sends `original` from `view_image`, code-mode `image()` and screenshot tool results when the +catalog row advertises `supports_image_detail_original`, and Z.AI answers that value with HTTP 400 +`Invalid API parameter, please check the documentation.` for the whole request. The image stays in +thread history, so without a projection every later turn of that thread fails the same way. + +`src/adapters/openai-responses/zai-input.ts` degrades `original` to `high`, the codex default, in +message `content` arrays and in every array-valued tool `output` (`function_call_output`, +`custom_tool_call_output` and siblings). Image bytes, part order, call ids and all other fields are +unchanged. The projection copies only changed items and returns the source body when nothing +changes. Historical images are rewritten on every send, so a thread that already holds an +`original` image recovers without client changes. + +Eligibility is the exact final send URL `https://api.z.ai/api/v1/responses`, the registry `zai` +row's Responses resource. A custom-named provider that resolves to the same URL receives the same +projection; query-routed variants, lookalike hosts, other Z.AI resources and every other +destination keep `original`. `src/adapters/openai-responses/passthrough.ts` applies it immediately +after the [OpenGateway projection](opengateway.md), whose destination is disjoint. The Chat wire +already degrades `original` for every provider in `src/responses/parser-content.ts`. + +`tests/adapters/openai/zai-input.test.ts` covers message and tool-output projection, identity +preservation, the destination boundary and adapter serialization for the registry row, a +custom-named provider at the same URL and an unrelated Responses destination. diff --git a/tests/adapters/openai/zai-input.test.ts b/tests/adapters/openai/zai-input.test.ts new file mode 100644 index 00000000000..69f254d85f5 --- /dev/null +++ b/tests/adapters/openai/zai-input.test.ts @@ -0,0 +1,128 @@ +import { describe, expect, test } from "bun:test"; +import { createResponsesPassthroughAdapter as createResponsesPassthroughAdapterProduction } from "../../../src/adapters/openai-responses"; +import { normalizeZaiResponsesInput } from "../../../src/adapters/openai-responses/zai-input"; +import { enrichProviderFromRegistry, providerConfigSeed } from "../../../src/providers/derive"; +import { getProviderRegistryEntry } from "../../../src/providers/registry"; +import type { OcxProviderConfig } from "../../../src/types"; +import { withTestTranslatorBudget } from "../../helpers/translator-budget"; + +const createResponsesPassthroughAdapter = (...args: Parameters) => + withTestTranslatorBudget(createResponsesPassthroughAdapterProduction(...args)); + +const url = "https://api.z.ai/api/v1/responses"; +const image = (id: string, detail?: string) => ({ + type: "input_image", + image_url: `data:image/png;base64,${id}`, + ...(detail === undefined ? {} : { detail }), +}); + +function project(input: unknown[], destination = url): unknown[] { + const body = { model: "glm-5.3-flash", input }; + const snapshot = JSON.stringify(body); + const normalized = normalizeZaiResponsesInput(body, destination) as { input: unknown[] }; + expect(JSON.stringify(body)).toBe(snapshot); + return normalized.input; +} + +async function serialize(provider: OcxProviderConfig, input: unknown[]) { + const request = await createResponsesPassthroughAdapter(provider).buildRequest({ + modelId: "glm-5.3-flash", + context: { messages: [] }, + stream: true, + options: {}, + _rawBody: { model: "glm-5.3-flash", input }, + }, { headers: new Headers() }); + return { url: request.url, body: JSON.parse(request.body) as { input: Array> } }; +} + +describe("Z.AI Responses image detail", () => { + test("user message images degrade original detail to high without touching bytes or order", () => { + const input = project([ + { type: "message", role: "user", content: [{ type: "input_text", text: "look" }, image("AAA", "original"), image("BBB", "low")] }, + ]); + expect(input[0]).toEqual({ + type: "message", + role: "user", + content: [{ type: "input_text", text: "look" }, image("AAA", "high"), image("BBB", "low")], + }); + }); + + test("custom and function tool outputs degrade original detail and keep their call ids", () => { + const input = project([ + { type: "custom_tool_call", call_id: "call_a", name: "exec", input: "view_image()" }, + { type: "custom_tool_call_output", call_id: "call_a", output: [{ type: "input_text", text: "Script completed" }, image("AAA", "original")] }, + { type: "function_call", call_id: "call_b", name: "screenshot", arguments: "{}" }, + { type: "function_call_output", call_id: "call_b", output: [image("BBB", "original")] }, + ]); + expect(input[0]).toEqual({ type: "custom_tool_call", call_id: "call_a", name: "exec", input: "view_image()" }); + expect(input[1]).toEqual({ + type: "custom_tool_call_output", + call_id: "call_a", + output: [{ type: "input_text", text: "Script completed" }, image("AAA", "high")], + }); + expect(input[3]).toEqual({ type: "function_call_output", call_id: "call_b", output: [image("BBB", "high")] }); + }); + + test("bodies without original detail keep their identity", () => { + const body = { + model: "glm-5.3-flash", + input: [ + { type: "message", role: "user", content: [image("AAA", "high"), image("BBB")] }, + { type: "function_call_output", call_id: "call_a", output: "plain text" }, + ], + }; + expect(normalizeZaiResponsesInput(body, url)).toBe(body); + }); + + test("other destinations, including query-routed variants, keep original detail", () => { + const body = { input: [{ type: "message", role: "user", content: [image("AAA", "original")] }] }; + expect(normalizeZaiResponsesInput(body, `${url}?route=custom`)).toBe(body); + expect(normalizeZaiResponsesInput(body, "https://api.openai.com/v1/responses")).toBe(body); + expect(normalizeZaiResponsesInput(body, "https://api.z.ai.example.com/api/v1/responses")).toBe(body); + }); + + test("the registry zai row serializes high detail on the wire", async () => { + const provider = { ...providerConfigSeed(getProviderRegistryEntry("zai")!), apiKey: "test-key" }; + enrichProviderFromRegistry("zai", provider); + const { url: sent, body } = await serialize(provider, [ + { type: "message", role: "user", content: [{ type: "input_text", text: "look" }, image("AAA", "original")] }, + { type: "custom_tool_call", call_id: "call_a", name: "exec", input: "view_image()" }, + { type: "custom_tool_call_output", call_id: "call_a", output: [{ type: "input_text", text: "done" }, image("BBB", "original")] }, + ]); + expect(sent).toBe(url); + expect(JSON.stringify(body)).not.toContain("\"original\""); + expect(body.input[0]).toMatchObject({ content: [{ type: "input_text", text: "look" }, image("AAA", "high")] }); + expect(body.input.find(item => item.type === "custom_tool_call_output")).toMatchObject({ + call_id: "call_a", + output: [{ type: "input_text", text: "done" }, image("BBB", "high")], + }); + }); + + test("a custom-named provider at the same destination gets the same projection", async () => { + const provider: OcxProviderConfig = { + adapter: "openai-responses", + baseUrl: "https://api.z.ai", + responsesPath: "/api/v1/responses", + authMode: "key", + apiKey: "test-key", + }; + const { url: sent, body } = await serialize(provider, [ + { type: "message", role: "user", content: [image("AAA", "original")] }, + ]); + expect(sent).toBe(url); + expect(body.input[0]).toMatchObject({ content: [image("AAA", "high")] }); + }); + + test("a different Responses destination keeps original detail on the wire", async () => { + const provider: OcxProviderConfig = { + adapter: "openai-responses", + baseUrl: "https://relay.example.com/v1", + authMode: "key", + apiKey: "test-key", + }; + const { body } = await serialize(provider, [ + { type: "message", role: "user", content: [image("AAA", "original")] }, + ]); + expect(body.input[0]).toMatchObject({ content: [image("AAA", "original")] }); + }); +}); diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 647aad825c5..805d38ac478 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1265,6 +1265,7 @@ "opencode-go-session-header.test.ts": "providers", "opencode-management-transport.test.ts": "providers", "opencode-zen-deepseek-reasoning.test.ts": "providers", "opencode-zen-gemini-wire.test.ts": "providers", "opencode-zen-rate-limit.test.ts": "providers", "opengateway-input.test.ts": "adapters/openai", "opengateway-completion-receipts.test.ts": "responses", + "zai-input.test.ts": "adapters/openai", "opengateway-provider.test.ts": "providers", "opengateway-key-validation.test.ts": "providers", "openrouter-provider-routing.test.ts": "providers", "openrouter-quota-reset-cooldown-4024.test.ts": "providers", "opper-provider.test.ts": "providers", "tokenlab-protocols.test.ts": "providers", From 7649c6f4f5de1b526df61b68b52076db251659d9 Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 14:51:44 +0900 Subject: [PATCH 36/60] docs(es): mirror the #9081 Antigravity prompt note and #9099 context base path (#9122) Co-authored-by: lidge-jun --- docs-site/src/content/docs/es/guides/codex-integration.md | 2 +- docs-site/src/content/docs/es/reference/adapters.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs-site/src/content/docs/es/guides/codex-integration.md b/docs-site/src/content/docs/es/guides/codex-integration.md index 2092f7439e3..c6f4c7d1672 100644 --- a/docs-site/src/content/docs/es/guides/codex-integration.md +++ b/docs-site/src/content/docs/es/guides/codex-integration.md @@ -581,7 +581,7 @@ Si la autorización no está disponible, usa el panel independiente directamente Una respuesta original que muestre el uso disponible o un estado protegido finaliza el juicio inmediatamente. Los créditos disponibles o la Reserva Luna activa también dejan la respuesta sin cambios y terminan el ensayo, incluso cuando se agota el uso ordinario. Esto preserva el estado de derecho existente de la aplicación. Si el agotamiento elegible aparece de nuevo, se requiere otro ensayo explícito; el consentimiento anterior no reactiva silenciosamente la corrección. -**Volver a la observación** desarma la corrección. El límite de tres minutos acota la corrección de la respuesta, no el tiempo que tarda Codex en refrescar su visualización. Tanto el vencimiento como el regreso a la observación solicitan una nueva respuesta de uso; la aplicación puede conservar su pantalla anterior hasta que llegue esa respuesta. El panel muestra esta limitación antes del consentimiento de prueba y mientras espera la respuesta original; no puede confirmar la actualización de caché de la aplicación. **Detener el servicio** cierra sus conexiones y deja el certificado para su reutilización; las conexiones activas pueden interrumpirse. Para renovar o retirar la confianza, detenga el servicio y cierre primero el Codex. La renovación prepara un nuevo certificado no confiable; revise la nueva huella digital antes de registrarla. Una acción incierta no se vuelve a intentar automáticamente. Los certificados están restringidos a la autenticación del servidor TLS. Si el estado muestra `renewal-required`, detenga el servicio y cierre Codex, luego renueve el certificado anterior antes de comenzar de nuevo. La URL nativa API debe coincidir con la dirección del oyente y el puerto reales del proxy. Las direcciones IPv4 e IPv6 no son intercambiables aquí; `localhost` alias ambiguos son rechazados. La actualización automática de la conexión MCP de Codex y el formato de configuración no invalidan la observación. Los cambios de modelo, autenticación, perfil y enrutamiento aún requieren un contexto de observación fresco; el servicio no adopta silenciosamente esos cambios durante una prueba. +**Volver a la observación** desarma la corrección. El límite de tres minutos acota la corrección de la respuesta, no el tiempo que tarda Codex en refrescar su visualización. Tanto el vencimiento como el regreso a la observación solicitan una nueva respuesta de uso; la aplicación puede conservar su pantalla anterior hasta que llegue esa respuesta. El panel muestra esta limitación antes del consentimiento de prueba y mientras espera la respuesta original; no puede confirmar la actualización de caché de la aplicación. **Detener el servicio** cierra sus conexiones y deja el certificado para su reutilización; las conexiones activas pueden interrumpirse. Para renovar o retirar la confianza, detenga el servicio y cierre primero el Codex. La renovación prepara un nuevo certificado no confiable; revise la nueva huella digital antes de registrarla. Una acción incierta no se vuelve a intentar automáticamente. Los certificados están restringidos a la autenticación del servidor TLS. Si el estado muestra `renewal-required`, detenga el servicio y cierre Codex, luego renueve el certificado anterior antes de comenzar de nuevo. La URL nativa API debe coincidir con la dirección del oyente y el puerto reales del proxy. Las direcciones IPv4 e IPv6 no son intercambiables aquí; `localhost` alias ambiguos son rechazados. Con la gestión experimental de contexto activada, la ruta base administrada `/backend-api/codex` también es válida en ese oyente. La actualización automática de la conexión MCP de Codex y el formato de configuración no invalidan la observación. Los cambios de modelo, autenticación, perfil y enrutamiento aún requieren un contexto de observación fresco; el servicio no adopta silenciosamente esos cambios durante una prueba. El servicio conserva su dirección PAC y puertos de conexión local para su reutilización después de un reinicio. Con el mismo certificado de confianza, una aplicación ya configurada puede volver a conectarse a través de su PAC en caché; reiniciar el servicio nunca reanuda una prueba de corrección. Si un puerto guardado no se puede vincular o los metadatos de conexión no son válidos, el inicio se niega en lugar de asignar otra dirección de forma silenciosa. El primer comienzo exitoso posee `codex-desktop-compatibility/connection.json` bajo la casa OpenCodex. No elimine ese archivo como una solución de reinicio de rutina: una dirección diferente requiere iniciar la aplicación con una nueva conexión administrada. diff --git a/docs-site/src/content/docs/es/reference/adapters.md b/docs-site/src/content/docs/es/reference/adapters.md index 6401f255c86..78b2a743551 100644 --- a/docs-site/src/content/docs/es/reference/adapters.md +++ b/docs-site/src/content/docs/es/reference/adapters.md @@ -221,6 +221,7 @@ Consulta [Gemini nativo con Antigravity](/es/reference/proxy-formats/#native-gem - Prompt de sistema → `systemInstruction`; mensajes → `contents[]` (asistente → `model`); herramientas → `functionDeclarations`. Imágenes con URL de datos → `inline_data`. Audio WAV y MP3 → `inline_data` (`audio/wav`, `audio/mp3`), salvo para los modelos Claude en Antigravity, que conservan el marcador de texto. Un resultado de herramienta marcado como error se envía como `functionResponse.response.error`, la clave que Google documenta para una llamada fallida; los demás resultados usan `response.result`. - Los endpoints de proyecto de Vertex usan `aiplatform.googleapis.com` para `global`, `aiplatform.us.rep.googleapis.com` y `aiplatform.eu.rep.googleapis.com` para las multirregiones `us` y `eu`, y `-aiplatform.googleapis.com` para una región como `us-central1`. - Vertex AI y Antigravity solo reintentan una solicitud que recibe un `429` si la respuesta incluye una señal de reintento, como un encabezado `Retry-After` válido, e informan de inmediato cuando se agota la cuota. +- En las solicitudes de Cloud Code Assist dirigidas a `gemini-3.7-flash`, `gemini-3.8-flash` o `gemini-4-neon`, el proxy elimina los tres párrafos de apertura de identidad de Claude Code / Claude Agent SDK cuando cada uno forma su propio párrafo (una apertura que comparte párrafo con otro texto se mantiene en el prompt) y reformula dos frases desencadenantes del prompt de sistema. De lo contrario, estas generaciones responden con `429 RESOURCE_EXHAUSTED` a esas frases. - La guía compartida del catálogo de herramientas usa una redacción verificada con Antigravity Gemini 3.8 Flash para evitar un `429 RESOURCE_EXHAUSTED` provocado por el prompt. Las herramientas disponibles, las restricciones de argumentos y las reglas del asistente del modo de código de Codex no cambian. Esto no suprime los errores de cuota reales. - Los identificadores de llamada a herramientas se sintetizan cuando Gemini los omite. Vertex y Antigravity preservan y reproducen valores opacos de `thoughtSignature` para que las continuaciones de resultados de herramientas conserven la continuidad del razonamiento de Gemini. La caché de firma se captura en el directorio config, por lo que las continuaciones también sobreviven a los reinicios de proxy. - **Las formas de respuesta mal formadas fallan al cerrarse.** Un candidato reclamado, su `content`, o su `content.parts` que no es el contenedor documentado termina el turno con un error `google response contained invalid …` nombrando la razón estructural y el tipo del valor ofensivo - nunca su contenido. La ausencia se maneja por separado de la corrupción: una ausencia, `null` o `content` vacío o `parts` todavía completa el turno normalmente, un fragmento de flujo continuo cuyo `candidates` está ausente, `null` o vacío se omite para que el turno se complete en una trama terminal posterior, y una respuesta almacenada en memoria intermedia que no lleva ningún candidato en todos los retornos `google response contained no candidates`. Una raíz `data: null` keepalive marco todavía se omite como relleno. From 93a4572f8fe690a1043aa95e98233abb1f448ae7 Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Wed, 25 Nov 2026 14:54:27 +0900 Subject: [PATCH 37/60] fix(windows): verify service owners when WMI evidence is missing (#9027) * fix(windows): verify service owners when WMI evidence is missing Use same-account query handles for eligible wrapper snapshots and captured Scheduler engines on Windows x64. Keep ambiguous identities, expired deadlines and changed registrations refused, and report Windows stop evidence separately from a registration query failure. * fix(windows): bound native snapshot reads and verify idle state after refresh --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- .../docs/es/reference/cli/lifecycle.md | 2 + .../docs/fr/reference/cli/lifecycle.md | 2 + .../docs/ja/reference/cli/lifecycle.md | 2 + .../docs/ko/reference/cli/lifecycle.md | 2 + .../content/docs/reference/cli/lifecycle.md | 2 + .../docs/ru/reference/cli/lifecycle.md | 2 + .../docs/tr/reference/cli/lifecycle.md | 2 + .../docs/zh-cn/reference/cli/lifecycle.md | 2 + .../docs/zh-tw/reference/cli/lifecycle.md | 2 + src/cli/index.ts | 17 ++- src/cli/stop-report.ts | 6 +- src/cli/stop-windows-checked.ts | 22 ++-- src/lib/process-control.ts | 6 +- src/server/management-api.ts | 3 +- src/service/windows-checked-stop-live.ts | 19 ++- src/service/windows-process-evidence.ts | 104 +++++++++++++---- src/service/windows-process-native.ts | 10 +- src/service/windows-task-instance-stop.ts | 100 +++++++++++++--- structure/ops/windows-checked-stop.md | 31 +++-- tests/cli/uninstall.test.ts | 2 + tests/lib/process-control-graceful.test.ts | 3 +- tests/providers/xai/grok-lifecycle.test.ts | 5 +- .../windows/windows-checked-stop-live.test.ts | 90 ++++++++++++++- .../windows/windows-process-evidence.test.ts | 109 +++++++++++++++++- tests/windows/windows-stop-callers.test.ts | 10 +- tests/windows/windows-stop-ocx-stop.test.ts | 6 + 26 files changed, 469 insertions(+), 92 deletions(-) diff --git a/docs-site/src/content/docs/es/reference/cli/lifecycle.md b/docs-site/src/content/docs/es/reference/cli/lifecycle.md index 2dcea720ea7..85c95422fcd 100644 --- a/docs-site/src/content/docs/es/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/es/reference/cli/lifecycle.md @@ -48,6 +48,8 @@ ocx start --socks5-off Si un proceso hermano sirve un Remote Link guardado, `ocx stop` verifica la instancia y la titularidad del Link y detiene solo ese proceso. El enrutamiento compartido se conserva. +En Windows x64, si WMI no devuelve el propietario de un proceso auxiliar del servicio que coincide con la instalación, OpenCodex puede verificar la cuenta de Windows y la hora de creación mediante un identificador del proceso en ejecución. Si no se puede confirmar el propietario, el proceso sigue en ejecución. Si el error menciona el registro en el Programador de tareas, consúltalo con `ocx service status`. + Un Child de Remote Link sin supervisor que recibe una señal de apagado restaura Codex nativo y Grok administrado antes de liberar su listener, comprobando de nuevo la conexión atendida antes de cada escritura. La supervisión de servicio o Desktop, la propiedad de otra instancia y los traspasos de reinicio o reciclaje conservan las integraciones. El Child aplaza la restauración de Codex nativo y Grok solo cuando una parada activa y verificada del padre es titular del recibo correspondiente. El Child completa la limpieza de archivos con la sincronización bloqueada antes de liberar el listener. Un recibo antiguo o ilegible, por sí solo, mantiene el listener abierto y conserva las pruebas de recuperación. Durante el apagado se rechaza un reinicio vinculado con `409 runtime_stopping`. Una terminación forzada puede omitir los manejadores de señales; sigue siendo necesaria la restauración del `ocx stop` del padre. Para volver a enrutar Codex por el Home, inicia primero el Child con `ocx start`, o `ocx service start` si está instalado como servicio, y después ejecuta `ocx sync --restart-codex`. Iniciar por sí solo no restablece el enrutamiento. Sincronizar con el Child detenido también lo restablece, pero apuntaría a un listener que no está ejecutándose: inicia primero el Child. Durante el apagado por señal sin supervisor, si se rechaza la limpieza de archivos o la restauración de Codex nativo o Grok, incluso por titularidad no verificable, el listener permanece abierto y la sincronización queda pausada; repara la configuración o la evidencia de titularidad indicada y vuelve a ejecutar `ocx stop`. Para salir del Home después de una parada rechazada, `ocx disconnect --recover-config --yes` completa la recuperación de la configuración y reinicia el Child retenido como OpenCodex independiente. Una parada o recuperación todavía en curso sigue rechazando el reinicio. Una parada explícita comprueba que el Child sigue atendiendo la conexión Link guardada y admite el bloqueo de parada. Después elimina las integraciones de archivos creadas por el Link antes de detener el proceso o el servicio. Si la conexión guardada no es válida, ha cambiado de titular o se rechaza la limpieza de archivos, repara la conexión o las pruebas de titularidad indicadas y vuelve a intentarlo. La parada también se rechaza antes de terminar el proceso si un registro de recuperación anterior impediría la restauración nativa. En una parada explícita con `ocx stop`, la restauración nativa se intenta después de que el Child haya terminado; un rechazo informa de la restauración incompleta y conserva las pruebas de recuperación, pero el listener ya está detenido. diff --git a/docs-site/src/content/docs/fr/reference/cli/lifecycle.md b/docs-site/src/content/docs/fr/reference/cli/lifecycle.md index 781cc6bd4e8..04a41adb756 100644 --- a/docs-site/src/content/docs/fr/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/fr/reference/cli/lifecycle.md @@ -34,6 +34,8 @@ ocx start --socks5-off Si une instance sœur dessert un Remote Link enregistré, `ocx stop` vérifie l’instance et la propriété du Link et arrête uniquement ce processus. Le routage partagé est conservé. +Sous Windows x64, si WMI ne renvoie pas le propriétaire du processus associé au lanceur du service, OpenCodex peut vérifier le compte Windows et l’heure de création à partir d’un handle du processus en cours. Le processus continue de fonctionner si son propriétaire reste inconnu. Si l’erreur mentionne l’enregistrement dans le Planificateur de tâches, vérifiez-le avec `ocx service status`. + Un Link Child non supervisé supprime les intégrations de fichiers créées par le Link, puis restaure Codex natif et Grok avant de libérer son listener lors d’un signal, en revérifiant la connexion à chaque écriture. Les intégrations autonomes antérieures et les modifications de l’utilisateur sont conservées. Pendant cet arrêt par signal sans supervision, si le nettoyage des fichiers ou la restauration de Codex natif ou Grok est refusé, y compris en cas de propriété non vérifiable, le listener reste ouvert et la synchronisation est suspendue : réparez la configuration signalée, puis relancez `ocx stop`. Pour quitter le Home après un refus, `ocx disconnect --recover-config --yes` termine la récupération de la configuration et redémarre le Child restant en OpenCodex autonome. Un arrêt ou une récupération encore en cours continue de refuser le redémarrage. Un arrêt explicite vérifie que le Child dessert toujours la connexion Link enregistrée et prend en charge le verrou d’arrêt. Il nettoie ces fichiers avant d’arrêter le processus ou le service. Si la connexion enregistrée est invalide, a changé de propriétaire ou si le nettoyage est refusé, corrigez la connexion ou les preuves de propriété signalées, puis réessayez. Un ancien enregistrement de récupération qui empêcherait la restauration native refuse aussi l’arrêt avant la terminaison. Service/Desktop, sibling et transfert de redémarrage préservent les intégrations. Le Child ne diffère la restauration de Codex natif et de Grok que si un arrêt actif et vérifié du parent possède le reçu correspondant. Le Child nettoie les fichiers avec la synchronisation suspendue avant de libérer le listener. Un reçu ancien ou illisible ne suffit pas : le listener reste ouvert et les preuves de récupération sont conservées. Lors d’un `ocx stop` explicite, la restauration native est tentée après la sortie du Child ; un refus conserve les preuves de récupération et signale une restauration incomplète, avec le listener déjà arrêté. L’arrêt refuse le redémarrage avec `409 runtime_stopping`. Une terminaison forcée peut éviter le signal ; la restauration par `ocx stop` reste nécessaire. La commande doit enregistrer son reçu de récupération avant de demander l’arrêt au gestionnaire du service ou au processus. Sous Linux, l’arrêt direct exige la prise en charge de pidfd par le noyau. Sous macOS, l’arrêt direct envoie un seul SIGTERM. Si l’arrêt direct échoue, consultez le terminal ou le superviseur du Child, corrigez le problème signalé, puis relancez `ocx stop`. diff --git a/docs-site/src/content/docs/ja/reference/cli/lifecycle.md b/docs-site/src/content/docs/ja/reference/cli/lifecycle.md index c3c98eb676d..87b2c1e1742 100644 --- a/docs-site/src/content/docs/ja/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ja/reference/cli/lifecycle.md @@ -30,6 +30,8 @@ ocx start --socks5-off 監督プロセスのない Link Child は終了シグナル時、各書き込みで接続を再確認し、リスナーを閉じる前に Codex と管理対象 Grok を復元します。サービス・Desktop、sibling、再起動の引き継ぎ、親 stop 記録がある場合は設定を保持します。終了中の再起動は `409 runtime_stopping` です。強制終了はシグナル処理を省略する場合があり、親 `ocx stop` の復元も必要です。 +Windows x64 では、該当するサービスラッパーの所有者を WMI で取得できない場合、OpenCodex は実行中のプロセスのハンドルから Windows アカウントと作成時刻を確認できます。所有者を確認できないラッパーは実行を続けます。エラーがタスク スケジューラへの登録を示している場合は、`ocx service status` で登録状態を確認してください。 + 実行中のプロキシを (PID によって) 停止し、PID ファイルを削除します。スタンドアロンの所有者ではネイティブ Codex を復元します。マネージド バックグラウンド サービスがインストールされている場合、`ocx stop` はそれを最初に停止するため、プロキシを再起動できません。Web ダッシュボードのサイドバーにあるプロキシ レバーを下まで引く停止操作は同じ処理 (`POST /api/stop`) を実行しますが、Windows タスク スケジューラだけは例外です。タスク終了後もラッパーがプロキシを再起動しうるため、ダッシュボードは `respawnable_service` で拒否し、何も変更せずに `ocx stop` の実行を促します。 接続済みの hub クライアントでは、`ocx stop`(成功した API 停止を含む)は接続が所有する Codex のルーティング、モデルカタログ、Grok 設定を保持します。`ocx start` はルーティングを再注入せず、その設定で再び処理します。Codex を自身のアカウントへ戻すには `ocx disconnect`、既にネイティブルーティングへ戻した後の再適用には `ocx sync --restart-codex` を使います。 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 928134c2276..e5a73f9c8df 100644 --- a/docs-site/src/content/docs/ko/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ko/reference/cli/lifecycle.md @@ -46,6 +46,8 @@ ocx start --socks5-off 감독 프로세스 없이 실행되는 Link Child는 종료 신호 처리 시 각 쓰기 직전에 연결을 재확인하고 리스너를 닫기 전에 Codex 기본 설정과 관리 Grok 설정을 복원합니다. 서비스·Desktop 감독, sibling, 재시작·재활용 인계, 부모 stop 영수증이 있으면 설정을 보존합니다. 종료 중 재시작 요청은 `409 runtime_stopping`입니다. 강제 종료는 신호 처리를 건너뛸 수 있어 부모 `ocx stop`의 복원도 필요합니다. +Windows x64에서 WMI가 서비스 래퍼의 소유자를 반환하지 않으면 OpenCodex가 실행 중인 프로세스의 핸들로 Windows 계정과 생성 시각을 확인할 수 있습니다. 소유권을 확인할 수 없는 래퍼는 계속 실행됩니다. 오류가 작업 스케줄러 등록을 명시하면 `ocx service status`로 등록 상태를 확인하세요. + 실행 중인 프록시를 PID 기준으로 중지하고 PID 파일을 삭제합니다. 독립 실행 소유자라면 기본 Codex를 복원합니다. 관리형 백그라운드 서비스가 설치되어 있으면 `ocx stop`이 먼저 그 서비스를 중지하므로 프록시가 다시 올라올 수 없습니다. 웹 대시보드 사이드바의 프록시 레버를 끝까지 당기는 정지도 같은 동작(`POST /api/stop`)을 하지만, Windows 작업 스케줄러는 예외입니다. 작업이 끝나도 래퍼가 프록시를 다시 띄울 수 있어서, 대시보드는 `respawnable_service`로 거절하고 아무것도 바꾸지 않은 채 `ocx stop` 실행을 안내합니다. diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index 822aa6a7225..2cea913f521 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -88,6 +88,8 @@ ocx start --socks5-off An unsupervised Link Child handling a shutdown signal removes file integrations created by the Link, then restores native Codex and managed Grok before releasing its listener, rechecking the served connection before each write. Pre-existing standalone file integrations and user edits are preserved. During that unsupervised signal cleanup, if file cleanup or native Codex/Grok restoration is refused, including unverified ownership, the listener stays bound with synchronization paused; repair the reported configuration or ownership evidence and retry `ocx stop`. To leave Home after a refused stop, `ocx disconnect --recover-config --yes` completes configuration recovery and restarts the retained Child as standalone OpenCodex. A stop or recovery still in progress continues to refuse restart. Service/Desktop supervision, sibling ownership and restart/recycle handoff preserve integrations. The Child defers native Codex and Grok restoration only when a verified running parent stop owns the matching receipt. File cleanup and its synchronization fence still run before the listener is released. A stale or unreadable receipt alone keeps the listener bound and the recovery evidence intact. Shutdown rejects bound restart with `409 runtime_stopping`. +On Windows x64, when WMI returns no owner for a matching service wrapper, OpenCodex can verify the Windows account and process creation time through a live handle. A wrapper whose ownership remains unknown is left running. If the error specifically names Task Scheduler registration, use `ocx service status` to inspect that registration. + An explicit `ocx stop` verifies that the running Child still serves the saved Link connection and supports the stop fence, then removes Link-created file integrations before stopping the process or service. If the saved connection is invalid, has changed owners, or file cleanup is refused, the command stops before terminating anything. Repair the saved connection or the reported ownership evidence and retry. The command also refuses before termination if an older recovery record would prevent native restoration; repair the reported evidence and retry. Native Codex/Grok restoration is then attempted by the stopping command after the Child exits. A refusal at that stage reports incomplete restoration and preserves recovery evidence; the listener is already stopped. Forced termination can bypass signal handlers; parent `ocx stop` restoration remains necessary. To route Codex through Home again after such a stop, start the Child (`ocx start`, or `ocx service start` for an installed service) and then run `ocx sync --restart-codex`. Starting alone does not reapply routing. With Home available, sync also reapplies its enabled file integrations. A sync run while the Child is stopped still reapplies routing, which points Codex at a listener that is not running, so start the Child first. The stopping command must record its recovery receipt before asking a service manager or process to stop. Linux requires kernel pidfd support for direct termination. On macOS, the direct path sends a single SIGTERM. If the direct stop fails, check the Child’s terminal or supervisor for the reason, repair the reported evidence, and retry `ocx stop`. 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 aadc1a9e35f..658bdf6354a 100644 --- a/docs-site/src/content/docs/ru/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ru/reference/cli/lifecycle.md @@ -52,6 +52,8 @@ ocx start --socks5-off Link Child без супервизора при сигнале восстанавливает нативный Codex и управляемый Grok до закрытия listener, проверяя подключение перед каждой записью. Сервис/Desktop, sibling, передача перезапуска и квитанция stop родителя сохраняют настройки. Во время завершения перезапуск возвращает `409 runtime_stopping`. Принудительное завершение может обойти сигнал; восстановление родителем `ocx stop` остаётся необходимым. +В Windows x64, если WMI не сообщает владельца процесса-обёртки этой службы, OpenCodex может проверить учётную запись Windows и время создания по дескриптору работающего процесса. Если владельца подтвердить не удалось, процесс продолжит работу. Если ошибка указывает на регистрацию в планировщике заданий, проверьте её командой `ocx service status`. + Остановить работающий прокси (по PID) и удалить PID-file; для автономного владельца также восстановить native Codex. Если установлена managed background service, `ocx stop` сначала останавливает и её, чтобы она не перезапустила прокси обратно. Рычаг прокси в боковой панели веб-дашборда, потянутый до упора вниз, выполняет то же действие (`POST /api/stop`) на всех бэкендах, кроме планировщика заданий Windows: там обёртка может перезапустить прокси после завершения задачи, поэтому дашборд отказывает с `respawnable_service`, ничего не меняет и просит выполнить `ocx stop`. diff --git a/docs-site/src/content/docs/tr/reference/cli/lifecycle.md b/docs-site/src/content/docs/tr/reference/cli/lifecycle.md index b51bae76a75..f4e494a2dd8 100644 --- a/docs-site/src/content/docs/tr/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/tr/reference/cli/lifecycle.md @@ -52,6 +52,8 @@ ocx start --socks5-off Gözetimsiz Link Child kapanma sinyalinde her yazmadan önce bağlantıyı doğrular ve dinleyiciyi bırakmadan önce yerel Codex ile yönetilen Grok ayarlarını geri yükler. Servis/Desktop, sibling, yeniden başlatma devri ve üst stop makbuzu ayarları korur. Kapanma sırasında yeniden başlatma `409 runtime_stopping` döndürür. Zorla sonlandırma sinyali atlayabilir; üst `ocx stop` geri yüklemesi yine gereklidir. +Windows x64’te WMI eşleşen hizmet sarmalayıcısının sahibini bildirmezse OpenCodex, çalışan sürecin tanıtıcısı üzerinden Windows hesabını ve oluşturulma zamanını doğrulayabilir. Sahibi doğrulanamayan sarmalayıcı çalışmaya devam eder. Hata özellikle Görev Zamanlayıcı kaydını belirtiyorsa kaydı `ocx service status` ile inceleyin. + Çalışan proxy'yi (PID'ye göre) durdurun, PID dosyasını kaldırın ve yerel Codex'i geri yükleyin. Yönetilen bir arka plan servisi kuruluysa `ocx stop` proxy'yi yeniden oluşturamaması için önce onu da durdurur. Web kontrol panelinin kenar çubuğundaki proxy kolunu sonuna kadar çekmek aynı eylemi (`POST /api/stop`) Windows Görev Zamanlayıcı dışındaki tüm arka uçlarda çalıştırır: orada görev bittikten sonra sarmalayıcı proxy'yi yeniden başlatabilir, bu yüzden panel `respawnable_service` ile reddeder, hiçbir şeyi değiştirmez ve `ocx stop` çalıştırmanızı ister. diff --git a/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md b/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md index a69574f15a7..136b747f9d9 100644 --- a/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md @@ -30,6 +30,8 @@ ocx start --socks5-off 无人监督的 Link Child 处理退出信号时,会在每次写入前核对连接,并在关闭监听器前恢复 Codex 原生配置及受管理的 Grok。服务/Desktop、sibling、重启交接和父进程 stop 收据会保留配置。退出中的重启请求返回 `409 runtime_stopping`。强制终止可能跳过信号处理,仍需父进程 `ocx stop` 的恢复路径。 +在 Windows x64 上,如果 WMI 未返回匹配的服务包装进程的所有者,OpenCodex 可以通过运行中进程的句柄核实 Windows 帐户和进程创建时间。无法确认所有者时,该进程将继续运行。如果错误明确指出任务计划程序的注册问题,请用 `ocx service status` 查看注册状态。 + 停止正在运行的代理(按 PID),移除 PID 文件;独立运行的所有者还会恢复原生 Codex。如果安装了受管后台服务,`ocx stop` 还会先停止该服务,这样它就无法重新拉起代理。Web 仪表盘侧栏的代理拉杆拉到底时,在多数后端执行同样的操作(`POST /api/stop`),但 Windows 任务计划程序除外:任务结束后包装器仍可能重新拉起代理,只有运行在代理之外的 stop 才能在恢复客户端配置前确认这个重启窗口,因此仪表盘会以 `respawnable_service` 拒绝、不做任何更改,并提示改用 `ocx stop`。 对于已连接的 hub 客户端,`ocx stop`(包括成功的 API 停止)会保留连接所拥有的 Codex 路由、模型目录和 Grok 配置。`ocx start` 使用这些保留的配置恢复服务,不会重新注入路由。要让 Codex 回到自己的账户,请运行 `ocx disconnect`;若已恢复为原生路由,要重新应用连接路由,请运行 `ocx sync --restart-codex`。 diff --git a/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md b/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md index 56f49e6bd29..6555880c0e4 100644 --- a/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md @@ -30,6 +30,8 @@ ocx start --socks5-off 無人監督的 Link Child 處理結束訊號時,會在每次寫入前核對連線,並在關閉接聽器前還原 Codex 原生設定及受管理的 Grok。服務/Desktop、sibling、重新啟動交接和父程序 stop 收據會保留設定。結束中的重新啟動要求回傳 `409 runtime_stopping`。強制終止可能略過訊號處理,仍需父程序 `ocx stop` 的還原路徑。 +在 Windows x64 上,若 WMI 未傳回相符服務包裝程序的擁有者,OpenCodex 可透過執行中程序的控制代碼確認 Windows 帳戶與程序建立時間。若無法確認擁有者,該程序會繼續執行。若錯誤明確指出工作排程器的註冊問題,請用 `ocx service status` 檢查註冊狀態。 + 停止執行中的代理(依 PID)、移除 PID 檔案,並還原原生 Codex。若已安裝受管背景服務,`ocx stop` 也會先停止它,使其無法重新生成代理。網頁儀表板側欄的代理拉桿拉到底時,在多數後端執行相同動作(`POST /api/stop`),但 Windows 工作排程器除外:工作結束後包裝程序仍可能重新啟動 Proxy,因此儀表板會以 `respawnable_service` 拒絕、不做任何變更,並請你改用 `ocx stop`。 對已連線的 hub 用戶端,`ocx stop`(包括成功的 API 停止)會保留連線擁有的 Codex 路由、目錄和 Grok 設定,`ocx start` 會再次提供服務。明確停止 Remote Link Child 時,若共用設定還原成功,則會還原原生 Codex 路由、目錄與已備份的續接歷程中繼資料,並移除受管理的 Grok 設定。已儲存的 Home 連線會保留,可用 `ocx disconnect` 移除。 diff --git a/src/cli/index.ts b/src/cli/index.ts index 9d97024f7b8..90fda75454d 100755 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -127,7 +127,7 @@ import { type StopApproval, } from "./stop-approval"; import { summarizeStopRun, type StopOutcome, type StopRunRecord } from "./stop-report"; -import { confirmGuardedFreed, inspectGuardedTarget, noServiceStop, observeGuardedStopped, orphanDiscoveryCap, stopGuardedManager, stopServiceForOcxStop, stopServiceForUninstall, stopWindowFailed, verifyUninstallStopWindow, windowsChildStopHeld, windowsPartAHeldUnchanged, windowsPartAHolds, windowsPartAReceiptRecord, windowsPartBDue, windowsPartBOwnsPortWait, windowsStopRequiresReceipt } from "./stop-windows-checked"; +import { confirmGuardedFreed, inspectGuardedTarget, noServiceStop, observeGuardedStopped, orphanDiscoveryCap, stopGuardedManager, stopServiceForOcxStop, stopServiceForUninstall, stopWindowFailed, verifyUninstallStopWindow, windowsChildStopHeld, windowsPartAFailureMessage, windowsPartAHeldUnchanged, windowsPartAHolds, windowsPartAReceiptRecord, windowsPartBDue, windowsPartBOwnsPortWait, windowsStopRequiresReceipt } from "./stop-windows-checked"; import { runCli } from "./root"; import { isProcessAlive, ProxyOwnershipRefusedError, refusalNextStep, stopProxy } from "../lib/process-control"; import { startupDataPlaneToken } from "../lib/service-secrets"; @@ -1222,21 +1222,18 @@ async function handleStopUnlocked(snapshot: GuardedStopSnapshot | undefined, onF // No "won't respawn" claim here: a stopped Task Scheduler can still respawn through // its wrapper, which the verification below is what actually settles. if (stoppedService) console.log("🛑 Service manager stopped."); + const heldByWindows = windowsPartAHolds(record); + ownershipBlocked = heldByWindows || ownershipBlocked; // #7771: no POST and no shared teardown. if (serviceStop === "failed") { // A manager that would not stop can respawn the proxy. That is a real stop failure, // not a history-only one, and an update must not replace files over it (#3008). stopFailed = true; - console.error("❌ The installed service manager did not stop; it may respawn the proxy."); + if (!heldByWindows) console.error("❌ The installed service manager did not stop; it may respawn the proxy."); } if (serviceStop === "state-unknown") { - // Nothing refused to stop — the scheduler state could not be READ. Saying "did not - // stop" sends the operator looking for the wrong problem, and `/api/stop` answers - // the same case with service_state_unknown. stopFailed = true; - console.error("❌ The Windows Task Scheduler state could not be read, so this stop cannot tell whether a wrapper would respawn the proxy."); - console.error(" Run 'ocx service status' to see the query error, repair Task Scheduler access, then retry."); + if (!heldByWindows) console.error("❌ The service state could not be verified. Check 'ocx service status' for details."); } - ownershipBlocked = windowsPartAHolds(record) || ownershipBlocked; // #7771: no POST and no shared teardown. // #8960: a held Part A that changed nothing owes no teardown, so the receipt this run claimed // before it goes too. Kept, the next stop inherits it and budgets one more probe, so each // refused retry needed more time than the last and an update could wedge for good. @@ -1571,10 +1568,10 @@ async function handleUninstall() { observed.serviceStop = outcome; if (outcome === "absent") return false; if (outcome === "failed") { - throw new Error("the installed service manager did not stop; it may respawn the proxy"); + throw new Error(windowsPartAFailureMessage() ?? "the installed service manager did not stop; it may respawn the proxy"); } if (outcome === "state-unknown") { - throw new Error("the Windows Task Scheduler state could not be read, so this uninstall cannot tell whether a manager is still running. Run 'ocx service status' to see the query error"); + throw new Error(windowsPartAFailureMessage() ?? "the service state could not be verified. Check 'ocx service status' for details"); } return true; }); diff --git a/src/cli/stop-report.ts b/src/cli/stop-report.ts index 831a81073c3..6a333829180 100644 --- a/src/cli/stop-report.ts +++ b/src/cli/stop-report.ts @@ -61,6 +61,8 @@ export interface StopRunRecord { receiptClearFailed: boolean; /** Windows checked stop: the reason a Part A or Part B result was not a success. */ serviceStopReason?: StopServiceReason; + /** Operator diagnostic from the checked stop, used in the existing summary message. */ + serviceStopMessage?: string; /** Windows checked stop: Part B found another program on the port after ours were gone. */ portHeldByForeign?: boolean; } @@ -126,8 +128,8 @@ function stopMessage(record: StopRunRecord, signals: StopRunSignals, outcome: St if (record.proxy === "ownership-refused") return "The proxy refused the stop; it belongs to a different opencodex home."; if (record.proxy === "unresolvable-pid") return "A proxy is answering, but its process id could not be resolved, so it was not stopped."; if (record.proxy === "stop-failed") return "The proxy process could not be stopped."; - if (record.service === "failed") return "The installed service manager did not stop and may respawn the proxy."; - if (record.service === "state-unknown") return "The service manager state could not be read."; + if (record.service === "failed") return record.serviceStopMessage ?? "The installed service manager did not stop and may respawn the proxy."; + if (record.service === "state-unknown") return record.serviceStopMessage ?? "The service manager state could not be read."; if (record.service === "error") return "Stopping the installed service failed."; if (record.inheritedTeardownBlocks) return "An earlier stop left an outstanding shared teardown that could not be confirmed."; if (record.sharedTeardown === "failed") return "The shared teardown failed; client configuration may still point at the stopped proxy."; diff --git a/src/cli/stop-windows-checked.ts b/src/cli/stop-windows-checked.ts index 95cb46e0657..466e960b9bb 100644 --- a/src/cli/stop-windows-checked.ts +++ b/src/cli/stop-windows-checked.ts @@ -173,16 +173,24 @@ export function windowsPartBOwnsPortWait(): boolean { return windows() && state.result?.outcome === "stopped"; } -/** - * A Part A result other than stopped/absent holds the child stop (030 "Two parts"): no - * POST, the shared teardown skipped, proxy unknown. Records the additive reason. - */ -export function windowsPartAHolds(record: StopRunRecord): boolean { +function failedWindowsPartA(): WindowsCheckedStopResult | null { const result = state.result; - if (!windows() || !result || result.outcome === "stopped" || result.outcome === "absent") return false; + return windows() && result && result.outcome !== "stopped" && result.outcome !== "absent" ? result : null; +} + +export function windowsPartAFailureMessage(): string | undefined { + const result = failedWindowsPartA(); + return result ? describeWindowsPartA(result) : undefined; +} + +/** A refused Part A holds the child stop and records its diagnostic without repeating it. */ +export function windowsPartAHolds(record: StopRunRecord): boolean { + const result = failedWindowsPartA(); + if (!result) return false; const reason = windowsStopReason(result); if (reason) record.serviceStopReason = reason; - console.error(" " + describeWindowsPartA(result)); + record.serviceStopMessage = describeWindowsPartA(result); + console.error(" " + record.serviceStopMessage); if (!state.snapshotless) return true; record.proxy = "unknown"; console.error(" The proxy was left running and the shared teardown skipped: the service could relaunch it."); diff --git a/src/lib/process-control.ts b/src/lib/process-control.ts index 847bed3ff1c..f74b7691032 100644 --- a/src/lib/process-control.ts +++ b/src/lib/process-control.ts @@ -180,8 +180,7 @@ function refusalFallbackMessage(code: string | null): string { + "stopping the manager from inside it would end the process before native Codex is " + "restored."; case "service_state_unknown": - return "The running proxy refused to stop: the service manager state could not be read, " - + "so it cannot tell whether a wrapper would respawn it."; + return "The running proxy refused to stop: the Windows service or process state could not be verified."; default: return "The running proxy refused to stop and sent no reason."; } @@ -208,8 +207,7 @@ export function refusalNextStep(code: string | null): string { + "again is not the missing step. Run `ocx service status` to see whether the service " + "is still registered."; case "service_state_unknown": - return "Run `ocx service status` to see the query error, repair the service manager " - + "access, then retry."; + return "Check the reported stop reason and run `ocx service status` to inspect service registration."; default: return "Run `ocx service status` to inspect the service state."; } diff --git a/src/server/management-api.ts b/src/server/management-api.ts index 7b88553969d..5a1453e1d10 100644 --- a/src/server/management-api.ts +++ b/src/server/management-api.ts @@ -545,11 +545,10 @@ export async function handleManagementAPI( }, 409, req, config); } if (serviceStop === "state-unknown") { - // Same case, same remedy as the pre-check: the query is what needs fixing. return jsonResponse({ success: false, code: "service_state_unknown", - message: "The Windows Task Scheduler state could not be read, so this proxy cannot tell whether a wrapper would respawn it. Shared client config was left alone. Run `ocx service status` to see the query error, repair Task Scheduler access, then retry.", + message: "The Windows service or process state could not be verified, so the stop could not be confirmed. Shared client config was left alone.", }, 409, req, config); } // The pre-check above already refused the respawnable case without a receipt, so diff --git a/src/service/windows-checked-stop-live.ts b/src/service/windows-checked-stop-live.ts index 8b324bbd609..aba2d04c3f3 100644 --- a/src/service/windows-checked-stop-live.ts +++ b/src/service/windows-checked-stop-live.ts @@ -40,7 +40,7 @@ import { import { windowsProcessNative, type WindowsProcessNativeApi, type WindowsTerminateResult } from "./windows-process-native"; import type { WindowsListenerIdentity, WindowsPortSample, WindowsStopConfirmDeps } from "./windows-stop-confirm"; import { windowsSchedulerCsvIncludesTask } from "./windows-scheduler"; -import { WINDOWS_TASK_INSTANCE_STOP_SCRIPT, verifyWindowsTaskStopProof } from "./windows-task-instance-stop"; +import { windowsTaskInstanceStopScript, verifyWindowsTaskEngineProof, verifyWindowsTaskStopProof } from "./windows-task-instance-stop"; // Only a missing task after connecting to the local root folder establishes absence. const TASK_REGISTRATION_SCRIPT = String.raw` @@ -273,6 +273,8 @@ export function stopperUnderHomeWrapper( export interface WindowsCheckedStopLiveOptions { run?: WindowsStopCommandRunner; + /** Use an injected engine observer with an injected runner. Synthetic PIDs never reach the live kernel. */ + taskEngineIdentity?: WindowsProcessNativeApi["sameUserIdentity"]; /** * The `sc.exe qc` query that proves the registered WinSW service runs THIS installation's * executable. Defaults to the capped runner; tests inject it. @@ -370,12 +372,19 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption const deadline = performance.now() + Math.floor(timeoutMs); const withinDeadline = () => performance.now() < deadline && gate(); const launcher = windowsLauncherVbsPath(); - const script = Buffer.from(WINDOWS_TASK_INSTANCE_STOP_SCRIPT, "utf16le").toString("base64"); + const identity = options.taskEngineIdentity ?? (run === liveWindowsStopCommandRunner ? windowsProcessNative()?.sameUserIdentity : undefined); + const script = Buffer.from(windowsTaskInstanceStopScript(identity !== undefined), "utf16le").toString("base64"); let approved = false, dispatched = false, observedMutation = false; + let expectedVerdict: "ended" | "not-running" | null = null; let refusal: { cause: unknown } | undefined; const ended = await run("powershell", ["-NoProfile", "-NoLogo", "-NonInteractive", "-EncodedCommand", script], timeoutMs, async line => { - if (!verifyWindowsTaskStopProof(line, launcher) || !withinDeadline()) return false; + if (!withinDeadline()) return false; + if (identity) { + expectedVerdict = verifyWindowsTaskEngineProof(line, launcher, identity, withinDeadline); + if (!expectedVerdict) return false; + } else if (!verifyWindowsTaskStopProof(line, launcher)) return false; + if (!withinDeadline()) return false; try { await authorize?.(); } catch (cause) { @@ -394,7 +403,9 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption if (ended.timedOut || ended.status !== 0) return finish("failed", attempted || dispatched); const verdict = lines.at(-1); if (verdict === "unverified-registration" || verdict === "denied") return finish(verdict, attempted); - if (approved && (verdict === "ended" || verdict === "not-running")) return finish(verdict, attempted || verdict === "ended"); + if (approved && (verdict === "ended" || verdict === "not-running") && (!identity || verdict === expectedVerdict)) { + return finish(verdict, attempted || verdict === "ended"); + } return finish("failed", attempted || dispatched && verdict !== "failed"); }, async taskState(timeoutMs) { diff --git a/src/service/windows-process-evidence.ts b/src/service/windows-process-evidence.ts index 312291f2e8d..1a81f712dc5 100644 --- a/src/service/windows-process-evidence.ts +++ b/src/service/windows-process-evidence.ts @@ -21,11 +21,14 @@ import { join } from "node:path"; import { resolveTrustedWindowsPowerShellExe, resolveTrustedWindowsSystemDirectory } from "../lib/windows-elevation"; import { windowsLauncherVbsPath, windowsServiceScriptPath } from "./state"; +import { commandLineHasPathToken } from "./windows-command-line-token"; import type { WindowsProcessEntry } from "./windows-guarded-manager"; +import { windowsWrapperImage } from "./windows-stop-binding"; import { windowsProcessNative, windowsProcessPlatform, windowsProcessPlatformSimulated, + type WindowsProcessNativeApi, type WindowsProcessWatch, type WindowsTerminateResult, } from "./windows-process-native"; @@ -55,6 +58,8 @@ export type WindowsStopProcessEntry = WindowsProcessEntry & { startTime: number const SNAPSHOT_MAX_BUFFER = 16 * 1024 * 1024; const SMALL_MAX_BUFFER = 64 * 1024; const NATIVE_CIM_TOLERANCE_MS = 1; +const OWNER_READ_LIMIT = 32; +const OWNER_READ_BUDGET_MS = 1_500; /** * Owner reads stop being admitted this long before the snapshot's cap, counted from the * helper's own process start. It covers one in-flight 1 s CIM call plus serialization and @@ -114,7 +119,7 @@ export function windowsProcessSnapshotScript(timeoutMs: number): string { .map(path => Buffer.from(path, "utf8").toString("base64")); return [ "[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false);", - "$ownerBudget = @{ Remaining = 32; Clock = [Diagnostics.Stopwatch]::StartNew();", + `$ownerBudget = @{ Remaining = ${OWNER_READ_LIMIT}; Clock = [Diagnostics.Stopwatch]::StartNew();`, " Until = [Diagnostics.Process]::GetCurrentProcess().StartTime.ToUniversalTime().AddMilliseconds(" + ownerCutoffMs + ") };", "$currentSid = $null; try { $currentSid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value } catch { $currentSid = $null };", "$tokens = @('" + paths.join("','") + "') | ForEach-Object { [regex]::Escape([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($_))) };", @@ -131,14 +136,14 @@ export function windowsProcessSnapshotScript(timeoutMs: number): string { " (($_.Name -match '^(wscript|cscript|cmd)\\.exe$') -or (-not $_.Name) -or ($_.CommandLine -like '*opencodex-service*')) });", "$owners = @{};", "foreach ($process in ($priority + $fallback)) {", - " if (!$currentSid -or $ownerBudget.Remaining -le 0 -or $ownerBudget.Clock.ElapsedMilliseconds -ge 1500", + ` if (!$currentSid -or $ownerBudget.Remaining -le 0 -or $ownerBudget.Clock.ElapsedMilliseconds -ge ${OWNER_READ_BUDGET_MS}`, " -or [DateTime]::UtcNow -ge $ownerBudget.Until) { break };", " $ownerBudget.Remaining--;", " try {", " $owner = Invoke-CimMethod -InputObject $process -MethodName GetOwnerSid -OperationTimeoutSec 1 -ErrorAction Stop;", - " if ($ownerBudget.Clock.ElapsedMilliseconds -ge 1500 -or [DateTime]::UtcNow -ge $ownerBudget.Until) { break };", + ` if ($ownerBudget.Clock.ElapsedMilliseconds -ge ${OWNER_READ_BUDGET_MS} -or [DateTime]::UtcNow -ge $ownerBudget.Until) { break };`, " $after = Get-CimInstance -InputObject $process -OperationTimeoutSec 1 -ErrorAction Stop;", - " if ($ownerBudget.Clock.ElapsedMilliseconds -ge 1500 -or [DateTime]::UtcNow -ge $ownerBudget.Until) { break };", + ` if ($ownerBudget.Clock.ElapsedMilliseconds -ge ${OWNER_READ_BUDGET_MS} -or [DateTime]::UtcNow -ge $ownerBudget.Until) { break };`, " $owners[$process.ProcessId] = @{ Sid = $owner.Sid; ReturnValue = $owner.ReturnValue;", " CreationDate = if ($after.CreationDate) { $after.CreationDate.ToUniversalTime().ToString('o') } else { $null } };", " } catch { continue }", @@ -150,10 +155,13 @@ export function windowsProcessSnapshotScript(timeoutMs: number): string { const SID_PATTERN = /^S-1-\d+(?:-\d+){1,15}$/i; const USER_ACCOUNT_SID_PATTERN = /^S-1-(?:5-21|12-1)(?:-\d{1,10}){4}$/i; -function foreignProcessOwner(record: Record, startTime: number | null): boolean | null { - const sid = (value: unknown): string | null => typeof value === "string" && value.length <= 256 && SID_PATTERN.test(value) +function sid(value: unknown): string | null { + return typeof value === "string" && value.length <= 256 && SID_PATTERN.test(value) && value.split("-").slice(3).every(part => Number(part) <= 0xffff_ffff) ? value.toUpperCase() : null; +} + +function foreignProcessOwner(record: Record, startTime: number | null): boolean | null { const current = sid(record.CurrentUserSid); const owner = record.Owner; if (startTime === null || current === null || typeof owner !== "object" || owner === null) return null; @@ -169,6 +177,12 @@ function foreignProcessOwner(record: Record, startTime: number /** Parse the snapshot JSON. Unparseable output is null: an unread table proves nothing. */ export function parseWindowsProcessSnapshot(output: string): WindowsStopProcessEntry[] | null { + return decodeSnapshot(output); +} + +type ObserveEntry = (entry: WindowsStopProcessEntry, record: Record) => WindowsStopProcessEntry; + +function decodeSnapshot(output: string, observe?: ObserveEntry): WindowsStopProcessEntry[] | null { let trimmed = output.trim(); if (!trimmed) return []; const prefix = "OCX_PROCESS_SNAPSHOT "; @@ -197,16 +211,17 @@ export function parseWindowsProcessSnapshot(output: string): WindowsStopProcessE const record = row as Record; const pid = Number(record.ProcessId); const parent = Number(record.ParentProcessId); - if (!Number.isSafeInteger(pid) || pid <= 0) continue; + if (!Number.isSafeInteger(pid) || pid <= 0 || pid > 0xffff_ffff) continue; const created = typeof record.CreationDate === "string" ? Date.parse(record.CreationDate) : Number.NaN; - entries.push({ + const entry = { pid, parentPid: Number.isSafeInteger(parent) && parent > 0 ? parent : null, name: typeof record.Name === "string" ? record.Name : null, commandLine: typeof record.CommandLine === "string" ? record.CommandLine : null, startTime: Number.isFinite(created) ? created : null, foreignOwner: foreignProcessOwner(record, Number.isFinite(created) ? created : null), - }); + }; + entries.push(observe ? observe(entry, record) : entry); } return entries; } @@ -220,38 +235,77 @@ export function overlayNativeCreationTimes( entries: readonly WindowsStopProcessEntry[], creationTime: (pid: number) => number | null, ): WindowsStopProcessEntry[] { - return entries.map(entry => { - if (entry.startTime === null) return { ...entry, foreignOwner: null }; - let native: number | null; + return entries.map(entry => overlayNativeCreationTime(entry, creationTime)); +} + +function overlayNativeCreationTime( + entry: WindowsStopProcessEntry, creationTime: (pid: number) => number | null, +): WindowsStopProcessEntry { + if (entry.startTime === null) return { ...entry, foreignOwner: null }; + let native: number | null; + try { + native = creationTime(entry.pid); + } catch { + native = null; + } + const agrees = native !== null && Math.abs(native - entry.startTime) <= NATIVE_CIM_TOLERANCE_MS; + return { ...entry, startTime: agrees ? native : null, foreignOwner: agrees ? entry.foreignOwner : null }; +} + +/** The helper emits UTC .NET round-trip dates. Preserve the four sub-ms digits discarded by Date.parse. */ +function cimCreationTicks(created: unknown, ms: number): bigint | null { + if (typeof created !== "string" || created.length !== 28 || ms < 0) return null; + const fraction = created.slice(23, 27); + if (!/^\d{3}0$/.test(fraction) || created !== new Date(ms).toISOString().slice(0, -1) + fraction + "Z") return null; + return 621_355_968_000_000_000n + BigInt(ms) * 10_000n + BigInt(fraction); +} + +function observeNativeSnapshot(native: WindowsProcessNativeApi, deadline: number): ObserveEntry { + const paths = [windowsLauncherVbsPath(), windowsServiceScriptPath()]; + const until = Math.min(deadline, performance.now() + OWNER_READ_BUDGET_MS); + let remaining = OWNER_READ_LIMIT; + const creationTime = (pid: number) => { + if (performance.now() >= deadline) return null; + const created = native.creationTime(pid); + return performance.now() < deadline ? created : null; + }; + return (entry, record) => { + const checked = overlayNativeCreationTime(entry, creationTime); + // A returned CIM owner whose validation failed remains unknown. Supplement only an absent sample. + if (record.Owner !== null || record.ProcessId !== entry.pid || checked.startTime === null + || checked.startTime !== entry.startTime || !windowsWrapperImage(entry.name) + || !paths.some(path => commandLineHasPathToken(entry.commandLine, path))) return checked; + const current = sid(record.CurrentUserSid); + const ticks = cimCreationTicks(record.CreationDate, checked.startTime); + if (!current || !USER_ACCOUNT_SID_PATTERN.test(current) || ticks === null || remaining <= 0 || performance.now() >= until) return checked; + remaining--; try { - native = creationTime(entry.pid); - } catch { - native = null; - } - const agrees = native !== null && Math.abs(native - entry.startTime) <= NATIVE_CIM_TOLERANCE_MS; - return { ...entry, startTime: agrees ? native : null, foreignOwner: agrees ? entry.foreignOwner : null }; - }); + if (native.sameUserIdentity(entry.pid, false, current)?.ticks === ticks && performance.now() < until) { + return { ...checked, foreignOwner: false }; + } + } catch { /* Inaccessible, exited and unverified processes cannot gain ownership evidence. */ } + return checked; + }; } /** Every process with its creation time, or null when the table cannot be read. */ export async function windowsProcessSnapshot(options: WindowsEvidenceOptions): Promise { const run = runnerFor(options); if (!run) return null; - let entries: WindowsStopProcessEntry[] | null; + const deadline = Number.isFinite(options.timeoutMs) ? performance.now() + options.timeoutMs : 0; try { - entries = parseWindowsProcessSnapshot(await run({ + const output = await run({ program: "powershell", args: powershellArgs(windowsProcessSnapshotScript(options.timeoutMs)), timeoutMs: options.timeoutMs, maxBufferBytes: SNAPSHOT_MAX_BUFFER, allowPartialOutput: true, - })); + }); + const native = windowsProcessNative(); + return decodeSnapshot(output, native ? observeNativeSnapshot(native, deadline) : undefined); } catch { return null; } - if (entries === null) return null; - const native = windowsProcessNative(); - return native ? overlayNativeCreationTimes(entries, pid => native.creationTime(pid)) : entries; } /** diff --git a/src/service/windows-process-native.ts b/src/service/windows-process-native.ts index 301edf24a11..94658ff1a56 100644 --- a/src/service/windows-process-native.ts +++ b/src/service/windows-process-native.ts @@ -68,8 +68,8 @@ export interface WindowsProcessNativeApi { captureChildExitCode?(pid: number): (() => number | null) | null; /** Creation time in epoch ms (FILETIME truncated to ms), or null when unreadable. */ creationTime(pid: number): number | null; - /** Creation in .NET ticks at CIM precision from a live process with the same token user. */ - sameUserIdentity(pid: number, withCommandLine?: boolean): { ticks: bigint; commandLine?: string } | null; + /** Creation in .NET ticks at CIM precision. A supplied SID must also match both process tokens. */ + sameUserIdentity(pid: number, withCommandLine?: boolean, expectedUserSid?: string): { ticks: bigint; commandLine?: string } | null; terminate(pid: number, boundStartTime: number | bigint): WindowsTerminateResult; openWatch(pid: number, boundStartTime: number): WindowsProcessWatch; /** PID of the running Task Scheduler service host, or null when it cannot be read. */ @@ -223,12 +223,14 @@ function loadNativeApi(): WindowsProcessNativeApi | null { k.CloseHandle(handle); } }, - sameUserIdentity(pid, withCommandLine) { + sameUserIdentity(pid, withCommandLine, expectedUserSid) { const handle = k.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid); if (!handle) return null; try { const fileTime = handleFileTime(handle); - if (fileTime === null || handleUserSid(handle) !== handleUserSid(k.GetCurrentProcess())) return null; + if (fileTime === null) return null; + const userSid = handleUserSid(handle); + if (userSid !== handleUserSid(k.GetCurrentProcess()) || (expectedUserSid !== undefined && userSid !== expectedUserSid)) return null; const commandLine = withCommandLine ? readWindowsProcessCommandLineFromHandle(handle) : undefined; if (handleExited(handle) !== false) return null; return { ticks: fileTimeToCimTicks(fileTime), commandLine }; diff --git a/src/service/windows-task-instance-stop.ts b/src/service/windows-task-instance-stop.ts index 0e057b8a21a..fc2b2f44941 100644 --- a/src/service/windows-task-instance-stop.ts +++ b/src/service/windows-task-instance-stop.ts @@ -1,16 +1,22 @@ import { TASK } from "./state"; import { windowsTaskRegistrationMatchesForStop } from "./windows-taskxml"; +const MAX_TASK_ENGINES = 32; + /** * Keep the registered task and captured IRunningTask objects in one COM session. * Send the Unicode XML and caller identity to the existing validator through an ASCII * line, then wait for its decision. Only the captured instances can receive Stop(). */ -export const WINDOWS_TASK_INSTANCE_STOP_SCRIPT = String.raw` +const TASK_INSTANCE_STOP_BODY = String.raw` $ErrorActionPreference = 'Stop' $ProgressPreference = 'SilentlyContinue' $PSModuleAutoLoadingPreference = 'None' $attempted = $false +function Get-EngineCreationTicks([int]$enginePid) { + $process = [Diagnostics.Process]::GetProcessById($enginePid) + try { $process.StartTime.ToUniversalTime().Ticks } finally { $process.Dispose() } +} try { [Console]::OutputEncoding = [Text.Encoding]::ASCII Import-Module ([IO.Path]::Combine($PSHOME,'Modules','Microsoft.PowerShell.Utility','Microsoft.PowerShell.Utility.psd1')) -Force @@ -28,9 +34,11 @@ try { $instances = $task.GetInstances(0) if ($null -eq $instances) { 'unverified-registration'; return } $verified = @() + $engines = @() $count = $instances.Count if ($null -eq $count) { 'unverified-registration'; return } - if ($count -gt 0) { + if ($nativeOwners -and ($count -lt 0 -or $count -gt ${MAX_TASK_ENGINES})) { 'unverified-registration'; return } + if (!$nativeOwners -and $count -gt 0) { Import-Module ([IO.Path]::Combine($PSHOME,'Modules','CimCmdlets','CimCmdlets.psd1')) -Force } for ($index = 1; $index -le $count; $index++) { @@ -39,17 +47,31 @@ try { $id = [Guid]$instance.InstanceGuid $enginePid = [uint32]$instance.EnginePID if ($id -eq [Guid]::Empty -or !$enginePid -or $instance.State -ne 4) { 'unverified-registration'; return } - $engine = CimCmdlets\Get-CimInstance Win32_Process -Filter ('ProcessId = ' + $enginePid) -OperationTimeoutSec 1 - if (!$engine.CreationDate) { 'unverified-registration'; return } - $owner = CimCmdlets\Invoke-CimMethod -InputObject $engine -MethodName GetOwnerSid -OperationTimeoutSec 1 - $after = CimCmdlets\Get-CimInstance -InputObject $engine -OperationTimeoutSec 1 - if ($owner.ReturnValue -ne 0 -or $owner.Sid -ne $sid -or $after.CreationDate -ne $engine.CreationDate) { - 'unverified-registration'; return + $target = @{ Instance = $instance; Id = $id; EnginePid = $enginePid } + if ($nativeOwners) { + $ticks = Get-EngineCreationTicks $enginePid + if ($ticks -le 0) { 'unverified-registration'; return } + $target.CreationTicks = $ticks + $cimTicks = ($ticks - ($ticks % 10)).ToString([Globalization.CultureInfo]::InvariantCulture) + $engines += @{ id = $id.ToString('D'); pid = $enginePid; ticks = $cimTicks } + } else { + $engine = CimCmdlets\Get-CimInstance Win32_Process -Filter ('ProcessId = ' + $enginePid) -OperationTimeoutSec 1 + if (!$engine.CreationDate) { 'unverified-registration'; return } + $owner = CimCmdlets\Invoke-CimMethod -InputObject $engine -MethodName GetOwnerSid -OperationTimeoutSec 1 + $after = CimCmdlets\Get-CimInstance -InputObject $engine -OperationTimeoutSec 1 + if ($owner.ReturnValue -ne 0 -or $owner.Sid -ne $sid -or $after.CreationDate -ne $engine.CreationDate) { + 'unverified-registration'; return + } } - $verified += @{ Instance = $instance; Id = $id; EnginePid = $enginePid } + $verified += $target } - $proof = Microsoft.PowerShell.Utility\ConvertTo-Json -Compress -InputObject @{ xml = $xml; sid = $sid; name = $account } + $evidence = @{ xml = $xml; sid = $sid; name = $account } + if ($nativeOwners) { + $evidence.count = $count + $evidence.engines = $engines + } + $proof = Microsoft.PowerShell.Utility\ConvertTo-Json -Depth 4 -Compress -InputObject $evidence $utf8 = [Text.UTF8Encoding]::new($false, $true) $stopClock = [Diagnostics.Stopwatch]::StartNew() [Console]::WriteLine([Convert]::ToBase64String($utf8.GetBytes($proof))) @@ -75,6 +97,9 @@ try { $target.Instance.EnginePID -ne $target.EnginePid -or $target.Instance.State -ne 4) { 'unverified-registration'; return } + if ($nativeOwners -and (Get-EngineCreationTicks $target.EnginePid) -ne $target.CreationTicks) { + 'unverified-registration'; return + } } foreach ($target in $verified) { if ($stopClock.ElapsedMilliseconds -ge $stopBeforeMs) { 'failed'; return } @@ -93,17 +118,60 @@ try { } `; -/** Compare exactly against the existing XML policy, using the same helper's Windows token. */ -export function verifyWindowsTaskStopProof(line: string, launcher: string): boolean { +export function windowsTaskInstanceStopScript(nativeOwners: boolean): string { + return (nativeOwners ? "$nativeOwners = $true\n" : "$nativeOwners = $false\n") + TASK_INSTANCE_STOP_BODY; +} + +export const WINDOWS_TASK_INSTANCE_STOP_SCRIPT = windowsTaskInstanceStopScript(false); + +interface TaskStopProof { + sid: string; + count?: number; + engines?: unknown[]; +} + +function readTaskStopProof(line: string, launcher: string): TaskStopProof | null { try { const bytes = Buffer.from(line, "base64"); - if (bytes.toString("base64") !== line) return false; + if (bytes.toString("base64") !== line) return null; const proof = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes)); if (typeof proof.xml !== "string" || typeof proof.sid !== "string" - || !/^S-1-(?:5-21|12-1)(?:-\d{1,10}){4}$/i.test(proof.sid)) return false; + || !/^S-1-(?:5-21|12-1)(?:-\d{1,10}){4}$/i.test(proof.sid) + || proof.sid.split("-").slice(-4).some((part: string) => Number(part) > 0xffff_ffff)) return null; const userIds = typeof proof.name === "string" && proof.name.trim() ? [proof.sid, proof.name] : [proof.sid]; - return windowsTaskRegistrationMatchesForStop(proof.xml, launcher, userIds); + return windowsTaskRegistrationMatchesForStop(proof.xml, launcher, userIds) ? proof : null; } catch { - return false; + return null; } } + +/** The legacy helper has already checked the engine owner through CIM. */ +export function verifyWindowsTaskStopProof(line: string, launcher: string): boolean { + const proof = readTaskStopProof(line, launcher); + return proof !== null && proof.count === undefined && proof.engines === undefined; +} + +type EngineIdentity = (pid: number, withCommandLine: false, expectedSid: string) => { ticks: bigint } | null; + +/** On x64 every captured engine needs positive same-token and creation-time evidence. */ +export function verifyWindowsTaskEngineProof(line: string, launcher: string, identity: EngineIdentity, + withinDeadline: () => boolean): "ended" | "not-running" | null { + const proof = readTaskStopProof(line, launcher); + if (!proof || !Array.isArray(proof.engines) || proof.engines.length !== proof.count || proof.count > MAX_TASK_ENGINES) return null; + // An empty capture has no stop targets. The helper checks the refreshed task's state after approval. + if (proof.count === 0) return "not-running"; + const ids = new Set(); + try { + for (const engine of proof.engines) { + if (!engine || typeof engine !== "object") return null; + const { id, pid, ticks } = engine as Record; + if (typeof id !== "string" || !/^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i.test(id) + || id === "00000000-0000-0000-0000-000000000000" || ids.has(id.toLowerCase()) + || typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0 || pid > 0x7fff_ffff + || typeof ticks !== "string" || !/^[1-9]\d{0,17}0$/.test(ticks) || !withinDeadline()) return null; + ids.add(id.toLowerCase()); + if (identity(pid, false, proof.sid)?.ticks.toString() !== ticks) return null; + } + } catch { return null; } + return "ended"; +} diff --git a/structure/ops/windows-checked-stop.md b/structure/ops/windows-checked-stop.md index de6897f0bdc..64186822d47 100644 --- a/structure/ops/windows-checked-stop.md +++ b/structure/ops/windows-checked-stop.md @@ -44,12 +44,17 @@ that baseline. Owner evidence arriving at or after either cutoff is discarded. Owner verification requires a successful `GetOwnerSid`, valid local/domain or Entra ID SIDs, and a fresh CIM read reporting the original creation time. Matching SIDs prove the current account. Different supported SIDs prove a foreign account. -Built-in and virtual service SIDs and failed or skipped lookups leave ownership unverified. -Raw SIDs stay within the snapshot parser. Later operations receive nullable `foreignOwner`. -All reads share the snapshot timeout and output cap. On x64 a native creation time is kept -only when it agrees with CIM within one millisecond. A disagreement clears creation time -and owner evidence. Elsewhere the CIM time is used for observation. The Schedule PID falls -back to a capped `sc.exe queryex Schedule` from the trusted system directory. +On Windows x64, a missing CIM owner sample for a wrapper with this installation's complete +launcher or script path can be supplemented by a query-only live handle. Its process creation +time must exactly match the original CIM microsecond, and its token user must match both the +caller and the supported SID reported by the helper. This bounded probe can confirm a same-user +wrapper only. It does not override conflicting evidence. Built-in and virtual service SIDs and +unresolved lookups remain unverified. Later operations receive nullable `foreignOwner`. +All reads share the snapshot timeout and output cap. On x64 a native creation-time read +must start and finish before the snapshot deadline and agree with CIM within one millisecond. +Otherwise the row retains its ancestry with unknown creation time and owner. Elsewhere the CIM +time is used for observation. The Schedule PID falls back to a capped `sc.exe queryex Schedule` +from the trusted system directory. ## Binding rule @@ -88,7 +93,12 @@ manager still running is `survived` (`unbound-wrapper` when the survivor was nev is `survived` while the proxy is still alive after the service reports stopped. The authorizer variant `guardedStopWindowsServiceChecked` runs its authorizer at entry, before each manager stop and before each terminate and reports a refusal as `WindowsCheckedStopRefusedError` with what had already happened. For Task -Scheduler it reauthorizes after validating the helper proof, before sending `stop-before` on stdin. The +Scheduler it reauthorizes after validating the helper proof, before sending `stop-before` on stdin. +With native identity support, each captured running instance carries its GUID, engine PID and +creation time through that exchange. The native handle must prove the matching process and +token user for every engine. The helper rechecks the registration and the captured instances +before calling their COM stop methods. The bounded CIM owner check remains the fallback when +native identity support is unavailable. The helper and outer deadlines must still be open after authorization. The helper starts its monotonic clock before sending proof. The parent measures from proof receipt and sends the earlier deadline as a cutoff on that clock. Time spent delivering approval and refreshing @@ -152,9 +162,10 @@ shape, the exact launcher, and the single run-as principal through `src/service/ The logon scope and every recovery-trigger scope must match the expected account. Only the recognized legacy shape without recovery triggers may omit the logon scope. The stop proof accepts a disabled task with the same ownership evidence. Installation health still requires an enabled task. -The helper requires a successful same-account SID check for every `EnginePID`, with the process -creation time re-read after the owner lookup. After approval it re-reads the registration XML and -refreshes every captured instance to verify that its GUID, engine PID and running state still agree. +Each `EnginePID` requires the native identity proof described above when available. +The CIM fallback re-reads process creation time after checking the owner SID. After approval the +helper re-reads the registration XML and refreshes every captured instance to verify that its GUID, +engine PID and running state still agree. It stops each captured `IRunningTask` by instance GUID. An empty collection counts as idle only if the final task state shows ready or disabled before the stop deadline. Failed proof returns `evidence-unreadable` with instructions to verify the task in Task Scheduler and repair an owned diff --git a/tests/cli/uninstall.test.ts b/tests/cli/uninstall.test.ts index 5af6ae3e244..e6448c040b8 100644 --- a/tests/cli/uninstall.test.ts +++ b/tests/cli/uninstall.test.ts @@ -393,6 +393,8 @@ describe("uninstall gates shared teardown on a proven service stop", () => { expect(fn).toContain('if (outcome === "absent") return false;'); expect(fn).toContain('if (outcome === "failed")'); expect(fn).toContain('if (outcome === "state-unknown")'); + expect(fn).toContain("throw new Error(windowsPartAFailureMessage() ??"); + expect(fn).not.toContain("the Windows Task Scheduler state could not be read"); }); test("shared teardown runs only when nothing that could still serve is unaccounted for", async () => { diff --git a/tests/lib/process-control-graceful.test.ts b/tests/lib/process-control-graceful.test.ts index 0e126a340c0..7102697cc3a 100644 --- a/tests/lib/process-control-graceful.test.ts +++ b/tests/lib/process-control-graceful.test.ts @@ -364,7 +364,7 @@ describe("409 refusal reporting", () => { expect(selfUnload).not.toContain("ocx stop"); const unknownState = await refusalFor("service_state_unknown"); - expect(unknownState).toContain("could not be read"); + expect(unknownState).toContain("service or process state could not be verified"); expect(unknownState).not.toContain("ocx stop"); const noBody = await refusalFor(null); @@ -507,6 +507,7 @@ describe("409 refusal reporting", () => { // server's message printed just above them recommends exactly that. expect(refusalNextStep("respawnable_service")).toContain("already asked the service manager"); expect(refusalNextStep("self_unload_service")).toContain("already asked the service manager"); + expect(refusalNextStep("service_state_unknown")).not.toContain("repair the service manager access"); }); test("concurrent refusals each keep their own cause", async () => { diff --git a/tests/providers/xai/grok-lifecycle.test.ts b/tests/providers/xai/grok-lifecycle.test.ts index b84f13c8def..fcc676468b8 100644 --- a/tests/providers/xai/grok-lifecycle.test.ts +++ b/tests/providers/xai/grok-lifecycle.test.ts @@ -460,7 +460,7 @@ describe("POST /api/stop teardown", () => { expect(teardownSource).toContain("restoreNativeCodexAsync(options)"); }); - test("an unreadable scheduler state gets the same diagnosis from the CLI and the API", () => { + test("CLI and API distinguish an unverified stop from a service that stayed running", () => { const serviceSource = readFileSync(repoPath("src", "service", "orchestration.ts"), "utf8"); // A manager that refused to stop and a query that could not answer are different // problems: reporting the second as "did not stop" sends the operator looking for the @@ -490,6 +490,9 @@ describe("POST /api/stop teardown", () => { expect(handler).toContain('if (serviceStop === "state-unknown")'); // The route answers the post-stop case with the same code as the pre-check. expect((handler.match(/service_state_unknown/g) ?? []).length).toBeGreaterThanOrEqual(2); + const postStopUnknown = handler.slice(handler.indexOf('if (serviceStop === "state-unknown")'), handler.indexOf("await performStopTeardown")); + expect(postStopUnknown).toContain("service or process state could not be verified"); + expect(postStopUnknown).not.toContain("repair Task Scheduler access"); }); test("maps a failed shutdown drain to a nonzero process exit", () => { diff --git a/tests/windows/windows-checked-stop-live.test.ts b/tests/windows/windows-checked-stop-live.test.ts index c01b352ff17..0b8766b113e 100644 --- a/tests/windows/windows-checked-stop-live.test.ts +++ b/tests/windows/windows-checked-stop-live.test.ts @@ -25,7 +25,7 @@ import { } from "../../src/service/windows-checked-stop-live"; import { windowsProcessNative, type WindowsProcessNativeApi } from "../../src/service/windows-process-native"; import { windowsLauncherVbsPath } from "../../src/service/state"; -import { WINDOWS_TASK_INSTANCE_STOP_SCRIPT } from "../../src/service/windows-task-instance-stop"; +import { windowsTaskInstanceStopScript } from "../../src/service/windows-task-instance-stop"; import { buildWindowsTaskXml, windowsTaskRegistrationHealthy } from "../../src/service/windows-taskxml"; import { resolveTrustedWindowsPowerShellExe } from "../../src/lib/windows-elevation"; import { winswExePath } from "../../src/lib/winsw"; @@ -255,6 +255,54 @@ describe("capped command answers", () => { } }); + test("native engine proof matches every captured instance before releasing the Scheduler helper", async () => { + const sid = "S-1-5-21-100-200-300-1001"; + const xml = buildWindowsTaskXml(undefined, windowsLauncherVbsPath(), undefined, sid) + .replace('', '' + sid + ''); + const ticks = 638628778070001230n; + const first = { id: "00000000-0000-0000-0000-000000000001", pid: 41, ticks: String(ticks) }; + const second = { ...first, id: "00000000-0000-0000-0000-000000000002", pid: 42 }; + const elapsed = { now: 0 }; + const now = spyOn(performance, "now").mockImplementation(() => elapsed.now); + const check = async (fields: Record, capture: (pid: number) => bigint | null, + verdict = "ended") => { + elapsed.now = 0; + const pids: number[] = []; + let releases = 0; + const deps = windowsCheckedStopLiveDeps({ taskEngineIdentity: (pid, withCommand, callerSid) => { + expect([withCommand, callerSid]).toEqual([false, sid]); + pids.push(pid); + const sample = capture(pid); + return sample === null ? null : { ticks: sample }; + }, run: async (_program, args, _timeout, authorizeProof) => { + expect(Buffer.from(args.at(-1)!, "base64").toString("utf16le")).toStartWith("$nativeOwners = $true"); + const line = Buffer.from(JSON.stringify({ xml, sid, ...fields })).toString("base64"); + return result(0, await authorizeProof!(line) ? verdict : "unverified-registration"); + } }); + const status = await deps.endTask(2_000, () => { releases++; }); + return [status, pids, releases]; + }; + const live = { count: 2, engines: [first, second] }; + try { + expect(await check(live, () => ticks)).toEqual(["ended", [41, 42], 1]); + expect(await check(live, pid => pid === 42 ? null : ticks)).toEqual(["unverified-registration", [41, 42], 0]); + expect(await check(live, () => ticks + 10n)).toEqual(["unverified-registration", [41], 0]); + expect(await check(live, () => { elapsed.now = 2_000; return ticks; })).toEqual(["unverified-registration", [41], 0]); + for (const fields of [{}, { ...live, engines: [] }, { ...live, engines: [first] }, { ...live, sid: "S-1-5-18" }, + { ...live, xml: "" }, { count: 33, engines: Array(33).fill(first) }, + ...[{ id: "00000000-0000-0000-0000-000000000000" }, { pid: 0 }, { ticks: "3e18" }].map(invalid => ({ + count: 1, engines: [{ ...first, ...invalid }], + }))]) { + expect(await check(fields, () => ticks)).toEqual(["unverified-registration", [], 0]); + } + expect(await check({ ...live, engines: [first, first] }, () => ticks)).toEqual(["unverified-registration", [41], 0]); + const idle = { count: 0, engines: [] }; + expect(await check(idle, () => null, "not-running")).toEqual(["not-running", [], 1]); + expect(await check(idle, () => null, "unverified-registration")).toEqual(["unverified-registration", [], 1]); + expect(await check(idle, () => null, "ended")).toEqual(["failed", [], 1]); + } finally { now.mockRestore(); } + }); + test("sc.exe query and stop", () => { expect(parseScQueryState(result(1060, "[SC] EnumQueryServicesStatus:OpenService FAILED 1060:"))).toBe("nonexistent"); expect(parseScQueryState(result(0, " STATE : 4 RUNNING"))).toBe("running"); @@ -405,6 +453,13 @@ $instances | Add-Member ScriptMethod Item { param($index) $this.Rows[$index - 1] $script:task = [pscustomobject]@{ Xml = 'original'; State = 4; Instances = $instances } if ($script:scenario -in @('hidden', 'idle', 'idle-state-deadline')) { $instances.Rows = @() } if ($script:scenario -eq 'idle') { $script:task.State = 3 } +if ($script:scenario -in @('native-idle', 'native-queued')) { + $instances.Rows = @() + $script:task | Add-Member -Force ScriptProperty State { + if ($script:taskReads -eq 1) { throw 'state read before registration recheck' } + if ($script:scenario -eq 'native-queued') { 2 } else { 3 } + } +} if ($script:scenario -eq 'idle-state-deadline') { $script:task | Add-Member -Force ScriptProperty State { if ($script:taskReads -eq 2) { $script:elapsed = 2000 } @@ -440,21 +495,28 @@ function Get-CimInstance { } function Invoke-CimMethod { param($InputObject, $MethodName, $OperationTimeoutSec) + if ($script:scenario -like 'native-*') { throw 'native proof must not use WMI owner lookup' } if ($MethodName -ne 'GetOwnerSid') { throw 'wrong method' } $owner = if ($script:scenario -eq 'foreign' -and $InputObject.Pid -eq 43) { $script:sid + '1' } else { $script:sid } @{ ReturnValue = 0; Sid = $owner } } +function Get-FixtureProcess([int]$enginePid) { + $ticks = [long]638628778070001237 + $enginePid * 10 + if ($script:scenario -eq 'native-reused' -and $script:taskReads -eq 2 -and $enginePid -eq 43) { $ticks++ } + $obj = [pscustomobject]@{ StartTime = [datetime]::new($ticks, [DateTimeKind]::Utc) } + $obj | Add-Member ScriptMethod Dispose {} + $obj +} `; - const helper = WINDOWS_TASK_INSTANCE_STOP_SCRIPT + const fixtureHelper = (native: boolean) => windowsTaskInstanceStopScript(native) .replace("[Diagnostics.Stopwatch]::StartNew()", "Start-FixtureClock") .replace("[Console]::ReadLine()", "Read-FixtureApproval") .replace(/^\s*Import-Module .*'CimCmdlets\.psd1'.*$/m, "") .replaceAll("CimCmdlets\\", "") .replace("Microsoft.PowerShell.Utility\\New-Object -ComObject Schedule.Service", "New-Object -ComObject FixtureScheduler") + .replace("[Diagnostics.Process]::GetProcessById($enginePid)", "Get-FixtureProcess $enginePid") .replace("[Security.Principal.WindowsIdentity]::GetCurrent()", "([pscustomobject]@{ User = @{ Value = $script:sid }; Name = 'HOST\\test' })"); - expect(helper).toContain("$service = New-Object -ComObject FixtureScheduler"); - expect(helper).not.toContain("Schedule.Service"); // All launches share one 60 s window (each capped at the spawn budget), so a hang fails here // with the active scenario named, inside the 120 s Linux batch deadline. const deadline = Date.now() + 60_000; @@ -467,11 +529,20 @@ function Invoke-CimMethod { ["rejected", "unverified-registration", ""], ["hidden", "unverified-registration", ""], ["idle", "not-running", ""], + ["native-verified", "ended", "42,43"], + ["native-reused", "unverified-registration", ""], + ["native-idle", "not-running", ""], + ["native-queued", "unverified-registration", ""], ["late-approval", "failed", ""], ["deadline-before-first", "failed", ""], ["deadline-between-stops", "failed", "42"], ["idle-state-deadline", "failed", ""], ]) { + const native = scenario!.startsWith("native-"); + const helper = fixtureHelper(native); + expect(helper).toContain("$service = New-Object -ComObject FixtureScheduler"); + expect(helper).not.toContain("Schedule.Service"); + expect(helper).not.toContain("::GetProcessById"); // Production runs the helper alone, which silences progress before its first module use. The fixture // runs first here and its Add-Member/[pscustomobject] calls autoload Microsoft.PowerShell.Utility, which // writes a "Preparing modules for first use" CLIXML progress record to stderr on a cold runner. @@ -488,6 +559,17 @@ function Invoke-CimMethod { ]); expect({ scenario, stderr, code, output: stdout.trim().split(/\r?\n/).slice(-2) }) .toEqual({ scenario, stderr: "", code: 0, output: [status, "Stopped=" + stopped] }); + if (native) { + const line = stdout.trim().split(/\r?\n/)[0]!; + const proof = JSON.parse(Buffer.from(line, "base64").toString("utf8")); + if (scenario === "native-idle" || scenario === "native-queued") { + expect(proof).toMatchObject({ count: 0, engines: [] }); + expect(proof).not.toHaveProperty("state"); + } else { + expect(proof).toMatchObject({ count: 2, + engines: [{ pid: 42, ticks: "638628778070001650" }, { pid: 43, ticks: "638628778070001660" }] }); + } + } } }, 65_000); diff --git a/tests/windows/windows-process-evidence.test.ts b/tests/windows/windows-process-evidence.test.ts index ad3e46f8826..adce696b871 100644 --- a/tests/windows/windows-process-evidence.test.ts +++ b/tests/windows/windows-process-evidence.test.ts @@ -1,10 +1,11 @@ // Process evidence for the checked Windows stop (#7771): creation times, the Schedule // service PID, the checked terminate and the exit watch. Hermetic everywhere except the // cases gated on real Windows, which exercise the owner snapshot and x64 FFI on our own child. -import { afterEach, describe, expect, test } from "bun:test"; +import { afterEach, describe, expect, spyOn, test } from "bun:test"; import { join } from "node:path"; import { SPAWN_BUDGET_MS } from "../helpers/test-budget"; import { observeClientStopOwner, readClientStopProcessStart } from "../../src/client/stop-teardown-owner"; +import { resolveWindowsCurrentSid } from "../../src/codex/windows-current-sid"; import { resolveTrustedWindowsPowerShellExe, resolveTrustedWindowsSystemDirectory } from "../../src/lib/windows-elevation"; import { windowsLauncherVbsPath } from "../../src/service/state"; @@ -78,6 +79,101 @@ const SNAPSHOT_JSON = JSON.stringify([ { ProcessId: 4, ParentProcessId: 0, Name: "System", CommandLine: null, CreationDate: null }, ]); +describe("snapshot native wrapper owner proof", () => { + const created = "2026-11-12T01:02:03.1234560Z"; + const ms = Date.parse(created); + const ticks = 621_355_968_000_000_000n + BigInt(ms) * 10_000n + 4_560n; + const sid = "S-1-5-21-100-200-300-1002"; + const row = (pid: number) => ({ ProcessId: pid, ParentProcessId: 7, Name: "wscript.exe", + CommandLine: `wscript.exe "${windowsLauncherVbsPath()}"`, CurrentUserSid: sid, Owner: null, CreationDate: created }); + const snapshot = (rows: object[], timeoutMs = 5_000) => + windowsProcessSnapshot({ timeoutMs, run: async () => JSON.stringify(rows) }); + + test("proves only an eligible wrapper with a missing CIM owner and the same live incarnation", async () => { + setWindowsProcessPlatformForTests("win32"); + const calls: number[] = []; + setWindowsProcessNativeForTests(fakeNative({ + creationTime: pid => pid === 19 ? ms + 1 : ms, + sameUserIdentity: (pid, _withCommandLine, expectedSid) => { + calls.push(pid); + if (expectedSid !== sid && expectedSid !== "S-1-12-1-100-200-300-400") return null; + if (pid === 12) return { ticks: ticks + 10n }; // Same epoch ms, different CIM microsecond. + if (pid === 13) throw new Error("unavailable"); + if (pid === 14) return null; + return { ticks }; + }, + })); + const output = await snapshot([ + row(10), { ...row(11), CurrentUserSid: "S-1-12-1-100-200-300-400" }, + row(12), row(13), row(14), + { ...row(15), CurrentUserSid: "S-1-5-18" }, { ...row(16), CurrentUserSid: "S-1-5-21-100-200-300-4294967296" }, + { ...row(17), CommandLine: row(17).CommandLine.replace('vbs"', 'vbs.bak"') }, { ...row(18), Name: "unrelated.exe" }, + row(19), { ...row(20), CreationDate: "invalid" }, { ...row(21), CreationDate: created.replace("4560", "457") }, + { ...row(22), Owner: { Sid: "S-1-5-21-100-200-300-1003", ReturnValue: 0, CreationDate: created } }, + { ...row(23), Owner: { Sid: sid, ReturnValue: 2, CreationDate: created } }, + { ...row(24), Owner: { Sid: sid, ReturnValue: 0, CreationDate: created.replace("4560", "4570") } }, + row(0), row(0x1_0000_0000), + ]); + expect(output?.filter(entry => entry.foreignOwner === false).map(entry => entry.pid)).toEqual([10, 11]); + expect(output?.filter(entry => entry.foreignOwner === true).map(entry => entry.pid)).toEqual([22]); + expect(calls).toEqual([10, 11, 12, 13, 14]); + expect(JSON.stringify(output)).not.toContain(sid); + }); + + test("bounds optional native reads and leaves unread owners unknown", async () => { + setWindowsProcessPlatformForTests("win32"); + let calls = 0; + setWindowsProcessNativeForTests(fakeNative({ creationTime: () => ms, sameUserIdentity: () => { calls++; return { ticks }; } })); + const rows = Array.from({ length: 34 }, (_, i) => row(i + 100)); + const bounded = await snapshot(rows); + expect(calls).toBe(32); + expect(bounded).toHaveLength(34); + expect(bounded?.slice(32).every(entry => entry.foreignOwner === null)).toBe(true); + const expired = await snapshot([row(201)], 0); + expect(calls).toBe(32); + expect(expired?.[0]?.foreignOwner).toBeNull(); + setWindowsProcessNativeForTests(null); + expect((await snapshot([row(202)]))?.[0]?.foreignOwner).toBeNull(); + }); + + test("discards proof that returns after the original snapshot deadline", async () => { + setWindowsProcessPlatformForTests("win32"); + const creationPids: number[] = []; + let now = 0, reads = 0; + const clock = spyOn(performance, "now").mockImplementation(() => now); + try { + setWindowsProcessNativeForTests(fakeNative({ creationTime: pid => { + creationPids.push(pid); + return ms; + }, sameUserIdentity: () => { + reads++; + now = 100; + return { ticks }; + } })); + const entries = await snapshot([row(10), row(11)], 100); + expect(reads).toBe(1); + expect(creationPids).toEqual([10]); + expect(entries?.map(entry => entry.foreignOwner)).toEqual([null, null]); + expect(entries?.[1]).toMatchObject({ pid: 11, parentPid: 7, startTime: null }); + } finally { + clock.mockRestore(); + } + }); + + test("discards a native creation-time read that finishes at the snapshot deadline", async () => { + setWindowsProcessPlatformForTests("win32"); + let now = 0; + const clock = spyOn(performance, "now").mockImplementation(() => now); + try { + setWindowsProcessNativeForTests(fakeNative({ creationTime: () => { now = 100; return ms; } })); + const entries = await snapshot([row(10)], 100); + expect(entries?.[0]).toMatchObject({ pid: 10, parentPid: 7, startTime: null, foreignOwner: null }); + } finally { + clock.mockRestore(); + } + }); +}); + describe("Windows process evidence: pure decoding", () => { test("FILETIME converts to epoch ms by truncation; zero is unreadable", () => { expect(fileTimeToEpochMs(116_444_736_000_000_000n + 12_345_678n)).toBe(1_234); @@ -352,6 +448,17 @@ test.skipIf(process.platform !== "win32")("the live capped snapshot reads and re }, 10_000); describe("Windows process evidence: live x64 primitive", () => { + test.skipIf(liveX64)("matches an expected user SID on the current process handle", () => { + const current = resolveWindowsCurrentSid(() => { throw new Error("native current SID unavailable"); }); + const other = current === "S-1-5-21-1-2-3-4" ? "S-1-5-21-1-2-3-5" : "S-1-5-21-1-2-3-4"; + const native = windowsProcessNative(); + expect(native).not.toBeNull(); + const identity = native!.sameUserIdentity(process.pid); + expect(typeof identity?.ticks).toBe("bigint"); + expect(native!.sameUserIdentity(process.pid, false, current)?.ticks).toBe(identity!.ticks); + expect(native!.sameUserIdentity(process.pid, false, other)).toBeNull(); + }); + test.skipIf(liveX64)("reads a child's creation time, refuses a mismatched identity and ends the bound one", async () => { const child = Bun.spawn([process.execPath, "-e", "setInterval(() => {}, 1000)"], { stdio: ["ignore", "ignore", "ignore"], windowsHide: true, diff --git a/tests/windows/windows-stop-callers.test.ts b/tests/windows/windows-stop-callers.test.ts index 19ef54be61c..05ba0917896 100644 --- a/tests/windows/windows-stop-callers.test.ts +++ b/tests/windows/windows-stop-callers.test.ts @@ -6,7 +6,7 @@ */ import { afterEach, describe, expect, test } from "bun:test"; -import { inspectGuardedTarget, resetOcxWindowsStopForTests, stopGuardedManager } from "../../src/cli/stop-windows-checked"; +import { inspectGuardedTarget, resetOcxWindowsStopForTests, stopGuardedManager, stopServiceForUninstall, windowsPartAFailureMessage } from "../../src/cli/stop-windows-checked"; import { runGuardedManagerStep, type GuardedStopSnapshot } from "../../src/cli/stop-approval"; import { ROUTE_PART_A_CAP_MS, ROUTE_STRAY_SWEEP_CAP_MS, routeServiceStop } from "../../src/server/stop-service-route"; import { completeWindowsServiceStopReceipt, windowsServiceRemovalStop as removalStop, windowsServiceStopBeforeRestore as stopBeforeRestore } from "../../src/service/cli-windows-stop"; @@ -90,6 +90,14 @@ describe("/api/stop service stop on Windows", () => { }); describe("ocx service stop on Windows", () => { + test("CLI uninstall retains the specific checked-stop refusal", async () => { + const detail = "same-account ownership of a service wrapper could not be proven"; + resetOcxWindowsStopForTests("win32"); + setWindowsServiceStopHooksForTests({ partA: async () => partAResult("unknown", { detail }) }); + expect(await stopServiceForUninstall()).toBe("state-unknown"); + expect(windowsPartAFailureMessage()).toContain(detail); + }); + test("a discovered orphan's endpoint is used for both receipt and stop", async () => { setWindowsServiceStopHooksForTests({ partA: async () => partAResult("stopped"), partB: async () => partBResult("freed") }); const endpoint = { hostname: "127.0.0.1", port: 12001 }; diff --git a/tests/windows/windows-stop-ocx-stop.test.ts b/tests/windows/windows-stop-ocx-stop.test.ts index bd4e135b133..3ae2786ef78 100644 --- a/tests/windows/windows-stop-ocx-stop.test.ts +++ b/tests/windows/windows-stop-ocx-stop.test.ts @@ -84,6 +84,12 @@ describe("plain ocx stop on Windows: Part A holds the child stop", () => { expect(run.summary).toMatchObject({ schema: "ocx-stop/1", outcome: "failed", service, proxy: "unknown", sharedTeardown: "skipped" }); if (reason) expect(run.summary.serviceStopReason).toBe(reason); else expect("serviceStopReason" in run.summary).toBe(false); + if (outcome === "unknown") { + expect(run.summary.message).toContain("fixture unknown"); + expect(run.stderr.split(String(run.summary.message))).toHaveLength(2); + expect(run.stderr).not.toContain("repair Task Scheduler access"); + expect("serviceStopMessage" in run.summary).toBe(false); + } expect(run.stderr).toContain("The proxy was left running and the shared teardown skipped"); }); } From 27fbfc3d23ea9d37dedcc16a12a37d45df6fbb65 Mon Sep 17 00:00:00 2001 From: Arthur tinseau <65445747+atinseau@users.noreply.github.com> Date: Wed, 25 Nov 2026 06:55:10 +0100 Subject: [PATCH 38/60] feat(combos): add quota-only failover and a same-model guard (#9089) Quota-only Combo failover advances only on confirmed quota or billing exhaustion and keeps paid targets behind consent; a same-model guard keeps a model-locked fallback on the same model. Maintainer fix: a confirmed billing exhaustion answered with 400/422 advances the chain after every hard stop. Co-authored-by: JUN --- src/codex/routing/selection.ts | 10 + src/codex/subagent-model-fallback.ts | 2 +- src/combos/billing.ts | 16 + src/combos/cooldown-store.ts | 20 +- src/combos/failover.ts | 48 +- src/combos/resolve.ts | 104 +- src/combos/suggestion-channel.ts | 10 + src/combos/types.ts | 12 + src/lib/client-error-body.ts | 8 + src/providers/api-key-cooldowns.ts | 20 +- src/providers/key-failover.ts | 27 +- src/router.ts | 40 +- src/server/management/combo-routes.ts | 7 + src/server/messages-native.ts | 4 +- src/server/request-log-committed-terminal.ts | 2 + src/server/responses/adapter-dispatch.ts | 36 +- src/server/responses/codex-auth-error.ts | 7 +- src/server/responses/codex-ws-exchange.ts | 15 +- .../responses/combo-admission-snapshot.ts | 36 +- src/server/responses/combo-session-recall.ts | 82 +- src/server/responses/combo-tool-loop-pin.ts | 68 +- src/server/responses/core-combo-failure.ts | 170 ++- src/server/responses/core-combo.ts | 228 ++++- src/server/responses/core-errors.ts | 88 +- src/server/responses/core-options.ts | 5 + src/server/responses/core.ts | 4 +- src/server/responses/fetch-helpers.ts | 2 + src/server/responses/request-prepare.ts | 206 +++- src/server/responses/response-effects.ts | 4 +- src/server/responses/send-admission.ts | 89 ++ .../responses/shadow-target-availability.ts | 2 + src/server/responses/ws-upstream.ts | 2 + src/types/config.ts | 4 + structure/fallback-policy.md | 73 ++ structure/runtime.md | 2 +- structure/transports/responses-failover.md | 3 + .../anthropic-combo-account-cooldown.test.ts | 10 +- .../anthropic-pool-usage-limit.test.ts | 87 ++ tests/helpers/responses-core-source.ts | 2 + ...neric-oauth-combo-account-cooldown.test.ts | 121 ++- tests/oauth/generic-oauth-failover.test.ts | 3 +- .../responses-dispatch-receipt.test.ts | 84 +- .../responses-fetch-helpers-boundary.test.ts | 2 + .../shadow-intercept-target-lifecycle.test.ts | 7 + .../combo-committed-terminal-cooldown.test.ts | 9 +- tests/routing/combo-management-api.test.ts | 19 + ...uter-combo-failover-classification.test.ts | 12 + .../combo-loopback-metered-consent.test.ts | 882 +++++++++++++++- .../server-combo-cooldown-recording.test.ts | 4 + ...erver-combo-tool-loop-continuation.test.ts | 967 +++++++++++++++++- .../server-combo-zero-output-failover.test.ts | 19 + 51 files changed, 3501 insertions(+), 183 deletions(-) create mode 100644 src/combos/billing.ts create mode 100644 src/server/responses/send-admission.ts diff --git a/src/codex/routing/selection.ts b/src/codex/routing/selection.ts index 64d16cebeeb..0f87bb341df 100644 --- a/src/codex/routing/selection.ts +++ b/src/codex/routing/selection.ts @@ -108,6 +108,16 @@ export function isCodexAccountHeldAtUsageLimit( ); } +/** A missing, unusable or throttled member is not evidence that the whole pool spent its allowance. */ +export function codexPoolHasConfirmedUsageLimit(config: OcxConfig, now: number, refusedId?: string): boolean { + const ids = [ + MAIN_CODEX_ACCOUNT_ID, + ...(config.codexAccounts ?? []).filter(isSelectableCodexPoolAccount).map(account => account.id), + ].filter(id => !isCodexAccountPaused(config, id) && !isCodexAccountPlanExcluded(config, id) + && isCodexAccountUsable(config, id)); + return ids.length > 0 && ids.every(id => id === refusedId || isCodexAccountHeldAtUsageLimit(config, id, now)); +} + /** The automatic-rotation policies that also bind the legacy keep-the-active-account fallback. */ export function isCodexAccountRotationExcluded( config: OcxConfig, diff --git a/src/codex/subagent-model-fallback.ts b/src/codex/subagent-model-fallback.ts index 57daa2bc6a8..ca0d259ea8f 100644 --- a/src/codex/subagent-model-fallback.ts +++ b/src/codex/subagent-model-fallback.ts @@ -467,7 +467,7 @@ export function getSubagentQuotaPrimeStateForTests(): { }; } -function rewriteParsedModel(parsed: OcxParsedRequest, model: string): void { +export function rewriteParsedModel(parsed: OcxParsedRequest, model: string): void { parsed.modelId = model; if (parsed._rawBody && typeof parsed._rawBody === "object") { (parsed._rawBody as { model?: string }).model = model; diff --git a/src/combos/billing.ts b/src/combos/billing.ts new file mode 100644 index 00000000000..1de13a9cfa5 --- /dev/null +++ b/src/combos/billing.ts @@ -0,0 +1,16 @@ +import { getProviderRegistryEntry } from "../providers/registry"; +import { normalizedBaseUrl } from "../providers/openai-forward-destination"; +import { comboProviderBilling, type ComboProviderBilling, type SuggestionProvider } from "./suggestion-channel"; + +/** Strict Combos require consent whenever the transport does not establish an included route. */ +export function configuredComboProviderBilling(provider: SuggestionProvider): ComboProviderBilling { + const registry = getProviderRegistryEntry(provider.name); + const authMode = provider.authMode ?? registry?.authKind; + const adapter = provider.adapter ?? registry?.adapter; + const baseUrl = provider.baseUrl ?? registry?.baseUrl; + if (authMode === "oauth" && registry?.authKind === "oauth" && registry.oauthFamily === "anthropic" + && adapter === registry.adapter && baseUrl && normalizedBaseUrl(baseUrl) === normalizedBaseUrl(registry.baseUrl)) { + return "subscription"; + } + return comboProviderBilling({ ...provider, authMode, adapter, baseUrl }); +} diff --git a/src/combos/cooldown-store.ts b/src/combos/cooldown-store.ts index 2ed23eb18ab..cd5c2baa5a1 100644 --- a/src/combos/cooldown-store.ts +++ b/src/combos/cooldown-store.ts @@ -31,8 +31,8 @@ import { atomicWriteFile } from "../config/atomic-write"; import { withConfigMutationLockSync } from "../config/mutation-lock"; import { getConfigDir } from "../config/paths"; -export interface PersistableCooldown { cooldownUntil: number; revision: number; status?: number } -type StoredRow = { cooldownUntil: number; status?: number }; +export interface PersistableCooldown extends StoredRow { revision: number } +type StoredRow = { cooldownUntil: number; status?: number; quotaExhausted?: true }; const FILE = "combo-cooldowns.json"; const FLUSH_DELAY_MS = 250; @@ -59,9 +59,13 @@ function readStoredRows(path: string): Record { const rows: Record = {}; if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return rows; for (const [key, value] of Object.entries(parsed as Record)) { - const row = value as { cooldownUntil?: unknown; status?: unknown } | null; + const row = value as { cooldownUntil?: unknown; status?: unknown; quotaExhausted?: unknown } | null; if (typeof row?.cooldownUntil !== "number" || !Number.isFinite(row.cooldownUntil)) continue; - rows[key] = { cooldownUntil: row.cooldownUntil, ...(typeof row.status === "number" ? { status: row.status } : {}) }; + rows[key] = { + cooldownUntil: row.cooldownUntil, + ...(typeof row.status === "number" ? { status: row.status } : {}), + ...(row.quotaExhausted === true ? { quotaExhausted: true } : {}), + }; } return rows; } @@ -101,7 +105,7 @@ export class PersistedCooldownMap extends Map extends Map own.cooldownUntil ? other - : { cooldownUntil: own.cooldownUntil, ...(own.status !== undefined ? { status: own.status } : {}) }; + : { + cooldownUntil: own.cooldownUntil, + ...(own.status !== undefined ? { status: own.status } : {}), + ...(own.quotaExhausted === true ? { quotaExhausted: true } : {}), + }; } mkdirSync(dir, { recursive: true }); atomicWriteFile(path, JSON.stringify(out)); diff --git a/src/combos/failover.ts b/src/combos/failover.ts index a155777d770..5eb186317f2 100644 --- a/src/combos/failover.ts +++ b/src/combos/failover.ts @@ -26,6 +26,9 @@ interface TargetCooldown { cooldownUntil: number; revision: number; status?: number; + quotaExhausted?: true; + /** Process-local credential binding. Cooldown files carry the advisory marker only. */ + quotaBinding?: string; } const DEFAULT_COOLDOWN_MS = 60_000; @@ -132,6 +135,20 @@ export function comboTargetCooldownStatus( ? targetCooldowns.get(cooldownMapKey(comboId, target))?.status : undefined; } +export function strictComboTargetCooldown( + comboId: string, + target: Pick, + activeBinding: string | undefined, + now: number, +): "quota exhausted" | "cooldown" | undefined { + if (!isComboTargetInCooldown(comboId, target, now)) return undefined; + const entry = targetCooldowns.get(cooldownMapKey(comboId, target))!; + if (!entry.quotaExhausted) return "cooldown"; + if (activeBinding && entry.quotaBinding === activeBinding) return "quota exhausted"; + // A replaced key or a cooldown loaded from disk has to be checked afresh. + return undefined; +} + /** Identity of the current live write, independent of its possibly repeated expiry. */ export function comboTargetCooldownRevision( comboId: string, @@ -223,6 +240,7 @@ export function coolComboTarget( status?: number; code?: string | null; message?: string; + quotaBinding?: string; }, ): boolean { const now = options?.now ?? Date.now(); @@ -255,6 +273,7 @@ export function coolComboTarget( // Local fallbacks are capped at ten minutes; explicit server delays at one day. cooldownUntil: now + (serverDelayMs ?? Math.min(Math.max(cooldownMs, 1), MAX_COOLDOWN_MS)), status: options?.status, + ...(options?.quotaBinding ? { quotaExhausted: true, quotaBinding: options.quotaBinding } : {}), }); sweepExpiredOnWrite(now); return true; @@ -286,6 +305,7 @@ export interface CommittedTerminalServingAttempt { export interface CommittedTerminalCooldownFacts { comboId?: string; + quotaOnlyFallback?: boolean; terminalStatus?: string; terminalReason?: CommittedIncompleteReason; servingAttempt?: CommittedTerminalServingAttempt; @@ -304,7 +324,7 @@ export interface CommittedTerminalCooldownFacts { * effort and context configuration stay untouched. */ export function coolComboTargetForCommittedTerminal(facts: CommittedTerminalCooldownFacts): void { - if (!facts.comboId || facts.terminalStatus !== "incomplete") return; + if (!facts.comboId || facts.quotaOnlyFallback || facts.terminalStatus !== "incomplete") return; const cooldownMs = facts.terminalReason === undefined ? undefined : COMMITTED_TERMINAL_COOLDOWN_MS[facts.terminalReason]; @@ -801,6 +821,26 @@ function hasAccountExhaustionCode(code?: string | null): boolean { return ACCOUNT_EXHAUSTION_CODES.has(normalized) || normalized === "insufficient_quota"; } +const BILLING_EXHAUSTION_CODES = new Set([ + "credit_balance_exhausted", "credit_balance_too_low", "insufficient_balance", "billing_hard_limit_reached", + "organization_spend_limit_exceeded", "project_spend_limit_exceeded", "organization_usage_limit_exceeded", +]); + +/** Use structured budget evidence or a recognized quota refusal, never a bare 429. */ +export function isConfirmedComboExhaustion(status: number, message: string, code?: string, type?: string): boolean { + if (isAnthropicBillingFailure(status, message, code ?? type) || isAnthropicExtraUsageFailure(status, message, code ?? type)) return true; + const identity = code ?? type; + const normalized = normalizedFailureCode(identity); + // A structured exhaustion code is authoritative on a request, quota or upstream failure status. + const structuredStatus = status === 400 || status === 402 || status === 422 || status === 429 || (status >= 500 && status < 600); + if (structuredStatus && (hasAccountExhaustionCode(identity) || BILLING_EXHAUSTION_CODES.has(normalized))) return true; + if (status !== 402 && status !== 429 && status !== 502) return false; + if (normalized === "rate_limit_exceeded" || normalized === "too_many_requests" + || isTransientRequestRateLimit({ status, code: identity, message }) + || /rate limit|per minute|per second/i.test(message)) return false; + return status === 429 && ACCOUNT_EXHAUSTION_TEXT.test(message); +} + /** * A free-tier cap the upstream evaluates PER REQUEST rather than per account window. These * needles used to reach only `isProviderScopedQuotaCap`, so a single oversized free-tier prompt @@ -1766,6 +1806,7 @@ export function comboFailureDecision( providerModerationRefusal?: boolean; /** Whole-body 413 intake verdict ({@link isProviderIntakeRefusalBody}); false vetoes the hop. */ providerIntakeRefusal?: boolean; + confirmedQuotaExhaustion?: boolean; }, ): ComboFailureDecision { const rootRawCode = typeof options?.rootCode === "number" ? String(options.rootCode) : options?.rootCode; @@ -1797,6 +1838,7 @@ function decideComboFailure( providerModerationRefusal?: boolean; /** Whole-body 413 intake verdict ({@link isProviderIntakeRefusalBody}); false vetoes the hop. */ providerIntakeRefusal?: boolean; + confirmedQuotaExhaustion?: boolean; }, ): ComboFailureDecision { if (status === 499) return "stop"; @@ -1924,8 +1966,8 @@ function decideComboFailure( if (options?.failedAdapter === "kiro" && isKiroAccountProfileRefusal(status, message)) return "hop"; // A structured account-window exhaustion code is provider-state evidence even inside a // 400 / invalid_request_error envelope, so it must precede that stop. Exhaustion prose alone - // never reaches this arm: a validation error can quote quota wording back (#7625). - if (hasAccountExhaustionCode(rawCode)) return "hop"; + // never reaches this arm (#7625). A quota-only Combo's confirmed billing exhaustion joins it here. + if (hasAccountExhaustionCode(rawCode) || options?.confirmedQuotaExhaustion) return "hop"; // OpenRouter can wrap an opaque provider failure as a numeric 400 with `metadata.raw: "ERROR"` // and no type. Let a heterogeneous combo try another target in this case, while keeping // malformed response_format diagnostics terminal and preserving any structured code. diff --git a/src/combos/resolve.ts b/src/combos/resolve.ts index 4f256fdb60e..b6cfba35382 100644 --- a/src/combos/resolve.ts +++ b/src/combos/resolve.ts @@ -1,12 +1,13 @@ import { errorDestinationText, providerErrorDestinationLabel } from "../lib/error-destination"; import type { OcxComboTarget, OcxConfig } from "../types"; -import { getCachedProviderRoutingQuota } from "../providers/quota-routing-cache"; +import { getCachedProviderRoutingQuota, providerQuotaRoutingBinding } from "../providers/quota-routing-cache"; import type { ProviderQuota, ProviderQuotaWindow } from "../providers/quota-types"; import { sleepWithAbort } from "../lib/upstream-retry"; import { clearComboTargetCooldownIfUnchanged, comboTargetCooldownRevision, comboTargetCooldownStatus, + strictComboTargetCooldown, coolComboTarget, earliestComboCooldown, isComboTargetInCooldown, @@ -31,6 +32,13 @@ export interface ComboPick { cooldownReprobeTargets?: Record; } +// Route picks can be projected into diagnostics. Keep credential evidence off their shape. +const pickedQuotaBindings = new WeakMap(); + +export function comboPickQuotaBinding(pick: ComboPick): string | undefined { + return pickedQuotaBindings.get(pick); +} + interface SelectionState { lastCooldownReprobeAt?: number; activeKey?: string; @@ -134,6 +142,17 @@ function targetProviderIsUsable(config: OcxConfig, target: OcxComboTarget, now: return providerExclusionReason(config, target, now) === undefined; } +function comboQuotaBinding(config: OcxConfig, target: OcxComboTarget): string | undefined { + const provider = config.providers[target.provider]; + // A fixed-key verdict cannot speak for an OAuth account or a rotating key pool. + if (!provider || (provider.apiKeyPool?.length ?? 0) > 1) return undefined; + const credential = providerQuotaRoutingBinding(target.provider, provider); + return credential ? JSON.stringify([ + credential, config.blockedModelRedirects, provider.modelAliases, provider.modelAdapters, + provider.responsesPath, provider.chatCompletionsPath, provider.googleMode, provider.project, provider.location, + ]) : undefined; +} + /** * OCX-11: the coarse fallback trigger for a target the picker passed over for a reason other * than a cooldown (provider missing or disabled, cached quota spent, ineligible for the request). @@ -151,11 +170,13 @@ export function comboTargetSkipTrigger( * classified by the HTTP status its entry kept: 429/402 is quota, 401/403 is permission, and any * other or missing status is transient. */ -function exclusionCause(reason: ComboExclusionReason, comboId: string, target: OcxComboTarget, now: number): ComboTargetUnavailableCause { +function exclusionCause(reason: ComboExclusionReason, comboId: string, target: OcxComboTarget, now: number, + quotaOnly = false): ComboTargetUnavailableCause { if (reason === "quota exhausted") return "quota"; if (reason === "ineligible for this request") return "unsupported"; if (reason !== "cooldown") return "unavailable"; const status = comboTargetCooldownStatus(comboId, target, now); + if (quotaOnly) return status === 401 || status === 403 ? "permission" : "transient"; return status === 429 || status === 402 ? "quota" : status === 401 || status === 403 ? "permission" : "transient"; } @@ -171,10 +192,18 @@ function targetExclusionReason( target: NormalizedComboTarget, eligible: ((target: NormalizedComboTarget) => boolean) | undefined, now: number, + quotaOnly = false, + quotaExhausted?: (target: NormalizedComboTarget, now: number) => boolean, ): ComboExclusionReason | undefined { let reason = providerExclusionReason(config, target, now); - const cooldown = reason ? undefined : earliestComboCooldown(comboId, [target], now); - if (cooldown) reason = "cooldown"; + // A caller that resolves redirects replaces the declared provider's cached quota with its destination's. + if (quotaOnly && quotaExhausted && (!reason || reason === "quota exhausted")) { + reason = quotaExhausted(target, now) ? "quota exhausted" : undefined; + } + if (!reason) { + reason = quotaOnly ? strictComboTargetCooldown(comboId, target, comboQuotaBinding(config, target), now) + : isComboTargetInCooldown(comboId, target, now) ? "cooldown" : undefined; + } if (!reason && eligible) { try { if (!eligible(target)) reason = "ineligible for this request"; @@ -196,9 +225,11 @@ export function comboTargetUnavailableCause( target: NormalizedComboTarget, eligible?: (target: NormalizedComboTarget) => boolean, now = Date.now(), + quotaExhausted?: (target: NormalizedComboTarget, now: number) => boolean, ): ComboTargetUnavailableCause | undefined { - const reason = targetExclusionReason(config, comboId, target, eligible, now); - return reason ? exclusionCause(reason, comboId, target, now) : undefined; + const quotaOnly = getCombo(config, comboId)?.quotaOnlyFallback; + const reason = targetExclusionReason(config, comboId, target, eligible, now, quotaOnly, quotaExhausted); + return reason ? exclusionCause(reason, comboId, target, now, quotaOnly) : undefined; } export function comboExclusion( @@ -206,13 +237,15 @@ export function comboExclusion( comboId: string, eligible?: (target: NormalizedComboTarget) => boolean, now = Date.now(), + quotaExhausted?: (target: NormalizedComboTarget, now: number) => boolean, ): ComboExclusion { - const targets = getCombo(config, comboId)?.targets ?? []; + const combo = getCombo(config, comboId); + const targets = combo?.targets ?? []; const classes: ComboTargetUnavailableCause[] = []; const reasons = targets.flatMap((target, index) => { - const reason = targetExclusionReason(config, comboId, target, eligible, now); + const reason = targetExclusionReason(config, comboId, target, eligible, now, combo?.quotaOnlyFallback, quotaExhausted); if (!reason) return []; - classes.push(exclusionCause(reason, comboId, target, now)); + classes.push(exclusionCause(reason, comboId, target, now, combo?.quotaOnlyFallback)); return [`target ${index + 1} (${errorDestinationText(providerErrorDestinationLabel(target.provider))}): ${reason}`]; }).join("; "); return { @@ -448,6 +481,7 @@ export function pickComboTarget( options: { exclude?: Iterable; eligible?: (target: NormalizedComboTarget) => boolean; + quotaExhausted?: (target: NormalizedComboTarget, now: number) => boolean; /** Disable recovery for picks without request context or picks already in flight. */ allowCooldownReprobe?: boolean; /** Request-scoped cooldown bypasses, each bound to the write it was reserved against. */ @@ -462,6 +496,24 @@ export function pickComboTarget( if (!combo) throw new UnknownComboError(comboId); const excluded = new Set(options.exclude ?? []); const now = options.now ?? Date.now(); + if (combo.quotaOnlyFallback) { + for (const [targetIndex, target] of combo.targets.entries()) { + const key = targetKey(target); + if (excluded.has(key)) continue; + const reason = providerExclusionReason(config, target, now); + if (reason && reason !== "quota exhausted") return null; + // The caller resolves redirects, so its verdict replaces the declared provider's cached quota. + if (options.quotaExhausted ? options.quotaExhausted(target, now) : reason === "quota exhausted") continue; + const quotaBinding = comboQuotaBinding(config, target); + const cooldown = strictComboTargetCooldown(comboId, target, quotaBinding, now); + if (cooldown === "quota exhausted") continue; + if (cooldown || options.eligible?.(target) === false) return null; + const pick = { comboId, target, targetIndex, attempted: [...excluded, key], writerGeneration }; + if (quotaBinding) pickedQuotaBindings.set(pick, quotaBinding); + return pick; + } + return null; + } const cooldownReprobeTargets = new Map(options.cooldownReprobeTargets); if (options.allowCooldownReprobe !== false && !options.preview && excluded.size === 0) { for (const [key, revision] of reserveAllCooledTargets(config, comboId, now, options.eligible) ?? []) { @@ -616,6 +668,7 @@ export function advanceComboAfterFailure( now?: number; cooldownMs?: number; eligible?: (target: NormalizedComboTarget) => boolean; + quotaExhausted?: (target: NormalizedComboTarget, now: number) => boolean; cooldownScope?: ComboFailureCooldownScope; /** A request-local deadline can advance the ladder without penalizing its target. */ recordFailure?: boolean; @@ -623,12 +676,14 @@ export function advanceComboAfterFailure( status?: number; code?: string | null; message?: string; + quotaBinding?: string; /** Account-qualified provider label of the account this failure came from, when a pool resolved one. */ failedAccount?: string; } = {}, ): ComboPick | null { - if (options.recordFailure !== false) noteComboFailure(pick.comboId, pick.target, pick.writerGeneration); const combo = getCombo(config, pick.comboId); + const recordFailure = options.recordFailure !== false && (!combo?.quotaOnlyFallback || !!options.quotaBinding); + if (recordFailure) noteComboFailure(pick.comboId, pick.target, pick.writerGeneration); // A 429 from a pooled provider names the ACCOUNT that is spent, not the target. The pool // records that account's own cooldown and rotates past it, so cooling the target here blacks // out the accounts that still answer: on 2026-09-28 one Anthropic account replied @@ -639,13 +694,13 @@ export function advanceComboAfterFailure( // including the pool's OWN "all accounts are cooled" 429, which refuses locally before it picks // one. That is what keeps this from trading a blackhole for a hammer: when nothing else is // holding the target back, the target cooldown still does. - // A 402 credit refusal is the provider-scoped twin: the caller names an account only after the - // pool has cooled it and still holds an eligible sibling. + // A credit refusal (402, or 400 with the same body) is the provider-scoped twin: the caller names + // an account only after the pool has cooled it and still holds an eligible sibling. const accountScoped = options.failedAccount !== undefined - && (options.status === 429 ? options.cooldownScope === "target" : options.status === 402); + && (options.status === 429 ? options.cooldownScope === "target" : options.status === 400 || options.status === 402); // "none" records no cooldown at all: the failure described the request, not the target, so // the target must stay immediately selectable for the next (differently shaped) request. - if (options.recordFailure !== false && options.cooldownScope !== "none" && !accountScoped) { + if (recordFailure && options.cooldownScope !== "none" && !accountScoped) { const cooldownTargets = options.cooldownScope === "provider" && combo ? combo.targets.filter(target => target.provider === pick.target.provider) : [pick.target]; @@ -663,12 +718,13 @@ export function advanceComboAfterFailure( // null hands the decision to `pickComboTargetWithWait`, which waits a normal target out // inside the combo's wait budget or dispatches the last resort when none is reachable. // Without the policy the eligible set is unchanged and the pick is exactly as before. - const defersLastResort = combo?.cooldownWaitPolicy === "before-last-resort" + const defersLastResort = !combo?.quotaOnlyFallback && combo?.cooldownWaitPolicy === "before-last-resort" && combo.targets.some(target => !target.lastResort); return pickComboTarget(config, pick.comboId, { exclude: pick.attempted, - preview: options.recordFailure === false, + preview: !recordFailure, now: options.now, + quotaExhausted: options.quotaExhausted, cooldownReprobeTargets: pick.cooldownReprobeTargets ? Object.entries(pick.cooldownReprobeTargets) : undefined, @@ -683,6 +739,7 @@ export async function pickComboTargetWithWait( options: { exclude?: Iterable; eligible?: (target: NormalizedComboTarget) => boolean; + quotaExhausted?: (target: NormalizedComboTarget, now: number) => boolean; waitForCooldownMs: number; abortSignal?: AbortSignal; /** Disable recovery when retrying a target after its normal cooldown. */ @@ -693,6 +750,9 @@ export async function pickComboTargetWithWait( sleep?: (ms: number, signal?: AbortSignal) => Promise; }, ): Promise { + if (getCombo(config, comboId)?.quotaOnlyFallback) { + return options.abortSignal?.aborted ? null : pickComboTarget(config, comboId, options); + } const now = options.now ?? Date.now(); const excluded = new Set(options.exclude ?? []); const customEligible = options.eligible; @@ -854,11 +914,17 @@ export function clearComboSelectionState(comboId?: string): void { selectionState.delete(comboId); } -export function tryPickComboModel(config: OcxConfig, modelId: string, preview = false): ComboPick | null { +export function tryPickComboModel( + config: OcxConfig, + modelId: string, + preview = false, + quotaExhausted?: (target: OcxComboTarget, now: number) => boolean, +): ComboPick | null { const comboId = resolveComboId(config, modelId); if (!comboId) return null; if (!getCombo(config, comboId)) throw new UnknownComboError(comboId); - const picked = pickComboTarget(config, comboId, { preview, allowCooldownReprobe: false }); - if (!picked) throw new NoAvailableComboTargetsError(comboId, comboExclusion(config, comboId)); + const now = Date.now(); + const picked = pickComboTarget(config, comboId, { preview, allowCooldownReprobe: false, quotaExhausted, now }); + if (!picked) throw new NoAvailableComboTargetsError(comboId, comboExclusion(config, comboId, undefined, now, quotaExhausted)); return picked; } diff --git a/src/combos/suggestion-channel.ts b/src/combos/suggestion-channel.ts index 83fcb195711..9258257dbcf 100644 --- a/src/combos/suggestion-channel.ts +++ b/src/combos/suggestion-channel.ts @@ -77,6 +77,16 @@ function hostOf(baseUrl: string | undefined): string { } } +export type ComboProviderBilling = "subscription" | "local" | "consent"; + +/** Classify the effective transport. The server applies registry defaults before calling this. */ +export function comboProviderBilling(provider: SuggestionProvider): ComboProviderBilling { + const { authMode, baseUrl } = provider; + const host = hostOf(baseUrl).replace(/\.$/, ""); + if (authMode === "local" && ["localhost", "127.0.0.1", "[::1]"].includes(host)) return "local"; + return subscriptionMaker(provider) ? "subscription" : "consent"; +} + export function channelTier(provider: SuggestionProvider, model: string): ChannelTier { const host = hostOf(provider.baseUrl); if (provider.authMode === "forward" diff --git a/src/combos/types.ts b/src/combos/types.ts index b1fe95e3a50..fecf19453cc 100644 --- a/src/combos/types.ts +++ b/src/combos/types.ts @@ -55,6 +55,8 @@ export interface NormalizedComboTarget { } export interface NormalizedComboConfig { + quotaOnlyFallback?: true; + preserveFallbackModel?: true; /** Operator consent, effective only on a loopback-only proxy. */ allowMeteredTargets?: boolean; strategy: OcxComboStrategy; @@ -197,6 +199,14 @@ export function comboConfigIssues( } const body = raw as Record; + for (const setting of ["quotaOnlyFallback", "preserveFallbackModel"] as const) { + const value = body[setting]; + if (value !== undefined && typeof value !== "boolean") { + issues.push({ path: [setting], message: `${setting} must be a boolean` }); + } else if (value === true && body.strategy !== undefined && body.strategy !== "failover") { + issues.push({ path: [setting], message: `${setting} requires the failover strategy` }); + } + } if (body.allowMeteredTargets !== undefined && typeof body.allowMeteredTargets !== "boolean") { issues.push({ path: ["allowMeteredTargets"], message: "allowMeteredTargets must be a boolean" }); } @@ -581,6 +591,8 @@ export function normalizeComboConfig(raw: OcxComboConfig): NormalizedComboConfig : null; return { strategy: raw.strategy ?? "failover", + ...((raw.strategy ?? "failover") === "failover" && raw.quotaOnlyFallback === true ? { quotaOnlyFallback: true as const } : {}), + ...((raw.strategy ?? "failover") === "failover" && raw.preserveFallbackModel === true ? { preserveFallbackModel: true as const } : {}), ...(raw.allowMeteredTargets === true ? { allowMeteredTargets: true } : {}), stickyLimit: raw.stickyLimit ?? 1, cooldownMs: raw.cooldownMs, diff --git a/src/lib/client-error-body.ts b/src/lib/client-error-body.ts index ed2e492823f..27474550acf 100644 --- a/src/lib/client-error-body.ts +++ b/src/lib/client-error-body.ts @@ -176,7 +176,15 @@ export function carryProxyErrorPresentation(source: object, ta return target; } export function isProxyError(value: object): boolean { return proxyErrors.has(value); } +const proxyQuotaExhaustions = new WeakSet(); +export function isProxyQuotaExhaustion(response: Response): boolean { return proxyQuotaExhaustions.has(response); } +export function markProxyQuotaExhaustion(response: Response): Response { + proxyQuotaExhaustions.add(response); + return markProxyError(response); +} export function carryProxyError(source: object, target: T): T { + if (source instanceof Response && target instanceof Response + && source.status === target.status && isProxyQuotaExhaustion(source)) markProxyQuotaExhaustion(target); return isProxyError(source) ? carryProxyErrorPresentation(source, markProxyError(target)) : target; } /** The tool guard records only messages it constructs for this response's request context. */ diff --git a/src/providers/api-key-cooldowns.ts b/src/providers/api-key-cooldowns.ts index 42b00424ee3..e5fe83af5f0 100644 --- a/src/providers/api-key-cooldowns.ts +++ b/src/providers/api-key-cooldowns.ts @@ -1,13 +1,22 @@ /** Process-local cooldown state shared by selection validation and key failover. */ -const keyCooldowns = new Map(); +const keyCooldowns = new Map(); function cooldownKey(providerName: string, keyId: string): string { return `${providerName}\0${keyId}`; } -export function setKeyCooldown(providerName: string, keyId: string, cooldownUntil: number): void { +/** + * `quotaSpent` marks a refusal that proved the key's quota or credit is spent. A rate limit leaves + * it unset, because that key serves again once the window passes. + */ +export function setKeyCooldown(providerName: string, keyId: string, cooldownUntil: number, quotaSpent = false): void { const key = cooldownKey(providerName, keyId); - keyCooldowns.set(key, { cooldownUntil: Math.max(keyCooldowns.get(key)?.cooldownUntil ?? 0, cooldownUntil) }); + const previous = keyCooldowns.get(key); + const quotaSpentUntil = Math.max(previous?.quotaSpentUntil ?? 0, quotaSpent ? cooldownUntil : 0); + keyCooldowns.set(key, { + cooldownUntil: Math.max(previous?.cooldownUntil ?? 0, cooldownUntil), + ...(quotaSpentUntil > 0 ? { quotaSpentUntil } : {}), + }); } export function isKeyInCooldown(providerName: string, keyId: string, now = Date.now()): boolean { @@ -26,6 +35,11 @@ export function getKeyCooldownUntil(providerName: string, keyId: string, now = D return entry.cooldownUntil > now ? entry.cooldownUntil : null; } +/** True while the key is cooling because a refusal proved its quota or credit spent. */ +export function isKeyQuotaSpent(providerName: string, keyId: string, now = Date.now()): boolean { + return (keyCooldowns.get(cooldownKey(providerName, keyId))?.quotaSpentUntil ?? 0) > now; +} + export function sweepExpiredApiKeyCooldowns(now = Date.now()): number { let removed = 0; for (const [key, cooldown] of keyCooldowns) { diff --git a/src/providers/key-failover.ts b/src/providers/key-failover.ts index 7b57925504b..533b6f0dc6d 100644 --- a/src/providers/key-failover.ts +++ b/src/providers/key-failover.ts @@ -104,19 +104,20 @@ function replayOnlyResponse(response: Response, chunks: readonly Uint8Array[]): * before streaming the unread remainder. A rotation storm must not be gated on * reading N full error payloads. Any failure — no body, already consumed, slow, * malformed — returns undefined and leaves the `Retry-After` path in charge. + * `text` is the decoded prefix, so a caller can classify the refusal without a second read. */ export async function readQuotaResetAt( response: Response, nowOrOptions: number | QuotaResetReadOptions = {}, -): Promise<{ at: number | undefined; response: Response }> { - if (!response.body) return { at: undefined, response }; +): Promise<{ at: number | undefined; response: Response; text: string }> { + if (!response.body) return { at: undefined, response, text: "" }; const options = typeof nowOrOptions === "number" ? { now: nowOrOptions } : nowOrOptions; const now = options.now ?? Date.now(); let reader: ReadableStreamDefaultReader; try { reader = response.body.getReader(); } catch { - return { at: undefined, response }; + return { at: undefined, response, text: "" }; } const chunks: Uint8Array[] = []; let transferred = false; @@ -192,14 +193,14 @@ export async function readQuotaResetAt( }, }); transferred = true; - return { at: parseQuotaResetAt(text, now), response: rebuiltResponse(response, rest) }; + return { at: parseQuotaResetAt(text, now), response: rebuiltResponse(response, rest), text }; } catch (error) { const clientAborted = options.signal?.aborted === true; void reader.cancel(error).catch(() => {}).finally(() => { try { reader.releaseLock(); } catch { /* already released */ } }); if (clientAborted) throw options.signal!.reason ?? error; - return { at: undefined, response: replayOnlyResponse(response, chunks) }; + return { at: undefined, response: replayOnlyResponse(response, chunks), text: "" }; } finally { if (timer !== undefined) clearTimeout(timer); if (!transferred) { @@ -829,6 +830,7 @@ export function rateLimitRetryDelayMs( export function recordDistributedKeyFailure( config: OcxConfig, providerName: string, selection: ProviderApiKeySelection | undefined, status: 401 | 429 | "billing", now = Date.now(), retryAfter?: string | null, quotaResetAt?: number, + quotaExhausted = false, ): boolean { const provider = config.providers[providerName]; if (!selection?.distributed || !provider || provider.authMode === "oauth" || provider.authMode === "forward") return false; @@ -838,7 +840,7 @@ export function recordDistributedKeyFailure( const delay = status === "billing" ? ANTHROPIC_BILLING_COOLDOWN_MS : status === 401 ? MAX_COOLDOWN_MS : quotaResetAt !== undefined ? Math.max(1, quotaResetAt - now) : parseRetryAfterMs(retryAfter, now) ?? DEFAULT_COOLDOWN_MS; for (const entry of provider.apiKeyPool ?? []) if (entry.key === failed.key) { - setKeyCooldown(providerName, entry.id, now + delay); + setKeyCooldown(providerName, entry.id, now + delay, status === "billing" || quotaExhausted); } sweepExpiredOnWrite(now); return true; @@ -854,6 +856,8 @@ function rotateKeyAfterFailure( attemptedSelection?: ProviderApiKeySelection, quotaResetAt?: number, acceptsFreshProvider?: (provider: OcxProviderConfig) => boolean, + /** The refusal body proved the key's quota spent. A credit refusal (`billing`) always does. */ + quotaExhausted = false, ): OcxProviderConfig | null { const provider = config.providers[providerName]; if (!provider) return null; @@ -861,7 +865,7 @@ function rotateKeyAfterFailure( if (attemptedSelection?.distributed) { if (acceptsFreshProvider && !acceptsFreshProvider(provider)) return null; - if (!recordDistributedKeyFailure(config, providerName, attemptedSelection, failureStatus, now, retryAfterHeader, quotaResetAt)) return null; + if (!recordDistributedKeyFailure(config, providerName, attemptedSelection, failureStatus, now, retryAfterHeader, quotaResetAt, quotaExhausted)) return null; if (!(provider.apiKeyPool ?? []).some(entry => !entry.disabled && !isKeyInCooldown(providerName, entry.id, now))) return null; return allocateDistributedKey(providerName, provider, now); } @@ -936,7 +940,7 @@ function rotateKeyAfterFailure( : quotaResetAt !== undefined ? Math.max(quotaResetAt - now, 1) : parseRetryAfterMs(retryAfterHeader, now) ?? DEFAULT_COOLDOWN_MS; - setKeyCooldown(providerName, outcome.value.failedId, now + cooldownMs); + setKeyCooldown(providerName, outcome.value.failedId, now + cooldownMs, failureStatus === "billing" || quotaExhausted); sweepExpiredOnWrite(now); } if ("exhaustedCount" in outcome.value) { @@ -967,8 +971,10 @@ export function rotateKeyOn429( attemptedKey?: string, attemptedSelection?: ProviderApiKeySelection, quotaResetAt?: number, + quotaExhausted?: boolean, ): OcxProviderConfig | null { - return rotateKeyAfterFailure(config, providerName, 429, retryAfterHeader, now, attemptedKey, attemptedSelection, quotaResetAt); + return rotateKeyAfterFailure(config, providerName, 429, retryAfterHeader, now, attemptedKey, attemptedSelection, quotaResetAt, + undefined, quotaExhausted); } /** @@ -993,6 +999,8 @@ interface RotateProviderTransportOptions { retryAfter?: string | null; /** Epoch ms from `parseQuotaResetAt`, when the upstream dated the reset in its body. */ quotaResetAt?: number; + /** The 429 body proved the key's quota or credit spent, so a quota-only Combo may leave the pool. */ + quotaExhausted?: boolean; now?: number; attemptedKey?: string; attemptedSelection?: ProviderApiKeySelection; @@ -1019,6 +1027,7 @@ export function rotateProviderTransportOn429( options.attemptedKey, options.attemptedSelection ?? routedProvider._apiKeyAttempt, options.quotaResetAt, + options.quotaExhausted, ); if (!rotated) return null; return applyRotatedTransport(providerName, routedProvider, rotated, options.promptCacheKey); diff --git a/src/router.ts b/src/router.ts index 167f6528dd7..32ab546d3c1 100644 --- a/src/router.ts +++ b/src/router.ts @@ -12,6 +12,10 @@ import { type ComboPick, } from "./combos"; import type { NormalizedComboConfig } from "./combos/types"; +import { cachedProviderQuotaIsExhausted } from "./combos/resolve"; +import { getCachedProviderRoutingQuota } from "./providers/quota-routing-cache"; +import { codexQuotaScopeForModel } from "./codex/routing/health-store"; +import { codexPoolHasConfirmedUsageLimit } from "./codex/routing/selection"; import { hasOwnProvider } from "./config/provider-name"; import { anthropicInstanceRowShapeMatches } from "./providers/anthropic-instance-id"; import { isProviderApiKeyPaused } from "./providers/api-key-pause"; @@ -517,7 +521,7 @@ function routeModelInternal( } if (!bypassCombos && !preservesPhysicalComboProvider(config)) { - const combo = tryPickComboModel(config, modelId, preview); + const combo = tryPickComboModel(config, modelId, preview, (target, now) => comboDestinationQuotaExhausted(config, target, now)); if (combo) { const concrete = `${combo.target.provider}/${combo.target.model}`; // The selected target is already a concrete provider/model reference. Resolve it without @@ -755,6 +759,40 @@ export function routeConcreteModel(config: OcxConfig, modelId: string): RouteRes return routeModelInternal(config, modelId, true, undefined); } +/** + * OCX-11: where a combo target physically dispatches, after provider aliases and + * blockedModelRedirects. A target that does not resolve keeps its configured selector; its + * dispatch fails on its own. + */ +export function resolvedComboDestination(config: OcxConfig, target: { provider: string; model: string }): { provider: string; model: string } { + try { + const route = routeConcreteModel(config, `${target.provider}/${target.model}`); + return { provider: route.providerName, model: route.modelId }; + } catch { + return { provider: target.provider, model: target.model }; + } +} + +/** + * Quota-only selection reads the quota of the destination a target resolves to, after redirects: + * the cached quota of a key provider, or the confirmed usage limits of the canonical Codex pool. + */ +export function comboDestinationQuotaExhausted(config: OcxConfig, target: { provider: string; model: string }, now: number): boolean { + let route: RouteResult; + try { + route = routeConcreteModel(config, `${target.provider}/${target.model}`); + } catch { + return false; + } + if (cachedProviderQuotaIsExhausted(getCachedProviderRoutingQuota(route.providerName, route.provider, now), now, route.modelId)) { + return true; + } + return route.codexAccountMode === "pool" && !route.codexAccountId + && isCanonicalOpenAiForwardProvider(route.provider) + && codexQuotaScopeForModel(route.modelId) === "shared" + && codexPoolHasConfirmedUsageLimit(config, now); +} + function routeByKnownModelPattern(config: OcxConfig, modelId: string, redirectState: BlockedModelRedirectState): RouteResult | undefined { for (const { providerNames, prefixes } of MODEL_PROVIDER_PATTERNS) { if (prefixes.some(prefix => modelId.startsWith(prefix))) { diff --git a/src/server/management/combo-routes.ts b/src/server/management/combo-routes.ts index 539d0405525..c7a2eb88bee 100644 --- a/src/server/management/combo-routes.ts +++ b/src/server/management/combo-routes.ts @@ -238,8 +238,15 @@ export async function handleComboRoutes(ctx: ManagementContext): Promise = body.combo; + const savedFailoverOptions: Record = {}; + if (requestedCombo.strategy === undefined || requestedCombo.strategy === "failover") { + for (const key of ["quotaOnlyFallback", "preserveFallbackModel"] as const) { + if (!Object.hasOwn(requestedCombo, key) && previous?.[key] === true) savedFailoverOptions[key] = true; + } + } const effectiveCombo = { ...requestedCombo, + ...savedFailoverOptions, // Clients that do not expose this opt-in must preserve it on unrelated edits. ...(!Object.hasOwn(requestedCombo, "cooldownReprobe") && previous?.cooldownReprobe !== undefined ? { cooldownReprobe: previous.cooldownReprobe } diff --git a/src/server/messages-native.ts b/src/server/messages-native.ts index 9ce4c251fa4..4014a404a78 100644 --- a/src/server/messages-native.ts +++ b/src/server/messages-native.ts @@ -4,7 +4,7 @@ import { createMessagesSseErrorFilter } from "./messages-sse-error-filter"; import type { MessagesFailureVerdictSink } from "../claude/failure-verdict"; import { upstreamErrorIsLocal } from "./request-log-failure-detail"; import { boundedMessagesDisplayCount, ownedAnthropicErrorPayload, ownedAnthropicErrorResponse, messagesOverflowPresentation, messagesRelayedOverflowPresentation } from "../lib/messages-error-body"; -import { attachComboFailureEvidence, isProxyError, markProxyError } from "../lib/client-error-body"; +import { attachComboFailureEvidence, isProxyError, markProxyError, markProxyQuotaExhaustion } from "../lib/client-error-body"; import { captureAccountAutoPauseAttempt, wasAccountAutoPaused } from "../oauth/account-auto-pause"; import { createPhysicalSendReporter, reportDispatchSends, type RequestExecutionBudget, type SingleUseDispatchPermit } from "../lib/request-execution-budget"; import { createInferenceSendBudget, expandInferenceOAuthSendBudget } from "./inference/context"; @@ -559,7 +559,7 @@ async function runNativeMessagesAttempt(options: NativeMessagesExecution, attemp const response = markProxyError(fail(429, message, "rate_limit_error"), date === undefined ? undefined : "usage"); const advice = error.retryAfterSeconds !== null ? formatClientRetryAfter(error.retryAfterSeconds) : undefined; if (advice !== undefined) response.headers.set("retry-after", advice); - return response; + return error.usageLimit !== null && logCtx.comboQuotaOnlyFallback ? markProxyQuotaExhaustion(response) : response; } if (error instanceof OAuthAccountPausedError) return markProxyError(fail(403, publicOAuthAuthenticationErrorMessage(error), "permission_error"), publicOAuthErrorPresentation(error)); if (error instanceof OAuthLoginRequiredError) return markProxyError(fail(401, publicOAuthAuthenticationErrorMessage(error), "authentication_error"), publicOAuthErrorPresentation(error)); diff --git a/src/server/request-log-committed-terminal.ts b/src/server/request-log-committed-terminal.ts index af648878e3c..7521c7ab3f3 100644 --- a/src/server/request-log-committed-terminal.ts +++ b/src/server/request-log-committed-terminal.ts @@ -11,6 +11,7 @@ export interface CommittedComboLogFields { comboTarget?: { provider: string; model: string }; comboWriterGeneration?: number; comboTargetOutputCeiling?: number | null; + comboQuotaOnlyFallback?: boolean; /** Closed capacity/health reason recognized from a committed terminal; null when none applies. */ committedIncompleteReason?: CommittedIncompleteReason | null; } @@ -64,6 +65,7 @@ export function reportCommittedTerminalCooldown( try { committedTerminalCooldownHandler?.({ ...(logCtx.comboId !== undefined ? { comboId: logCtx.comboId } : {}), + ...(logCtx.comboQuotaOnlyFallback ? { quotaOnlyFallback: true } : {}), ...(meta?.terminalStatus !== undefined ? { terminalStatus: meta.terminalStatus } : {}), ...(logCtx.committedIncompleteReason ? { terminalReason: logCtx.committedIncompleteReason } : {}), ...(servingAttempt ? { diff --git a/src/server/responses/adapter-dispatch.ts b/src/server/responses/adapter-dispatch.ts index 781ed69b448..e4893acd25e 100644 --- a/src/server/responses/adapter-dispatch.ts +++ b/src/server/responses/adapter-dispatch.ts @@ -53,7 +53,6 @@ import { hasKeyPoolFailover, rotateProviderTransportOn401, rateLimitRetryDelayMs, - readQuotaResetAt, rotateProviderTransportOn429, } from "../../providers/key-failover"; import { @@ -108,7 +107,7 @@ import { createAnthropicThinkingRecovery } from "./anthropic-thinking-recovery"; import { shouldAttemptImageTierRetry } from "../image-retry"; import { isTransientConsoleGoUploadRejection } from "../../providers/opencode-zen-rate-limit"; import { formatAdapterUpstreamFailure } from "./adapter-failure-message"; -import { consumeComboFailure } from "./core-combo-failure"; +import { consumeComboFailure, readQuotaRefusal, recordGenericAccountRefusal } from "./core-combo-failure"; import { streamingContextOverflowResponse, jsonContextOverflowResponse, lateAttributionLimitResponse } from "./context-overflow"; import { OllamaLateAttributionBudgetError } from "../../adapters/ollama-native"; import { isFixedCodexAccount } from "./core-codex-account"; @@ -1296,14 +1295,9 @@ export async function prepareAdapterExchange( // released below; a failed or slow read just leaves the header path in charge. // Peeks a bounded prefix and hands back a Response still carrying the whole // body, so the cancel below still releases the socket. - let peeked: Awaited>; - try { - peeked = await readQuotaResetAt(upstreamResponse, { signal: options.abortSignal }); - } catch { - cleanupUpstreamAbort(); - upstream.abort(); - return clientCancelledResponse(); - } + // The same prefix tells a spent quota from a rate limit, for a quota-only Combo leaving the pool. + const peeked = await readQuotaRefusal(upstreamResponse, options.abortSignal).catch(() => undefined); + if (!peeked) { cleanupUpstreamAbort(); upstream.abort(); return clientCancelledResponse(); } if (options.abortSignal?.aborted) { cleanupUpstreamAbort(); upstream.abort(); @@ -1317,6 +1311,7 @@ export async function prepareAdapterExchange( attemptedKey: route.provider.apiKey, promptCacheKey: parsed.options.promptCacheKey, quotaResetAt, + quotaExhausted: peeked.quotaExhausted, }); if (!rotated) break; if (billingRecoveryActive && (options.abortSignal?.aborted || upstream.signal.aborted)) { @@ -1565,6 +1560,10 @@ export async function prepareAdapterExchange( && transportState.genericFailovers < transportState.genericFailoverLimit && isGenericOAuthFailoverEnabled(config, route.providerName) ) { + // Record whether this refusal proved a spent quota, for a quota-only Combo's sibling check. + const refusal = await readQuotaRefusal(upstreamResponse, options.abortSignal).catch(() => undefined); + if (!refusal) { cleanupUpstreamAbort(); upstream.abort(); return clientCancelledResponse(); } + upstreamResponse = refusal.response; // Intersection with the shared request budget. This arm re-sends through // rebuildAndRefetch, so the roster cap alone would let one request walk the roster on // an allowance the rest of the request cannot see. A refusal ends the ladder with the @@ -1587,6 +1586,8 @@ export async function prepareAdapterExchange( !adapterOwnsDispatch && genericRefetchCountsSends(), ); if (!hop.allowed) break; + recordGenericAccountRefusal(route.providerName, transportState.genericFailoverAccountId, + route.modelId, upstreamResponse.headers.get("retry-after"), refusal.quotaExhausted); const nextAccountId = rotateGenericOAuthAccountOn429( config, route.providerName, @@ -1868,7 +1869,16 @@ export async function prepareAdapterExchange( if (route.providerName === "kiro") upstreamResponse = await normalizeFinalKiroHttpError(upstreamResponse, upstream.signal); const grokOAuth = isXaiGrokOAuth(route.providerName, route.provider); + const poolUsageLimit = (!options.comboAttempt || logCtx.comboQuotaOnlyFallback) + && upstreamResponse.status === 429 && anthropicInstance && route.provider.authMode === "oauth" + && !isNonReplayableResponse(upstreamResponse) + ? anthropicRoutingFor(anthropicInstance).anthropicPoolUsageLimitAfterRefusal(Date.now(), transportState.anthropicRouteDecision, route.modelId) + : null; if (options.comboAttempt) { + if (poolUsageLimit) { + void upstreamResponse.body?.cancel().catch(() => {}); + upstreamResponse = anthropicPoolCooldownResponse(poolUsageLimit, { comboAttempt: true, logCtx }); + } // No pre-read guard: `consumeComboFailure` -> `readBoundedResponseBody` reads // `response.body` itself with the abort signal threaded through, and the combo // contract is that this body's getter is touched exactly once. A guard here would be @@ -1926,11 +1936,7 @@ export async function prepareAdapterExchange( // The last pool account just refused on spent quota and recovery found no replacement: // answer the usage limit now (#6991), so Codex stops instead of retrying into the local // refusal that every later attempt meets until the first window reopens. - const poolUsageLimit = upstreamResponse.status === 429 && anthropicInstance && route.provider.authMode === "oauth" - ? anthropicRoutingFor(anthropicInstance).anthropicPoolUsageLimitAfterRefusal(Date.now(), transportState.anthropicRouteDecision, route.modelId) - : null; - // Combo children returned above; the flag is passed anyway so this site states the same rule. - if (poolUsageLimit) return anthropicPoolCooldownResponse(poolUsageLimit, { comboAttempt: options.comboAttempt, logCtx }); + if (poolUsageLimit) return anthropicPoolCooldownResponse(poolUsageLimit, { logCtx }); // Upstreams occasionally echo request details in error bodies — scrub token-shaped // material before it reaches the client-facing error surface. const upstreamRetryAfter = upstreamResponse.headers.get("retry-after"); diff --git a/src/server/responses/codex-auth-error.ts b/src/server/responses/codex-auth-error.ts index 1f0fc920e37..fa9ed5eca8b 100644 --- a/src/server/responses/codex-auth-error.ts +++ b/src/server/responses/codex-auth-error.ts @@ -1,4 +1,4 @@ -import { markProxyError } from "../../lib/client-error-body"; +import { markProxyError, markProxyQuotaExhaustion } from "../../lib/client-error-body"; import { CodexInstallationIdUnavailableError } from "../../codex/installation-id"; import { formatErrorResponse } from "../../bridge"; import { @@ -85,11 +85,14 @@ export function mapCodexAuthContextErrorToResponse( } if (error instanceof CodexAccountCooldownError) { const response = cooldownErrorResponse(error, options.now, options.accountSelector); + if (error instanceof CodexMainAccountCreditsOffError || error instanceof CodexPoolAccountCreditsOffError) { + return markProxyQuotaExhaustion(response); + } // Exact class only (#7850): main hard-lock, credit, Reserve, recovery-withheld and future // policy subclasses keep their own retry semantics, including in combo target cooldowns. const presentation = error instanceof CodexMainAccountHardLockError ? "hard_lock" : error instanceof CodexRecoveryWithheldError ? "recovery" - : error instanceof CodexMainAccountCreditsOffError || error instanceof CodexPoolAccountCreditsOffError || error instanceof CodexReserveUnavailableError ? undefined + : error instanceof CodexReserveUnavailableError ? undefined : options.accountSelector ? "cooldown_pinned" : "cooldown"; return markProxyError(error.constructor === CodexAccountCooldownError ? markCodexAccountCooldownResponse(response) : response, presentation); } diff --git a/src/server/responses/codex-ws-exchange.ts b/src/server/responses/codex-ws-exchange.ts index 77cdccaa217..33b1f1c6bb5 100644 --- a/src/server/responses/codex-ws-exchange.ts +++ b/src/server/responses/codex-ws-exchange.ts @@ -10,6 +10,7 @@ import { CodexWsMetadata, type CodexWsQuotaObserver } from "./codex-ws-metadata" import { CODEX_RESPONSES_HTTP_URL, type PreparedCodexWsRequest } from "./codex-ws-request"; import { CodexWsCorrelation } from "./codex-ws-correlation"; import type { CodexWsSession } from "./codex-ws-session"; +import { captureSendAdmission } from "./send-admission"; import { UPGRADE_DEADLINE_MS, CODEX_WS_LIVENESS_PING_INTERVAL_MS, CODEX_WS_RESPONSE_PRELUDE_TIMEOUT_MS, CODEX_WS_COMMITTED_SILENT_INTERVALS, MAX_CODEX_WS_FRAME_BYTES, MAX_CODEX_WS_QUEUE_BYTES, markCodexWsResponse, markCodexWsPreludeProjection, normalizeResponsesWsRelayEvent, closedBeforeTerminalMessage, @@ -127,7 +128,7 @@ function refusalErrorBody(source: unknown): Record { /** The sole SSE exchange state machine for both one-shot and retained sockets. */ export function codexWsExchange(options: ExchangeOptions): Promise { - const { session, url, init, prepared, sseFallback, onQuota, beforeDispatch, bunVersion, nativeControl, beforeContinuation, + const { session, url, init, prepared, onQuota, beforeDispatch, bunVersion, nativeControl, beforeContinuation, preOutputRefusalHold } = options; const metadataContext = options.metadataContext ?? {}; const { headers } = prepared; @@ -135,6 +136,11 @@ export function codexWsExchange(options: ExchangeOptions): Promise { let incrementalPlan = options.incrementalPlan; let recoveryAdmissionPending = false; const signal = init.signal ?? undefined; + // Socket callbacks run outside the request's async context, so its send admission is bound here, + // for the frames and for the HTTP fallbacks those callbacks start. + const admission = captureSendAdmission(); + const sseFallback = ((input: Parameters[0], fallbackInit?: RequestInit) => + admission.run(() => options.sseFallback(input, fallbackInit))) as typeof globalThis.fetch; return new Promise((resolve, reject) => { const ws = session.socket; @@ -538,6 +544,7 @@ export function codexWsExchange(options: ExchangeOptions): Promise { if (terminal || signal?.aborted || session.closed || ws.readyState !== WebSocket.OPEN) { throw new Error("Native steering connection is no longer available"); } + admission.assert(); beforeDispatch?.(new Headers(headers)); if (frame.type === "response.create") { // The exact serialized successor and its body, so admission can price the @@ -574,7 +581,10 @@ export function codexWsExchange(options: ExchangeOptions): Promise { failStream(error); return; } - try { options.onPhysicalDispatch?.(frameText); } catch (error) { + try { + admission.assert(); + options.onPhysicalDispatch?.(frameText); + } catch (error) { // Admission refused before the frame left. This is a pre-open rejection, // not a transport failure and not an authorization to replay over SSE. settledPreOpen = true; @@ -714,6 +724,7 @@ export function codexWsExchange(options: ExchangeOptions): Promise { resolve(await sseFallback(url, init)); return; } + admission.assert(); beforeDispatch?.(new Headers(headers)); if (signal?.aborted) { onAbort(); return; } // The recovery is the full create, so that is the frame the replay guard records. diff --git a/src/server/responses/combo-admission-snapshot.ts b/src/server/responses/combo-admission-snapshot.ts index ea1be5a3ef2..b8b0d8b8beb 100644 --- a/src/server/responses/combo-admission-snapshot.ts +++ b/src/server/responses/combo-admission-snapshot.ts @@ -1,4 +1,38 @@ -import type { OcxConfig, OcxProviderConfig, OcxComboConfig } from "../../types"; +import type { OcxConfig, OcxProviderConfig, OcxComboConfig, OcxComboTarget } from "../../types"; +import { routeConcreteModel, type RouteResult } from "../../router"; +import { configuredComboProviderBilling } from "../../combos/billing"; +import { targetKey } from "../../combos/identifiers"; + +export function comboTargetRequiresConsent( + config: OcxConfig, target: OcxComboTarget, quotaOnly: boolean, resolved?: RouteResult, +): boolean { + if (target.metered) return true; + if (!quotaOnly) return false; + const provider = config.providers[target.provider]; + if (provider && configuredComboProviderBilling({ ...provider, name: target.provider }) === "consent") return true; + try { + const route = resolved ?? routeConcreteModel(config, `${target.provider}/${target.model}`); + return configuredComboProviderBilling({ ...route.provider, name: route.providerName }) === "consent"; + } catch { + return false; + } +} + +/** + * Whether a Combo send that waited after admission needs paid-call consent under the live config. The live + * target and Combo rule apply to the destination's live row and to the destination as prepared. The rule the + * send was admitted under stays a floor, and a Combo deleted during the wait keeps the strictest rule. + */ +export function liveComboSendRequiresConsent( + liveConfig: OcxConfig, comboId: string, target: OcxComboTarget, admittedQuotaOnly: boolean, destination: RouteResult, +): boolean { + const liveCombo = liveConfig.combos?.[comboId]; + const liveTarget = liveCombo?.targets.find(candidate => targetKey(candidate) === targetKey(target)) ?? target; + const quotaOnly = admittedQuotaOnly || liveCombo === undefined || liveCombo.quotaOnlyFallback === true; + const liveDestination = { ...destination, provider: liveConfig.providers[destination.providerName] ?? destination.provider }; + return comboTargetRequiresConsent(liveConfig, liveTarget, quotaOnly, liveDestination) + || comboTargetRequiresConsent(liveConfig, liveTarget, quotaOnly, destination); +} const providerFields = [ "adapter", "authMode", "baseUrl", "codexAccountMode", "anthropicOAuthInstance", "disabled", diff --git a/src/server/responses/combo-session-recall.ts b/src/server/responses/combo-session-recall.ts index 2f569c595bc..8fe99f53374 100644 --- a/src/server/responses/combo-session-recall.ts +++ b/src/server/responses/combo-session-recall.ts @@ -11,12 +11,17 @@ export interface ComboTurnEffort { interface ComboRecallEntry { comboId: string; target: Pick; + routeIdentity?: string; + /** The resolved model that served the turn, which a continuation's model lock keeps. */ + servingModel?: string; responseModel: string; at: number; /** UTF-8 size of `responseModel`, the only client-influenced field of unbounded length. */ bytes: number; /** Present only when a JEV decision, not ordinary Combo policy, set the completed request's effort. */ turnEffort?: ComboTurnEffort; + /** A quota-only turn whose Combo, target or provider left the config. It keeps the lane so its continuation is refused. */ + orphaned?: true; } const RECALL_CAPACITY = 256; @@ -42,6 +47,14 @@ function deleteEntry(lane: string): boolean { return true; } +/** + * Forget a lane whose target can no longer serve, unless a fresh entry still decides its continuation: a + * quota-only turn's pin or the serving model a model lock keeps. + */ +function forgetUnusableEntry(lane: string, entry: ComboRecallEntry): void { + if ((!entry.routeIdentity && !entry.servingModel) || Date.now() - entry.at >= RECALL_TTL_MS) deleteEntry(lane); +} + /** * UTF-8 size of a remembered model id, or null when it is too large to retain. * @@ -68,10 +81,14 @@ export function rememberComboForLane( responseModel: string, writerGeneration: number, turnEffort?: ComboTurnEffort, + routeIdentity?: string, + servingModel?: string, ): void { if (!lane || !comboId || !responseModel.trim()) return; - // Reject even a same-named recreated owner: its previous in-flight turn is obsolete. - if (writerGeneration < Math.max(lastReconciledGeneration, captureConfigGeneration())) return; + // Reject even a same-named recreated owner: its previous in-flight turn is obsolete. A quota-only turn is judged + // by the ownership check below and by its route identity when its continuation arrives, so a reconcile that + // only touched other Combos keeps its pin. + if (!routeIdentity && writerGeneration < Math.max(lastReconciledGeneration, captureConfigGeneration())) return; // An unretainable model id DECLINES the write; it must not clear the lane. Every other // rejection above returns the same way, and clearing here would let a late completion erase // a newer selection that this function has no ordering information to compare against. @@ -84,6 +101,8 @@ export function rememberComboForLane( at: Date.now(), bytes, ...(turnEffort ? { turnEffort: { effort: turnEffort.effort } } : {}), + ...(routeIdentity ? { routeIdentity } : {}), + ...(servingModel ? { servingModel } : {}), }; if (liveOwners && !ownsEntry(liveOwners, entry)) return; deleteEntry(lane); @@ -99,6 +118,21 @@ export function rememberComboForLane( } } +/** + * The quota-only Combo that answered the lane's last Combo turn while the lane is fresh, whether or not its + * target can still serve. Only a quota-only turn records its route identity. + */ +export function quotaOnlyComboForLane(lane: string | undefined): string | undefined { + const entry = lane ? recall.get(lane) : undefined; + return entry?.routeIdentity && Date.now() - entry.at < RECALL_TTL_MS ? entry.comboId : undefined; +} + +/** The resolved model that served the lane's last turn for `comboId` while the lane is fresh, whether or not its target can still serve. */ +export function servingModelForLane(lane: string | undefined, comboId: string): string | undefined { + const entry = lane ? recall.get(lane) : undefined; + return entry?.comboId === comboId && Date.now() - entry.at < RECALL_TTL_MS ? entry.servingModel : undefined; +} + export function recallComboForLane( config: OcxConfig, lane: string | undefined, @@ -109,11 +143,11 @@ export function recallComboForLane( if (!entry) return undefined; const combo = getCombo(config, entry.comboId); const provider = config.providers[entry.target.provider]; - if (Date.now() - entry.at >= RECALL_TTL_MS + if (entry.orphaned || Date.now() - entry.at >= RECALL_TTL_MS || !Object.hasOwn(config.providers, entry.target.provider) || !provider || provider.disabled === true || !combo?.targets.some(target => targetKey(target) === targetKey(entry.target))) { - deleteEntry(lane); + forgetUnusableEntry(lane, entry); return undefined; } return entry.responseModel === model ? entry.comboId : undefined; @@ -128,20 +162,37 @@ export function recallComboTargetForLane( config: OcxConfig, lane: string | undefined, comboId: string, -): Pick | undefined { +): (Pick & Pick) | undefined { if (!lane || !comboId) return undefined; const entry = recall.get(lane); if (!entry || entry.comboId !== comboId) return undefined; + const target = peekComboTargetForLane(config, lane, comboId); + if (!target) forgetUnusableEntry(lane, entry); + return target; +} + +/** + * `recallComboTargetForLane` without forgetting a lane whose target can no longer serve, so a + * caller that refuses the continuation finds the same Combo on the next attempt. + */ +export function peekComboTargetForLane( + config: OcxConfig, + lane: string | undefined, + comboId: string, +): (Pick & Pick) | undefined { + const entry = lane ? recall.get(lane) : undefined; + if (!entry || entry.comboId !== comboId) return undefined; const combo = getCombo(config, entry.comboId); const provider = config.providers[entry.target.provider]; - if (Date.now() - entry.at >= RECALL_TTL_MS + if (entry.orphaned || Date.now() - entry.at >= RECALL_TTL_MS || !Object.hasOwn(config.providers, entry.target.provider) || !provider || provider.disabled === true - || !combo?.targets.some(target => targetKey(target) === targetKey(entry.target))) { - deleteEntry(lane); - return undefined; - } - return { provider: entry.target.provider, model: entry.target.model }; + || !combo?.targets.some(target => targetKey(target) === targetKey(entry.target))) return undefined; + return { + ...entry.target, + ...(entry.routeIdentity ? { routeIdentity: entry.routeIdentity } : {}), + ...(entry.servingModel ? { servingModel: entry.servingModel } : {}), + }; } /** @@ -183,9 +234,12 @@ export function reconcileComboRecall(context: GenerationContext): number { }; let removed = 0; for (const [lane, entry] of recall) { - if (!ownsEntry(context, entry) || Date.now() - entry.at >= RECALL_TTL_MS) { - if (deleteEntry(lane)) removed += 1; - } + const expired = Date.now() - entry.at >= RECALL_TTL_MS; + if (!expired && ownsEntry(context, entry)) continue; + // A fresh quota-only turn keeps owning its lane once its Combo, target or provider leaves the config, so + // its tool continuation is refused instead of reaching another model. + if (!expired && entry.routeIdentity) entry.orphaned = true; + else if (deleteEntry(lane)) removed += 1; } return removed; } diff --git a/src/server/responses/combo-tool-loop-pin.ts b/src/server/responses/combo-tool-loop-pin.ts index 95c88721ff2..cd28d6cfdb7 100644 --- a/src/server/responses/combo-tool-loop-pin.ts +++ b/src/server/responses/combo-tool-loop-pin.ts @@ -17,13 +17,46 @@ * * A new user message is never pinned; re-deciding per user turn is what a combo is for. */ -import { pickComboTarget, targetKey, type ComboPick } from "../../combos"; +import { createHash } from "node:crypto"; +import { getCombo, pickComboTarget, targetKey, type ComboPick } from "../../combos"; +import { comboTargetUnavailableCause } from "../../combos/resolve"; +import { routeConcreteModel, type RouteResult } from "../../router"; import type { NormalizedComboTarget } from "../../combos/types"; import type { OcxConfig } from "../../types"; import { recallComboTargetForLane } from "./combo-session-recall"; +import { sessionLaneIdFromRequest } from "../request-log-conversation"; export const COMBO_TOOL_LOOP_PIN_REASON = "combo-tool-loop-pin"; +/** The lane a tool loop is pinned to. A quota-only Combo serving a Claude bridge pool session keys it by that session. */ +export function comboToolLoopLane(headers: Headers, quotaOnly: boolean, claudeBridgePoolSession?: string): string | undefined { + return quotaOnly && claudeBridgePoolSession ? `claude-bridge:${claudeBridgePoolSession}` : sessionLaneIdFromRequest(headers); +} + +/** Match the serving wire, destination, Codex account and account mode across a config reload without retaining its URL. */ +export function comboToolLoopRouteIdentity(route: RouteResult): string { + const { providerName, modelId, provider, codexAccountId, codexAccountMode } = route; + return createHash("sha256").update(JSON.stringify([ + providerName, modelId, provider.adapter, provider.authMode, provider.baseUrl, + provider.responsesPath, provider.chatCompletionsPath, provider.modelAdapters?.[modelId], + provider.googleMode, provider.project, provider.location, codexAccountId, codexAccountMode, + ])).digest("hex"); +} + +/** Whether `selector` still resolves to the route a pinned continuation recorded. A selector that no longer resolves does not. */ +export function pinnedRouteStillResolves(config: OcxConfig, selector: string, routeIdentity: string | undefined): boolean { + try { + return comboToolLoopRouteIdentity(routeConcreteModel(config, selector)) === routeIdentity; + } catch { + return false; + } +} + +/** Whether the live config still lists `target` in Combo `comboId`. A pinned continuation needs both to remain. */ +export function comboStillHasTarget(config: OcxConfig, comboId: string, target: Pick): boolean { + return getCombo(config, comboId)?.targets.some(candidate => targetKey(candidate) === targetKey(target)) === true; +} + function isToolOutputItem(item: unknown): boolean { if (!item || typeof item !== "object" || Array.isArray(item)) return false; const type = (item as { type?: unknown }).type; @@ -32,21 +65,24 @@ function isToolOutputItem(item: unknown): boolean { /** * Whether this request resumes an assistant turn by returning tool results: its Responses - * `input` (or Chat `messages`) ends with a tool output. + * `input` (or Chat `messages`) ends with a tool output. Developer items a client appends after the + * results do not start a new turn. */ export function isToolLoopContinuation(body: unknown): boolean { if (!body || typeof body !== "object" || Array.isArray(body)) return false; const { input, messages } = body as { input?: unknown; messages?: unknown }; - if (Array.isArray(input)) return input.length > 0 && isToolOutputItem(input[input.length - 1]); - if (Array.isArray(messages) && messages.length > 0) { - const last = messages[messages.length - 1]; + const lastTurnItem = (items: unknown[]): unknown => items.findLast(item => + !item || typeof item !== "object" || (item as { role?: unknown }).role !== "developer"); + if (Array.isArray(input)) return isToolOutputItem(lastTurnItem(input)); + if (Array.isArray(messages)) { + const last = lastTurnItem(messages); return !!last && typeof last === "object" && (last as { role?: unknown }).role === "tool"; } return false; } /** - * The pick that keeps a tool loop on its previous target, or undefined to select normally. + * The previous target, a confirmed quota stop, or undefined to select normally. * Uses a non-mutating preview so a pinned request never disturbs round-robin rotation state. */ export function toolLoopPinnedPick(args: { @@ -55,16 +91,32 @@ export function toolLoopPinnedPick(args: { lane: string | undefined; body: unknown; eligible: (target: NormalizedComboTarget) => boolean; + /** Quota-only verdict on the destination a target resolves to, after redirects. */ + quotaExhausted?: (target: NormalizedComboTarget, now: number) => boolean; now?: number; -}): ComboPick | undefined { +}): ComboPick | "quota-exhausted" | undefined { if (!isToolLoopContinuation(args.body)) return undefined; const previous = recallComboTargetForLane(args.config, args.lane, args.comboId); if (!previous) return undefined; const previousKey = targetKey(previous); + const combo = getCombo(args.config, args.comboId); + const pinnedTarget = combo?.targets.find(target => targetKey(target) === previousKey); + if (combo?.quotaOnlyFallback) { + if (!previous.routeIdentity + || !pinnedRouteStillResolves(args.config, `${previous.provider}/${previous.model}`, previous.routeIdentity)) return undefined; + } + if (combo?.quotaOnlyFallback && pinnedTarget + && comboTargetUnavailableCause(args.config, args.comboId, pinnedTarget, undefined, args.now, args.quotaExhausted) === "quota") { + return "quota-exhausted"; + } const pick = pickComboTarget(args.config, args.comboId, { + // This is a continuation of a previously selected target, outside the new-turn order. + exclude: combo?.quotaOnlyFallback ? combo.targets.map(targetKey).filter(key => key !== previousKey) : undefined, eligible: target => targetKey(target) === previousKey && args.eligible(target), + quotaExhausted: args.quotaExhausted, now: args.now, preview: true, }); - return pick ? { ...pick, attempted: [previousKey] } : undefined; + if (pick) pick.attempted = [previousKey]; + return pick ?? undefined; } diff --git a/src/server/responses/core-combo-failure.ts b/src/server/responses/core-combo-failure.ts index ec67d89adc5..e8fe1bceac9 100644 --- a/src/server/responses/core-combo-failure.ts +++ b/src/server/responses/core-combo-failure.ts @@ -1,11 +1,13 @@ import { recordUpstreamProviderErrorDetail, recordUpstreamValidationDetail, type FailureDetail } from "../request-log-failure-detail"; -import { carryProxyErrorPresentation } from "../../lib/client-error-body"; +import { carryProxyErrorPresentation, isProxyError, isProxyQuotaExhaustion } from "../../lib/client-error-body"; import { carryPolicyCandidateRefusal } from "./policy-request-scope"; import { comboFailureEvidence, carryProxyError } from "../../lib/client-error-body"; import { carryWorkflowRefusal } from "../workflow-refusal"; import { codexAccountModelRefusal, codexAccountModelRefusalHardStopCode, + coolComboTarget, + isConfirmedComboExhaustion, isMalformedResponseFormatRequest, isOpenRouterOpaque400Envelope, isUnofferedToolCallRefusal, @@ -17,7 +19,11 @@ import { import { parseRetryAfterMs } from "../../combos"; import type { ConsumedComboFailure, HandleResponsesOptions } from "./core-options"; import type { OcxConfig, OcxUsage } from "../../types"; +import type { RouteResult } from "../../router"; import { codexQuotaScopeForModel, getCodexQuotaHealthSnapshot } from "../../codex/routing"; +import { codexPoolHasConfirmedUsageLimit } from "../../codex/routing/selection"; +import { isCodexAccountGenerationLive } from "../../codex/account-store"; +import type { CodexAuthContext } from "../../codex/auth-context"; import { readBoundedResponseBody } from "../../lib/bounded-body"; import { carryAnthropicRefusalCredential } from "../../oauth/anthropic-account-refusal"; import { carryCodexAccountCooldownResponse } from "../../codex/account-cooldown-response"; @@ -46,12 +52,22 @@ import { stampMetaMusePlanRefusal } from "../../providers/meta-muse-plan-refusal import type { RequestFailureCause } from "../../usage/telemetry-contract"; import { isRewrittenUpstreamError } from "../../adapters/upstream-http-error"; import { configuredAnthropicInstance } from "../../providers/anthropic-instance"; +import { comboPickQuotaBinding, type ComboPick } from "../../combos/resolve"; import { getAccountSet } from "../../oauth/store"; import { anthropicRefusalCredentialIsCurrent } from "../../oauth/anthropic-account-refusal"; import { isAnthropicBillingFailure } from "../../providers/anthropic-billing-refusal"; import { anthropicRoutingFor, formatAnthropicProviderForLog } from "../../oauth/anthropic-routing"; import { codexAccountLogLabel, oauthAccountLogLabel } from "../../codex/account-label"; -import { isGenericFailoverProvider, rotateGenericOAuthAccountOn429 } from "../../oauth/generic-account-failover"; +import { + eligibleFailoverAccounts, hasEligibleGenericOAuthFailoverTarget, isGenericFailoverProvider, rotateGenericOAuthAccountOn429, +} from "../../oauth/generic-account-failover"; +import { classifyModelFamilyForQuota } from "../../oauth/account-quota-rank"; +import { oauthCredentialSlot } from "../../oauth/credential-siblings"; +import { antigravityAccountSupportsModel } from "../../providers/antigravity-account-roster"; +import { anthropicRatePolicyFor } from "../../oauth/anthropic-rate-limit-policy"; +import type { AnthropicInstanceId } from "../../providers/anthropic-instance-id"; +import { isKeyQuotaSpent } from "../../providers/api-key-cooldowns"; +import { readQuotaResetAt } from "../../providers/key-failover"; import { MAIN_CODEX_ACCOUNT_ID } from "../../codex/account-id"; import { providerCodexAccountMode } from "../../providers/registry"; import { baseProviderLabel } from "../../providers/label"; @@ -91,24 +107,76 @@ export function cooledPoolAccountLabel(config: OcxConfig, providerName: string, * cools it under the pool's own Retry-After policy, and spare the target only when the pool still * has an eligible sibling. The rotator only peeks round-robin here: nothing is sent to that sibling. * A lone account or an all-cooled pool returns null and cools the target. + * The refusal's quota verdict is recorded first, for a quota-only Combo's sibling check. */ export function cooledGenericOAuthAccountLabel( config: OcxConfig, providerName: string, modelId: string, label: string | undefined, retryAfter: string | undefined, + quotaExhausted: boolean, ): string | undefined { const provider = config.providers[providerName]; if (!label || !provider || !isGenericFailoverProvider(providerName, provider)) return undefined; const base = baseProviderLabel(providerName); const matches = getAccountSet(providerName)?.accounts.filter(account => oauthAccountLogLabel(account.id, base) === label) ?? []; - return matches.length === 1 - && rotateGenericOAuthAccountOn429(config, providerName, matches[0]!.id, retryAfter, Date.now(), modelId, false) + if (matches.length !== 1) return undefined; + recordGenericAccountRefusal(providerName, matches[0]!.id, modelId, retryAfter, quotaExhausted); + return rotateGenericOAuthAccountOn429(config, providerName, matches[0]!.id, retryAfter, Date.now(), modelId, false) ? label : undefined; } /** - * A 402 credit-balance refusal names one Anthropic OAuth account -- the evidence the pool already - * accepts on a 403 -- but the pool rotates only on 401/403/429, so the 402 reaches the combo with - * that account still selectable. Cool it under the pool's entitlement backoff and spare the target + * Generic OAuth accounts whose last 429 proved a spent quota. The pool records only that an account + * cooled, so a quota-only Combo reads this to tell a spent sibling from a rate-limited one. A verdict + * lasts as long as the cooldown the pool derives from the same Retry-After. A later ordinary refusal + * neither clears nor extends it, because a spent quota does not return before its own deadline. + */ +const genericQuotaVerdicts = new Map(); +const genericVerdictKey = (providerName: string, accountId: string, modelId: string | null | undefined): string => + [oauthCredentialSlot(providerName), accountId, classifyModelFamilyForQuota(providerName, modelId) ?? ""].join("\0"); + +/** Record what a generic OAuth 429 proved before the pool cools that account. */ +export function recordGenericAccountRefusal( + providerName: string, accountId: string, modelId: string | null | undefined, + retryAfter: string | null | undefined, quotaExhausted: boolean, now = Date.now(), +): void { + for (const [key, until] of genericQuotaVerdicts) if (until <= now) genericQuotaVerdicts.delete(key); + if (!quotaExhausted) return; + const key = genericVerdictKey(providerName, accountId, modelId); + // The pool's own defaults for an undated 429 (rotateGenericOAuthAccountOnRefusal). + const cooldownMs = parseRetryAfterMs(retryAfter, now, { preserveImmediate: true, preserveServerDelay: true }) + ?? (providerName === "kiro" ? 10_000 : 60_000); + genericQuotaVerdicts.set(key, Math.max(genericQuotaVerdicts.get(key) ?? 0, now + cooldownMs)); +} + +export function clearGenericAccountQuotaVerdictsForTests(): void { + genericQuotaVerdicts.clear(); +} + +/** True while a usable Anthropic account is held by a transient rate pause and by no quota or credit refusal. */ +function anthropicAccountOnlyRatePaused(instance: AnthropicInstanceId, now: number): boolean { + const routing = anthropicRoutingFor(instance); + const { anthropicRatePauseUntil } = anthropicRatePolicyFor(instance); + return (getAccountSet(instance)?.accounts ?? []).some(account => account.paused !== true && account.needsReauth !== true + && anthropicRatePauseUntil(account.id, now) !== undefined && routing.getAnthropicAccountHealthSnapshot(account.id, now) === null); +} + +/** + * True while an account other than the refused one is unavailable with no spent-quota verdict, such as + * one cooling after a rate limit. It may serve again soon, so a quota-only Combo stays on the pool. + */ +function genericSiblingMayRecover(providerName: string, refusedId: string, now: number, modelId: string): boolean { + const ready = new Set(eligibleFailoverAccounts(providerName, now, classifyModelFamilyForQuota(providerName, modelId))); + return (getAccountSet(providerName)?.accounts ?? []).some(account => account.id !== refusedId + && account.paused !== true && account.needsReauth !== true && !ready.has(account.id) + // An Antigravity sibling whose roster omits the model cannot serve it once it recovers. + && (providerName !== "google-antigravity" || antigravityAccountSupportsModel(providerName, account.id, modelId) !== false) + && (genericQuotaVerdicts.get(genericVerdictKey(providerName, account.id, modelId)) ?? 0) <= now); +} + +/** + * A credit-balance refusal (402, or 400 with the same body) names one Anthropic OAuth account -- + * the evidence the pool already accepts on a 403 -- but the pool rotates only on 401/403/429, so it + * reaches the combo with that account still selectable. Cool it under the pool's entitlement backoff and spare the target * only while a sibling is eligible; a lone account or an exhausted pool still cools the target. */ export function creditRefusedAnthropicAccountLabel( @@ -117,7 +185,7 @@ export function creditRefusedAnthropicAccountLabel( ): string | undefined { const instance = configuredAnthropicInstance(config, providerName); if (!label || !instance || config.providers[providerName]?.authMode !== "oauth" - || !isAnthropicBillingFailure(402, message, code)) return undefined; + || !isAnthropicBillingFailure(response.status, message, code)) return undefined; const routing = anthropicRoutingFor(instance); const matches = getAccountSet(instance)?.accounts.filter(account => formatAnthropicProviderForLog(instance, account.id) === label) ?? []; @@ -156,6 +224,92 @@ export function isAnthropicPoolLocalRefusal( && anthropicRoutingFor(instance).getAnthropicPoolRetryAfterSeconds(now) !== null; } +/** + * The pick's quota binding names its provider's credential together with the redirects and aliases + * that resolve its model, so it still describes a route that stayed with that provider. + */ +export function dispatchedComboQuotaBinding(pick: ComboPick, route: RouteResult): string | undefined { + return pick.target.provider === route.providerName ? comboPickQuotaBinding(pick) : undefined; +} + +export function rememberPinnedComboExhaustion(pick: ComboPick, route: RouteResult, failure: ConsumedComboFailure): void { + const quotaBinding = dispatchedComboQuotaBinding(pick, route); + if (!quotaBinding || isProxyQuotaExhaustion(failure.response)) return; + coolComboTarget(pick.comboId, pick.target, { + quotaBinding, writerGeneration: pick.writerGeneration, status: failure.response.status, + code: failure.upstreamCode, message: failure.classificationText, retryAfter: failure.retryAfter, resetAt: failure.resetAt, + }); +} + +export function confirmedComboExhaustion(failure: ConsumedComboFailure): boolean { + const { response, upstreamMessage, classificationText, upstreamCode, upstreamType } = failure; + return !isReplayRefusalResponse(response) && (isProxyQuotaExhaustion(response) || ( + !isProxyError(response) && isConfirmedComboExhaustion(response.status, upstreamMessage ?? classificationText, upstreamCode, upstreamType) + )); +} + +/** + * Whether a confirmed exhaustion lets a quota-only Combo leave this target. A pool answers for its + * own accounts, so the Combo advances only once none of them is eligible for the model. A sibling + * of a generic OAuth pool or a key in a pool must also have proved its quota spent, because one that + * was only rate-limited serves again when its window passes. + */ +export function comboAccountExhaustionCanAdvance( + config: OcxConfig, route: RouteResult, response: Response, servedAccountLabel: string | undefined, now: number, + auth: CodexAuthContext | undefined, +): boolean { + if (route.codexAccountMode === "pool" && isCanonicalOpenAiForwardProvider(route.provider)) { + if (route.codexAccountId || codexQuotaScopeForModel(route.modelId) !== "shared") return false; + const refusedId = !isProxyError(response) && auth?.kind === "pool" && !auth.fixedAccount + && isCodexAccountGenerationLive(auth.accountId, auth.generation) ? auth.accountId : undefined; + return codexPoolHasConfirmedUsageLimit(config, now, refusedId); + } + const anthropic = route.provider.authMode === "oauth" ? configuredAnthropicInstance(config, route.providerName) : undefined; + if (anthropic) { + // The pool marks its own spent verdict. A credit refusal was already recorded on its account, and + // it advances once no account is eligible or only waiting out a rate pause. + return isProxyQuotaExhaustion(response) || ((response.status === 400 || response.status === 402) + && anthropicRoutingFor(anthropic).getEligibleAnthropicAccounts(now, route.modelId).length === 0 + && !anthropicAccountOnlyRatePaused(anthropic, now)); + } + if (isGenericFailoverProvider(route.providerName, route.provider)) { + const base = baseProviderLabel(route.providerName); + const refused = getAccountSet(route.providerName)?.accounts + .find(account => oauthAccountLogLabel(account.id, base) === servedAccountLabel)?.id; + return !hasEligibleGenericOAuthFailoverTarget(route.providerName, refused ?? "", now, route.modelId) + && !genericSiblingMayRecover(route.providerName, refused ?? "", now, route.modelId); + } + // A key pool advances once every enabled key refused with a spent quota. A key that was only + // rate-limited serves again when its window passes, so its cooldown keeps the Combo here. + const keyPool = route.provider.apiKeyPool ?? []; + if (keyPool.length > 1) { + const enabledKeys = keyPool.filter(entry => !entry.disabled); + return isProxyQuotaExhaustion(response) || (enabledKeys.length > 0 + && enabledKeys.every(entry => isKeyQuotaSpent(route.providerName, entry.id, now))); + } + return true; +} + +/** + * Peek a 429's bounded body prefix for the reset it dates and whether it proves a spent quota. A + * pool records that verdict with the cooldown, so a quota-only Combo can tell a spent key or + * account from one that is only rate-limited. The returned response replays the same body. + */ +export async function readQuotaRefusal(response: Response, signal?: AbortSignal): Promise<{ + response: Response; at: number | undefined; quotaExhausted: boolean; +}> { + const peeked = await readQuotaResetAt(response, { signal }); + if (isNonReplayableResponse(response)) markResponseNonReplayable(peeked.response); + carryReplayRefusal(response, peeked.response); + carryProxyError(response, peeked.response); + const refusal = normalizeUpstreamErrorText(peeked.text, ""); + return { + response: peeked.response, + at: peeked.at, + quotaExhausted: isConfirmedComboExhaustion(response.status, refusal.message ?? refusal.safeText, refusal.code, refusal.type), + }; +} + export function sanitizedRetryAfter(value: string | null, now: number): string | undefined { const trimmed = value?.trim(); if (!trimmed || trimmed.length > 128) return undefined; diff --git a/src/server/responses/core-combo.ts b/src/server/responses/core-combo.ts index 92d1aec8d49..cc7cfae4c60 100644 --- a/src/server/responses/core-combo.ts +++ b/src/server/responses/core-combo.ts @@ -5,7 +5,7 @@ import { isPlaintextV2AgentMessagesEnabled } from "../../config/multi-agent-surf import { comboLogLabel, comboTargetLogLabel } from "../../combos/resolve"; import { clientFacingModelLabel, clientFacingModelText } from "../../lib/error-destination"; import { carryLocalFailureState, projectLocalModelRefusalLog, upstreamErrorIsLocal } from "../request-log-failure-detail"; -import { carryProxyErrorContext, hasProxyErrorMessage, isPausedTurn, markProxyError, rememberPausedTurn } from "../../lib/client-error-body"; +import { carryProxyErrorContext, hasProxyErrorMessage, isPausedTurn, isProxyQuotaExhaustion, markProxyError, rememberPausedTurn } from "../../lib/client-error-body"; import { isXaiPrivacyModeRefusal } from "../../providers/xai-privacy-mode"; import { classifyUpstreamCondition } from "../../lib/upstream-condition"; import { effectiveAzureOutputBudget } from "../../adapters/azure"; @@ -78,9 +78,14 @@ import { hasUnreadableEncryptedAgentTask } from "./encrypted-payload"; import { eagerCodexToolCatalogSurface, warnEagerCodexToolCatalog } from "./codex-tool-catalog"; import { clampComboCallerEffort, comboCapabilityGate } from "../../combos/request-capability"; import { comboAdvertisesEffortUnion } from "../../combos/capability-policy"; -import { requestStartComboConfig, snapshotComboAdmission, snapshotComboAdmissionProvider } from "./combo-admission-snapshot"; +import { + comboTargetRequiresConsent, liveComboSendRequiresConsent, requestStartComboConfig, snapshotComboAdmission, snapshotComboAdmissionProvider, +} from "./combo-admission-snapshot"; +import { runWithSendAdmission } from "./send-admission"; import { canDescribeComboImages } from "./request-sidecar-auth"; -import { captureRouteStaticPolicy, routeConcreteModel, comboRouteDecisionTrace } from "../../router"; +import { + captureRouteStaticPolicy, comboDestinationQuotaExhausted, comboRouteDecisionTrace, resolvedComboDestination, routeConcreteModel, type RouteResult, +} from "../../router"; import { memoryModelRouteReason } from "./memory-models"; import { poolAccountProviderLabel } from "../../providers/label"; import { isCanonicalOpenAiForwardProvider, OPENAI_CODEX_PROVIDER_ID } from "../../providers/openai-tiers"; @@ -96,16 +101,24 @@ import { applyDroidResponsesReasoningDefault } from "../droid-reasoning-default" import { isPlainObject } from "../../lib/plain-data"; import { clientCancelledResponse, + comboModelChangeRefused, comboUnavailable, comboUnavailableResponse, + comboMeteredConsentRefused, + toolLoopQuotaExhaustedResponse, + toolLoopTargetUnavailableResponse, targetIncompatibleResponse, unreadableEncryptedAgentTaskResponse, } from "./core-errors"; import { buildComboChildHeaders, + comboAccountExhaustionCanAdvance, + confirmedComboExhaustion, cooledGenericOAuthAccountLabel, cooledPoolAccountLabel, creditRefusedAnthropicAccountLabel, + dispatchedComboQuotaBinding, + rememberPinnedComboExhaustion, isAnthropicPoolLocalRefusal, createChildPassthroughCallbackGate, consumeComboFailure, @@ -121,8 +134,14 @@ import type { CodexAuthContext } from "../../codex/auth-context"; import type { ResponsesTerminalStatus } from "../../bridge"; import { beginRequestAttempt, sealRequestAttemptIdentity, finishRequestAttempt } from "../request-log"; import { sealedCredentialRefusals } from "../request-log-attempt-recovery"; -import { recallComboTurnEffortForLane, rememberComboForLane, type ComboTurnEffort } from "./combo-session-recall"; -import { COMBO_TOOL_LOOP_PIN_REASON, toolLoopPinnedPick } from "./combo-tool-loop-pin"; +import { + peekComboTargetForLane, recallComboTargetForLane, recallComboTurnEffortForLane, rememberComboForLane, servingModelForLane, + type ComboTurnEffort, +} from "./combo-session-recall"; +import { + COMBO_TOOL_LOOP_PIN_REASON, comboStillHasTarget, comboToolLoopLane, comboToolLoopRouteIdentity, isToolLoopContinuation, pinnedRouteStillResolves, + toolLoopPinnedPick, +} from "./combo-tool-loop-pin"; import { JEV_SESSION_PIN_ROUTE_REASON, jevSessionPinScope } from "./jev-session-pin"; import { runTurnAdapterSseResponses } from "./core-lifetime"; import { normalizePersistedJevDecision } from "../../usage/jev-stats"; @@ -157,20 +176,6 @@ import { resolveContextPrincipal } from "../auth-cors"; */ export const COMBO_TARGET_BASE_SENDS = CODEX_TEXT_GUARDED_BUDGET_POLICY.baseSendAllowance; -/** - * OCX-11: where a combo target physically dispatches, after provider aliases and - * blockedModelRedirects. A target that does not resolve keeps its configured selector; its - * dispatch fails on its own. - */ -function resolvedComboDestination(config: OcxConfig, target: { provider: string; model: string }): { provider: string; model: string } { - try { - const route = routeConcreteModel(config, `${target.provider}/${target.model}`); - return { provider: route.providerName, model: route.modelId }; - } catch { - return { provider: target.provider, model: target.model }; - } -} - /** * A combo's execution policy is DECLARED by the combo, not inherited from the single-target * profile. @@ -348,6 +353,11 @@ export async function executeComboResponses( // Every paid send also needs the key's current scope: a narrowed key never widens back. const currentAdmissionScope = () => intersectAdmissionModelScopes(admissionScope, resolveAdmissionModelScope(liveConfig, options.admission)); + // A configured key listed when the request started and removed since has no live scope left to intersect, + // so every send refuses it, as request preparation does for a bridge child. A key never listed stays unscoped. + const admittedKeyId = options.admission?.kind === "configured" ? options.admission.keyId : undefined; + const admittedKeyListed = (): boolean => admittedKeyId !== undefined && (liveConfig.apiKeys ?? []).some(key => key.id === admittedKeyId); + const keyListedAtAdmission = admittedKeyListed(); // Present only when an opted-in ingress supplied a native source; otherwise every child // takes the bridge below exactly as before. const protocolLanes = createComboProtocolLanes({ @@ -403,8 +413,9 @@ export async function executeComboResponses( observeLinkTurnExpansion(options.linkTurn, req, logCtx, body, requestedPreviousId.trim().length > 0 ? (unresolvedPrevious ? "unexpanded" : "chained") : "none"); // Live metered consent, checked before every paid send. - const maySpendOnTarget = (target: (typeof combo.targets)[number]): boolean => - !target.metered || admissionMayUseMeteredComboTargets(liveConfig, options.admission, liveConfig.combos?.[comboId]); + const maySpendOnTarget = (target: (typeof combo.targets)[number], route?: ReturnType): boolean => + !comboTargetRequiresConsent(config, target, combo.quotaOnlyFallback === true, route) + || admissionMayUseMeteredComboTargets(liveConfig, options.admission, liveConfig.combos?.[comboId]); const mayUseTarget = (target: (typeof combo.targets)[number]): boolean => maySpendOnTarget(target) && (combo.strategy !== "jev" || target.provider !== JEV_PROVIDER_ID); // The combo ladder owns the whole logical request, so the catalog diagnostic is counted here for @@ -662,6 +673,10 @@ export async function executeComboResponses( return true; }; const initialNow = Date.now(); + const toolLoopLane = comboToolLoopLane(req.headers, combo.quotaOnlyFallback === true, options.claudeBridgePoolSession); + const quotaExhausted = combo.quotaOnlyFallback + ? (target: (typeof combo.targets)[number], now: number) => comboDestinationQuotaExhausted(config, target, now) : undefined; + let blockedByConsent = false; const pickWithWait = (pickOptions: { exclude?: Iterable; eligible?: (target: NonNullable["targets"][number]) => boolean; @@ -669,30 +684,57 @@ export async function executeComboResponses( /** This request's own cooldown-reprobe reservation, carried through its failover hops. */ cooldownReprobeTargets?: Iterable; now?: number; - }) => pickComboTargetWithWait(config, comboId, { - ...pickOptions, - // Every pick, including the recovery picks that skip `targetEligible`, keeps metered - // targets away from callers that may not spend on them. - eligible: target => maySpendOnTarget(target) && (pickOptions.eligible?.(target) ?? true), - waitForCooldownMs: combo.waitForCooldownMs, - abortSignal: options.abortSignal, - }); + }) => { + blockedByConsent = false; + return pickComboTargetWithWait(config, comboId, { + ...pickOptions, + quotaExhausted, + eligible: target => { + const allowed = maySpendOnTarget(target); + if (!allowed && combo.quotaOnlyFallback) blockedByConsent = true; + return allowed && (pickOptions.eligible?.(target) ?? true); + }, + waitForCooldownMs: combo.waitForCooldownMs, + abortSignal: options.abortSignal, + }); + }; // An in-flight tool loop stays on the target that issued its calls while that target is still // selectable (#7298). Override routes never record a lane target, so they never pin either. + // The model that served the lane's last turn is read first, since an unusable pin can forget its lane. + const overrideRoute = Boolean(options.compactionRoutingOverride || options.mainHardLockFallbackOverride); + const recordedServingModel = overrideRoute || !isToolLoopContinuation(body) ? undefined : servingModelForLane(toolLoopLane, comboId); + // A quota-only pin that only lacks paid-call consent is refused for consent, as a new turn is. + let pinBlockedByConsent = false; const toolLoopPin = options.compactionRoutingOverride || options.mainHardLockFallbackOverride ? undefined : toolLoopPinnedPick({ config, comboId, - lane: sessionLaneIdFromRequest(req.headers), + lane: toolLoopLane, body, - eligible: target => maySpendOnTarget(target) && targetEligible(target), + eligible: target => { + const allowed = maySpendOnTarget(target); + if (!allowed && combo.quotaOnlyFallback) pinBlockedByConsent = true; + return allowed && targetEligible(target); + }, + quotaExhausted, now: initialNow, }); + if (toolLoopPin === "quota-exhausted") { + return options.abortSignal?.aborted ? clientCancelledResponse() : toolLoopQuotaExhaustedResponse(); + } + if (!toolLoopPin && combo.quotaOnlyFallback && isToolLoopContinuation(body)) { + if (options.abortSignal?.aborted) return clientCancelledResponse(); + return pinBlockedByConsent ? comboMeteredConsentRefused() : toolLoopTargetUnavailableResponse(); + } + // The route identity the lane recorded for a quota-only pin, checked again when its child sends. + const pinnedRouteIdentity = toolLoopPin && combo.quotaOnlyFallback + ? recallComboTargetForLane(config, toolLoopLane, comboId)?.routeIdentity : undefined; let pick = toolLoopPin ?? await pickWithWait({ eligible: targetEligible, now: initialNow, }); + if (!pick && blockedByConsent && !options.abortSignal?.aborted) return comboMeteredConsentRefused(); // Opt-in JEV session pin (#7525); override routes neither read nor write it, like the lane recall. const jevPin = options.compactionRoutingOverride || options.mainHardLockFallbackOverride ? undefined @@ -749,25 +791,39 @@ export async function executeComboResponses( } return options.abortSignal?.aborted ? clientCancelledResponse() - : comboUnavailable(comboId, undefined, comboExclusion(config, comboId, targetEligible)); + : comboUnavailable(comboId, undefined, comboExclusion(config, comboId, targetEligible, initialNow, quotaExhausted)); } // OCX-11: an ordered failover combo that starts on a later target than its first one, for any // reason (cooling down, provider disabled, cached quota spent, ineligible for this request), // makes a proactive hop, so the fallback policy decides before anything is sent. Both ends are // the resolved destinations, after provider aliases and blockedModelRedirects. const primaryTarget = combo.targets[0]; + // A continuation keeps the model that issued its tool calls, as its lane recorded it when that turn completed, + // even when the target can no longer be selected or its selector now resolves elsewhere. Override routes never + // record a lane target. + const servingRecord = overrideRoute || !isToolLoopContinuation(body) ? undefined : peekComboTargetForLane(config, toolLoopLane, comboId); + const modelLockTarget = servingRecord ?? primaryTarget; + const preservedModel = combo.preserveFallbackModel && modelLockTarget + ? recordedServingModel ?? resolvedComboDestination(config, modelLockTarget).model : undefined; // An allowed hop is recorded only once its dispatch is admitted below. let pendingHopCommit: (() => void) | undefined; if (!toolLoopPin && (combo.strategy ?? "failover") === "failover" && primaryTarget && targetKey(primaryTarget) !== targetKey(pick.target)) { const primaryCooling = isComboTargetInCooldown(comboId, primaryTarget, initialNow); + const from = resolvedComboDestination(config, primaryTarget); + const to = resolvedComboDestination(config, pick.target); + // A continuation's lock follows the model of the target its lane remembers, not the first target's. + if (preservedModel !== undefined && to.model !== preservedModel) { + return comboModelChangeRefused(); + } const proactive = guardFallbackHop(config, { site: "combo", route: `combo/${comboId}`, aliases: [requestedModel], - from: resolvedComboDestination(config, primaryTarget), - to: resolvedComboDestination(config, pick.target), - trigger: primaryCooling ? "cooldown" : comboTargetSkipTrigger(config, primaryTarget, initialNow), + from, + to, + trigger: combo.quotaOnlyFallback ? "quota_exhausted" + : primaryCooling ? "cooldown" : comboTargetSkipTrigger(config, primaryTarget, initialNow), admission: options.admission, retryAfter: primaryCooling ? comboCooldownRetryAfterSeconds(comboId, initialNow) ?? null : null, now: initialNow, @@ -1022,6 +1078,7 @@ export async function executeComboResponses( if (childLog) adoptFailedChildLog(childLog); return response; }; + if (combo.quotaOnlyFallback && lastFailure) return finalize(lastFailure); if (contextFailure) { return finalize(contextFailure.response, contextFailure.childLog); } @@ -1082,9 +1139,10 @@ export async function executeComboResponses( // fails either is skipped and an eligible sibling may still run. const dispatchScope = currentAdmissionScope(); const scopeAllowed = routeAllowedByScope(dispatchScope, targetRoute); - if (!scopeAllowed || !maySpendOnTarget(pick.target)) { + if (!scopeAllowed || !maySpendOnTarget(pick.target, targetRoute)) { + if (scopeAllowed && combo.quotaOnlyFallback) return comboMeteredConsentRefused(); const skipped: ComboPick = pick; - pick = await pickWithWait({ + pick = combo.quotaOnlyFallback ? null : await pickWithWait({ exclude: skipped.attempted, eligible: targetEligible, allowCooldownReprobe: false, @@ -1103,6 +1161,10 @@ export async function executeComboResponses( toolLoopTurnEffort = undefined; continue; } + if (preservedModel !== undefined && targetRoute.modelId !== preservedModel) { + if (lastFailedChildLog) adoptFailedChildLog(lastFailedChildLog); + return comboModelChangeRefused(); + } // Selection-free hard-lock preflight grants no hop. Enforce this actual first destination // against the locked source, after aliases and redirects resolve. if (firstComboTarget && options.mainHardLockFallbackOverride) { @@ -1128,7 +1190,7 @@ export async function executeComboResponses( aliases: [requestedModel], from: lastFailedTarget, to: { provider: targetRoute.providerName, model: targetRoute.modelId }, - trigger: fallbackTriggerForStatus(lastFailure.status), + trigger: combo.quotaOnlyFallback ? "quota_exhausted" : fallbackTriggerForStatus(lastFailure.status), admission: options.admission, failureStatus: lastFailure.status, retryAfter: lastFailedRetryAfter ?? null, @@ -1194,6 +1256,7 @@ export async function executeComboResponses( comboTarget: pick.target, comboWriterGeneration: pick.writerGeneration, comboTargetOutputCeiling: targetOutputCeiling, + comboQuotaOnlyFallback: combo.quotaOnlyFallback, ...(logCtx.conversationId ? { conversationId: logCtx.conversationId, conversationIdIsHermesFallback: logCtx.conversationIdIsHermesFallback } : {}), ...(logCtx.affinityLane ? { affinityLane: logCtx.affinityLane } : {}), ...(logCtx.surface ? { surface: logCtx.surface } : {}), @@ -1315,6 +1378,14 @@ export async function executeComboResponses( let hostedWebSearchStream = false; let consumedChildFailure: ConsumedComboFailure | undefined; let preflightModelRefusal: CodexAccountModelRefusal | undefined; + // Filled by a bridge child with the route it settled on. A native child sends to the planned route. + const childRoute: { route?: RouteResult; identity?: string } = {}; + // The transport sends to the live row of its destination's provider, so a child that settled on the planned + // provider, model and Codex account sends where this attempt planned. Another destination means a redirect + // or an account binding changed while the child prepared. + const childDestinationMoved = (): boolean => childRoute.route !== undefined + && (childRoute.route.providerName !== targetRoute.providerName || childRoute.route.modelId !== targetRoute.modelId + || childRoute.route.codexAccountId !== targetRoute.codexAccountId); const callbackGate = createChildPassthroughCallbackGate({ ...options, onResponseComplete: model => { @@ -1327,9 +1398,13 @@ export async function executeComboResponses( && Object.hasOwn(config.providers, completedTarget.provider) && provider && provider.disabled !== true && currentCombo?.targets.some(target => targetKey(target) === targetKey(completedTarget))) { + const childMoved = childDestinationMoved(); + const servedRouteIdentity = childMoved ? childRoute.identity : comboToolLoopRouteIdentity(targetRoute); rememberComboForLane( - sessionLaneIdFromRequest(req.headers), comboId, completedTarget, model, writerGeneration, + toolLoopLane, comboId, completedTarget, model, writerGeneration, jevEffortApplies ? turnEffort : undefined, + combo.quotaOnlyFallback ? servedRouteIdentity : undefined, + childMoved ? childRoute.route?.modelId : targetRoute.modelId, ); // A failed effort decision only refreshes the live pin, which another turn may have updated. jevPin?.complete(targetKey(completedTarget), failedPinEffortDecision ? undefined : initialJevDecision, writerGeneration); @@ -1360,6 +1435,7 @@ export async function executeComboResponses( }, }); let response: Response; + let sendRefused = false; try { const currentTargetProvider = pick.target.provider; const remainingTargets = combo.strategy === "jev" @@ -1372,7 +1448,36 @@ export async function executeComboResponses( && !isComboTargetInCooldown(comboId, target), ); const nativeChild = protocolLanes?.nativeChild(pick.target, targetRoute, targetSendBudget, turnEffort, jevEffortApplies); - response = nativeChild ? await dispatchNativeComboChild({ + // The child still waits on preparation and provider pacing, so its physical send checks the + // key's live scope and paid consent again. The live Combo rule, target and destination row count as + // well as the admitted ones, so a target marked paid, a quota-only rule turned on or a destination that + // became a paid API during the wait needs consent. + const admittedTarget = pick.target; + const pinnedSend = pinnedRouteIdentity !== undefined && pick === toolLoopPin; + // A pinned continuation must reach the target that issued its calls: the route this attempt planned and the + // selector's live resolution must still be the recorded one, and the bridge child must not have moved. + const pinnedRouteChanged = (): boolean => comboToolLoopRouteIdentity(targetRoute) !== pinnedRouteIdentity + || childDestinationMoved() + || !comboStillHasTarget(liveConfig, comboId, admittedTarget) + || !pinnedRouteStillResolves(liveConfig, targetKey(admittedTarget), pinnedRouteIdentity); + const sendRefusal = (): Response | undefined => { + if ((keyListedAtAdmission && !admittedKeyListed()) || !routeAllowedByScope(currentAdmissionScope(), targetRoute)) { + return admissionModelDeniedResponse(projectAdmissionModelDeniedLog(new AdmissionModelDeniedError(clientModelLabel, targetRoute), logCtx)); + } + if (pinnedSend && pinnedRouteChanged()) return toolLoopTargetUnavailableResponse(); + // The model lock also covers the model the bridge child settled on. + if (preservedModel !== undefined && childRoute.route !== undefined && childRoute.route.modelId !== preservedModel) { + return comboModelChangeRefused(); + } + // The bridge child resolves its own route, so the destination it settled on needs consent as well. + const quotaOnly = combo.quotaOnlyFallback === true; + const requiresConsent = comboTargetRequiresConsent(config, admittedTarget, quotaOnly, targetRoute) + || liveComboSendRequiresConsent(liveConfig, comboId, admittedTarget, quotaOnly, targetRoute) + || (childRoute.route !== undefined && liveComboSendRequiresConsent(liveConfig, comboId, admittedTarget, quotaOnly, childRoute.route)); + return requiresConsent && !admissionMayUseMeteredComboTargets(liveConfig, options.admission, liveConfig.combos?.[comboId]) + ? comboMeteredConsentRefused() : undefined; + }; + const admitted = await runWithSendAdmission(sendRefusal, async () => nativeChild ? await dispatchNativeComboChild({ source: options.protocolSource!, plan: nativeChild, comboDispatchPermit: hopDecision?.allowed ? hopDecision.permit : undefined, @@ -1404,9 +1509,10 @@ export async function executeComboResponses( // parent arrived with. sendBudget: targetSendBudget, comboAttempt: true, + comboChildRoute: childRoute, comboVisionSidecar, ...(omittingImages ? { comboOmitImages: true } - : capability.requiresVisionPlan(pick.target) ? { comboRequiresVisionPlan: true } : {}), + : capability.requiresVisionPlan(admittedTarget) ? { comboRequiresVisionPlan: true } : {}), ...(capability.unservable === "context" ? { comboContextDegraded: true } : {}), comboInitialSend: initialSend, comboDispatchPermit: hopDecision?.allowed ? hopDecision.permit : undefined, @@ -1435,7 +1541,9 @@ export async function executeComboResponses( onNativePassthroughTerminal: callbackGate.onTerminal, onNativePassthroughCancel: callbackGate.onCancel, onResponseComplete: callbackGate.onResponseComplete, - }); + })); + sendRefused = admitted.refused; + response = admitted.response; // Both lanes applied the initial choice before provider pins/caps; retain those transitions. restoreOriginalRequestedEffort(childLog, jevEffortApplies ? turnEffort?.effort : undefined); } catch (error) { @@ -1455,6 +1563,12 @@ export async function executeComboResponses( return clientCancelledResponse(); } + if (sendRefused) { + callbackGate.discard(); + finishRequestAttempt(attempt, response.status, Date.now() - segmentStartedAt(), childLog.usage); + return response; + } + // A native Chat child reports a pre-stream failure by status before any byte, so its body // is never peeked; a non-OK one takes the ordinary failure path below. if (response.ok && !runTurnAdapterSseResponses.has(response) && clientWireOf(response) === undefined) { @@ -1605,7 +1719,8 @@ export async function executeComboResponses( } lastFailedChildLog = childLog; // The failed child's resolved destination, so the next hop compares physical targets. - lastFailedTarget = { provider: targetRoute.providerName, model: targetRoute.modelId }; + const failedRoute = childRoute.route ?? targetRoute; + lastFailedTarget = { provider: failedRoute.providerName, model: failedRoute.modelId }; lastFailedRetryAfter = failure.retryAfter; // A replacement that answers 200 is unmarked, and its zero-output failure only exists once // preflight has rebuilt the stream as a fresh Response. A spent grant never hops: a status the @@ -1620,7 +1735,9 @@ export async function executeComboResponses( } // A non-replayable failure can come from a committed provider terminal or a send whose // outcome is ambiguous. Neither permits another target, regardless of the HTTP status. - const failureDecision = failure.nonReplayable || spentReplacement + const locallyConfirmedExhaustion = isProxyQuotaExhaustion(failure.response); + const confirmedExhaustion = combo.quotaOnlyFallback && confirmedComboExhaustion(failure); + const failureDecision = failure.nonReplayable || spentReplacement || (combo.quotaOnlyFallback && (!confirmedExhaustion || toolLoopPin)) ? "stop" : localDeadline || isPolicyCandidateRefusal(failure.response) ? "hop" : comboFailureDecision(failure.response.status, failure.classificationText, { @@ -1636,6 +1753,7 @@ export async function executeComboResponses( // The adapter the failed leg actually resolved: a configured `kiro` provider can route a // model through another wire via `modelAdapters`, and an unresolved leg grants no hop. failedAdapter: childLog.providerAdapter, + confirmedQuotaExhaustion: confirmedExhaustion, }); const wantsStream = (rawBody as { stream?: unknown } | null)?.stream === true; // Local byte admission has its own diagnostic; do not relabel it as an upstream refusal. @@ -1676,6 +1794,9 @@ export async function executeComboResponses( return lastFailure; } if (failureDecision === "stop") { + if (toolLoopPin && confirmedExhaustion && !failure.nonReplayable && !spentReplacement) { + rememberPinnedComboExhaustion(pick, targetRoute, failure); + } adoptFailedChildLog(childLog); if (classifyOverflow) { return wantsStream @@ -1724,15 +1845,22 @@ export async function executeComboResponses( // account label, which is stamped for pool and main-pool contexts alone (#8880). const poolAccountLabel = poolAccountProviderLabel(childLog.provider, pick.target.provider) ?? (childLog.accountLogLabel === "main" ? `${pick.target.provider}-main` : undefined); - const failedAccount = failure.response.status === 402 + // On 400 and 402 only a credit-balance refusal names an account, and the helper checks the body. + const failedAccount = failure.response.status === 400 || failure.response.status === 402 ? creditRefusedAnthropicAccountLabel( config, pick.target.provider, pick.target.model, poolAccountLabel, failure.classificationText, failure.upstreamCode, failure.response, ) : cooledPoolAccountLabel(config, pick.target.provider, pick.target.model, poolAccountLabel) ?? (failure.response.status === 429 && failureCooldownScope === "target" - ? cooledGenericOAuthAccountLabel(config, pick.target.provider, pick.target.model, childLog.accountLogLabel, failure.retryAfter) + ? cooledGenericOAuthAccountLabel(config, pick.target.provider, pick.target.model, childLog.accountLogLabel, failure.retryAfter, + confirmedComboExhaustion(failure)) : undefined); + if (combo.quotaOnlyFallback + && !comboAccountExhaustionCanAdvance(config, childRoute.route ?? targetRoute, failure.response, childLog.accountLogLabel, failureNow, resolvedAuth)) { + adoptFailedChildLog(childLog); + return lastFailure; + } // The target still cools on the pool's own refusal (the anti-hammer guard), but for the local // fallback rather than the pool's restated per-account Retry-After. const poolLocalRefusal = isAnthropicPoolLocalRefusal( @@ -1740,15 +1868,20 @@ export async function executeComboResponses( ); const codexLocalRefusal = isCodexAccountCooldownResponse(failure.response); const nextPick = advanceComboAfterFailure(config, pick, { + quotaExhausted, retryAfter: poolLocalRefusal || codexLocalRefusal ? undefined : failure.retryAfter, resetAt: codexLocalRefusal ? undefined : failure.resetAt, cooldownMs: combo.cooldownMs, now: failureNow, - recordFailure: !localDeadline, cooldownScope: failureCooldownScope, + recordFailure: !localDeadline && !(combo.quotaOnlyFallback && locallyConfirmedExhaustion), + cooldownScope: failureCooldownScope, eligible: targetEligible, status: failure.response.status, code: failure.upstreamCode, message: failure.classificationText, + // A child that settled on another destination got the refusal there, so the planned target keeps no cooldown. + quotaBinding: confirmedExhaustion && !poolLocalRefusal && !codexLocalRefusal && !childDestinationMoved() + ? dispatchedComboQuotaBinding(pick, targetRoute) : undefined, failedAccount, onCooldownRecorded: target => { failedTargetCooldownRecorded ||= targetKey(target) === failedTargetKey; @@ -1802,6 +1935,7 @@ export async function executeComboResponses( } if (!pick) { if (options.abortSignal?.aborted) return clientCancelledResponse(); + if (blockedByConsent) { adoptFailedChildLog(childLog); return comboMeteredConsentRefused(); } if (onlyReplayIncompatibleTargetsRemain(attemptedTargets)) { if (contextFailure || xaiPrivacyFailure) return exhaustedFailure(); adoptFailedChildLog(childLog); diff --git a/src/server/responses/core-errors.ts b/src/server/responses/core-errors.ts index 9580b873dcf..d82e3f59fda 100644 --- a/src/server/responses/core-errors.ts +++ b/src/server/responses/core-errors.ts @@ -1,5 +1,5 @@ import type { ComboExclusion, ComboUnavailableDiagnostics } from "../../combos/resolve"; -import { markProxyError } from "../../lib/client-error-body"; +import { markProxyError, markProxyQuotaExhaustion } from "../../lib/client-error-body"; import { appendClientRetryIn, formatClientRetryAfter } from "../../lib/client-retry-after"; import { readBoundedResponseBody } from "../../lib/bounded-body"; import { redactSecretString } from "../../lib/redact"; @@ -124,6 +124,87 @@ export function comboUnavailableResponse( } +export function comboMeteredConsentRefused(): Response { + return markProxyError(formatErrorResponse(403, "permission_error", + "This Combo stopped at a paid API target. The current caller has not authorized paid Combo calls.", + { code: "combo_metered_consent_required", classified: true })); +} + +export function toolLoopQuotaExhaustedResponse(): Response { + return markProxyError(formatErrorResponse(429, "rate_limit_error", + "This Combo's tool turn is waiting for its serving target's quota to recover.", + { code: "combo_tool_target_quota_exhausted", classified: true })); +} + +export function toolLoopTargetUnavailableResponse(): Response { + return markProxyError(Response.json({ error: { + type: "invalid_request_error", + code: "combo_tool_target_unavailable", + message: "This Combo cannot identify or use the target that issued the tool call. Restart the turn to select a new target.", + } }, { status: 409 })); +} + +/** A Combo refusal raised while a route resolves. Route resolvers rethrow it, and the request answers with its response. */ +export abstract class ComboRouteRefusal extends Error { + abstract response(): Response; +} + +/** A Combo with the model lock on would serve the request with a different resolved model. */ +export class ComboModelChangeRefusedError extends ComboRouteRefusal { + constructor() { + super("This Combo keeps the original model. Its next target resolves to a different model."); + this.name = "ComboModelChangeRefusedError"; + } + + response(): Response { + return comboModelChangeRefused(); + } +} + +/** A quota-only Combo stopped at a target that needs paid-call consent the caller does not have. */ +export class ComboMeteredConsentRequiredError extends ComboRouteRefusal { + constructor() { + super("This Combo stopped at a paid API target. The current caller has not authorized paid Combo calls."); + this.name = "ComboMeteredConsentRequiredError"; + } + + response(): Response { + return comboMeteredConsentRefused(); + } +} + +/** A quota-only tool continuation cannot establish or use the target that issued its calls. */ +export class ComboToolTargetUnavailableError extends ComboRouteRefusal { + constructor() { + super("This Combo cannot identify or use the target that issued the tool call."); + this.name = "ComboToolTargetUnavailableError"; + } + + response(): Response { + return toolLoopTargetUnavailableResponse(); + } +} + +/** A quota-only tool continuation's serving target has spent its quota. */ +export class ComboToolTargetQuotaExhaustedError extends ComboRouteRefusal { + constructor() { + super("This Combo's tool turn is waiting for its serving target's quota to recover."); + this.name = "ComboToolTargetQuotaExhaustedError"; + } + + response(): Response { + return toolLoopQuotaExhaustedResponse(); + } +} + +export function comboModelChangeRefused(): Response { + return markProxyError(Response.json({ error: { + type: "invalid_request_error", + code: "combo_model_change_refused", + message: new ComboModelChangeRefusedError().message, + } }, { status: 409 })); +} + export function comboUnavailable(comboId: string, now = Date.now(), exclusion?: ComboExclusion): Response { return comboUnavailableResponse(new NoAvailableComboTargetsError(comboId, exclusion).message, { retryAfter: comboCooldownRetryAfterSeconds(comboId, now), @@ -167,8 +248,9 @@ export function anthropicPoolCooldownResponse( if (options.logCtx) options.logCtx.errorCode = "usage_limit_reached"; return markProxyError(formatUsageLimitReachedResponse(refusal.message, refusal.usageLimit.resetsAt, refusal.retryAfterSeconds), refusal.usageLimit.resetsAt === null ? undefined : "usage"); } - return markProxyError(formatErrorResponse(429, "rate_limit_error", refusal.retryableMessage, - refusal.retryAfterSeconds === null ? undefined : { retryAfter: String(refusal.retryAfterSeconds) })); + const response = formatErrorResponse(429, "rate_limit_error", refusal.retryableMessage, + refusal.retryAfterSeconds === null ? undefined : { retryAfter: String(refusal.retryAfterSeconds) }); + return refusal.usageLimit === null ? markProxyError(response) : markProxyQuotaExhaustion(response); } diff --git a/src/server/responses/core-options.ts b/src/server/responses/core-options.ts index b6b2ead7754..443e1e0eb87 100644 --- a/src/server/responses/core-options.ts +++ b/src/server/responses/core-options.ts @@ -280,6 +280,11 @@ export interface HandleResponsesOptions { callerDirectAuth?: CallerDirectAuth | null; /** Internal recursion guard; callers outside this module must not set it. */ comboAttempt?: boolean; + /** + * Filled by a Combo bridge child with the route it settled on and that route's identity, so the Combo loop + * checks paid consent and a pinned continuation's route against the destination the child sends to. + */ + comboChildRoute?: { route?: RouteResult; identity?: string }; /** `union` combo with no member whose window fits: the child keeps the loose direct admission. */ comboContextDegraded?: boolean; /** A union combo admitted this image-bearing child through a dispatchable vision plan. */ diff --git a/src/server/responses/core.ts b/src/server/responses/core.ts index fc0e93f3f60..c8532585257 100644 --- a/src/server/responses/core.ts +++ b/src/server/responses/core.ts @@ -23,6 +23,7 @@ import { captureAdmissionPolicy } from "../capture-admission-policy"; import { captureHostedAdvisorSpendScope } from "./hosted-advisor-spend"; import { isPlaintextV2AgentMessagesEnabled } from "../../config/multi-agent-surface"; import { isUnattendedAgyAcpHttpTurn } from "../../adapters/agy-acp/policy"; +import { withSendAdmissionScope } from "./send-admission"; /** * Route one `/v1/responses` request through the adapter pipeline: recovery loop, passthrough * wire, image/web-search bridges, and the terminal-guard continuation. @@ -63,7 +64,8 @@ export async function handleResponses( hostedAdvisorSpendScope, // Once at ingress, spend observer included: a combo child inherits the parent's holder. sendBudget: options.sendBudget ?? createInferenceSendBudget(req, logCtx, hostedAdvisorSpendScope?.ceilings), - }, (req, config, logCtx, options) => handleResponsesInner(req, config, logCtx, options, requestDispatchers)); + }, (req, config, logCtx, options) => withSendAdmissionScope( + () => handleResponsesInner(req, config, logCtx, options, requestDispatchers))); const finalResponse = ownsBudget ? finalizeOwnedTranslatorBudget(response, translatorBudget, abortSignal) : response; if (!accountLoad.lease) { release(); return finalResponse; } return finalizeAccountLease(finalResponse, release); diff --git a/src/server/responses/fetch-helpers.ts b/src/server/responses/fetch-helpers.ts index 6750fe5b767..8a8fc4160f7 100644 --- a/src/server/responses/fetch-helpers.ts +++ b/src/server/responses/fetch-helpers.ts @@ -40,6 +40,7 @@ import { outboundCredentials } from "../../lib/outbound-credential-registry"; import { compressUpstreamRequestBody, isCanonicalCodexResponsesUrl } from "./request-compression"; import { redeemOutboundTurnState, TURN_STATE_BINDING_INIT, turnStateBinding } from "../turn-state-handles"; import { EXECUTOR_PHYSICAL_SEND_RECEIPT, inheritAdapterSupportExecutor, markPhysicalSendReceiptExecutor, registerAdapterSupportExecutor } from "../../lib/executor-physical-send-receipt"; +import { assertSendAdmission } from "./send-admission"; export { withUpstreamHttpVersion }; @@ -256,6 +257,7 @@ export function sendWithConnectionPolicy( ...(decide || redirectedToLoopback ? { [EGRESS_DECIDED]: true } : {}), ...{ [UPSTREAM_REWRITTEN]: true }, }; + assertSendAdmission(); (init as Record void) | undefined> | undefined)?.[PHYSICAL_SEND_GUARD]?.(target, headers); // Final headers, after plugin rewrites: an upstream can only echo what it received here, so the // request log refuses any diagnostic that repeats one of these values (see request-log-terminal-status). diff --git a/src/server/responses/request-prepare.ts b/src/server/responses/request-prepare.ts index 0b4303a1909..abcafd661cd 100644 --- a/src/server/responses/request-prepare.ts +++ b/src/server/responses/request-prepare.ts @@ -24,11 +24,19 @@ import { admitParsedJsonRequestBody, readJsonRequestBody, resolveInboundBodyLimi import { clientCancelledResponse, decodeRequestErrorResponse, + ComboMeteredConsentRequiredError, + ComboModelChangeRefusedError, + ComboRouteRefusal, + ComboToolTargetQuotaExhaustedError, + ComboToolTargetUnavailableError, comboUnavailable, unreadableEncryptedAgentTaskResponse, + comboMeteredConsentRefused, } from "./core-errors"; +import { advisorPlanRootConfig } from "./advisor-plan-slot"; +import { requireSendAdmission } from "./send-admission"; import { parseSyntheticRowId } from "../fast-row"; -import { resolveComboId, comboIdFromRawBody, comboExclusion, NoAvailableComboTargetsError, pickComboTarget } from "../../combos"; +import { resolveComboId, comboIdFromRawBody, comboExclusion, getCombo, NoAvailableComboTargetsError, pickComboTarget, targetKey } from "../../combos"; import { INTERCEPT_TARGET_UNAVAILABLE_CODE, interceptTargetUnavailableResponse, resolveChosenTarget, resolveShadowCallTarget } from "./shadow-target-availability"; import { MEMORY_MODEL_TARGET_UNAVAILABLE_CODE, @@ -37,7 +45,11 @@ import { memoryModelRouteReason, memoryModelTargetUnavailableResponse, } from "./memory-models"; -import { recallComboForLane } from "./combo-session-recall"; +import { peekComboTargetForLane, quotaOnlyComboForLane, recallComboForLane, rememberComboForLane } from "./combo-session-recall"; +import { + COMBO_TOOL_LOOP_PIN_REASON, comboStillHasTarget, comboToolLoopLane, comboToolLoopRouteIdentity, isToolLoopContinuation, pinnedRouteStillResolves, + toolLoopPinnedPick, +} from "./combo-tool-loop-pin"; import { sessionLaneIdFromRequest, conversationIdFromResponsesRequest, @@ -83,7 +95,7 @@ import { import { formatErrorResponse } from "../../bridge"; import { chatCanPreserveMandatoryToolChoice } from "./combo-required-tool-contract"; import { mapCodexAuthContextErrorToResponse } from "./codex-auth-error"; -import type { OcxParsedRequest } from "../../types"; +import type { OcxConfig, OcxParsedRequest } from "../../types"; import { buildToolBridgeMaps } from "./collaboration"; import { parseRequest } from "../../responses/parser"; import { responsesHasFileImage, responsesHasInstructionImage } from "../../adapters/claude-cli/instruction-images"; @@ -96,7 +108,9 @@ import type { PersistedUsageAttempt } from "../../usage/log"; import type { RouteResult } from "../../router"; import { captureRouteStaticPolicy, + comboDestinationQuotaExhausted, previewRouteModel, + resolvedComboDestination, routeConcreteModel, routeCompactionModel, routeModel, @@ -104,6 +118,7 @@ import { AnthropicSecondaryInstanceUnavailableError, } from "../../router"; import { evidenceFromBody } from "../../routing/request-evidence"; +import { comboTargetRequiresConsent, liveComboSendRequiresConsent } from "./combo-admission-snapshot"; import { resolvePolicyProfileId } from "../../routing/profile"; import { OPENAI_CODEX_PROVIDER_ID, isCanonicalOpenAiForwardProvider } from "../../providers/openai-tiers"; import { resolveNativeReasoningRetention } from "../../config/schema/native-reasoning-retention"; @@ -112,6 +127,7 @@ import { resolveSubagentFallbackChain, maybePrimeSubagentQuota, applySubagentModelFallback, + rewriteParsedModel, } from "../../codex/subagent-model-fallback"; import { codexAccountSelectionForTurn } from "../lifecycle"; import { isNativeMainTrafficBlocked } from "../../codex/native-profile-startup"; @@ -161,6 +177,7 @@ import { admissionModelDeniedResponse, projectAdmissionModelDeniedLog, AdmissionModelDeniedError, assertRouteAllowedByScope, + intersectAdmissionModelScopes, resolveAdmissionModelScope, routeAllowedByScope, } from "../admission-model-scope"; @@ -763,24 +780,117 @@ export async function prepareResponsesRequest( return markProxyError(formatErrorResponse(401, "authentication_error", "Anthropic Pool 2 requires an enabled configured provider")); } const admissionScope = options.admissionScope ?? resolveAdmissionModelScope(config, options.admission); + // Whether the admitted key is listed now, taken with the scope and before any later await. A + // configured key that is not listed stays unscoped, as resolveAdmissionModelScope treats it. + const admittedKeyId = options.admission?.kind === "configured" ? options.admission.keyId : undefined; + const admittedKeyListed = (current: OcxConfig): boolean => + admittedKeyId !== undefined && (current.apiKeys ?? []).some(key => key.id === admittedKeyId); + const keyListedAtAdmission = admittedKeyListed(advisorPlanRootConfig(config)); const advisorAdmissionPolicy = options.advisorAdmissionPolicy; + // What each Combo pick was admitted under, read from the config that selected it and before any await or + // wire normalization rewrites the route in place: its tool-loop identity, as a continuation re-routes the same + // target, the quota-only rule its paid consent follows, and whether its prepared destination needs that consent. + const comboRouteAdmissions = new WeakMap(); + // A quota-only tool continuation keeps the target that issued its calls, as in the Combo loop. Its pin is + // consulted before the router's ordered selection, which can stop at an earlier blocked target. + const toolLoopPinnedRoutes = new WeakSet(); + const pinnedComboContinuation = (selector: string): RouteResult | undefined => { + const comboId = resolveComboId(config, selector); + const combo = comboId ? config.combos?.[comboId] : undefined; + if (!comboId || !combo?.quotaOnlyFallback || !isToolLoopContinuation(body)) return undefined; + const pinned = toolLoopPinnedPick({ + config, + comboId, + lane: comboToolLoopLane(req.headers, true, options.claudeBridgePoolSession), + body, + // Consent does not decide the pin. A pinned target that lost paid-call consent is refused for consent below. + eligible: () => true, + quotaExhausted: (target, now) => comboDestinationQuotaExhausted(config, target, now), + }); + if (pinned === "quota-exhausted") throw new ComboToolTargetQuotaExhaustedError(); + if (!pinned) throw new ComboToolTargetUnavailableError(); + const routed = routeConcreteModel(config, `${pinned.target.provider}/${pinned.target.model}`); + const pinnedRoute: RouteResult = { ...routed, combo: pinned, routeKind: "combo", + routeReason: routed.routeReason === "blocked-model-redirect" ? "blocked-model-redirect" : COMBO_TOOL_LOOP_PIN_REASON }; + if (comboTargetRequiresConsent(config, pinned.target, true, pinnedRoute) + && !admissionMayUseMeteredComboTargets(config, options.admission, combo)) { + throw new ComboMeteredConsentRequiredError(); + } + toolLoopPinnedRoutes.add(pinnedRoute); + return pinnedRoute; + }; + const routeSelector = (selector: string): RouteResult => + pinnedComboContinuation(selector) ?? routeModel(config, selector, routeEvidence(options, parsed)); + // The subagent fallback chain checks availability through the same ordered selection, so a tool continuation + // answered by one of its quota-only Combos keeps that Combo before the chain is walked. Its result is marked + // pinned, so the reroute goes through the pin even when the Combo's selector matches the requested bare model. + type SubagentFallback = NonNullable> & { pinned?: true }; + const pinnedSubagentFallback = (chain: readonly string[] | null): SubagentFallback | undefined => { + if (!isToolLoopContinuation(body)) return undefined; + const lane = comboToolLoopLane(req.headers, true, options.claudeBridgePoolSession); + const comboId = quotaOnlyComboForLane(lane); + const combo = comboId === undefined ? undefined : config.combos?.[comboId]; + if (comboId === undefined || (combo && combo.quotaOnlyFallback !== true)) return undefined; + const from = parsed.modelId; + // Without a fallback chain, a request that names the Combo itself is pinned by its own route. + if (!chain && resolveComboId(config, from) === comboId) return undefined; + // A deleted Combo, one that left the chain or a target that cannot serve refuses, and the lane keeps it for a retry. + const selector = combo && chain?.find(entry => resolveComboId(config, entry) === comboId); + const target = selector ? peekComboTargetForLane(config, lane, comboId) : undefined; + if (!selector || !target) return { from, to: from, refusal: new ComboToolTargetUnavailableError().response() }; + // The same scoped fallback-policy admission as the chain's own rewrite. + const hop = guardFallbackHop(config, { + site: "subagent", + route: from, + from: { provider: route.providerName, model: route.modelId }, + to: resolvedComboDestination(config, target), + trigger: "unavailable", + admission: options.admission, + }); + if (!hop.ok) return { from, to: from, refusal: hop.response }; + hop.commit(); + rewriteParsedModel(parsed, selector); + return { from, to: selector, pinned: true }; + }; const captureInboundRoutePolicy = (candidate: RouteResult, captureRequestPolicy = true): RouteResult => { // Router-collapsed aliases bypass the combo loop. Re-pick before capturing destination // policy so random/RR cannot refuse while an unmetered target is still usable. - if (candidate.combo?.target.metered && !admissionMayUseMeteredComboTargets( - config, options.admission, config.combos?.[candidate.combo.comboId], - )) { + const collapsed = candidate.combo && config.combos?.[candidate.combo.comboId]; + const metered = (target: NonNullable["target"], route?: RouteResult) => + comboTargetRequiresConsent(config, target, collapsed?.quotaOnlyFallback === true, route); + if (candidate.combo && metered(candidate.combo.target, candidate) + && !admissionMayUseMeteredComboTargets(config, options.admission, collapsed)) { + const repickNow = Date.now(); + const quotaExhausted = (target: NonNullable["target"], now: number) => + comboDestinationQuotaExhausted(config, target, now); + let blockedByConsent = false; const pick = pickComboTarget(config, candidate.combo.comboId, { - eligible: target => !target.metered, + eligible: target => { + const allowed = !metered(target); + blockedByConsent ||= !allowed; + return allowed; + }, allowCooldownReprobe: false, + quotaExhausted, + now: repickNow, }); if (!pick) { + // A quota-only Combo stops at its first usable target, so a consent block is the reason it stopped. + if (blockedByConsent && collapsed?.quotaOnlyFallback) throw new ComboMeteredConsentRequiredError(); throw new NoAvailableComboTargetsError(candidate.combo.comboId, - comboExclusion(config, candidate.combo.comboId, target => !target.metered)); + comboExclusion(config, candidate.combo.comboId, target => !metered(target), repickNow, quotaExhausted)); } const routed = routeConcreteModel(config, `${pick.target.provider}/${pick.target.model}`); candidate = { ...routed, combo: pick, routeKind: "combo", routeReason: routed.routeReason === "blocked-model-redirect" ? "blocked-model-redirect" : "combo-pick" }; } + // The collapsed pick skips executeComboResponses, so its model lock is enforced here. + const pickedCombo = candidate.combo && getCombo(config, candidate.combo.comboId); + // A pinned continuation stays on the target that issued its calls, so it makes no hop to lock. + const lockedTarget = pickedCombo?.preserveFallbackModel && !toolLoopPinnedRoutes.has(candidate) + ? pickedCombo.targets[0] : undefined; + if (lockedTarget && candidate.modelId !== resolvedComboDestination(config, lockedTarget).model) { + throw new ComboModelChangeRefusedError(); + } // Every route this request path produces passes through here: the direct // name, an alias, a policy or combo selection, a compaction override, a // shadow-intercept target and both subagent-fallback re-routes. Checking @@ -803,6 +913,11 @@ export async function prepareResponsesRequest( providerName: candidate.providerName, modelId: previewXaiOauthWireModel(parsed, candidate, config, inboundWire), }); + if (candidate.combo) { + const quotaOnly = config.combos?.[candidate.combo.comboId]?.quotaOnlyFallback === true; + comboRouteAdmissions.set(candidate, { identity: comboToolLoopRouteIdentity(candidate), model: candidate.modelId, quotaOnly, + requiresConsent: comboTargetRequiresConsent(config, candidate.combo.target, quotaOnly, candidate) }); + } return candidate; }; try { @@ -815,7 +930,7 @@ export async function prepareResponsesRequest( ? routeConcreteModel(config, modelId) : parsed._compactionRequest === true ? routeCompactionModel(config, modelId, routeEvidence(options, parsed)) - : routeModel(config, modelId, routeEvidence(options, parsed)); + : routeSelector(modelId); // A Pool 2 selector may leave Pool 2 only through an operator-configured cross-provider // blocked-model redirect, which the router marks as a credential-domain rewrite. Any other // destination means the selector fell through to default resolution, which stays refused. @@ -886,6 +1001,8 @@ export async function prepareResponsesRequest( if (parsed._compactionRequest === true || options.compactionRoutingOverride) parsed._cursorIsolateConversation = true; route = memoryRoute ?? shadowRoute ?? resolveRoute(options.policyFallbackCandidate ? `${options.policyFallbackCandidate.provider}/${options.policyFallbackCandidate.model}` : parsed.modelId); + // A copy, since final normalization rewrites the route in place. + if (options.comboChildRoute) Object.assign(options.comboChildRoute, { route: { ...route }, identity: comboToolLoopRouteIdentity(route) }); // Selection-free hard-lock preflight grants no hop. Enforce the actual ranked destination // against the locked source before admitting this first selection. const hardLockProfileTrace = options.mainHardLockFallbackOverride ? route.routeDecision?.profile : undefined; @@ -945,6 +1062,7 @@ export async function prepareResponsesRequest( if (err instanceof NoAvailableComboTargetsError) { return comboUnavailable(err.comboId, undefined, err.exclusion); } + if (err instanceof ComboRouteRefusal) return err.response(); if (err instanceof NoEligiblePolicyCandidateError) { // Persist the evaluation trace (per-candidate exclusions + the // no-eligible reason) so failed policy requests stay auditable. @@ -1080,6 +1198,10 @@ export async function prepareResponsesRequest( await maybePrimeSubagentQuota(config, Date.now(), { nativeMainReadsForbidden }); } + // An exact-account request without a fallback chain skips the block below, so its quota-only lane decides here. + const exactAccountPinRefusal = threadSpawn && !options.comboAttempt && route.codexAccountId !== undefined + && initialSubagentFallbackChain === null ? pinnedSubagentFallback(null)?.refusal : undefined; + if (exactAccountPinRefusal) return exactAccountPinRefusal; // Subagent fallback must settle the final model/provider BEFORE route-dependent // normalization (virtual models, effort caps, service tier, wire protocol). // Preview the preferred Codex account without acquiring a probe lease or refreshing @@ -1129,7 +1251,7 @@ export async function prepareResponsesRequest( subagentFallbackModelEligibleAccountIdsForModel?.(route.modelId), ); subagentFallbackAccountId = previewAccountId ?? config.activeCodexAccountId ?? null; - const fallback = applySubagentModelFallback( + const fallback: SubagentFallback | null = pinnedSubagentFallback(fallbackChain) ?? applySubagentModelFallback( parsed, req.headers, config, @@ -1154,10 +1276,10 @@ export async function prepareResponsesRequest( } subagentQuotaFailureModel = fallback?.to ?? parsed.modelId; - if (fallback?.to && !slugsEquivalent(fallback.to, route.modelId)) { + if (fallback?.to && (fallback.pinned || !slugsEquivalent(fallback.to, route.modelId))) { try { route = captureInboundRoutePolicy( - routeModel(config, fallback.to, routeEvidence(options, parsed)), + routeSelector(fallback.to), ); leaveDirectLaneIfRerouted(options, route, parsed, logCtx); credentialDomainWasRewritten = true; @@ -1170,6 +1292,7 @@ export async function prepareResponsesRequest( if (err instanceof NoAvailableComboTargetsError) { return comboUnavailable(err.comboId, undefined, err.exclusion); } + if (err instanceof ComboRouteRefusal) return err.response(); if (err instanceof NoEligiblePolicyCandidateError) { logCtx.routeDecision = err.trace; } @@ -1281,7 +1404,7 @@ export async function prepareResponsesRequest( // makes the assignment readable, run selection again with the full configured chain // and keep the route in sync with any newly selected fallback. const recoverySelectionAdmission = codexAccountSelectionForTurn(options.turnAdmissionLease)?.(); - const fallback = (() => { + const fallback = ((): SubagentFallback | null => { try { const recoveryNativeMainBlocked = isNativeMainTrafficBlocked(); // Recompute ownership here rather than reusing the pre-decryption value: a @@ -1370,7 +1493,7 @@ export async function prepareResponsesRequest( recoveryNow, subagentFallbackModelEligibleAccountIdsForModel?.(parsed.modelId), ); - return applySubagentModelFallback( + return (threadSpawn ? pinnedSubagentFallback(resolveSubagentFallbackChain(parsed, config)) : undefined) ?? applySubagentModelFallback( parsed, req.headers, config, @@ -1399,10 +1522,10 @@ export async function prepareResponsesRequest( } subagentQuotaFailureModel = fallback?.to ?? parsed.modelId; - if (fallback?.to && !slugsEquivalent(fallback.to, route.modelId)) { + if (fallback?.to && (fallback.pinned || !slugsEquivalent(fallback.to, route.modelId))) { try { route = captureInboundRoutePolicy( - routeModel(config, fallback.to, routeEvidence(options, parsed)), + routeSelector(fallback.to), ); leaveDirectLaneIfRerouted(options, route, parsed, logCtx); credentialDomainWasRewritten = true; @@ -1415,6 +1538,7 @@ export async function prepareResponsesRequest( if (err instanceof NoAvailableComboTargetsError) { return comboUnavailable(err.comboId, undefined, err.exclusion); } + if (err instanceof ComboRouteRefusal) return err.response(); if (err instanceof NoEligiblePolicyCandidateError) { logCtx.routeDecision = err.trace; } @@ -1783,6 +1907,55 @@ export async function prepareResponsesRequest( ? admissionState.authCtx.accountId : config.activeCodexAccountId ?? null; + // A collapsed Combo pick skips executeComboResponses, which re-reads the key's live scope and paid + // consent before each send, and a Combo child is checked there against its configured target. + // Transport, sidecars and provider pacing still wait after this point, so the physical send checks + // the live scope again against the settled destination, the model actually sent, and a collapsed + // pick's paid consent. The captured scope stays an upper bound, so a widened key cannot widen it. + const collapsedCombo = route.combo && config.combos?.[route.combo.comboId]; + // The pick itself identifies the admitted route, so a Combo deleted before this point still gets the check. + const collapsedPick = route.combo; + const admittedPick = comboRouteAdmissions.get(route); + const admittedQuotaOnly = admittedPick?.quotaOnly ?? collapsedCombo?.quotaOnlyFallback === true; + if (options.comboAttempt || collapsedPick) { + const admission = options.admission; + const sendRefusal = (): Response | undefined => { + const liveConfig = advisorPlanRootConfig(config); + const liveScope = intersectAdmissionModelScopes(admissionScope, resolveAdmissionModelScope(liveConfig, admission)); + // A key listed at admission and removed since has no live scope left to intersect. + if ((keyListedAtAdmission && !admittedKeyListed(liveConfig)) || !routeAllowedByScope(liveScope, scopedDestination)) { + return admissionModelDeniedResponse(projectAdmissionModelDeniedLog(new AdmissionModelDeniedError(inboundSelector, scopedDestination), logCtx)); + } + if (!collapsedPick) return undefined; + // A pinned continuation must reach the target that issued its calls. Its selector is re-resolved from + // the live config, and a row that changed or no longer resolves refuses the send. + if (toolLoopPinnedRoutes.has(route) && (!comboStillHasTarget(liveConfig, collapsedPick.comboId, collapsedPick.target) + || !pinnedRouteStillResolves(liveConfig, targetKey(collapsedPick.target), admittedPick?.identity))) { + return new ComboToolTargetUnavailableError().response(); + } + // The live target, Combo rule and destination row decide too. The prepared destination's requirement is the + // one captured at admission, because the transport rewrites the route. + const requiresConsent = admittedPick?.requiresConsent === true + || liveComboSendRequiresConsent(liveConfig, collapsedPick.comboId, collapsedPick.target, admittedQuotaOnly, route); + return requiresConsent && !admissionMayUseMeteredComboTargets(liveConfig, admission, liveConfig.combos?.[collapsedPick.comboId]) + ? comboMeteredConsentRefused() : undefined; + }; + const refusal = sendRefusal(); + if (refusal) return refusal; + requireSendAdmission(sendRefusal); + } + // The Combo loop records its serving lane when a child completes. A collapsed quota-only pick + // records it on completion too, so its tool continuation finds the target that issued the call. + let rememberCollapsedComboLane: ((model: string) => void) | undefined; + const routeIdentity = admittedPick?.identity; + if (route.combo && admittedQuotaOnly && routeIdentity + && !options.compactionRoutingOverride && !options.mainHardLockFallbackOverride) { + const servingPick = route.combo; + const lane = comboToolLoopLane(req.headers, true, options.claudeBridgePoolSession); + rememberCollapsedComboLane = model => rememberComboForLane(lane, servingPick.comboId, servingPick.target, model, + servingPick.writerGeneration, undefined, routeIdentity, admittedPick?.model); + } + commitSkillsSnapshot?.(); return { inboundWire, @@ -1819,6 +1992,7 @@ export async function prepareResponsesRequest( clientRequestedStream, substituteMainCredential, callerAuthHeaders, + rememberCollapsedComboLane, }; } diff --git a/src/server/responses/response-effects.ts b/src/server/responses/response-effects.ts index 75bdd29158b..1aa78ac03d8 100644 --- a/src/server/responses/response-effects.ts +++ b/src/server/responses/response-effects.ts @@ -26,11 +26,12 @@ export function createResponsesEffects( | "poolAffinityKey" | "route" | "substituteMainCredential" + | "rememberCollapsedComboLane" >, sidecarState: Pick & Partial>, ) { const { options, req, config } = requestContext; - const { parsed, poolAffinityKey, route, substituteMainCredential } = requestState; + const { parsed, poolAffinityKey, route, substituteMainCredential, rememberCollapsedComboLane } = requestState; const { routedCompaction, preserveCompactionPrefix } = sidecarState; @@ -44,6 +45,7 @@ export function createResponsesEffects( || response.status !== "completed" || typeof response.model !== "string" || !response.model.trim()) return; responseCompletionNotified = true; + rememberCollapsedComboLane?.(response.model); options.onResponseComplete?.(response.model); }; diff --git a/src/server/responses/send-admission.ts b/src/server/responses/send-admission.ts new file mode 100644 index 00000000000..1db38a05e17 --- /dev/null +++ b/src/server/responses/send-admission.ts @@ -0,0 +1,89 @@ +import { AsyncLocalStorage } from "node:async_hooks"; + +/** + * Combo admission, checked again at the physical send. + * + * A Combo child and a Combo the router collapses to one pick check the key's model scope and paid + * consent before they dispatch, then still wait on transport and sidecar preparation and on provider + * pacing. Either can be withdrawn during those waits, so the send boundary checks again. + * + * Each request runs in its own slot, nested in the slot of the request or Combo loop that started it. + * A send passes every check up that chain, and a check a nested request adds stays in its own slot. + */ +interface SendAdmission { + parent: SendAdmission | undefined; + /** The answer for a request that may no longer send, or undefined while it still may. */ + refusal?: () => Response | undefined; + refused?: Response; +} + +const admissionScope = new AsyncLocalStorage(); + +export class SendAdmissionRefusedError extends Error { + constructor() { + super("The Combo admission of this request was withdrawn before the send"); + this.name = "SendAdmissionRefusedError"; + } +} + +/** + * Run one dispatch in a new slot nested in the current one. A refused send answers with its refusal, + * whatever the dispatch made of the thrown error. + */ +export async function runWithSendAdmission( + refusal: (() => Response | undefined) | undefined, + run: () => Promise, +): Promise<{ response: Response; refused: boolean }> { + const admission: SendAdmission = { parent: admissionScope.getStore(), refusal }; + try { + const response = await admissionScope.run(admission, run); + if (!admission.refused) return { response, refused: false }; + // A nested slot may already answer with this same refusal, whose body must stay readable. + if (response !== admission.refused) void response.body?.cancel().catch(() => undefined); + } catch (error) { + if (!admission.refused) throw error; + } + return { response: admission.refused, refused: true }; +} + +/** Open the slot of one request. */ +export async function withSendAdmissionScope(run: () => Promise): Promise { + return (await runWithSendAdmission(undefined, run)).response; +} + +/** Request preparation names the check its own sends must still pass. */ +export function requireSendAdmission(refusal: () => Response | undefined): void { + const admission = admissionScope.getStore(); + if (admission) admission.refusal = refusal; +} + +function assertAdmitted(innermost: SendAdmission | undefined): void { + for (let admission = innermost; admission; admission = admission.parent) { + const refused = admission.refusal?.(); + if (!refused) continue; + // Every slot from the send up to the one whose check failed answers with this refusal. + for (let marked = innermost; marked; marked = marked.parent) { + marked.refused = refused; + if (marked === admission) break; + } + throw new SendAdmissionRefusedError(); + } +} + +/** The physical send boundary: throws when the current request may no longer send. */ +export function assertSendAdmission(): void { + assertAdmitted(admissionScope.getStore()); +} + +/** + * Bind the current request's admission for work that socket callbacks start outside the request's + * async context. `assert` checks a frame before it is written, and `run` keeps an HTTP fallback in + * the request's admission, so its own physical send is checked. + */ +export function captureSendAdmission(): { assert(): void; run(work: () => T): T } { + const captured = admissionScope.getStore(); + return { + assert: () => assertAdmitted(captured), + run: work => captured ? admissionScope.run(captured, work) : work(), + }; +} diff --git a/src/server/responses/shadow-target-availability.ts b/src/server/responses/shadow-target-availability.ts index 4c329fb2ff9..4dd2b65a215 100644 --- a/src/server/responses/shadow-target-availability.ts +++ b/src/server/responses/shadow-target-availability.ts @@ -1,6 +1,7 @@ import { NoAvailableComboTargetsError } from "../../combos"; import { NoEligiblePolicyCandidateError, type RouteResult } from "../../router"; import { AdmissionModelDeniedError } from "../admission-model-scope"; +import { ComboRouteRefusal } from "./core-errors"; /** * Shadow-call interception names one operator-chosen target (#5618). When that target stops @@ -36,6 +37,7 @@ export function resolveChosenTarget( route = resolve(model); } catch (error) { if (error instanceof AdmissionModelDeniedError + || error instanceof ComboRouteRefusal || error instanceof NoAvailableComboTargetsError || error instanceof NoEligiblePolicyCandidateError) throw error; return { unavailable: error instanceof Error ? error.message : String(error) }; diff --git a/src/server/responses/ws-upstream.ts b/src/server/responses/ws-upstream.ts index 88e1a40aba8..e91e716b112 100644 --- a/src/server/responses/ws-upstream.ts +++ b/src/server/responses/ws-upstream.ts @@ -1,4 +1,5 @@ import { codexWsIncrementalHasRetainedState, codexWsIncrementalUploadEnabled, prepareIncrementalFrame } from "./codex-ws-incremental"; +import { assertSendAdmission } from "./send-admission"; import { OPENAI_API_RESPONSES_URL } from "./native-response-control"; import { isInjectionRequest } from "./native-injection-protocol"; import type { NativeResponseControl } from "./native-response-control"; @@ -228,6 +229,7 @@ export async function codexWsUpstreamFetch( // A local refusal is not a failed upgrade and must never enter the SSE fallback path. try { + assertSendAdmission(); beforeDispatch?.(new Headers(headers)); } catch (error) { return Promise.reject(error); diff --git a/src/types/config.ts b/src/types/config.ts index 6098edb96ea..69879d396d8 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -1522,6 +1522,10 @@ export interface OcxComboTarget { export interface OcxComboConfig { targets: OcxComboTarget[]; + /** Ordered failover advances only on confirmed target quota or billing exhaustion. */ + quotaOnlyFallback?: boolean; + /** Require every failover destination to resolve to the original model ID. */ + preserveFallbackModel?: boolean; /** Operator consent for metered targets on a loopback-only proxy. Default false; public listeners still require key consent. */ allowMeteredTargets?: boolean; /** Ordered failover (default), round-robin, weighted random, least-used, or quota reset-window selection. */ diff --git a/structure/fallback-policy.md b/structure/fallback-policy.md index 90c5d83db9e..01fed0919bf 100644 --- a/structure/fallback-policy.md +++ b/structure/fallback-policy.md @@ -30,6 +30,79 @@ the load warning name the section. A whole-config write does not degrade: `valid save cannot silently drop a refusal. Map keys are validated by the resolver, so one bad key never drops its siblings. +### Quota-only Combo execution + +For an ordered Combo with `quotaOnlyFallback`, `pickComboTarget` skips only exhausted targets. +Evidence is a fresh routing quota reading bound to the current credential or a live cooldown +explicitly marked by a confirmed upstream refusal. Existing cooldown rows without this marker +retain their normal expiry and are temporary blocks in this mode. The picker stops at the first +unattempted target blocked for another reason. It follows configured order and bypasses cooldown +wait, reprobe and last-resort reordering. The quota reading belongs to the destination the target +resolves to after model redirects. For the canonical Codex pool it is the pool's confirmed usage +limits. Selection in the Combo loop, a Combo the router collapses to one pick and a pinned tool +continuation all read this destination quota. + +The cooldown evidence is bound to the single key and route used for the send, including its model +redirects, aliases, adapters, send paths and Vertex project and location. A one-entry key pool +counts as a single key. The binding is private to the process. Replaced credentials, +edited routes and reloaded advisory cooldowns are checked again. +OAuth and key pools keep their native quota evaluation. + +After dispatch the Combo consumes bounded upstream failure evidence and trusted local pool +exhaustion. A generic 429, temporary throttle, request-wide budget refusal and quota-policy +hard lock carry no exhaustion evidence. A structured account or billing exhaustion code counts on +HTTP 400, 402, 422, 429 and 5xx responses. A pool answers for its own accounts. The native Codex +pool needs proof for each usable account. The native Anthropic pool supplies its own exhausted +verdict, and a credit refusal advances once no Anthropic account remains eligible and none is +held by a rate pause alone. A generic +OAuth pool advances once no account other than the refused one is eligible for the model and the +last refusal of every unavailable sibling proved a spent quota. An Antigravity sibling whose model +roster omits the model does not count. A key pool advances once every +enabled key refused with a spent quota or credit. Both verdicts come from the refusal body on the +adapter send path and last as long as the cooldown of that refusal. A rotation on another send path +records none, which keeps the Combo on the pool. A committed output ceiling does not cool a quota-only target. Scoped fallback policy, consent, account selection and replay +safeguards remain in force. Destinations outside recognized subscription channels and configured +loopback local routes require consent, including custom API providers and redirected destinations. +Without consent the Combo returns `combo_metered_consent_required`. +A tool continuation uses its remembered resolved target, including its send paths, per-model adapter +and the Codex account and account mode it resolves to. It stops with `combo_tool_target_unavailable` when that target cannot be established or used, +and with `combo_metered_consent_required` when the target still serves but lost paid-call consent. A pinned +tool continuation waits on its serving target. It records confirmed exhaustion only for a target +served by a single key of its own provider, a one-entry key pool included, so a redirected target, +an OAuth account pool or a pool of several keys keeps no target cooldown from it. +The lane keeps the last Combo turn only, without the IDs of the calls that turn issued, and a turn +served outside a Combo does not replace it. A continuation of a call from another turn on the same +lane therefore follows that last Combo turn. +A request continues a tool loop when it ends with a tool output, after any trailing developer items. A +request that ends with a user message starts a new turn. Turning `quotaOnlyFallback` off releases +outstanding continuations to ordinary Combo behavior. +`preserveFallbackModel` compares resolved model IDs even when the provider differs and returns +a conflict on mismatch, including for a Combo the router collapses to one pick. A continuation +compares against the model its lane recorded when that turn completed, even when the target can no longer be +selected or its selector now resolves elsewhere. +The lock also covers the model a Combo child settled on. +A Combo the router collapses to one pick, such as a subagent fallback alias, re-reads the key's +model scope and paid consent from the live config before its send, and a quota-only one that stops at a paid target without +consent returns `combo_metered_consent_required`. A quota-only one records its serving lane when it +completes, so its tool continuation stays on the target that lane remembers or stops like a +continuation in the Combo loop. A subagent continuation on that lane stops with +`combo_tool_target_unavailable` once its Combo is deleted or no longer in the request's fallback chain. +Reconciling the live config keeps such a lane until it expires, so a retry is refused as well. +A Combo child and a collapsed pick check the key's live model scope against the settled admission +destination, which includes a wire override only when that override is part of admission, and check +paid consent once more at the physical HTTP send and before each WebSocket frame or HTTP fallback, +after preparation and provider pacing. Consent follows the live target, Combo rule and destination +row as well as the admitted ones, and covers the destination a Combo child settled on. A Combo +deleted during the wait keeps the strictest rule. A +configured key removed since admission refuses every send, a native child's included. A +scope narrowed during those waits returns the model-scope refusal, withdrawn consent returns +`combo_metered_consent_required`, and a pinned target returns `combo_tool_target_unavailable` when it +left its Combo, its selector now resolves to another route or its Combo child settled on another provider, model or Codex +account. Nothing is sent in each case. A quota-only turn whose child settled on another destination +records that destination for its lane. A quota refusal there is judged against that destination's own +accounts and fallback policy, and leaves the planned target without a cooldown. A nested +request, such as a decision call, adds its own checks to its own sends only. + `resolveFallbackPolicy`: a device entry set to `false` for the kind refuses; a device `true` never reopens a hop. Otherwise the first route selector with a boolean decides, then the provider the hop starts from, then the global switch, then the default (allowed). Route selectors are the public diff --git a/structure/runtime.md b/structure/runtime.md index 5acf4bab5ef..8562eacb29e 100644 --- a/structure/runtime.md +++ b/structure/runtime.md @@ -504,7 +504,7 @@ This is also why the classifier cannot duplicate visible output. Native byte str Regression coverage: `tests/responses/responses-forward-prompt-envelope.test.ts`, `tests/routing/router-combo-failover-classification.test.ts`, `tests/routing/routing-policy-fallback.test.ts`, `tests/helpers/combo-context-overflow-cases.ts`, and `tests/server/server-combo-failover-e2e.test.ts`. Every combo, routing-profile, subagent and hard-lock hop to another model or provider first passes the [fallback policy](fallback-policy.md#sites). -`src/combos/failover.ts` uses a 10-minute fallback for a spent account usage window (codes `usage_limit_exceeded`, `usage_limit_reached`, `1308`, or `usage limit reached` / `usage limit has been reached` / `token-plan quota has been exhausted` prose, including HTTP 502) and for provider-scoped credential or billing failure codes such as `invalid_api_key` and `insufficient_quota`. This duration does not change failure classification or cooldown scope; upstream retry/reset signals and configured durations retain precedence. It caps explicit upstream `Retry-After` target cooldowns at 24 hours while reset-derived, configured, and fallback cooldowns remain capped at 10 minutes. `src/combos/resolve.ts` omits a target cooldown for a 429 only when the failed child identifies one account in an Anthropic OAuth or canonical Codex pool and that account has a live pool cooldown, or identifies one account in a generic OAuth pool that still has an eligible sibling. `src/server/responses/core-combo-failure.ts` checks the pool's health record before passing that attribution; for a generic OAuth pool it first hands the account (matched through its `accountLogLabel`) to `rotateGenericOAuthAccountOn429`, which cools it under the pool's own Retry-After policy even when the per-request account budget ended rotation before that account was recorded, and attributes the failure only when the rotator names a sibling. Unknown accounts, ambiguous labels, a lone or fully cooled generic OAuth pool, API-key providers, and other failures keep their ordinary target cooldown. An API-key pool needs no attribution: its 429 rotation walks every key inside the attempt, so a 429 reaches the combo only once every key is cooled. Regression coverage: `tests/oauth/generic-oauth-combo-account-cooldown.test.ts`. A 402 is the provider-scoped twin for an Anthropic OAuth pool: the pool rotates only on 401/403/429, so when the failed child identifies one pool account and the failure carries the exact credit-balance refusal (`isAnthropicBillingFailure`), `core-combo-failure.ts` records that account's refusal through the pool's `recordAnthropicAccountRefusal` (the same entitlement backoff a 403 credit refusal gets) and `resolve.ts` omits every target cooldown only while the pool still has an eligible account; a lone account, an exhausted pool, an unidentified account, or any other 402 keeps the provider-scoped cooldown. Regression coverage: `tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts`. The Anthropic OAuth pool's own all-accounts-cooled 429 is an unattributed exception: `isAnthropicPoolLocalRefusal` in `core-combo-failure.ts` requires an Anthropic OAuth instance (`anthropic`, or a configured and enabled `anthropic2` row) with `authMode: "oauth"`, status 429, no identified failed account, no eligible pool account and a live pool retry-after. The target then still cools, but for the local fallback instead of the restated per-account `Retry-After`, so a resumed or newly added account is not ignored until a 24-hour target cooldown expires. An upstream 429 on an API-key provider or on an identified pool account keeps its full `Retry-After`. Regression coverage: `tests/routing/always-on-429-failover.test.ts`. Cooldown entries in `src/combos/failover.ts` retain the failure status. The quota-only snapshot query records target/expiry pairs for unexpired 429/402 cooldowns using only cooldown map lookups. Its config-aware wrapper in `src/combos/resolve.ts` applies the picker's provider availability and cached quota checks before dispatch; request eligibility runs lazily only when exhaustion considers a 503, with throwing checks treated as ineligible. Responses exhaustion uses this evidence under the [failover contract](transports/responses-failover.md); ordinary cooldown selection and timing stay unchanged. Opt-in `cooldownReprobe: { enabled: true, intervalMs }` in `src/combos/resolve.ts` permits an initial non-preview request to reserve all-cooled eligible targets once per configured interval (default 300000 ms, range 1000..86400000). The synchronous reservation lives in selection state and resets on proxy restart or selection-state reset; the reserved target keys are carried only by that request's picks; shared cooldowns remain recorded and continue to exclude concurrent requests. Each reservation names the cooldown write's unique revision, not its expiry. A successful dispatch settles through `settleComboReprobeSuccess`, which lifts only that unchanged reserved write; unprobed and re-cooled targets stay recorded, including replacements with an identical Retry-After expiry. Route-level selection without request eligibility disables reprobes, as does the in-flight retry-after-cooldown path, which waits for normal expiry. Nested wait-path and JEV selections retain the same reservation without starting a second reprobe. After ordinary or last-resort-deferral waits and after an awaited JEV decision, selection rechecks provider and request eligibility at the current clock and permits only unchanged-revision bypasses. Preparation first checks available siblings without evaluating cooled targets; a throwing eligibility predicate is ineligible for recovery. Encrypted-task recovery relaxes only payload readability and retains metering, JEV, reasoning-replay and protocol-lane eligibility. Its recovery selection may reserve a reprobe only after Responses ingress, thread-spawn, enabled recovery configuration and non-child-attempt admission pass; refused recovery preserves cooldowns and the reservation. New failures record cooldowns normally, and provider quota, account admission, payload eligibility, metered-spend and cancellation checks remain authoritative. There is no timer; existing send bounds remain. The opt-in may retry a target before its server Retry-After. CLI `--cooldown-reprobe on|off` and `--cooldown-reprobe-interval` control it; omitted management fields preserve it on unrelated saves. Tests: `tests/codex-integration/combo-cooldown-reprobe.test.ts`, `tests/server/server-combo-cooldown-fallback.test.ts` and `tests/cli/cli-combo-parity.test.ts`. A zero-attempt `combo_unavailable` names why each target was skipped. `comboExclusionReasons` in `src/combos/resolve.ts` derives one coarse label per target from the picker's own checks, in picker order: `provider missing`, `provider disabled`, `quota exhausted`, `cooldown`, then `ineligible for this request` when the caller's eligibility predicate refuses it or throws. `NoAvailableComboTargetsError` and `comboUnavailable` append them to the message; the description carries target counts and indices, validated provider-id labels and closed reasons; configured model strings and combo aliases are omitted. Coverage: `tests/responses/responses-combo-exhausted-error.test.ts`. The same pass (`comboExclusion`) also yields machine-readable diagnostics (#7965): `comboUnavailableResponse` in `src/server/responses/core-errors.ts` adds `error.combo = { cause, targets, attempted, causes }` to the unchanged `combo_unavailable` code. A target's class is `quota` (cached quota spent, or a cooldown whose retained status is 429/402), `permission` (cooldown status 401/403), `transient` (any other cooldown, read through `comboTargetCooldownStatus` in `src/combos/failover.ts`), `unsupported` (request-ineligible, including the mandatory `tool_choice` refusals in `core-combo.ts`, where `comboTargetUnavailableCause` lets provider state, quota and live cooldowns keep precedence) or `unavailable` (provider missing or disabled); `cause` is the shared class, `mixed`, or `unknown`. The quota-snapshot exhaustion answer reports `quota` with the targets the ladder dispatched. Counts and closed classes only; no combo id, provider, model or upstream text. Coverage: `tests/responses/responses-combo-unavailable-cause.test.ts`. Ordinary local Codex account-cooldown refusals carry unforgeable process-local Response identity from `src/codex/account-cooldown-response.ts` through combo failure reconstruction. At target cooldown recording only, `core-combo.ts` drops their restated retry/reset metadata and retains capped local backoff; client retry advice and account admission remain unchanged. Main hard-lock, credit, Reserve and transient-policy subclasses are excluded. The [combo cooldown contract](transports/responses-failover.md#single-target-cooldown-retry-ownership) owns this distinction; `tests/server/server-combo-cooldown-recording.test.ts` covers recovery and upstream wire-copy controls. +`src/combos/failover.ts` uses a 10-minute fallback for a spent account usage window (codes `usage_limit_exceeded`, `usage_limit_reached`, `1308`, or `usage limit reached` / `usage limit has been reached` / `token-plan quota has been exhausted` prose, including HTTP 502) and for provider-scoped credential or billing failure codes such as `invalid_api_key` and `insufficient_quota`. This duration does not change failure classification or cooldown scope; upstream retry/reset signals and configured durations retain precedence. It caps explicit upstream `Retry-After` target cooldowns at 24 hours while reset-derived, configured, and fallback cooldowns remain capped at 10 minutes. `src/combos/resolve.ts` omits a target cooldown for a 429 only when the failed child identifies one account in an Anthropic OAuth or canonical Codex pool and that account has a live pool cooldown, or identifies one account in a generic OAuth pool that still has an eligible sibling. `src/server/responses/core-combo-failure.ts` checks the pool's health record before passing that attribution; for a generic OAuth pool it first hands the account (matched through its `accountLogLabel`) to `rotateGenericOAuthAccountOn429`, which cools it under the pool's own Retry-After policy even when the per-request account budget ended rotation before that account was recorded, and attributes the failure only when the rotator names a sibling. Unknown accounts, ambiguous labels, a lone or fully cooled generic OAuth pool, API-key providers, and other failures keep their ordinary target cooldown. An API-key pool needs no attribution: its 429 rotation walks every key inside the attempt, so a 429 reaches the combo only once every key is cooled. Regression coverage: `tests/oauth/generic-oauth-combo-account-cooldown.test.ts`. A 402, or a 400 carrying the same credit-balance refusal, is the provider-scoped twin for an Anthropic OAuth pool: the pool rotates only on 401/403/429, so when the failed child identifies one pool account and the failure carries the exact credit-balance refusal (`isAnthropicBillingFailure`), `core-combo-failure.ts` records that account's refusal through the pool's `recordAnthropicAccountRefusal` (the same entitlement backoff a 403 credit refusal gets) and `resolve.ts` omits every target cooldown only while the pool still has an eligible account; a lone account, an exhausted pool, an unidentified account, or any other 402 keeps the provider-scoped cooldown. Regression coverage: `tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts`. The Anthropic OAuth pool's own all-accounts-cooled 429 is an unattributed exception: `isAnthropicPoolLocalRefusal` in `core-combo-failure.ts` requires an Anthropic OAuth instance (`anthropic`, or a configured and enabled `anthropic2` row) with `authMode: "oauth"`, status 429, no identified failed account, no eligible pool account and a live pool retry-after. The target then still cools, but for the local fallback instead of the restated per-account `Retry-After`, so a resumed or newly added account is not ignored until a 24-hour target cooldown expires. An upstream 429 on an API-key provider or on an identified pool account keeps its full `Retry-After`. Regression coverage: `tests/routing/always-on-429-failover.test.ts`. Cooldown entries in `src/combos/failover.ts` retain the failure status. The quota-only snapshot query records target/expiry pairs for unexpired 429/402 cooldowns using only cooldown map lookups. Its config-aware wrapper in `src/combos/resolve.ts` applies the picker's provider availability and cached quota checks before dispatch; request eligibility runs lazily only when exhaustion considers a 503, with throwing checks treated as ineligible. Responses exhaustion uses this evidence under the [failover contract](transports/responses-failover.md); ordinary cooldown selection and timing stay unchanged. Opt-in `cooldownReprobe: { enabled: true, intervalMs }` in `src/combos/resolve.ts` permits an initial non-preview request to reserve all-cooled eligible targets once per configured interval (default 300000 ms, range 1000..86400000). The synchronous reservation lives in selection state and resets on proxy restart or selection-state reset; the reserved target keys are carried only by that request's picks; shared cooldowns remain recorded and continue to exclude concurrent requests. Each reservation names the cooldown write's unique revision, not its expiry. A successful dispatch settles through `settleComboReprobeSuccess`, which lifts only that unchanged reserved write; unprobed and re-cooled targets stay recorded, including replacements with an identical Retry-After expiry. Route-level selection without request eligibility disables reprobes, as does the in-flight retry-after-cooldown path, which waits for normal expiry. Nested wait-path and JEV selections retain the same reservation without starting a second reprobe. After ordinary or last-resort-deferral waits and after an awaited JEV decision, selection rechecks provider and request eligibility at the current clock and permits only unchanged-revision bypasses. Preparation first checks available siblings without evaluating cooled targets; a throwing eligibility predicate is ineligible for recovery. Encrypted-task recovery relaxes only payload readability and retains metering, JEV, reasoning-replay and protocol-lane eligibility. Its recovery selection may reserve a reprobe only after Responses ingress, thread-spawn, enabled recovery configuration and non-child-attempt admission pass; refused recovery preserves cooldowns and the reservation. New failures record cooldowns normally, and provider quota, account admission, payload eligibility, metered-spend and cancellation checks remain authoritative. There is no timer; existing send bounds remain. The opt-in may retry a target before its server Retry-After. CLI `--cooldown-reprobe on|off` and `--cooldown-reprobe-interval` control it; omitted management fields preserve it on unrelated saves. Tests: `tests/codex-integration/combo-cooldown-reprobe.test.ts`, `tests/server/server-combo-cooldown-fallback.test.ts` and `tests/cli/cli-combo-parity.test.ts`. A zero-attempt `combo_unavailable` names why each target was skipped. `comboExclusionReasons` in `src/combos/resolve.ts` derives one coarse label per target from the picker's own checks, in picker order: `provider missing`, `provider disabled`, `quota exhausted`, `cooldown`, then `ineligible for this request` when the caller's eligibility predicate refuses it or throws. `NoAvailableComboTargetsError` and `comboUnavailable` append them to the message; the description carries target counts and indices, validated provider-id labels and closed reasons; configured model strings and combo aliases are omitted. Coverage: `tests/responses/responses-combo-exhausted-error.test.ts`. The same pass (`comboExclusion`) also yields machine-readable diagnostics (#7965): `comboUnavailableResponse` in `src/server/responses/core-errors.ts` adds `error.combo = { cause, targets, attempted, causes }` to the unchanged `combo_unavailable` code. A target's class is `quota` (cached quota spent, or a cooldown whose retained status is 429/402), `permission` (cooldown status 401/403), `transient` (any other cooldown, read through `comboTargetCooldownStatus` in `src/combos/failover.ts`), `unsupported` (request-ineligible, including the mandatory `tool_choice` refusals in `core-combo.ts`, where `comboTargetUnavailableCause` lets provider state, quota and live cooldowns keep precedence) or `unavailable` (provider missing or disabled); `cause` is the shared class, `mixed`, or `unknown`. The quota-snapshot exhaustion answer reports `quota` with the targets the ladder dispatched. Counts and closed classes only; no combo id, provider, model or upstream text. Coverage: `tests/responses/responses-combo-unavailable-cause.test.ts`. Ordinary local Codex account-cooldown refusals carry unforgeable process-local Response identity from `src/codex/account-cooldown-response.ts` through combo failure reconstruction. At target cooldown recording only, `core-combo.ts` drops their restated retry/reset metadata and retains capped local backoff; client retry advice and account admission remain unchanged. Main hard-lock, credit, Reserve and transient-policy subclasses are excluded. The [combo cooldown contract](transports/responses-failover.md#single-target-cooldown-retry-ownership) owns this distinction; `tests/server/server-combo-cooldown-recording.test.ts` covers recovery and upstream wire-copy controls. ## Combo default effort precedence diff --git a/structure/transports/responses-failover.md b/structure/transports/responses-failover.md index 16cb1557c6b..2320798eb11 100644 --- a/structure/transports/responses-failover.md +++ b/structure/transports/responses-failover.md @@ -186,6 +186,9 @@ gets only the fixed placeholder in [tool-loop continuation](native-reasoning-ret See [Combo streaming boundaries](responses-combo-boundaries.md#combo-streaming-commit-boundary) for preflight, turn-lease and hop-warning ownership. Native mandatory-tool streams follow the [streaming required-tool contract](responses-combo-boundaries.md#streaming-required-tool-contract): a held missing-call completion can fail over, while committed output ends in a typed failure without replay. +The [quota-only Combo mode](../fallback-policy.md#quota-only-combo-execution) narrows the +conditions for a hop before the same request replay boundary. + Usage consumers preserve positive incomplete-history metadata and connected CLI usage follows the client-scoped hub contract, both specified in [usage accounting](../dashboard-and-usage.md#usage-accounting): readable totals are not a complete ledger, and local management and account data stay separate. Codex pool settings and their consumers follow the [reset-first ordering contract](../providers/openai-accounts.md#reset-first-account-ordering), including independent-quota fallback and preserved affinity. The shared atomic replacement publisher also identifies explicit Remote Workspace file writes as `remote-workspace`. Remote Workspace uses a separate, explicitly enabled server surface with structural WebSocket callbacks and awaited per-server cleanup; [its contract](../remote-workspace.md) owns that integration and records its isolated owner and support limits. Console upload-rejection recovery excludes query-bearing and fragment-bearing destinations even when their host and generation path match the canonical endpoint. diff --git a/tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts b/tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts index 3e9521ee77e..b80a5f0b948 100644 --- a/tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts +++ b/tests/adapters/anthropic/anthropic-combo-account-cooldown.test.ts @@ -243,15 +243,15 @@ test("a lone OAuth account without pool cooldown still cools the combo target", expect(sentTokens).toHaveLength(1); }); -/** The pool's own credit-balance wording (`isAccountRefusal`), on a 402. */ -function creditRefused(): Response { +/** The pool's own credit-balance wording (`isAccountRefusal`), on a 402 or the 400 Anthropic also sends. */ +function creditRefused(status = 402): Response { return Response.json({ type: "error", error: { type: "billing_error", message: "Your credit balance is too low to access the Anthropic API. Please go to Plans & Billing to upgrade or purchase credits.", - } }, { status: 402 }); + } }, { status }); } -test("one account's 402 credit refusal does not cool the combo target while a sibling is eligible", async () => { +test.each([400, 402])("one account's %p credit refusal does not cool the combo target while a sibling is eligible", async status => { const ids = await seed(2); const config = configFor(() => answered()); const anthropic = config.providers.anthropic as OcxProviderConfig & { fetch: typeof fetch }; @@ -259,7 +259,7 @@ test("one account's 402 credit refusal does not cool the combo target while a si anthropic.fetch = (async (_input, init) => { const token = String(new Headers(init?.headers).get("authorization")); sentTokens.push(token); - return token === `Bearer ${credential(0).access}` ? creditRefused() : answered(); + return token === `Bearer ${credential(0).access}` ? creditRefused(status) : answered(); }) as typeof fetch; const fallbackSends: string[] = []; config.providers.fallback = { diff --git a/tests/adapters/anthropic/anthropic-pool-usage-limit.test.ts b/tests/adapters/anthropic/anthropic-pool-usage-limit.test.ts index 466904c6600..56b5c1bffcb 100644 --- a/tests/adapters/anthropic/anthropic-pool-usage-limit.test.ts +++ b/tests/adapters/anthropic/anthropic-pool-usage-limit.test.ts @@ -15,14 +15,17 @@ import { getAnthropicAccountHealthSnapshot, recordAnthropicAccount429, recordAnthropicAccountRefusal, } from "../../../src/oauth/anthropic-routing"; import { claimAnthropicFamilyRevalidation, clearAllAnthropicFamilyQuota, observeAnthropicFamilyQuota } from "../../../src/oauth/anthropic-model-quota"; +import { clearAllAnthropicRatePauses, pauseAnthropicRateAdmission } from "../../../src/oauth/anthropic-rate-limit-policy"; import { clearGenericFailoverHealth } from "../../../src/oauth/generic-account-failover"; import { getAccountSet, saveCredential, setActiveAccount } from "../../../src/oauth/store"; import { clearAccountQuotaCache, resetProviderQuotaReconcileStateForTests } from "../../../src/providers/quota"; import { clearResponseStateForTests } from "../../../src/responses/state"; import { handleResponses } from "../../../src/server/responses"; +import { handleClaudeMessages } from "../../../src/server/claude-messages"; import { anthropicPoolCooldownResponse } from "../../../src/server/responses/core-errors"; import type { OcxConfig, OcxProviderConfig } from "../../../src/types"; import { removeTreeWithRetry } from "../../helpers/remove-tree"; +import { chatStream, chatSuccess } from "../../helpers/combo-failover-upstream"; const originalHome = process.env.OPENCODEX_HOME; let originalFetch: typeof globalThis.fetch; @@ -39,6 +42,7 @@ beforeEach(() => { clearAnthropicAccountPoolState(); forgetAnthropicFailoverQuorum(); clearAllAnthropicFamilyQuota(); + clearAllAnthropicRatePauses(); clearGenericFailoverHealth(); clearAccountQuotaCache(); resetProviderQuotaReconcileStateForTests(); @@ -53,6 +57,7 @@ afterEach(() => { clearAnthropicAccountPoolState(); forgetAnthropicFailoverQuorum(); clearAllAnthropicFamilyQuota(); + clearAllAnthropicRatePauses(); clearGenericFailoverHealth(); resetProviderQuotaReconcileStateForTests(); clearResponseStateForTests(); @@ -157,6 +162,88 @@ test.each([true, false])("every account held on quota answers usage_limit_reache expectNoAccountMaterial(text, ids); }); +test.each(["responses", "messages"])("quota-only %s fallback waits for the Anthropic pool verdict", async wire => { + const ids = await seed(); + const config = configFor(true, () => spent("7d", 60)); + config.providers.anthropic!.baseUrl = "https://api.anthropic.com"; + config.providers.backup = { adapter: "openai-chat", baseUrl: "https://backup.example/v1", apiKey: "fixture", + fetch: (async (_input, init) => { + sent.push("backup"); + return JSON.parse(String(init?.body)).stream ? chatStream("fallback") : chatSuccess("fallback", "m"); + }) as typeof fetch }; + config.combos = { strict: { strategy: "failover", quotaOnlyFallback: true, allowMeteredTargets: true, + targets: [{ provider: "anthropic", model: "claude-sonnet-4-5" }, { provider: "backup", model: "m" }] } }; + holdOnQuota(config, ids[0]!, 60, Date.now()); + const admission = { kind: "loopback", source: "loopback" } as const; + const req = new Request(`http://localhost/v1/${wire}`, { method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify(wire === "responses" ? { model: "combo/strict", input: "fixture", stream: false } + : { model: "combo/strict", messages: [{ role: "user", content: "fixture" }], max_tokens: 32, stream: false }) }); + const log = { model: "", provider: "" }; + const response = wire === "responses" ? await handleResponses(req, config, log, { admission }) + : await handleClaudeMessages(req, config, log, { admission, requestId: "fixture", start: Date.now() }); + expect(response.status, JSON.stringify({ body: await response.text(), attempts: sent.length })).toBe(200); + expect(sent).toHaveLength(2); + expect(sent[1]).toBe("backup"); +}); + +test("an ordinary Combo keeps the upstream 429 after the last pool account refuses", async () => { + const ids = await seed(); + const config = configFor(true, () => spent("7d", 60)); + config.combos = { ordinary: { strategy: "failover", targets: [{ provider: "anthropic", model: "claude-sonnet-4-5" }] } }; + holdOnQuota(config, ids[0]!, 60, Date.now()); + const response = await post(config, { model: "combo/ordinary" }); + expect(response.status).toBe(429); + expect(String((await errorOf(response)).message)).toContain("synthetic window spent"); + expect(sent).toHaveLength(1); +}); + +for (const status of [400, 402]) test.each([1, 2])(`quota-only advances on a ${status} credit refusal only once no pool account remains (%p accounts)`, async count => { + await seed(count); + const config = configFor(true, () => Response.json({ type: "error", error: { + type: "invalid_request_error", message: "Your credit balance is too low to access the Anthropic API.", + } }, { status })); + config.providers.anthropic!.baseUrl = "https://api.anthropic.com"; + config.providers.backup = { adapter: "openai-chat", baseUrl: "https://backup.example/v1", apiKey: "fixture", + fetch: (async () => { sent.push("backup"); return chatSuccess("fallback", "m"); }) as typeof fetch }; + config.combos = { strict: { strategy: "failover", quotaOnlyFallback: true, allowMeteredTargets: true, + targets: [{ provider: "anthropic", model: "claude-sonnet-4-5" }, { provider: "backup", model: "m" }] } }; + const response = await handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "combo/strict", input: "fixture", stream: false }), + }), config, { model: "", provider: "" }, { admission: { kind: "loopback", source: "loopback" } }); + const body = await response.text(); + expect(sent[0]).not.toBe("backup"); + if (count === 1) { + expect(response.status, body).toBe(200); + expect(sent.at(-1)).toBe("backup"); + } else { + // The refused account is recorded, and its sibling serves the next request. + expect(response.status, body).toBe(status); + expect(sent).not.toContain("backup"); + } +}); + +test("quota-only stays on the Anthropic pool after a credit refusal while a sibling waits out a rate pause", async () => { + const ids = await seed(2); + const config = configFor(true, () => Response.json({ type: "error", error: { + type: "invalid_request_error", message: "Your credit balance is too low to access the Anthropic API.", + } }, { status: 402 })); + config.providers.anthropic!.baseUrl = "https://api.anthropic.com"; + config.providers.backup = { adapter: "openai-chat", baseUrl: "https://backup.example/v1", apiKey: "fixture", + fetch: (async () => { sent.push("backup"); return chatSuccess("fallback", "m"); }) as typeof fetch }; + config.combos = { strict: { strategy: "failover", quotaOnlyFallback: true, allowMeteredTargets: true, + targets: [{ provider: "anthropic", model: "claude-sonnet-4-5" }, { provider: "backup", model: "m" }] } }; + // The other account is only throttled for a minute and serves again after it. + pauseAnthropicRateAdmission(ids[0]!, Date.now() + MINUTE); + const response = await handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "combo/strict", input: "fixture", stream: false }), + }), config, { model: "", provider: "" }, { admission: { kind: "loopback", source: "loopback" } }); + const body = await response.text(); + expect(response.status, body).toBe(402); + expect(sent).not.toContain("backup"); +}); + test("resets_at is the upstream window reset, and is omitted when any held account's reset is unknown", async () => { const ids = await seed(2); const config = configFor(true); diff --git a/tests/helpers/responses-core-source.ts b/tests/helpers/responses-core-source.ts index 56c5b1aaf3e..02a0a0643e1 100644 --- a/tests/helpers/responses-core-source.ts +++ b/tests/helpers/responses-core-source.ts @@ -94,6 +94,8 @@ export const RESPONSES_CORE_MODULES = [ "spend-storage-error.ts", // Reached from passthrough dispatch: local pacing refusals retain 429 and Retry-After. "pacing-overload.ts", + // Reached from core.ts, the Combo loop and the physical send: Combo admission checked again at the send. + "send-admission.ts", "reset-replay.ts", "passthrough-delivery.ts", // Reached from passthrough-delivery.ts: buffered combo children must honor a required tool_choice (#7456). diff --git a/tests/oauth/generic-oauth-combo-account-cooldown.test.ts b/tests/oauth/generic-oauth-combo-account-cooldown.test.ts index b8ec163c75d..350f6a296ad 100644 --- a/tests/oauth/generic-oauth-combo-account-cooldown.test.ts +++ b/tests/oauth/generic-oauth-combo-account-cooldown.test.ts @@ -11,7 +11,14 @@ import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { clearComboSelectionState, clearComboTargetCooldowns, isComboTargetInCooldown } from "../../src/combos"; -import { clearGenericFailoverHealth, eligibleFailoverAccounts } from "../../src/oauth/generic-account-failover"; +import { clearGenericFailoverHealth, eligibleFailoverAccounts, rotateGenericOAuthAccountOn429 } from "../../src/oauth/generic-account-failover"; +import { + clearGenericAccountQuotaVerdictsForTests, comboAccountExhaustionCanAdvance, recordGenericAccountRefusal, +} from "../../src/server/responses/core-combo-failure"; +import { oauthAccountLogLabel } from "../../src/codex/account-label"; +import { baseProviderLabel } from "../../src/providers/label"; +import { routeConcreteModel } from "../../src/router"; +import { clearAntigravityAccountRosters, recordAntigravityAccountRoster } from "../../src/providers/antigravity-account-roster"; import { genericPoolKey, peekRoundRobinAccount } from "../../src/oauth/pool-kernel"; import { getAccountSet, saveCredential, setActiveAccount } from "../../src/oauth/store"; import { clearAccountQuotaCache } from "../../src/providers/quota"; @@ -41,7 +48,9 @@ async function seed(count: number): Promise { } /** Accounts at or below `spentThrough` answer a one-hour 429; the rest answer 200. */ -function upstream(spentThrough: number): void { +function upstream( + spentThrough: number, error: Record = { message: "synthetic rate limit" }, firstAccountError = error, +): void { globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const url = String(input instanceof Request ? input.url : input); if (url.startsWith("https://fallback.test/")) { @@ -51,7 +60,7 @@ function upstream(spentThrough: number): void { const index = Number(new Headers(init?.headers).get("authorization")?.split("-").pop()); sends.push(String(index)); return index <= spentThrough - ? Response.json({ error: { message: "synthetic rate limit" } }, { status: 429, headers: { "retry-after": "3600" } }) + ? Response.json({ error: index === 1 ? firstAccountError : error }, { status: 429, headers: { "retry-after": "3600" } }) : chatSuccess("pool answer", "m1"); }) as typeof fetch; } @@ -81,6 +90,7 @@ beforeEach(() => { clearComboSelectionState(); clearComboTargetCooldowns(); clearGenericFailoverHealth(); + clearGenericAccountQuotaVerdictsForTests(); clearAccountQuotaCache(); clearResponseStateForTests(); releaseSpendHome = acquireOwnedSpendHome(); @@ -96,6 +106,7 @@ afterEach(async () => { clearGenericFailoverHealth(); clearAccountQuotaCache(); clearResponseStateForTests(); + clearAntigravityAccountRosters(); if (originalHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = originalHome; if (home) removeTreeWithRetry(home); @@ -131,6 +142,110 @@ test("every generic OAuth account spent still cools the combo target", async () expect(isComboTargetInCooldown("pooled", TARGET)).toBe(true); }, 20_000); +for (const accounts of [5, 2]) { + test(`quota-only failover leaves a generic OAuth pool only when no sibling remains (${accounts} accounts)`, async () => { + await seed(accounts); + upstream(4, { code: "insufficient_quota", message: "Account quota exhausted" }); + const quotaOnly: OcxConfig = { ...config, combos: { pooled: { strategy: "failover", quotaOnlyFallback: true, + allowMeteredTargets: true, targets: [TARGET, { provider: "fallback", model: "m2" }] } } }; + const response = await handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "combo/pooled", input: "Answer briefly", stream: false }), + }), quotaOnly, { model: "", provider: "" }, { admission: { kind: "loopback", source: "loopback" } }); + const text = await response.text(); + if (accounts === 5) { + // The request budget ended rotation before the healthy fifth account, which still serves. + expect(response.status).toBe(429); + expect(sends).not.toContain("B"); + } else { + expect(text).toContain("fallback answer"); + expect(sends).toEqual(["1", "2", "B"]); + } + }, 20_000); +} + +test("quota-only failover stays on a generic OAuth pool while a sibling is only rate-limited", async () => { + await seed(2); + upstream(2, { code: "insufficient_quota", message: "Account quota exhausted" }, + { message: "Rate limit reached for requests per minute" }); + const quotaOnly: OcxConfig = { ...config, combos: { pooled: { strategy: "failover", quotaOnlyFallback: true, + allowMeteredTargets: true, targets: [TARGET, { provider: "fallback", model: "m2" }] } } }; + const response = await handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "combo/pooled", input: "Answer briefly", stream: false }), + }), quotaOnly, { model: "", provider: "" }, { admission: { kind: "loopback", source: "loopback" } }); + await response.text(); + // The first account serves again once its rate-limit window passes, so the paid target waits. + expect(response.status).toBe(429); + expect(sends).toEqual(["1", "2"]); +}, 20_000); + +/** Whether a quota-only Combo may leave `provider` after `refused` answered a confirmed exhaustion. */ +function canAdvance(cfg: OcxConfig, provider: string, model: string, refused: string, at: number): boolean { + return comboAccountExhaustionCanAdvance(cfg, routeConcreteModel(cfg, `${provider}/${model}`), new Response(null, { status: 429 }), + oauthAccountLogLabel(refused, baseProviderLabel(provider)), at, undefined); +} + +test("a later rate limit leaves a generic OAuth account's spent-quota verdict to its own deadline", async () => { + await seed(2); + const [spent, refused] = getAccountSet("xai")!.accounts.map(account => account.id); + const now = Date.now(); + // A quota refusal dated one minute, then an ordinary rate limit that cools the account for an hour. + recordGenericAccountRefusal("xai", spent!, "m1", "60", true, now); + rotateGenericOAuthAccountOn429(config, "xai", spent!, "60", now, "m1", false); + recordGenericAccountRefusal("xai", spent!, "m1", "3600", false, now + 1); + rotateGenericOAuthAccountOn429(config, "xai", spent!, "3600", now + 1, "m1", false); + expect(canAdvance(config, "xai", "m1", refused!, now + 2)).toBe(true); + // The verdict ends with its own minute while the later rate limit still cools the account. + expect(canAdvance(config, "xai", "m1", refused!, now + 61_000)).toBe(false); +}); + +test("an Antigravity sibling whose roster omits the model does not hold a quota-only Combo", async () => { + const provider = "google-antigravity"; + const model = "gemini-3.8-flash"; + const cfg = { port: 0, defaultProvider: provider, providers: { [provider]: { + adapter: "google", authMode: "oauth", baseUrl: "https://daily-cloudcode-pa.googleapis.com", + googleMode: "cloud-code-assist", models: [model], oauthAccountFailover: { enabled: true }, + } } } as unknown as OcxConfig; + for (const index of [1, 2]) { + await saveCredential(provider, { + access: `synthetic-antigravity-access-${index}`, refresh: `synthetic-antigravity-refresh-${index}`, + expires: Date.now() + 3_600_000, accountId: `synthetic-antigravity-${index}`, + } as never, { addAccount: true }); + } + const [other, refused] = getAccountSet(provider)!.accounts.map(account => account.id); + recordAntigravityAccountRoster(provider, other!, [{ id: "gemini-other", wireModelId: "gemini-other" } as never]); + recordAntigravityAccountRoster(provider, refused!, [{ id: model, wireModelId: model } as never]); + const now = Date.now(); + // The sibling is only rate-limited, but it cannot serve this model at all. + rotateGenericOAuthAccountOn429(cfg, provider, other!, "3600", now, model, false); + expect(canAdvance(cfg, provider, model, refused!, now + 1)).toBe(true); +}); + +test("a pinned quota-only continuation leaves the target usable while its pool still has an account", async () => { + await seed(5); + upstream(0); + const quotaOnly: OcxConfig = { ...config, combos: { pooled: { strategy: "failover", quotaOnlyFallback: true, + allowMeteredTargets: true, targets: [TARGET, { provider: "fallback", model: "m2" }] } } }; + const send = (input: unknown) => handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json", "thread-id": "pinned-pool" }, + body: JSON.stringify({ model: "combo/pooled", input, stream: false }), + }), quotaOnly, { model: "", provider: "" }, { admission: { kind: "loopback", source: "loopback" } }); + expect(await (await send("Answer briefly")).text()).toContain("pool answer"); + upstream(4, { code: "insufficient_quota", message: "Account quota exhausted" }); + sends = []; + const continuation = await send([ + { type: "message", role: "user", content: [{ type: "input_text", text: "Answer briefly" }] }, + { type: "function_call", call_id: "call_1", name: "lookup", arguments: "{}" }, + { type: "function_call_output", call_id: "call_1", output: "done" }, + ]); + await continuation.text(); + // The request budget ended rotation before the fifth account, which still serves new turns. + expect(continuation.status).toBe(429); + expect(sends).not.toContain("B"); + expect(isComboTargetInCooldown("pooled", TARGET)).toBe(false); +}, 20_000); + test("the combo's sibling check does not advance a round-robin pool onto an unsent account", async () => { await seed(5); upstream(4); diff --git a/tests/oauth/generic-oauth-failover.test.ts b/tests/oauth/generic-oauth-failover.test.ts index c44fed673de..6410beef746 100644 --- a/tests/oauth/generic-oauth-failover.test.ts +++ b/tests/oauth/generic-oauth-failover.test.ts @@ -344,7 +344,8 @@ describe("sidecar on429 wiring", () => { test("budget-withheld attribution proves a cooldown-eligible generic OAuth target", () => { // Kiro and non-Kiro continuation, native passthrough and run-turn have budget-denial branches. // A durable two-account quorum is insufficient because it intentionally ignores cooldowns. - expect(coreSource.match(/hasEligibleGenericOAuthFailoverTarget\(/g)).toHaveLength(4); + // The fifth call decides whether a quota-only Combo may leave a generic OAuth pool. + expect(coreSource.match(/hasEligibleGenericOAuthFailoverTarget\(/g)).toHaveLength(5); // The check must GATE the log, not merely run beside it: every call site wraps // noteAttemptRecoveryWithheld in the eligibility condition. expect(coreSource.match(/hasEligibleGenericOAuthFailoverTarget\([\s\S]*?\)\s*\)\s*noteAttemptRecoveryWithheld/g)).toHaveLength(4); diff --git a/tests/responses/responses-dispatch-receipt.test.ts b/tests/responses/responses-dispatch-receipt.test.ts index 0b10a9aa58e..6e7cad676ee 100644 --- a/tests/responses/responses-dispatch-receipt.test.ts +++ b/tests/responses/responses-dispatch-receipt.test.ts @@ -4,6 +4,9 @@ import { codexWsExchange } from "../../src/server/responses/codex-ws-exchange"; import { CodexWsSession } from "../../src/server/responses/codex-ws-session"; import { prepareCodexWsRequest } from "../../src/server/responses/codex-ws-request"; import { createRequestExecutionBudget } from "../../src/lib/request-execution-budget"; +import { + assertSendAdmission, requireSendAdmission, runWithSendAdmission, withSendAdmissionScope, +} from "../../src/server/responses/send-admission"; import { streamingInit } from "../helpers/ws-upstream-fixtures"; const realWebSocket = globalThis.WebSocket; @@ -41,9 +44,10 @@ test("HTTP local dispatch refusal leaves receipt and physical executor untouched class FakeSocket { static latest: FakeSocket; static onSend: ((data: string) => void) | undefined; + static autoOpen = true; listeners = new Map void>>(); sent: string[] = []; - constructor() { FakeSocket.latest = this; queueMicrotask(() => this.emit("open", {})); } + constructor() { FakeSocket.latest = this; if (FakeSocket.autoOpen) queueMicrotask(() => this.emit("open", {})); } addEventListener(name: string, fn: (event: unknown) => void) { if (!this.listeners.has(name)) this.listeners.set(name, new Set()); this.listeners.get(name)!.add(fn); @@ -54,7 +58,7 @@ class FakeSocket { close() {} } -afterEach(() => { FakeSocket.onSend = undefined; }); +afterEach(() => { FakeSocket.onSend = undefined; FakeSocket.autoOpen = true; }); test("WebSocket receipt refusal before send rejects without fallback", async () => { globalThis.WebSocket = FakeSocket as unknown as typeof WebSocket; @@ -74,6 +78,56 @@ test("WebSocket receipt refusal before send rejects without fallback", async () }); const wsUrl = "https://chatgpt.com/backend-api/codex/responses"; + +test("a WebSocket frame is not sent once the request's Combo admission is withdrawn", async () => { + globalThis.WebSocket = FakeSocket as unknown as typeof WebSocket; + const init = streamingInit(); + const prepared = prepareCodexWsRequest(wsUrl, init)!; + const session = new CodexWsSession("wss://chatgpt.com/backend-api/codex/responses", prepared.headers, false); + let admitted = true, fallbacks = 0, receipts = 0; + try { + expect(session.reserve()).toBe(true); + const result = await runWithSendAdmission(() => admitted ? undefined : new Response("fixture refusal", { status: 403 }), () => { + const exchange = codexWsExchange({ session, url: wsUrl, init, prepared, + sseFallback: (async () => { fallbacks++; return new Response("unexpected"); }) as unknown as typeof fetch, + onPhysicalDispatch: () => { receipts++; }, + }); + // Withdrawn after the exchange started and before its socket opened. + admitted = false; + return exchange; + }); + expect(result.refused).toBe(true); + expect(result.response.status).toBe(403); + expect(FakeSocket.latest.sent).toHaveLength(0); + expect(receipts).toBe(0); + expect(fallbacks).toBe(0); + } finally { session.dispose(); } +}); + +test("an HTTP fallback a socket callback starts still checks the request's Combo admission", async () => { + globalThis.WebSocket = FakeSocket as unknown as typeof WebSocket; + FakeSocket.autoOpen = false; + const init = streamingInit(); + const prepared = prepareCodexWsRequest(wsUrl, init)!; + const session = new CodexWsSession("wss://chatgpt.com/backend-api/codex/responses", prepared.headers, false); + let admitted = true, fallbacks = 0; + // Created outside the request's slot, like a native socket event. + setTimeout(() => { + admitted = false; + FakeSocket.latest.emit("error", {}); + }, 10); + try { + expect(session.reserve()).toBe(true); + const result = await runWithSendAdmission(() => admitted ? undefined : new Response("fixture refusal", { status: 403 }), + () => codexWsExchange({ session, url: wsUrl, init, prepared, + // The fallback's physical send reads the request's admission, as fetch-helpers does. + sseFallback: (async () => { assertSendAdmission(); fallbacks++; return new Response("unexpected"); }) as unknown as typeof fetch, + })); + expect(result.refused).toBe(true); + expect(result.response.status).toBe(403); + expect(fallbacks).toBe(0); + } finally { session.dispose(); } +}); const wsProvider = (physical: typeof fetch) => Object.assign({ adapter: "openai-responses", baseUrl: wsUrl }, { fetch: physical }); test("providerFetch WS send failure shares one receipt with HTTP fallback", async () => { @@ -126,3 +180,29 @@ test("D7: accepted WS receipt remains charged if send and local HTTP admission b expect(overrides).toBe(1); expect(httpSends).toBe(0); expect(receipts).toBe(1); expect(refunds).toBe(0); expect(budget.used).toBe(1); }); + +test("a nested request's check stays in its own slot while the enclosing check still applies to its sends", async () => { + const refusal = (status: number) => new Response(null, { status }); + let enclosingAdmitted = true; + const result = await runWithSendAdmission(() => enclosingAdmitted ? undefined : refusal(403), async () => { + // An auxiliary request names its own check, which refuses its send. + const auxiliary = await withSendAdmissionScope(async () => { + requireSendAdmission(() => refusal(409)); + assertSendAdmission(); + return new Response("sent"); + }); + expect(auxiliary.status).toBe(409); + // The enclosing request still sends under its own check. + expect(() => assertSendAdmission()).not.toThrow(); + enclosingAdmitted = false; + const nested = await withSendAdmissionScope(async () => { + assertSendAdmission(); + return new Response("sent"); + }); + expect(nested.status).toBe(403); + return new Response("enclosing answer"); + }); + // A send refused by the enclosing check refuses the enclosing request too. + expect(result.refused).toBe(true); + expect(result.response.status).toBe(403); +}); diff --git a/tests/responses/responses-fetch-helpers-boundary.test.ts b/tests/responses/responses-fetch-helpers-boundary.test.ts index 222c0f0e750..0b720007146 100644 --- a/tests/responses/responses-fetch-helpers-boundary.test.ts +++ b/tests/responses/responses-fetch-helpers-boundary.test.ts @@ -235,6 +235,8 @@ describe("Responses fetch-helper import boundary", () => { // Opt-in outbound Codex history slimming at the final send. "./history-slim", "./request-compression", + // Combo admission checked again at the send (src/server/responses/send-admission.ts); node: built-ins only. + "./send-admission", "./ws-upstream", ]); }); diff --git a/tests/responses/shadow-intercept-target-lifecycle.test.ts b/tests/responses/shadow-intercept-target-lifecycle.test.ts index 37adc12f12c..084c1f7239a 100644 --- a/tests/responses/shadow-intercept-target-lifecycle.test.ts +++ b/tests/responses/shadow-intercept-target-lifecycle.test.ts @@ -13,6 +13,8 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { handleResponses } from "../../src/server/responses"; import { handleManagementAPI } from "../../src/server/management-api"; +import { ComboModelChangeRefusedError } from "../../src/server/responses/core-errors"; +import { resolveChosenTarget } from "../../src/server/responses/shadow-target-availability"; import { INTERCEPT_TARGET_UNAVAILABLE_CODE, INTERCEPT_TARGET_UNAVAILABLE_STATUS, @@ -23,6 +25,11 @@ import { catalogConvergenceFactory } from "../helpers/catalog-convergence"; import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; import { removeTreeWithRetry } from "../helpers/remove-tree"; +test("a chosen target that collapses to a model-locked Combo keeps the model-change refusal", () => { + expect(() => resolveChosenTarget("combo/locked", () => { throw new ComboModelChangeRefusedError(); })) + .toThrow(ComboModelChangeRefusedError); +}); + const SOURCE = "gpt-5.6-luna"; const TARGET_MODEL = "helper-fast"; const TARGET = `helper/${TARGET_MODEL}`; diff --git a/tests/routing/combo-committed-terminal-cooldown.test.ts b/tests/routing/combo-committed-terminal-cooldown.test.ts index ae17c6262ab..9b848195a6c 100644 --- a/tests/routing/combo-committed-terminal-cooldown.test.ts +++ b/tests/routing/combo-committed-terminal-cooldown.test.ts @@ -226,7 +226,7 @@ describe("committed-terminal combo cooldown", () => { expect(targetKey(pick.target)).toBe(targetKey({ provider: "b", model: "m2" })); }); - test("addFinalRequestLog passes comboTarget, outputCeiling and respects paused turn from child context", async () => { + test.each([false, true])("a committed output ceiling respects quota-only routing (%s)", async quotaOnly => { registerCommittedTerminalCooldownHandler(coolComboTargetForCommittedTerminal); try { const cfg: OcxConfig = { @@ -242,6 +242,8 @@ describe("committed-terminal combo cooldown", () => { combos: { aliasCombo: { strategy: "failover", + quotaOnlyFallback: quotaOnly, + allowMeteredTargets: true, targets: [{ provider: "a", model: "m-alias" }], }, }, @@ -270,6 +272,7 @@ describe("committed-terminal combo cooldown", () => { cfg, pausedParentLog, { + admission: { kind: "loopback", source: "loopback" }, translatorBudget: budget1, setTerminalOutcomeRecorder: recorder => { terminalRecorder = recorder; }, }, @@ -322,6 +325,7 @@ describe("committed-terminal combo cooldown", () => { cfg, unpausedParentLog, { + admission: { kind: "loopback", source: "loopback" }, translatorBudget: budget2, setTerminalOutcomeRecorder: recorder => { unpausedTerminalRecorder = recorder; }, }, @@ -348,7 +352,8 @@ describe("committed-terminal combo cooldown", () => { nativeTerminal!("incomplete"); unpausedTerminalRecorder?.("incomplete"); addFinalRequestLog("ocx-test-unpaused", Date.now(), unpausedParentLog, 200, { terminalStatus: "incomplete" }, () => {}); - expect(isComboTargetInCooldown("aliasCombo", { provider: "a", model: "m-alias" })).toBe(true); + expect(isComboTargetInCooldown("aliasCombo", { provider: "a", model: "m-alias" })).toBe(!quotaOnly); + if (quotaOnly) expect(pickComboTarget(cfg, "aliasCombo")?.target.model).toBe("m-alias"); } finally { registerCommittedTerminalCooldownHandler(undefined); } diff --git a/tests/routing/combo-management-api.test.ts b/tests/routing/combo-management-api.test.ts index ec6fad73d0c..3f4b687983c 100644 --- a/tests/routing/combo-management-api.test.ts +++ b/tests/routing/combo-management-api.test.ts @@ -320,6 +320,25 @@ describe("combo management API", () => { }); }); + test("quota-only and same-model options survive a partial PUT and can be cleared", async () => { + await withTempHome(async () => { + const config = baseConfig({ combos: undefined }); + saveConfig(config); + const targets = [{ provider: "a", model: "m1" }]; + const put = (changes: Record) => comboApi(config, "PUT", "/api/combos", { + id: "quota-route", combo: { targets, ...changes }, + }); + expect((await put({ quotaOnlyFallback: "yes" }))?.status).toBe(400); + expect((await put({ strategy: "round-robin", quotaOnlyFallback: true }))?.status).toBe(400); + const flags = { quotaOnlyFallback: true, preserveFallbackModel: true }; + expect((await responseJson(await put(flags))).combo).toMatchObject(flags); + expect((await responseJson(await put({}))).combo).toMatchObject(flags); + expect((await responseJson(await put({ quotaOnlyFallback: false, preserveFallbackModel: false }))).combo) + .not.toHaveProperty("quotaOnlyFallback"); + expect(config.combos?.["quota-route"]).not.toHaveProperty("preserveFallbackModel"); + }); + }); + test("model notes round-trip across strategies and reject invalid lengths", async () => { await withTempHome(async () => { const config = baseConfig({ combos: undefined }); diff --git a/tests/routing/router-combo-failover-classification.test.ts b/tests/routing/router-combo-failover-classification.test.ts index 3715ea98f67..f638efe77ea 100644 --- a/tests/routing/router-combo-failover-classification.test.ts +++ b/tests/routing/router-combo-failover-classification.test.ts @@ -1892,3 +1892,15 @@ describe("provider moderation refusal: safety-system wording and framed native s } }); }); +test("a quota-only confirmed billing exhaustion hops on 400/422 but never past a hard stop", () => { + const message = JSON.stringify({ error: { code: "project_spend_limit_exceeded", message: "Project spend limit exceeded" } }); + for (const status of [400, 422]) { + const code = "project_spend_limit_exceeded"; + // Ordinary Combos keep the request-validation stop; only the quota-only verdict opens the hop. + expect(comboFailureDecision(status, message, { code })).toBe("stop"); + expect(comboFailureDecision(status, message, { code, confirmedQuotaExhaustion: true })).toBe("hop"); + for (const rootCode of ["cyber_policy", "origin_rejected", "upstream_no_response"]) { + expect(comboFailureDecision(status, message, { code, rootCode, confirmedQuotaExhaustion: true })).toBe("stop"); + } + } +}); diff --git a/tests/server/combo-loopback-metered-consent.test.ts b/tests/server/combo-loopback-metered-consent.test.ts index fe33a368a57..633e025a113 100644 --- a/tests/server/combo-loopback-metered-consent.test.ts +++ b/tests/server/combo-loopback-metered-consent.test.ts @@ -1,4 +1,4 @@ -import { afterEach, beforeEach, expect, test } from "bun:test"; +import { afterEach, beforeEach, expect, mock, spyOn, test } from "bun:test"; import type { OcxConfig, OcxComboStrategy } from "../../src/types"; import { handleResponses } from "../../src/server/responses"; import { handleChatCompletions } from "../../src/server/chat-completions"; @@ -7,12 +7,30 @@ import { handleResponsesCompact } from "../../src/server/responses/compact"; import { admissionMayUseMeteredComboTargets } from "../../src/server/admission-model-scope"; import { resolveApiAuth, type DataPlaneAdmission } from "../../src/server/auth-cors"; import { clearComboTargetCooldowns, coolComboTarget } from "../../src/combos/failover"; -import { clearComboSelectionState } from "../../src/combos/resolve"; +import { clearComboSelectionState, tryPickComboModel } from "../../src/combos/resolve"; +import { comboDestinationQuotaExhausted } from "../../src/router"; +import { linkAdvisorPlanConfig } from "../../src/server/responses/advisor-plan-slot"; import { noteSubagentModelFailure, resetSubagentModelFallbackStateForTests } from "../../src/codex/subagent-model-fallback"; import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; import { createWebsocketHandler } from "../../src/server/index/websocket-handler"; import { tryReserveCodexWebSocket } from "../../src/codex/websocket-registry"; import { buildResponsesWsData, type WsData } from "../../src/server/ws-bridge"; +import { clearCachedProviderQuotas, setCachedProviderQuotaForTests } from "../../src/providers/quota-routing-cache"; +import type { ProviderQuota } from "../../src/providers/quota-types"; +import { capRequestExecutionBudgetSends, CODEX_TEXT_GUARDED_BUDGET_POLICY, createRequestExecutionBudget } from "../../src/lib/request-execution-budget"; +import { saveCodexAccountCredential } from "../../src/codex/account-store"; +import { clearAccountQuota, setAccountQuotaFromParsed } from "../../src/codex/quota"; +import { clearCodexUpstreamHealth, recordCodexUpstreamOutcome } from "../../src/codex/routing"; +import { chatSuccess } from "../helpers/combo-failover-upstream"; +import { clearKeyCooldowns } from "../../src/providers/key-failover"; +import { saveConfig } from "../../src/config"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; +import * as requestPacing from "../../src/providers/request-pacing"; +import * as coreAuth from "../../src/server/responses/core-auth"; +import * as requestPrepare from "../../src/server/responses/request-prepare"; const issued = { id: "issued", name: "issued", key: "ocx_data_" + "a".repeat(40), createdAt: "2026-10-15T00:00:00Z" }; const keyed: DataPlaneAdmission = { kind: "configured", keyId: issued.id, source: "bearer" }; @@ -20,8 +38,26 @@ const local: DataPlaneAdmission = { kind: "loopback", source: "loopback" }; const originalRandom = Math.random; let sent: string[]; let release: () => void; -beforeEach(() => { sent = []; release = acquireOwnedSpendHome(); clearComboSelectionState(); clearComboTargetCooldowns(); }); -afterEach(() => { Math.random = originalRandom; release(); clearComboSelectionState(); clearComboTargetCooldowns(); resetSubagentModelFallbackStateForTests(); }); +let releaseHeldPacing: (() => void) | undefined; +const originalHome = process.env.OPENCODEX_HOME; +let home: string; +// A home per test, so a case that persists its config leaves nothing for the next one. +beforeEach(() => { home = mkdtempSync(join(tmpdir(), "ocx-loopback-consent-")); process.env.OPENCODEX_HOME = home; sent = []; release = acquireOwnedSpendHome(); clearComboSelectionState(); clearComboTargetCooldowns(); clearKeyCooldowns(); }); +afterEach(() => { + releaseHeldPacing?.(); + releaseHeldPacing = undefined; + mock.restore(); + Math.random = originalRandom; + // The lease surfaces a release failure; the home is restored and removed either way. + try { + release(); + } finally { + clearComboSelectionState(); clearComboTargetCooldowns(); clearCachedProviderQuotas(); clearKeyCooldowns(); resetSubagentModelFallbackStateForTests(); + if (originalHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = originalHome; + removeTreeWithRetry(home); + } +}); function config(flag?: boolean, strategy: OcxComboStrategy = "failover"): OcxConfig { const provider = (name: string) => ({ adapter: "openai-chat" as const, baseUrl: `https://${name}.test/v1`, apiKey: "fixture", models: ["m"], fetch: (async () => { sent.push(name); return Response.json({ error: { message: "fixture refusal", type: "invalid_request_error" } }, { status: 400 }); }) as typeof fetch }); @@ -46,6 +82,504 @@ async function post(wire: string, cfg: OcxConfig, admission: DataPlaneAdmission, await response.text(); return response.status; } + +test("quota-only failover returns a transient rate limit without sending to a metered target", async () => { + const cfg = config(true); + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }], + }; + cfg.providers.subscription!.fetch = (async () => { + sent.push("subscription"); + return Response.json({ error: { code: "rate_limit_exceeded", message: "Usage limit reached. Try again shortly." } }, + { status: 429, headers: { "Retry-After": "2" } }); + }) as typeof fetch; + expect(await post("responses", cfg, local)).toBe(429); + expect(sent).toEqual(["subscription"]); +}); + +test("quota-only failover never treats a preexisting transient cooldown as exhausted quota", async () => { + const cfg = config(true); + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }], + }; + coolComboTarget("chain", { provider: "subscription", model: "m" }, { status: 429, code: "rate_limit_exceeded" }); + expect(await post("responses", cfg, local)).toBe(503); + expect(sent).toEqual([]); +}); + +for (const wire of ["responses", "messages"]) { + test(`${wire}: quota-only failover advances on a quota refusal and remembers it across requests`, async () => { + const cfg = config(true); + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }], + }; + cfg.providers.subscription!.fetch = (async () => { + sent.push("subscription"); + return Response.json({ error: { code: "insufficient_quota", message: "Quota exhausted" } }, + { status: 429, headers: { "Retry-After": "30" } }); + }) as typeof fetch; + expect(await post(wire, cfg, local)).toBe(400); + expect(await post(wire, cfg, local)).toBe(400); + expect(sent).toEqual(["subscription", "paid", "paid"]); + }); +} + +// A billing exhaustion code is authoritative on 400 and 422 too; quota-only failover must advance on it. +for (const status of [400, 422]) { + for (const consent of [true, false]) { + test(`quota-only failover ${consent ? "advances past" : "stops at the consent check after"} a ${status} billing exhaustion`, async () => { + const cfg = config(consent); + Object.assign(cfg.providers.subscription!, { authMode: "local", baseUrl: "http://127.0.0.1:19012/v1", allowPrivateNetwork: true }); + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }], + }; + cfg.providers.subscription!.fetch = (async () => { + sent.push("subscription"); + return Response.json({ error: { code: "project_spend_limit_exceeded", message: "Project spend limit exceeded" } }, { status }); + }) as typeof fetch; + expect(await post("responses", cfg, local)).toBe(consent ? 400 : 403); + expect(sent).toEqual(consent ? ["subscription", "paid"] : ["subscription"]); + }); + } +} + +test("replacing a provider credential rechecks its quota before any paid fallback", async () => { + const cfg = config(true); + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }], + }; + cfg.providers.subscription!.fetch = (async (_input, init) => { + const active = new Headers(init?.headers).get("authorization"); + if (active === "Bearer fixture-replacement") { + sent.push("replacement"); + return Response.json({ error: { message: "New credential was used", type: "invalid_request_error" } }, { status: 400 }); + } + sent.push("subscription"); + return Response.json({ error: { code: "insufficient_quota", message: "Quota exhausted" } }, + { status: 429, headers: { "Retry-After": "30" } }); + }) as typeof fetch; + expect(await post("responses", cfg, local)).toBe(400); + const updated = { ...cfg, providers: { ...cfg.providers, + subscription: { ...cfg.providers.subscription!, apiKey: "fixture-replacement" }, + } }; + expect(await post("responses", updated, local)).toBe(400); + expect(sent).toEqual(["subscription", "paid", "replacement"]); +}); + +test("quota-only Codex pool fallback waits until every usable account has exhaustion evidence", async () => { + const cfg = config(true); + cfg.providers.openai = { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward" }; + cfg.providers.paid!.fetch = (async () => { sent.push("paid"); return chatSuccess("fallback", "m"); }) as typeof fetch; + cfg.combos!.chain = { strategy: "failover", quotaOnlyFallback: true, allowMeteredTargets: true, + targets: [{ provider: "openai", model: "gpt-5.6-luna" }, { provider: "paid", model: "m" }] }; + const accounts = ["strict-pool-a", "strict-pool-b"]; + cfg.codexAccounts = accounts.map((id, index) => ({ id, email: `${id}@example.test`, isMain: false, logLabel: `pstrict${index}` })); + cfg.codexPool = { poolOnly: true }; + cfg.activeCodexAccountId = accounts[0]; + for (const id of accounts) saveCodexAccountCredential(id, { + accessToken: "fixture-access", refreshToken: "fixture-refresh", + expiresAt: Date.now() + 300_000, chatgptAccountId: `workspace-${id}`, + }); + try { + const reset = Math.floor((Date.now() + 600_000) / 1000); + setAccountQuotaFromParsed(accounts[0]!, { weeklyPercent: 100, weeklyResetAt: reset }); + recordCodexUpstreamOutcome(cfg, accounts[1]!, 429, { retryAfter: "30" }); + expect(await post("responses", cfg, local)).toBe(401); + expect(sent).toEqual([]); + setAccountQuotaFromParsed(accounts[1]!, { weeklyPercent: 100, weeklyResetAt: reset }); + expect(await post("responses", cfg, local)).toBe(200); + expect(sent).toEqual(["paid"]); + } finally { + for (const id of accounts) clearAccountQuota(id); + clearCodexUpstreamHealth(); + } +}); + +test("quota-only failover honors the same-model constraint even across providers", async () => { + const cfg = config(true); + cfg.providers.paid!.models = ["different"]; + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, preserveFallbackModel: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "different", metered: true }], + }; + cfg.providers.subscription!.fetch = (async () => { + sent.push("subscription"); + return Response.json({ error: { code: "insufficient_quota", message: "Quota exhausted" } }, { status: 429 }); + }) as typeof fetch; + expect(await post("responses", cfg, local)).toBe(409); + expect(await post("responses", cfg, local)).toBe(409); + expect(sent).toEqual(["subscription"]); +}); + +for (const redirected of [false, true]) { + test(`quota-only failover requires consent for a known paid API${redirected ? " reached by redirect" : ""}`, async () => { + const cfg = config(false); + cfg.providers["openai-apikey"] = { ...cfg.providers.paid!, baseUrl: "https://api.openai.com/v1" }; + if (redirected) { + Object.assign(cfg.providers.primary!, { authMode: "local", baseUrl: "http://127.0.0.1:19012/v1", allowPrivateNetwork: true }); + cfg.blockedModelRedirects = { "primary/m": "openai-apikey/m" }; + } + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: redirected ? "primary" : "openai-apikey", model: "m", metered: false }], + }; + const response = await handleResponses(request("responses"), cfg, { provider: "", model: "" }, { admission: local }); + expect(await response.json()).toMatchObject({ error: { code: "combo_metered_consent_required" } }); + expect(response.status).toBe(403); + expect(sent).toEqual([]); + cfg.combos!.chain!.allowMeteredTargets = true; + expect(await post("responses", cfg, keyed)).toBe(403); + expect(sent).toEqual([]); + cfg.apiKeys![0] = { ...issued, allowMeteredComboTargets: true }; + expect(await post("responses", cfg, keyed)).toBe(400); + expect(await post("responses", cfg, local)).toBe(400); + expect(sent).toEqual(["paid", "paid"]); + }); +} + +test("quota-only failover stops before an unmarked custom API key without consent", async () => { + const cfg = config(false); + Object.assign(cfg.providers.subscription!, { authMode: "local", baseUrl: "http://127.0.0.1:19012/v1", allowPrivateNetwork: true }); + cfg.providers.subscription!.fetch = (async () => { + sent.push("subscription"); + return Response.json({ error: { code: "insufficient_quota", message: "Quota exhausted" } }, { status: 429 }); + }) as typeof fetch; + cfg.combos!.chain = { + strategy: "failover", quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: false }], + }; + expect(await post("responses", cfg, local)).toBe(403); + expect(sent).toEqual(["subscription"]); + cfg.combos!.chain!.allowMeteredTargets = true; + expect(await post("responses", cfg, local)).toBe(400); + expect(sent).toEqual(["subscription", "subscription", "paid"]); +}); + +test("quota-only failover respects authentication, quota uncertainty and missing consent", async () => { + const cfg = config(false); + Object.assign(cfg.providers.subscription!, { authMode: "local", baseUrl: "http://127.0.0.1:19012/v1", allowPrivateNetwork: true }); + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }, { provider: "primary", model: "m" }], + }; + for (const [status, code, message] of [ + [401, "invalid_api_key", "Unauthorized"], + [429, "rate_limit_error", "Slow down"], + [429, "insufficient_quota", "Quota exhausted"], + ] as const) { + cfg.providers.subscription!.fetch = (async () => { + sent.push("subscription"); + return Response.json({ error: { code, message } }, { status }); + }) as typeof fetch; + expect(await post("responses", cfg, local)).toBe(code === "insufficient_quota" ? 403 : status); + } + expect(sent).toEqual(["subscription", "subscription", "subscription"]); +}); + +test("quota-only failover can skip fresh exhausted quota before sending but retries stale quota", async () => { + const cfg = config(true); + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }], + }; + setCachedProviderQuotaForTests("subscription", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + expect(await post("responses", cfg, local)).toBe(400); + setCachedProviderQuotaForTests("subscription", { updatedAt: Date.now() - 3_600_000, weeklyPercent: 100 } as ProviderQuota); + expect(await post("responses", cfg, local)).toBe(400); + expect(sent).toEqual(["paid", "subscription"]); +}); + +test("quota-only selection reads the quota of a redirected destination", async () => { + const cfg = config(true); + cfg.blockedModelRedirects = { "subscription/m": "primary/m" }; + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }], + }; + cfg.providers.primary!.fetch = (async () => { sent.push("primary"); return chatSuccess("redirected", "m"); }) as typeof fetch; + setCachedProviderQuotaForTests("subscription", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + expect(await post("responses", cfg, local)).toBe(200); + setCachedProviderQuotaForTests("primary", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + expect(await post("responses", cfg, local)).toBe(400); + expect(sent).toEqual(["primary", "paid"]); +}); + +test("a router-collapsed quota-only Combo reads the quota of a redirected destination", async () => { + const cfg = config(true); + cfg.defaultProvider = "primary"; + cfg.providers.mirror = { ...cfg.providers.subscription!, baseUrl: "https://mirror.test/v1", + fetch: (async () => { sent.push("mirror"); return chatSuccess("mirrored", "m"); }) as typeof fetch }; + cfg.blockedModelRedirects = { "subscription/m": "mirror/m" }; + cfg.combos!.chain = { + ...cfg.combos!.chain!, alias: "chain-model", quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }], + }; + cfg.subagentModelFallback = ["chain-model"]; + setCachedProviderQuotaForTests("subscription", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + noteSubagentModelFailure("primary/m", "429", cfg); + const response = await handleResponses(request("responses", "primary/m", { "x-openai-subagent": "collab_spawn" }), + cfg, { model: "", provider: "" }, { admission: local }); + await response.text(); + expect(sent).toEqual(["mirror"]); +}); + +test("a router-collapsed quota-only Combo skips a Codex pool whose usable accounts are all spent", async () => { + const cfg = config(true); + cfg.defaultProvider = "primary"; + cfg.providers.openai = { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward" }; + cfg.providers.subscription!.fetch = (async () => { sent.push("subscription"); return chatSuccess("fallback", "m"); }) as typeof fetch; + cfg.combos!.chain = { strategy: "failover", alias: "chain-model", quotaOnlyFallback: true, allowMeteredTargets: true, + targets: [{ provider: "openai", model: "gpt-5.6-luna" }, { provider: "subscription", model: "m" }] }; + cfg.subagentModelFallback = ["chain-model"]; + const accounts = ["collapsed-pool-a", "collapsed-pool-b"]; + cfg.codexAccounts = accounts.map((id, index) => ({ id, email: `${id}@example.test`, isMain: false, logLabel: `pcollapsed${index}` })); + cfg.codexPool = { poolOnly: true }; + cfg.activeCodexAccountId = accounts[0]; + for (const id of accounts) saveCodexAccountCredential(id, { + accessToken: "fixture-access", refreshToken: "fixture-refresh", + expiresAt: Date.now() + 300_000, chatgptAccountId: `workspace-${id}`, + }); + try { + const reset = Math.floor((Date.now() + 600_000) / 1000); + for (const id of accounts) setAccountQuotaFromParsed(id, { weeklyPercent: 100, weeklyResetAt: reset }); + noteSubagentModelFailure("primary/m", "429", cfg); + const response = await handleResponses(request("responses", "primary/m", { "x-openai-subagent": "collab_spawn" }), + cfg, { model: "", provider: "" }, { admission: local }); + await response.text(); + expect(sent).toEqual(["subscription"]); + } finally { + for (const id of accounts) clearAccountQuota(id); + clearCodexUpstreamHealth(); + } +}); + +for (const [fallbackModel, allowed] of [["other", false], ["m", true]] as const) { + test(`a router-collapsed quota-only Combo keeps the model lock (${fallbackModel})`, async () => { + const cfg = config(true); + cfg.defaultProvider = "primary"; + cfg.providers.paid!.models = ["m", "other"]; + cfg.providers.paid!.fetch = (async () => { sent.push("paid"); return chatSuccess("paid", fallbackModel); }) as typeof fetch; + cfg.combos!.chain = { + ...cfg.combos!.chain!, alias: "chain-model", quotaOnlyFallback: true, preserveFallbackModel: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: fallbackModel, metered: true }], + }; + cfg.subagentModelFallback = ["chain-model"]; + setCachedProviderQuotaForTests("subscription", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + noteSubagentModelFailure("primary/m", "429", cfg); + const response = await handleResponses(request("responses", "primary/m", { "x-openai-subagent": "collab_spawn" }), + cfg, { model: "", provider: "" }, { admission: local }); + const body = await response.text(); + if (allowed) { + expect(sent).toEqual(["paid"]); + } else { + expect(response.status).toBe(409); + expect(body).toContain("combo_model_change_refused"); + expect(sent).toEqual([]); + } + }); +} + +const sameProviderResolutions = { + "a bare model redirect": (cfg: OcxConfig) => { cfg.blockedModelRedirects = { retired: "m" }; }, + "a model alias": (cfg: OcxConfig) => { cfg.providers.subscription!.modelAliases = { m: "retired" }; }, +}; +for (const [resolution, configure] of Object.entries(sameProviderResolutions)) { + for (const code of ["insufficient_quota", "usage_limit_reached"]) { + test(`quota-only failover remembers ${code} on a target resolved through ${resolution}`, async () => { + const cfg = config(true); + configure(cfg); + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "retired" }, { provider: "paid", model: "m", metered: true }], + }; + const sentModels: string[] = []; + cfg.providers.subscription!.fetch = (async (_url: string | URL | Request, init?: RequestInit) => { + sent.push("subscription"); + sentModels.push((JSON.parse(String(init?.body)) as { model: string }).model); + return Response.json({ error: { code, message: "Quota exhausted" } }, { status: 429, headers: { "Retry-After": "30" } }); + }) as typeof fetch; + expect(await post("responses", cfg, local)).toBe(400); + expect(await post("responses", cfg, local)).toBe(400); + expect(sentModels).toEqual(["m"]); + expect(sent).toEqual(["subscription", "paid", "paid"]); + }); + } +} + +test("a router-collapsed Combo rechecks paid consent on the live config before it sends", async () => { + const live = config(false); + live.defaultProvider = "primary"; + live.combos!.chain = { + ...live.combos!.chain!, alias: "chain-model", quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }], + }; + live.subagentModelFallback = ["chain-model"]; + const view = linkAdvisorPlanConfig(live, { ...live, combos: { chain: { ...live.combos!.chain!, allowMeteredTargets: true } } }); + setCachedProviderQuotaForTests("subscription", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + noteSubagentModelFailure("primary/m", "429", view); + const response = await handleResponses(request("responses", "primary/m", { "x-openai-subagent": "collab_spawn" }), + view, { model: "", provider: "" }, { admission: local }); + expect(await response.json()).toMatchObject({ error: { code: "combo_metered_consent_required" } }); + expect(sent).toEqual([]); +}); + +test("a router-collapsed Combo rechecks the key's live model scope before it sends", async () => { + const live = config(true); + live.defaultProvider = "primary"; + live.combos!.chain = { + ...live.combos!.chain!, alias: "chain-model", quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }], + }; + live.subagentModelFallback = ["chain-model"]; + live.apiKeys = [{ ...issued, allowMeteredComboTargets: true, allowedProviders: ["primary", "subscription"] }]; + const view = linkAdvisorPlanConfig(live, { ...live, apiKeys: [{ ...issued, allowMeteredComboTargets: true }] }); + setCachedProviderQuotaForTests("subscription", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + noteSubagentModelFailure("primary/m", "429", view); + const response = await handleResponses(request("responses", "primary/m", { "x-openai-subagent": "collab_spawn" }), + view, { model: "", provider: "" }, { admission: keyed }); + expect(response.status).toBe(403); + expect(await response.json()).toMatchObject({ error: { type: "model_not_allowed_for_key" } }); + expect(sent).toEqual([]); +}); + +test("a quota-only Combo with no usable target names its redirected destination's spent quota", () => { + const cfg = config(true); + cfg.providers.mirror = { ...cfg.providers.subscription!, baseUrl: "https://mirror.test/v1" }; + cfg.blockedModelRedirects = { "subscription/m": "mirror/m" }; + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }], + }; + setCachedProviderQuotaForTests("mirror", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + setCachedProviderQuotaForTests("paid", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + expect(() => tryPickComboModel(cfg, "combo/chain", true, (target, now) => comboDestinationQuotaExhausted(cfg, target, now))) + .toThrow(/target 1 \([^)]*\): quota exhausted/); +}); + +for (const exhaustedPrimary of [false, true]) { + test(`a router-collapsed quota-only Combo answers the consent refusal when a paid target stops it${exhaustedPrimary ? " after an exhausted primary" : ""}`, async () => { + const cfg = config(false); + cfg.defaultProvider = "primary"; + cfg.combos!.chain = { + ...cfg.combos!.chain!, alias: "chain-model", quotaOnlyFallback: true, + targets: exhaustedPrimary + ? [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }] + : [{ provider: "paid", model: "m" }], + }; + cfg.subagentModelFallback = ["chain-model"]; + if (exhaustedPrimary) setCachedProviderQuotaForTests("subscription", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + noteSubagentModelFailure("primary/m", "429", cfg); + const response = await handleResponses(request("responses", "primary/m", { "x-openai-subagent": "collab_spawn" }), + cfg, { model: "", provider: "" }, { admission: local }); + expect(response.status).toBe(403); + expect(await response.json()).toMatchObject({ error: { code: "combo_metered_consent_required" } }); + expect(sent).toEqual([]); + }); +} + +test("quota-only failover remembers exhaustion on a target with a one-entry key pool", async () => { + const cfg = config(true); + cfg.providers.subscription!.apiKeyPool = [{ id: "only", key: "fixture" }]; + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }], + }; + cfg.providers.subscription!.fetch = (async () => { + sent.push("subscription"); + return Response.json({ error: { code: "insufficient_quota", message: "Quota exhausted" } }, { status: 429, headers: { "Retry-After": "30" } }); + }) as typeof fetch; + expect(await post("responses", cfg, local)).toBe(400); + expect(await post("responses", cfg, local)).toBe(400); + expect(sent).toEqual(["subscription", "paid", "paid"]); +}); + +const routeEdits = { + "send path": (cfg: OcxConfig) => { cfg.providers.subscription!.chatCompletionsPath = "/v2/chat/completions"; }, + "redirected model's adapter": (cfg: OcxConfig) => { cfg.providers.subscription!.modelAdapters = { m: "openai-responses" }; }, + "Vertex project": (cfg: OcxConfig) => { cfg.providers.subscription!.project = "project-b"; }, + "Vertex location": (cfg: OcxConfig) => { cfg.providers.subscription!.location = "europe-west4"; }, +}; +for (const [edit, apply] of Object.entries(routeEdits)) { + test(`quota-only failover retries a remembered exhausted target once its ${edit} changes`, async () => { + const cfg = config(true); + cfg.blockedModelRedirects = { retired: "m" }; + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "retired" }, { provider: "paid", model: "m", metered: true }], + }; + cfg.providers.subscription!.fetch = (async () => { + sent.push("subscription"); + return Response.json({ error: { code: "insufficient_quota", message: "Quota exhausted" } }, { status: 429, headers: { "Retry-After": "30" } }); + }) as typeof fetch; + expect(await post("responses", cfg, local)).toBe(400); + expect(await post("responses", cfg, local)).toBe(400); + apply(cfg); + expect(await post("responses", cfg, local)).toBe(400); + expect(sent).toEqual(["subscription", "paid", "paid", "subscription", "paid"]); + }); +} + +for (const [status, code] of [[400, "insufficient_quota"], [422, "usage_limit_exceeded"], [503, "usage_limit_exceeded"]] as const) { + test(`quota-only failover advances on a structured exhaustion code with HTTP ${status}`, async () => { + const cfg = config(true); + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }], + }; + cfg.providers.subscription!.fetch = (async () => { + sent.push("subscription"); + return Response.json({ error: { code, message: "Account quota exhausted" } }, { status }); + }) as typeof fetch; + expect(await post("responses", cfg, local)).toBe(400); + expect(sent.at(-1)).toBe("paid"); + }); +} + +test("quota-only failover stops on validation prose that only mentions quota", async () => { + const cfg = config(true); + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }], + }; + cfg.providers.subscription!.fetch = (async () => { + sent.push("subscription"); + return Response.json({ error: { message: "You exceeded your current quota", type: "invalid_request_error" } }, { status: 400 }); + }) as typeof fetch; + expect(await post("responses", cfg, local)).toBe(400); + expect(sent).toEqual(["subscription"]); +}); + +for (const restraint of ["send budget", "cancellation", "scoped provider policy"] as const) { + test(`quota-only failover cannot bypass ${restraint}`, async () => { + const cfg = config(true); + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }], + }; + if (restraint === "scoped provider policy") cfg.fallback = { routes: { "combo/chain": { provider: false } } }; + const abort = new AbortController(); + cfg.providers.subscription!.fetch = (async () => { + sent.push("subscription"); + if (restraint === "cancellation") abort.abort(); + return Response.json({ error: { code: "insufficient_quota", message: "Quota exhausted" } }, { status: 429 }); + }) as typeof fetch; + const response = await handleResponses(request("responses"), cfg, { provider: "", model: "" }, { + admission: local, abortSignal: abort.signal, + ...(restraint === "send budget" ? { + sendBudget: capRequestExecutionBudgetSends(createRequestExecutionBudget(CODEX_TEXT_GUARDED_BUDGET_POLICY), 1), + } : {}), + }); + expect(response.status).toBe(restraint === "cancellation" ? 499 : 429); + await response.text(); + expect(sent).toEqual(["subscription"]); + }); +} + for (const wire of ["responses", "chat", "messages", "compact"]) { test(`${wire}: local operator opt-in permits metered targets, default and spoofed consent deny`, async () => { expect(await post(wire, config(), local, spoof)).toBe(503); @@ -148,3 +682,343 @@ test("WebSocket frames retain local or keyed consent and reject spoofed consent" await websocket(cfg, keyed); expect(sent).toEqual(["paid"]); }); + +/** + * Holds the second send of `provider` at its pacing wait until `release` runs, so a test changes the config + * while that send is known to wait. `entered` resolves once the send is held there. + */ +function secondPacingWait(provider: string): { entered: Promise; release: () => void } { + const wait = requestPacing.waitForProviderRequestSlot; + let calls = 0; + let release!: () => void; + const released = new Promise(resolve => { release = resolve; }); + releaseHeldPacing = release; + const entered = new Promise(resolve => { + spyOn(requestPacing, "waitForProviderRequestSlot").mockImplementation(async (...args) => { + if (args[0] === provider && ++calls === 2) { + resolve(); + await released; + } + return wait(...args); + }); + }); + return { entered, release }; +} + +/** Resolves once the held pacing wait is reached, and fails when the pending request settles first. */ +async function pacingStarted(paced: { entered: Promise }, waiting: Promise): Promise { + const first = await Promise.race([paced.entered.then(() => undefined), waiting]); + if (first) throw new Error(`request settled before pacing: ${first.status}`); +} + +const rateLimited = { message: "Rate limit reached for requests per minute" }; +for (const [label, firstKeyError, advances] of [ + ["every key proves spent quota", { code: "insufficient_quota", message: "Quota exhausted" }, true], + ["one key is only rate-limited", rateLimited, false], +] as const) { + test(`quota-only failover leaves a key pool only when ${label}`, async () => { + const cfg = config(true); + cfg.providers.subscription!.apiKey = "key-one"; + cfg.providers.subscription!.apiKeyPool = [{ id: "one", key: "key-one" }, { id: "two", key: "key-two" }]; + cfg.combos!.chain = { + ...cfg.combos!.chain!, quotaOnlyFallback: true, + targets: [{ provider: "subscription", model: "m" }, { provider: "paid", model: "m", metered: true }], + }; + cfg.providers.subscription!.fetch = (async (_url: string | URL | Request, init?: RequestInit) => { + const keyLabels: Record = { "Bearer key-one": "one", "Bearer key-two": "two" }; + const key = keyLabels[new Headers(init?.headers).get("authorization") ?? ""] ?? "unexpected"; + sent.push(key); + if (key === "unexpected") { + return Response.json({ error: { message: "unexpected credential", type: "invalid_request_error" } }, { status: 400 }); + } + const error = key === "one" ? firstKeyError : { code: "insufficient_quota", message: "Quota exhausted" }; + return Response.json({ error }, { status: 429 }); + }) as typeof fetch; + // Key rotation commits the next key to the persisted row, so the pool has to exist on disk. + saveConfig(cfg); + await post("responses", cfg, local); + expect(sent).toEqual(advances ? ["one", "two", "paid"] : ["one", "two"]); + }); +} + +for (const collapsed of [false, true]) { + test(`a ${collapsed ? "router-collapsed " : ""}quota-only paid send rechecks consent after it waited for pacing`, async () => { + const cfg = config(true); + cfg.defaultProvider = "primary"; + cfg.combos!.chain = { ...cfg.combos!.chain!, alias: "chain-model", quotaOnlyFallback: true, targets: [{ provider: "paid", model: "m" }] }; + cfg.subagentModelFallback = ["chain-model"]; + cfg.providers.paid!.requestPacing = { enabled: true, minIntervalMs: 1_500 }; + const send = () => collapsed + ? handleResponses(request("responses", "primary/m", { "x-openai-subagent": "collab_spawn" }), cfg, { model: "", provider: "" }, { admission: local }) + : handleResponses(request("responses"), cfg, { model: "", provider: "" }, { admission: local }); + if (collapsed) noteSubagentModelFailure("primary/m", "429", cfg); + const pacedSend = secondPacingWait("paid"); + await (await send()).text(); + const waiting = send(); + await pacingStarted(pacedSend, waiting); + cfg.combos!.chain!.allowMeteredTargets = false; + pacedSend.release(); + const refused = await waiting; + expect(refused.status).toBe(403); + expect(await refused.json()).toMatchObject({ error: { code: "combo_metered_consent_required" } }); + expect(sent).toEqual(["paid"]); + }); +} + +for (const collapsed of [false, true]) { + test(`a ${collapsed ? "router-collapsed " : ""}quota-only paid send rechecks the key's live model scope after it waited for pacing`, async () => { + const cfg = config(true); + cfg.defaultProvider = "primary"; + cfg.combos!.chain = { ...cfg.combos!.chain!, alias: "chain-model", quotaOnlyFallback: true, targets: [{ provider: "paid", model: "m" }] }; + cfg.subagentModelFallback = ["chain-model"]; + cfg.apiKeys = [{ ...issued, allowMeteredComboTargets: true }]; + cfg.providers.paid!.requestPacing = { enabled: true, minIntervalMs: 1_500 }; + const send = () => collapsed + ? handleResponses(request("responses", "primary/m", { "x-openai-subagent": "collab_spawn" }), cfg, { model: "", provider: "" }, { admission: keyed }) + : handleResponses(request("responses"), cfg, { model: "", provider: "" }, { admission: keyed }); + if (collapsed) noteSubagentModelFailure("primary/m", "429", cfg); + const pacedSend = secondPacingWait("paid"); + await (await send()).text(); + const waiting = send(); + await pacingStarted(pacedSend, waiting); + cfg.apiKeys = [{ ...issued, allowMeteredComboTargets: true, allowedProviders: ["primary"] }]; + pacedSend.release(); + const refused = await waiting; + expect(refused.status).toBe(403); + expect(await refused.json()).toMatchObject({ error: { type: "model_not_allowed_for_key" } }); + expect(sent).toEqual(["paid"]); + }); +} + +test("a Combo child rechecks the key's live scope against the model it sends after a pacing wait", async () => { + const cfg = config(true); + cfg.providers["openai-apikey"] = { + adapter: "openai-responses", baseUrl: "https://api.openai.com/v1", authMode: "key", apiKey: "fixture-key", + models: ["gpt-5.6-sol-pro", "gpt-5.6-sol"], requestPacing: { enabled: true, minIntervalMs: 1_500 }, + fetch: (async () => { + sent.push("openai-apikey"); + return Response.json({ error: { message: "fixture refusal", type: "invalid_request_error" } }, { status: 400 }); + }) as typeof fetch, + }; + cfg.combos!.chain = { ...cfg.combos!.chain!, quotaOnlyFallback: true, targets: [{ provider: "openai-apikey", model: "gpt-5.6-sol-pro" }] }; + cfg.apiKeys = [{ ...issued, allowMeteredComboTargets: true }]; + const send = () => handleResponses(request("responses"), cfg, { model: "", provider: "" }, { admission: keyed }); + const pacedSend = secondPacingWait("openai-apikey"); + await (await send()).text(); + const waiting = send(); + await pacingStarted(pacedSend, waiting); + // The public virtual model stays allowed, but the wire model it sends does not. + cfg.apiKeys = [{ ...issued, allowMeteredComboTargets: true, allowedModels: ["openai-apikey/gpt-5.6-sol-pro"] }]; + pacedSend.release(); + const refused = await waiting; + expect(refused.status).toBe(403); + expect(await refused.json()).toMatchObject({ error: { type: "model_not_allowed_for_key" } }); + expect(sent).toEqual(["openai-apikey"]); +}); + +for (const wire of ["responses", "chat"] as const) { + test(`a Combo child refuses a configured key removed while its send waited for pacing${wire === "chat" ? " on the native Chat path" : ""}`, async () => { + const cfg = config(true); + // An unmarked target of an ordinary Combo needs no paid consent, so only the key itself admits the send. + cfg.combos!.chain = { strategy: "failover", targets: [{ provider: "subscription", model: "m" }] }; + cfg.apiKeys = [issued]; + cfg.providers.subscription!.requestPacing = { enabled: true, minIntervalMs: 1_500 }; + // The Chat variant sends each eligible candidate natively, outside request preparation. + if (wire === "chat") cfg.protocols = { rollout: { nativeChatCombos: true } }; + const send = () => wire === "chat" + ? handleChatCompletions(request("chat"), cfg, { model: "", provider: "" }, { requestId: "consent-test", start: Date.now(), admission: keyed }) + : handleResponses(request("responses"), cfg, { model: "", provider: "" }, { admission: keyed }); + const pacedSend = secondPacingWait("subscription"); + await (await send()).text(); + const waiting = send(); + await pacingStarted(pacedSend, waiting); + cfg.apiKeys = []; + pacedSend.release(); + const refused = await waiting; + expect(refused.status).toBe(403); + expect(JSON.stringify(await refused.json())).toMatch(/model_not_allowed_for_key|not allowed for this API key/); + expect(sent).toEqual(["subscription"]); + }); +} + +for (const [change, apply] of [ + ["a target marked paid", (cfg: OcxConfig) => { cfg.combos!.chain!.targets[0]!.metered = true; }], + ["a quota-only rule turned on", (cfg: OcxConfig) => { cfg.combos!.chain!.quotaOnlyFallback = true; }], +] as const) for (const collapsed of [false, true]) { + test(`a ${collapsed ? "router-collapsed send" : "Combo child"} rechecks ${change} while it waited for pacing`, async () => { + const cfg = config(false); + cfg.defaultProvider = "primary"; + // An unmarked paid API target of an ordinary Combo needs consent only once it is marked paid or the + // quota-only rule applies. + cfg.combos!.chain = { strategy: "failover", alias: "chain-model", targets: [{ provider: "paid", model: "m" }] }; + cfg.subagentModelFallback = ["chain-model"]; + cfg.providers.paid!.requestPacing = { enabled: true, minIntervalMs: 1_500 }; + const send = () => collapsed + ? handleResponses(request("responses", "primary/m", { "x-openai-subagent": "collab_spawn" }), cfg, { model: "", provider: "" }, { admission: local }) + : handleResponses(request("responses"), cfg, { model: "", provider: "" }, { admission: local }); + if (collapsed) noteSubagentModelFailure("primary/m", "429", cfg); + const pacedSend = secondPacingWait("paid"); + await (await send()).text(); + const waiting = send(); + await pacingStarted(pacedSend, waiting); + apply(cfg); + pacedSend.release(); + const refused = await waiting; + expect(refused.status).toBe(403); + expect(await refused.json()).toMatchObject({ error: { code: "combo_metered_consent_required" } }); + expect(sent).toEqual(["paid"]); + }); +} + +test("a Combo child refuses a configured key removed while its credentials were being resolved", async () => { + const cfg = config(true); + cfg.combos!.chain = { strategy: "failover", targets: [{ provider: "subscription", model: "m" }] }; + cfg.apiKeys = [issued]; + const resolveAuth = coreAuth.resolveResponsesCodexAuth; + spyOn(coreAuth, "resolveResponsesCodexAuth").mockImplementation(async (...args) => { + // Removed after the request was admitted, while preparation awaits its credentials. + cfg.apiKeys = []; + return resolveAuth(...args); + }); + const response = await handleResponses(request("responses"), cfg, { model: "", provider: "" }, { admission: keyed }); + expect(response.status).toBe(403); + expect(await response.json()).toMatchObject({ error: { type: "model_not_allowed_for_key" } }); + expect(sent).toEqual([]); +}); + +test("a router-collapsed quota-only send keeps its consent rule when the Combo is deleted during the pacing wait", async () => { + const cfg = config(true); + cfg.defaultProvider = "primary"; + // An unmarked paid API target needs consent only under the quota-only rule. + cfg.combos!.chain = { ...cfg.combos!.chain!, alias: "chain-model", quotaOnlyFallback: true, targets: [{ provider: "paid", model: "m" }] }; + cfg.subagentModelFallback = ["chain-model"]; + cfg.providers.paid!.requestPacing = { enabled: true, minIntervalMs: 1_500 }; + const send = () => handleResponses(request("responses", "primary/m", { "x-openai-subagent": "collab_spawn" }), + cfg, { model: "", provider: "" }, { admission: local }); + noteSubagentModelFailure("primary/m", "429", cfg); + const pacedSend = secondPacingWait("paid"); + await (await send()).text(); + const waiting = send(); + await pacingStarted(pacedSend, waiting); + // Deleting the Combo also removes the loopback consent it carried. + delete cfg.combos!.chain; + pacedSend.release(); + const refused = await waiting; + expect(refused.status).toBe(403); + expect(await refused.json()).toMatchObject({ error: { code: "combo_metered_consent_required" } }); + expect(sent).toEqual(["paid"]); +}); + +for (const collapsed of [false, true]) { + test(`a ${collapsed ? "router-collapsed send" : "Combo child"} of a quota-only Combo reclassifies its redirected destination from the live provider`, async () => { + // Consent stays withheld throughout, so only the destination's live class changes the outcome. + const cfg = config(false); + cfg.defaultProvider = "primary"; + const loopbackRow = (name: string) => ({ adapter: "openai-chat" as const, authMode: "local" as const, baseUrl: "http://127.0.0.1:9/v1", + allowPrivateNetwork: true, models: ["m"], + fetch: (async () => { sent.push(name); return Response.json({ error: { message: "fixture refusal", type: "invalid_request_error" } }, { status: 400 }); }) as typeof fetch }); + cfg.providers.selector = loopbackRow("selector"); + cfg.providers.mirror = { ...loopbackRow("mirror"), requestPacing: { enabled: true, minIntervalMs: 1_500 } }; + cfg.blockedModelRedirects = { "selector/m": "mirror/m" }; + cfg.combos!.chain = { strategy: "failover", alias: "chain-model", quotaOnlyFallback: true, + targets: [{ provider: "selector", model: "m" }] }; + cfg.subagentModelFallback = ["chain-model"]; + const send = () => collapsed + ? handleResponses(request("responses", "primary/m", { "x-openai-subagent": "collab_spawn" }), cfg, { model: "", provider: "" }, { admission: local }) + : handleResponses(request("responses"), cfg, { model: "", provider: "" }, { admission: local }); + if (collapsed) noteSubagentModelFailure("primary/m", "429", cfg); + const pacedSend = secondPacingWait("mirror"); + // The explicit loopback local destination sends without paid-call consent. + await (await send()).text(); + const waiting = send(); + await pacingStarted(pacedSend, waiting); + // The redirect destination becomes a paid API row while the send waits. + cfg.providers.mirror = { ...cfg.providers.mirror!, authMode: "key", baseUrl: "https://mirror.example/v1", apiKey: "fixture" }; + pacedSend.release(); + const refused = await waiting; + expect(refused.status).toBe(403); + expect(await refused.json()).toMatchObject({ error: { code: "combo_metered_consent_required" } }); + expect(sent).toEqual(["mirror"]); + }); +} + +test("a quota-only Combo with no target left names the quota of a redirected destination", async () => { + const cfg = config(true); + cfg.combos!.chain = { ...cfg.combos!.chain!, quotaOnlyFallback: true, targets: [{ provider: "subscription", model: "m" }] }; + cfg.blockedModelRedirects = { "subscription/m": "primary/m" }; + setCachedProviderQuotaForTests("primary", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + const response = await handleResponses(request("responses"), cfg, { model: "", provider: "" }, { admission: local }); + expect(response.status).toBe(503); + expect(await response.json()).toMatchObject({ error: { code: "combo_unavailable", combo: { cause: "quota" } } }); + expect(sent).toEqual([]); +}); + +test("a Combo child that settles on a paid destination the parent never saw needs paid-call consent", async () => { + const cfg = config(false); + const loopbackRow = (name: string) => ({ adapter: "openai-chat" as const, authMode: "local" as const, baseUrl: "http://127.0.0.1:9/v1", + allowPrivateNetwork: true, models: ["m"], + fetch: (async () => { sent.push(name); return Response.json({ error: { message: "fixture refusal", type: "invalid_request_error" } }, { status: 400 }); }) as typeof fetch }); + cfg.providers.selector = loopbackRow("selector"); + cfg.providers.mirror = loopbackRow("mirror"); + cfg.blockedModelRedirects = { "selector/m": "mirror/m" }; + cfg.combos!.chain = { strategy: "failover", quotaOnlyFallback: true, targets: [{ provider: "selector", model: "m" }] }; + const prepare = requestPrepare.prepareResponsesRequest; + spyOn(requestPrepare, "prepareResponsesRequest").mockImplementation(async (...args) => { + if (!args[0].options.comboAttempt) return prepare(...args); + // The child resolves its route while the redirect points at the paid API, then the redirect is restored. + cfg.blockedModelRedirects = { "selector/m": "paid/m" }; + try { + return await prepare(...args); + } finally { + cfg.blockedModelRedirects = { "selector/m": "mirror/m" }; + } + }); + const refused = await handleResponses(request("responses"), cfg, { model: "", provider: "" }, { admission: local }); + expect(refused.status).toBe(403); + expect(await refused.json()).toMatchObject({ error: { code: "combo_metered_consent_required" } }); + expect(sent).toEqual([]); +}); + +test("a router-collapsed send keeps the quota-only rule it was selected under when the Combo changes during credential resolution", async () => { + const cfg = config(true); + cfg.defaultProvider = "primary"; + cfg.combos!.chain = { ...cfg.combos!.chain!, alias: "chain-model", quotaOnlyFallback: true, targets: [{ provider: "paid", model: "m" }] }; + cfg.subagentModelFallback = ["chain-model"]; + noteSubagentModelFailure("primary/m", "429", cfg); + const resolveAuth = coreAuth.resolveResponsesCodexAuth; + spyOn(coreAuth, "resolveResponsesCodexAuth").mockImplementation(async (...args) => { + // Both changed after the pick was selected, while preparation awaits its credentials. + cfg.combos!.chain!.quotaOnlyFallback = false; + cfg.combos!.chain!.allowMeteredTargets = false; + return resolveAuth(...args); + }); + const response = await handleResponses(request("responses", "primary/m", { "x-openai-subagent": "collab_spawn" }), + cfg, { model: "", provider: "" }, { admission: local }); + expect(response.status).toBe(403); + expect(await response.json()).toMatchObject({ error: { code: "combo_metered_consent_required" } }); + expect(sent).toEqual([]); +}); + +test("a router-collapsed send keeps the consent its prepared paid destination needs when the live row becomes local", async () => { + const cfg = config(true); + cfg.defaultProvider = "primary"; + cfg.combos!.chain = { ...cfg.combos!.chain!, alias: "chain-model", quotaOnlyFallback: true, targets: [{ provider: "paid", model: "m" }] }; + cfg.subagentModelFallback = ["chain-model"]; + cfg.providers.paid!.requestPacing = { enabled: true, minIntervalMs: 1_500 }; + const send = () => handleResponses(request("responses", "primary/m", { "x-openai-subagent": "collab_spawn" }), + cfg, { model: "", provider: "" }, { admission: local }); + noteSubagentModelFailure("primary/m", "429", cfg); + const pacedSend = secondPacingWait("paid"); + await (await send()).text(); + const waiting = send(); + await pacingStarted(pacedSend, waiting); + // The live row becomes a local route and the caller loses paid-call consent while the send waits. + // A transport that keeps the prepared row would still send to the paid API. + cfg.providers.paid = { ...cfg.providers.paid!, authMode: "local", baseUrl: "http://127.0.0.1:9/v1", allowPrivateNetwork: true }; + cfg.combos!.chain!.allowMeteredTargets = false; + pacedSend.release(); + const refused = await waiting; + expect(refused.status).toBe(403); + expect(await refused.json()).toMatchObject({ error: { code: "combo_metered_consent_required" } }); + expect(sent).toEqual(["paid"]); +}); diff --git a/tests/server/server-combo-cooldown-recording.test.ts b/tests/server/server-combo-cooldown-recording.test.ts index c56214036bb..1dc7eff8ceb 100644 --- a/tests/server/server-combo-cooldown-recording.test.ts +++ b/tests/server/server-combo-cooldown-recording.test.ts @@ -26,6 +26,7 @@ import { isCodexAccountCooldownResponse } from "../../src/codex/account-cooldown import { consumeComboFailure } from "../../src/server/responses/core-combo-failure"; import { mapCodexAuthContextErrorToResponse } from "../../src/server/responses/codex-auth-error"; import { finalizeAccountLease } from "../../src/server/responses/core-lifetime"; +import { isProxyQuotaExhaustion } from "../../src/lib/client-error-body"; /** The Responses mapping every combo child's local auth refusal goes through. */ function localRefusal(error: CodexAccountCooldownError, now: number): Response { @@ -277,6 +278,9 @@ for (const policy of [ } const consumed = await consumeComboFailure(response, undefined, now); expect(isCodexAccountCooldownResponse(consumed.response)).toBe(false); + expect(isProxyQuotaExhaustion(consumed.response)).toBe( + error instanceof CodexMainAccountCreditsOffError || error instanceof CodexPoolAccountCreditsOffError, + ); expect(consumed.retryAfter).toBe(reserve ? undefined : "84692"); if (error instanceof CodexMainAccountHardLockError) expect(consumed.upstreamCode).toBe("usage_limit_reached"); await consumed.response.text(); diff --git a/tests/server/server-combo-tool-loop-continuation.test.ts b/tests/server/server-combo-tool-loop-continuation.test.ts index ebfbaf4cced..73b67d09574 100644 --- a/tests/server/server-combo-tool-loop-continuation.test.ts +++ b/tests/server/server-combo-tool-loop-continuation.test.ts @@ -7,12 +7,14 @@ * acceptable: a plaintext reasoning placeholder on the DeepSeek Responses and Chat wires, * an intact tool_use/tool_result pair with no fabricated thinking for Anthropic. */ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, mock, spyOn, test } from "bun:test"; import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { clearComboSelectionState, clearComboTargetCooldowns } from "../../src/combos"; import { clearKeyCooldowns } from "../../src/providers/key-failover"; +import { clearCachedProviderQuotas, setCachedProviderQuotaForTests } from "../../src/providers/quota-routing-cache"; +import type { ProviderQuota } from "../../src/providers/quota-types"; import { clearReasoningReplayCacheForTests } from "../../src/responses/reasoning-replay-cache"; import { clearResponseStateForTests, @@ -20,13 +22,28 @@ import { responseStatePersistPendingForTests, } from "../../src/responses/state"; import { handleResponses } from "../../src/server/responses"; +import { handleClaudeMessages } from "../../src/server/claude-messages"; import { clearComboRecallForTests } from "../../src/server/responses/combo-session-recall"; -import { COMBO_TOOL_LOOP_PIN_REASON, isToolLoopContinuation } from "../../src/server/responses/combo-tool-loop-pin"; +import { + COMBO_TOOL_LOOP_PIN_REASON, comboToolLoopLane, comboToolLoopRouteIdentity, isToolLoopContinuation, +} from "../../src/server/responses/combo-tool-loop-pin"; +import { rememberComboForLane } from "../../src/server/responses/combo-session-recall"; +import { captureConfigGeneration } from "../../src/lib/state-store-sweeper"; +import { saveConfig } from "../../src/config"; +import type { RouteResult } from "../../src/router"; import type { RequestLogContext } from "../../src/server/request-log"; import type { OcxConfig, OcxProviderConfig } from "../../src/types"; import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; import { acquireOwnedSpendHome } from "../helpers/owned-spend-home"; import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { noteSubagentModelFailure, resetSubagentModelFallbackStateForTests } from "../../src/codex/subagent-model-fallback"; +import * as requestPacing from "../../src/providers/request-pacing"; +import * as coreAuth from "../../src/server/responses/core-auth"; +import * as requestPrepare from "../../src/server/responses/request-prepare"; +import { handleManagementAPI } from "../../src/server/management-api"; +import { setLiveStateStoreConfig } from "../../src/lib/state-store-registrations"; +import { catalogConvergenceFactory } from "../helpers/catalog-convergence"; +import { ManagementRequest } from "../helpers/management-auth"; type Item = Record; @@ -35,13 +52,16 @@ let previousHome: string | undefined; let isolatedCodexHome: IsolatedCodexHome | null = null; const servers: Array> = []; let releaseSpendHome: (() => void) | undefined; +let releaseHeldPacing: (() => void) | undefined; function resetState(): void { clearComboSelectionState(); clearComboRecallForTests(); clearComboTargetCooldowns(); clearKeyCooldowns(); + clearCachedProviderQuotas(); clearReasoningReplayCacheForTests(); + resetSubagentModelFallbackStateForTests(); } beforeEach(() => { @@ -55,6 +75,9 @@ beforeEach(() => { }); afterEach(async () => { + releaseHeldPacing?.(); + releaseHeldPacing = undefined; + mock.restore(); releaseSpendHome?.(); releaseSpendHome = undefined; let responseStatePending = true; @@ -154,7 +177,115 @@ async function post(config: OcxConfig, input: unknown, headers: Record void; +} = {}) { + const { alias = "auto-model", firstModel = "home/m0" } = setup; + const sent: string[] = []; + const home = serve(() => { sent.push("home"); return Response.json(responsesBody("m0", [answer("wrong target")])); }); + const primary = serve(() => { sent.push("primary"); return Response.json(responsesBody("m1", [answer("wrong target")])); }); + const backup = serve(async request => { + sent.push("backup"); + const body = await request.json() as { input: Item[] }; + return Response.json(responsesBody("m2", [ + body.input.at(-1)?.type === "function_call_output" ? answer("Rain today.") : issuedCall, + ])); + }); + const cfg = combo({ + home: provider("openai-responses", baseUrl(home)), + primary: provider("openai-responses", baseUrl(primary)), + backup: provider("openai-responses", baseUrl(backup)), + }, [{ provider: "primary", model: "m1" }, { provider: "backup", model: "m2" }], + { quotaOnlyFallback: true, allowMeteredTargets: true, alias }); + cfg.subagentModelFallback = [alias]; + noteSubagentModelFailure(firstModel, "429", cfg); + const subagent = (input: unknown, model = "home/m0") => handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", + headers: { "content-type": "application/json", "x-openai-subagent": "collab_spawn", "thread-id": lane }, + body: JSON.stringify({ model, input, tools, stream: false, store: false }), + }), cfg, { model: "", provider: "" }, { admission: { kind: "loopback", source: "loopback" } }); + setup.beforeFirstTurn?.(cfg); + setCachedProviderQuotaForTests("primary", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + expect(await (await subagent([userMessage("weather?")], firstModel)).text()).toContain("get_weather"); + clearCachedProviderQuotas(); + return { cfg, sent, subagent }; +} + +/** A quota-only Combo whose only target, backup/m2, issues a tool call and answers its result. */ +function singleTargetQuotaOnlyCombo() { + const sent: string[] = []; + const backup = serve(async request => { + sent.push("backup"); + const body = await request.json() as { input: Item[] }; + return Response.json(responsesBody("m2", [ + body.input.at(-1)?.type === "function_call_output" ? answer("Rain today.") : issuedCall, + ])); + }); + const cfg = combo({ backup: provider("openai-responses", baseUrl(backup)) }, [{ provider: "backup", model: "m2" }], + { quotaOnlyFallback: true, allowMeteredTargets: true }); + return { cfg, sent }; +} + +/** + * Redirects backup/m2 to another provider only while a Combo child prepares, so the child settles on that + * provider while the parent and the send-time checks see backup/m2 again. + */ +function redirectWhileChildPrepares(cfg: OcxConfig, to: string): void { + const prepare = requestPrepare.prepareResponsesRequest; + spyOn(requestPrepare, "prepareResponsesRequest").mockImplementation(async (...args) => { + if (!args[0].options.comboAttempt) return prepare(...args); + cfg.blockedModelRedirects = { "backup/m2": to }; + try { + return await prepare(...args); + } finally { + delete cfg.blockedModelRedirects; + } + }); +} + +/** + * Holds every pacing wait of `provider` until `release` runs. `held` resolves once a send waits there, + * and fails when the pending request settles first. + */ +function holdPacingWaits(provider: string) { + let release!: () => void; + const released = new Promise(resolve => { release = resolve; }); + releaseHeldPacing = release; + let reached!: () => void; + const entered = new Promise(resolve => { reached = resolve; }); + const wait = requestPacing.waitForProviderRequestSlot; + spyOn(requestPacing, "waitForProviderRequestSlot").mockImplementation(async (...args) => { + if (args[0] === provider) { + reached(); + await released; + } + return wait(...args); + }); + const held = async (waiting: Promise): Promise => { + const first = await Promise.race([entered.then(() => undefined), waiting]); + if (first) throw new Error(`request settled before pacing: ${first.status}`); + }; + return { held, release }; +} + +/** Deletes a Combo through `DELETE /api/combos`, which reconciles live state as on a running server. */ +async function deleteComboThroughManagement(cfg: OcxConfig, id: string): Promise { + const url = `http://localhost/api/combos?id=${id}`; + const deleted = await handleManagementAPI(new ManagementRequest(url, { method: "DELETE" }), new URL(url), cfg, { + createManagementConvergeCodex: catalogConvergenceFactory(), + }); + expect(deleted?.status).toBe(200); } describe("isToolLoopContinuation", () => { @@ -165,6 +296,24 @@ describe("isToolLoopContinuation", () => { expect(isToolLoopContinuation({ input: "hello" })).toBe(false); expect(isToolLoopContinuation({ messages: [{ role: "user", content: "x" }, { role: "tool", content: "y" }] })).toBe(true); }); + + test("developer items after the tool results still resume the turn", () => { + const developer = { type: "message", role: "developer", content: [{ type: "input_text", text: "context" }] }; + expect(isToolLoopContinuation({ input: [...bareContinuation, developer, developer] })).toBe(true); + expect(isToolLoopContinuation({ input: [userMessage("hi"), developer] })).toBe(false); + expect(isToolLoopContinuation({ input: [developer] })).toBe(false); + expect(isToolLoopContinuation({ messages: [{ role: "tool", content: "y" }, { role: "developer", content: "z" }] })).toBe(true); + }); + + test("the pinned route identity follows the Codex account and account mode the route resolves to", () => { + const route = { providerName: "openai", modelId: "gpt-5", provider: { adapter: "openai-responses", baseUrl: "https://api.example/v1" } } as RouteResult; + expect(comboToolLoopRouteIdentity({ ...route, codexAccountId: "account-a" })) + .toBe(comboToolLoopRouteIdentity({ ...route, codexAccountId: "account-a" })); + expect(comboToolLoopRouteIdentity({ ...route, codexAccountId: "account-a" })) + .not.toBe(comboToolLoopRouteIdentity({ ...route, codexAccountId: "account-b" })); + expect(comboToolLoopRouteIdentity({ ...route, codexAccountMode: "direct" })) + .not.toBe(comboToolLoopRouteIdentity({ ...route, codexAccountMode: "pool" })); + }); }); describe("combo tool-loop continuation safety (#7298)", () => { @@ -262,6 +411,818 @@ describe("combo tool-loop continuation safety (#7298)", () => { expect(deepseekHits).toBe(1); }); + test("quota-only failover keeps a tool continuation on its serving target after the primary recovers", async () => { + let primaryExhausted = true; + let backupExhausted = false; + const sent: string[] = []; + const exhausted = () => Response.json({ + error: { code: "insufficient_quota", message: "Quota exhausted" }, + }, { status: 429 }); + const primary = serve(() => { + sent.push("primary"); + return primaryExhausted ? exhausted() : Response.json(responsesBody("m1", [answer("wrong target")])); + }); + const backup = serve(async request => { + sent.push("backup"); + const body = await request.json() as { input: Item[] }; + return backupExhausted ? exhausted() : Response.json(responsesBody("m2", [ + body.input.at(-1)?.type === "function_call_output" ? answer("Rain today.") : issuedCall, + ])); + }); + const config = combo({ + primary: provider("openai-responses", baseUrl(primary)), + backup: provider("openai-responses", baseUrl(backup)), + }, [{ provider: "primary", model: "m1" }, { provider: "backup", model: "m2" }], { quotaOnlyFallback: true, allowMeteredTargets: true }); + const lane = { "thread-id": "quota-tool-continuation" }; + expect(await (await post(config, [userMessage("weather?")], lane)).text()).toContain("get_weather"); + primaryExhausted = false; + clearComboTargetCooldowns("auto"); + expect(await (await post(config, bareContinuation, lane)).text()).toContain("Rain today."); + backupExhausted = true; + const stopped = await post(config, bareContinuation, lane); + expect(stopped.status).toBe(429); + await stopped.text(); + const retried = await post(config, bareContinuation, lane); + expect(retried.status).toBe(429); + expect(await retried.json()).toMatchObject({ error: { code: "combo_tool_target_quota_exhausted" } }); + expect(sent).toEqual(["primary", "backup", "backup", "backup"]); + }); + + test("a quota-only continuation without its serving lane makes no upstream send", async () => { + const sent: string[] = []; + const primary = serve(() => { + sent.push("primary"); + return Response.json(responsesBody("m1", [issuedCall])); + }); + const backup = serve(() => { + sent.push("backup"); + return Response.json(responsesBody("m2", [answer("Wrong turn")])); + }); + const cfg = combo({ + primary: provider("openai-responses", baseUrl(primary)), + backup: provider("openai-responses", baseUrl(backup)), + }, [{ provider: "primary", model: "m1" }, { provider: "backup", model: "m2" }], + { quotaOnlyFallback: true, allowMeteredTargets: true }); + expect(await (await post(cfg, [userMessage("weather?")], { "thread-id": "lost-lane" })).text()).toContain("get_weather"); + const result = await post(cfg, bareContinuation); + expect(result.status).toBe(409); + expect(await result.json()).toMatchObject({ error: { code: "combo_tool_target_unavailable" } }); + const redirected = { ...cfg, blockedModelRedirects: { "primary/m1": "backup/m2" } }; + const rerouted = await post(redirected, bareContinuation, { "thread-id": "lost-lane" }); + expect(rerouted.status).toBe(409); + await rerouted.text(); + expect(sent).toEqual(["primary"]); + }); + + for (const [label, backupProvider] of [ + ["", (url: string) => provider("openai-responses", url)], + [" through a per-model adapter", (url: string) => provider("openai-chat", url, { modelAdapters: { m2: "openai-responses" } })], + ] as const) test(`a router-collapsed quota-only continuation stays on the target that issued the call${label}`, async () => { + const sent: string[] = []; + const home = serve(() => { + sent.push("home"); + return Response.json(responsesBody("m0", [answer("wrong target")])); + }); + const primary = serve(() => { + sent.push("primary"); + return Response.json(responsesBody("m1", [answer("wrong target")])); + }); + const backup = serve(async request => { + sent.push("backup"); + const body = await request.json() as { input: Item[] }; + return Response.json(responsesBody("m2", [ + body.input.at(-1)?.type === "function_call_output" ? answer("Rain today.") : issuedCall, + ])); + }); + const cfg = combo({ + home: provider("openai-responses", baseUrl(home)), + primary: provider("openai-responses", baseUrl(primary)), + backup: backupProvider(baseUrl(backup)), + }, [{ provider: "primary", model: "m1" }, { provider: "backup", model: "m2" }], + { quotaOnlyFallback: true, allowMeteredTargets: true, alias: "auto-model" }); + cfg.subagentModelFallback = ["auto-model"]; + noteSubagentModelFailure("home/m0", "429", cfg); + const subagent = (input: unknown, lane: string) => handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", + headers: { "content-type": "application/json", "x-openai-subagent": "collab_spawn", "thread-id": lane }, + body: JSON.stringify({ model: "home/m0", input, tools, stream: false, store: false }), + }), cfg, { model: "", provider: "" }, { admission: { kind: "loopback", source: "loopback" } }); + + setCachedProviderQuotaForTests("primary", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + expect(await (await subagent([userMessage("weather?")], "collapsed-lane")).text()).toContain("get_weather"); + clearCachedProviderQuotas(); + expect(await (await subagent(bareContinuation, "collapsed-lane")).text()).toContain("Rain today."); + const lost = await subagent(bareContinuation, "unknown-lane"); + expect(lost.status).toBe(409); + expect(await lost.json()).toMatchObject({ error: { code: "combo_tool_target_unavailable" } }); + expect(sent).toEqual(["backup", "backup"]); + }); + + for (const [label, change] of [ + ["an earlier target is disabled", (cfg: OcxConfig) => { cfg.providers.primary!.disabled = true; }], + ["the model lock is on", (cfg: OcxConfig) => { cfg.combos!.auto!.preserveFallbackModel = true; }], + ] as const) test(`a router-collapsed quota-only continuation reaches the target that issued the call when ${label}`, async () => { + const { cfg, sent, subagent } = await collapsedSubagentTurn(`collapsed-${label}`); + change(cfg); + const resumed = await subagent(bareContinuation); + expect(await resumed.text()).toContain("Rain today."); + expect(sent).toEqual(["backup", "backup"]); + }); + + test("a pinned subagent continuation passes the scoped fallback policy of the subagent rewrite", async () => { + const { cfg, sent, subagent } = await collapsedSubagentTurn("pinned-policy"); + cfg.providers.primary!.disabled = true; + // The operator now forbids provider hops away from the subagent's own model. + cfg.fallback = { routes: { "home/m0": { provider: false } } }; + const refused = await subagent(bareContinuation); + expect(await refused.json()).toMatchObject({ error: { code: "fallback_refused" } }); + expect(sent).toEqual(["backup"]); + }); + + test("a pinned subagent continuation refuses once its serving target is disabled, even after the subagent model recovers", async () => { + const { cfg, sent, subagent } = await collapsedSubagentTurn("pinned-disabled"); + resetSubagentModelFallbackStateForTests(); + cfg.providers.backup!.disabled = true; + for (const attempt of ["first", "retry"]) { + const refused = await subagent(bareContinuation); + expect(refused.status, attempt).toBe(409); + expect(await refused.json()).toMatchObject({ error: { code: "combo_tool_target_unavailable" } }); + } + expect(sent).toEqual(["backup"]); + }); + + test("a pinned subagent continuation refuses when its serving row changes while the send waits for pacing", async () => { + const { cfg, sent, subagent } = await collapsedSubagentTurn("pinned-row-change"); + const elsewhere = serve(() => { sent.push("elsewhere"); return Response.json(responsesBody("m2", [answer("wrong endpoint")])); }); + const pacing = holdPacingWaits("backup"); + const waiting = subagent(bareContinuation); + await pacing.held(waiting); + // Same provider name, model, scope and consent, but a different endpoint. + cfg.providers.backup = { ...cfg.providers.backup!, baseUrl: baseUrl(elsewhere) }; + pacing.release(); + const refused = await waiting; + expect(refused.status).toBe(409); + expect(await refused.json()).toMatchObject({ error: { code: "combo_tool_target_unavailable" } }); + expect(sent).toEqual(["backup"]); + }); + + test("a quota-only continuation refuses when its serving row changes while the Combo child waits for pacing", async () => { + const { cfg, sent } = singleTargetQuotaOnlyCombo(); + const elsewhere = serve(() => { sent.push("elsewhere"); return Response.json(responsesBody("m2", [answer("wrong endpoint")])); }); + const lane = { "thread-id": "child-row-change" }; + expect(await (await post(cfg, [userMessage("weather?")], lane)).text()).toContain("get_weather"); + const pacing = holdPacingWaits("backup"); + const waiting = post(cfg, bareContinuation, lane); + await pacing.held(waiting); + // Same provider name, model, scope and consent, but a different endpoint. + cfg.providers.backup = { ...cfg.providers.backup!, baseUrl: baseUrl(elsewhere) }; + pacing.release(); + const refused = await waiting; + expect(refused.status).toBe(409); + expect(await refused.json()).toMatchObject({ error: { code: "combo_tool_target_unavailable" } }); + expect(sent).toEqual(["backup"]); + }); + + test("a quota-only continuation refuses when its Combo child settled on another provider", async () => { + const { cfg, sent } = singleTargetQuotaOnlyCombo(); + const elsewhere = serve(() => { sent.push("elsewhere"); return Response.json(responsesBody("m2", [answer("wrong endpoint")])); }); + cfg.providers.elsewhere = provider("openai-responses", baseUrl(elsewhere)); + const lane = { "thread-id": "child-row-aba" }; + expect(await (await post(cfg, [userMessage("weather?")], lane)).text()).toContain("get_weather"); + redirectWhileChildPrepares(cfg, "elsewhere/m2"); + const refused = await post(cfg, bareContinuation, lane); + expect(refused.status).toBe(409); + expect(await refused.json()).toMatchObject({ error: { code: "combo_tool_target_unavailable" } }); + expect(sent).toEqual(["backup"]); + }); + + test("a quota-only turn whose Combo child sent to another provider records it, so its continuation is refused", async () => { + const { cfg, sent } = singleTargetQuotaOnlyCombo(); + const elsewhere = serve(() => { sent.push("elsewhere"); return Response.json(responsesBody("m2", [issuedCall])); }); + cfg.providers.elsewhere = provider("openai-responses", baseUrl(elsewhere)); + const lane = { "thread-id": "turn-row-aba" }; + redirectWhileChildPrepares(cfg, "elsewhere/m2"); + expect(await (await post(cfg, [userMessage("weather?")], lane)).text()).toContain("get_weather"); + mock.restore(); + // backup/m2 resolves to the target that did not issue the call. + const refused = await post(cfg, bareContinuation, lane); + expect(refused.status).toBe(409); + expect(await refused.json()).toMatchObject({ error: { code: "combo_tool_target_unavailable" } }); + expect(sent).toEqual(["elsewhere"]); + }); + + test("a quota-only continuation through an unchanged virtual model target resumes on it", async () => { + const sent: string[] = []; + // The built-in OpenAI API row keeps its canonical endpoint, so its fetch stands in for the upstream. + const virtualRow = provider("openai-responses", "https://api.openai.com/v1", { + fetch: (async (_url: string | URL | Request, init?: RequestInit) => { + const body = JSON.parse(String(init?.body)) as { input: Item[]; model: string }; + sent.push(body.model); + return Response.json(responsesBody(body.model, [ + body.input.at(-1)?.type === "function_call_output" ? answer("Rain today.") : issuedCall, + ])); + }) as typeof fetch, + }); + const cfg = combo({ "openai-apikey": virtualRow }, + [{ provider: "openai-apikey", model: "gpt-5.6-sol-pro" }], { quotaOnlyFallback: true, allowMeteredTargets: true }); + const lane = { "thread-id": "virtual-model-loop" }; + expect(await (await post(cfg, [userMessage("weather?")], lane)).text()).toContain("get_weather"); + expect(await (await post(cfg, bareContinuation, lane)).text()).toContain("Rain today."); + expect(sent).toHaveLength(2); + }); + + for (const [label, to, refused] of [ + ["another model", "elsewhere/m3", true], + ["the same model on another provider", "elsewhere/m2", false], + ] as const) test(`the model lock checks a Combo child that settles on ${label}`, async () => { + const { cfg, sent } = singleTargetQuotaOnlyCombo(); + const elsewhere = serve(async request => { + const body = await request.json() as { model: string }; + sent.push(`elsewhere ${body.model}`); + return Response.json(responsesBody(body.model, [answer("Rain today.")])); + }); + cfg.providers.elsewhere = provider("openai-responses", baseUrl(elsewhere)); + cfg.combos!.auto!.preserveFallbackModel = true; + redirectWhileChildPrepares(cfg, to); + const response = await post(cfg, [userMessage("weather?")], { "thread-id": `child-model-${label}` }); + if (refused) { + expect(response.status).toBe(409); + expect(await response.json()).toMatchObject({ error: { code: "combo_model_change_refused" } }); + expect(sent).toEqual([]); + } else { + expect(await response.text()).toContain("Rain today."); + expect(sent).toEqual(["elsewhere m2"]); + } + }); + + test("a quota refusal from a Combo child that settled on another provider does not cool the planned target", async () => { + const { cfg, sent } = singleTargetQuotaOnlyCombo(); + const exhausted = serve(() => { + sent.push("elsewhere"); + return Response.json({ error: { code: "insufficient_quota", message: "Quota exhausted" } }, { status: 429 }); + }); + cfg.providers.elsewhere = provider("openai-responses", baseUrl(exhausted)); + redirectWhileChildPrepares(cfg, "elsewhere/m2"); + const refused = await post(cfg, [userMessage("weather?")], { "thread-id": "redirected-quota" }); + expect(refused.status).toBe(429); + await refused.text(); + mock.restore(); + // backup/m2 itself never refused, so the next turn still reaches it. + expect(await (await post(cfg, [userMessage("weather?")], { "thread-id": "after-redirected-quota" })).text()).toContain("get_weather"); + expect(sent).toEqual(["elsewhere", "backup"]); + }); + + for (const [label, change] of [ + ["its target leaves the Combo", (cfg: OcxConfig) => { cfg.combos!.auto!.targets = [{ provider: "other", model: "m9" }]; }], + ["its Combo is deleted", (cfg: OcxConfig) => { delete cfg.combos!.auto; }], + ] as const) { + test(`a pinned continuation in the Combo loop refuses when ${label} while it waits for pacing`, async () => { + const { cfg, sent } = singleTargetQuotaOnlyCombo(); + const lane = { "thread-id": `combo-membership-${label}` }; + expect(await (await post(cfg, [userMessage("weather?")], lane)).text()).toContain("get_weather"); + const pacing = holdPacingWaits("backup"); + const waiting = post(cfg, bareContinuation, lane); + await pacing.held(waiting); + change(cfg); + pacing.release(); + const refused = await waiting; + expect(refused.status).toBe(409); + expect(await refused.json()).toMatchObject({ error: { code: "combo_tool_target_unavailable" } }); + expect(sent).toEqual(["backup"]); + }); + + test(`a pinned subagent continuation refuses when ${label} while it waits for pacing`, async () => { + const { cfg, sent, subagent } = await collapsedSubagentTurn(`collapsed-membership-${label}`); + const pacing = holdPacingWaits("backup"); + const waiting = subagent(bareContinuation); + await pacing.held(waiting); + change(cfg); + pacing.release(); + const refused = await waiting; + expect(refused.status).toBe(409); + expect(await refused.json()).toMatchObject({ error: { code: "combo_tool_target_unavailable" } }); + expect(sent).toEqual(["backup"]); + }); + } + + for (const [label, redirected] of [["an unchanged route", false], ["a redirect to another model", true]] as const) { + test(`the model lock keeps a collapsed turn's serving model after the quota-only rule is turned off (${label})`, async () => { + const { cfg, sent } = await collapsedSubagentTurn(`collapsed-lock-${label}`); + const elsewhere = serve(() => { sent.push("elsewhere"); return Response.json(responsesBody("m3", [answer("wrong model")])); }); + cfg.providers.elsewhere = provider("openai-responses", baseUrl(elsewhere)); + cfg.combos!.auto!.quotaOnlyFallback = false; + cfg.combos!.auto!.preserveFallbackModel = true; + if (redirected) cfg.blockedModelRedirects = { "backup/m2": "elsewhere/m3" }; + const resumed = await post(cfg, bareContinuation, { "thread-id": `collapsed-lock-${label}` }); + if (redirected) { + expect(resumed.status).toBe(409); + expect(await resumed.json()).toMatchObject({ error: { code: "combo_model_change_refused" } }); + expect(sent).toEqual(["backup"]); + } else { + expect(await resumed.text()).toContain("Rain today."); + expect(sent).toEqual(["backup", "backup"]); + } + }); + } + + test("a quota-only turn records its pin when an unrelated Combo is deleted while it is in flight", async () => { + const { cfg, sent } = singleTargetQuotaOnlyCombo(); + cfg.combos!.other = { strategy: "failover", targets: [{ provider: "backup", model: "m9" }] }; + setLiveStateStoreConfig(cfg); + const lane = { "thread-id": "unrelated-delete" }; + const pacing = holdPacingWaits("backup"); + const firstTurn = post(cfg, [userMessage("weather?")], lane); + await pacing.held(firstTurn); + await deleteComboThroughManagement(cfg, "other"); + pacing.release(); + expect(await (await firstTurn).text()).toContain("get_weather"); + expect(await (await post(cfg, bareContinuation, lane)).text()).toContain("Rain today."); + expect(sent).toEqual(["backup", "backup"]); + }); + + test("a pinned subagent continuation stays refused after the management API deletes its Combo", async () => { + const { cfg, sent, subagent } = await collapsedSubagentTurn("pinned-managed-delete"); + // The deletion reconciles live state, as on a running server. + setLiveStateStoreConfig(cfg); + await deleteComboThroughManagement(cfg, "auto"); + resetSubagentModelFallbackStateForTests(); + for (const attempt of ["first", "retry"]) { + const refused = await subagent(bareContinuation); + expect(refused.status, attempt).toBe(409); + expect(await refused.json()).toMatchObject({ error: { code: "combo_tool_target_unavailable" } }); + } + expect(sent).toEqual(["backup"]); + }); + + test("a pinned subagent retry stays refused after a recreated Combo refuses a direct continuation", async () => { + const { cfg, sent, subagent } = await collapsedSubagentTurn("recreated-combo"); + setLiveStateStoreConfig(cfg); + const auto = cfg.combos!.auto!; + await deleteComboThroughManagement(cfg, "auto"); + // Recreated under the same ID, with the quota-only rule on. + cfg.combos = { ...cfg.combos, auto }; + const direct = await post(cfg, bareContinuation, { "thread-id": "recreated-combo" }); + expect(direct.status).toBe(409); + await direct.text(); + resetSubagentModelFallbackStateForTests(); + const retried = await subagent(bareContinuation); + expect(retried.status).toBe(409); + expect(await retried.json()).toMatchObject({ error: { code: "combo_tool_target_unavailable" } }); + expect(sent).toEqual(["backup"]); + }); + + test("an exact-account subagent continuation on a quota-only lane refuses once its fallback chain is cleared", async () => { + const sent: string[] = []; + const backup = serve(() => { sent.push("backup"); return Response.json(responsesBody("m2", [answer("wrong target")])); }); + const cfg = { + port: 0, + defaultProvider: "openai", + activeCodexAccountId: "pool-a", + providers: { + openai: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward", codexAccountMode: "pool" }, + backup: provider("openai-responses", baseUrl(backup)), + }, + codexAccounts: [ + { id: "main", email: "main@example.test", isMain: true }, + { id: "pool-a", email: "pool@example.test", isMain: false, chatgptAccountId: "pool_acc" }, + ], + codexAccountNamespaces: { team: "pool-a" }, + combos: { auto: { strategy: "failover", alias: "auto-model", quotaOnlyFallback: true, allowMeteredTargets: true, + targets: [{ provider: "backup", model: "m2" }] } }, + } as OcxConfig; + const headers = { "content-type": "application/json", "x-openai-subagent": "collab_spawn", "thread-id": "exact-account-lane" }; + // An earlier turn on this lane fell back to the quota-only Combo, and the fallback chain was cleared since. + rememberComboForLane(comboToolLoopLane(new Headers(headers), true), "auto", { provider: "backup", model: "m2" }, "m2", + captureConfigGeneration(), undefined, "recorded-route"); + const response = await handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", + headers, + body: JSON.stringify({ model: "team/gpt-5.6-sol", input: bareContinuation, tools, stream: false, store: false }), + }), cfg, { model: "", provider: "" }, { admission: { kind: "loopback", source: "loopback" } }); + expect(response.status).toBe(409); + expect(await response.json()).toMatchObject({ error: { code: "combo_tool_target_unavailable" } }); + expect(sent).toEqual([]); + }); + + test("a refused direct continuation keeps the lane, so a pinned subagent retry is refused too", async () => { + const { cfg, sent, subagent } = await collapsedSubagentTurn("refused-direct-keeps-lane"); + cfg.providers.backup!.disabled = true; + const direct = await post(cfg, bareContinuation, { "thread-id": "refused-direct-keeps-lane" }); + expect(direct.status).toBe(409); + await direct.text(); + resetSubagentModelFallbackStateForTests(); + const retried = await subagent(bareContinuation); + expect(retried.status).toBe(409); + expect(await retried.json()).toMatchObject({ error: { code: "combo_tool_target_unavailable" } }); + expect(sent).toEqual(["backup"]); + }); + + for (const [label, change] of [ + ["its Combo is deleted", (cfg: OcxConfig) => { delete cfg.combos!.auto; }], + ["its Combo leaves the fallback chain and the subagent model recovers", (cfg: OcxConfig) => { + cfg.subagentModelFallback = ["primary/m1"]; + resetSubagentModelFallbackStateForTests(); + }], + ["the fallback chain is cleared and the subagent model recovers", (cfg: OcxConfig) => { + cfg.subagentModelFallback = []; + resetSubagentModelFallbackStateForTests(); + }], + ] as const) test(`a pinned subagent continuation refuses once ${label}`, async () => { + const { cfg, sent, subagent } = await collapsedSubagentTurn(`pinned-${label}`); + change(cfg); + const refused = await subagent(bareContinuation); + expect(refused.status).toBe(409); + expect(await refused.json()).toMatchObject({ error: { code: "combo_tool_target_unavailable" } }); + expect(sent).toEqual(["backup"]); + }); + + test("a quota-only continuation whose serving target lost paid-call consent is refused for consent", async () => { + const { cfg, sent } = singleTargetQuotaOnlyCombo(); + const lane = { "thread-id": "withdrawn-consent" }; + expect(await (await post(cfg, [userMessage("weather?")], lane)).text()).toContain("get_weather"); + cfg.combos!.auto!.allowMeteredTargets = false; + const refused = await post(cfg, bareContinuation, lane); + expect(refused.status).toBe(403); + expect(await refused.json()).toMatchObject({ error: { code: "combo_metered_consent_required" } }); + expect(sent).toEqual(["backup"]); + }); + + test("a pinned subagent continuation whose serving target lost paid-call consent is refused for consent", async () => { + const { cfg, sent, subagent } = await collapsedSubagentTurn("pinned-consent"); + cfg.combos!.auto!.allowMeteredTargets = false; + const refused = await subagent(bareContinuation); + expect(refused.status).toBe(403); + expect(await refused.json()).toMatchObject({ error: { code: "combo_metered_consent_required" } }); + expect(sent).toEqual(["backup"]); + }); + + test("a pinned subagent continuation reaches its Combo when the Combo alias is the requested model's bare name", async () => { + // The turn fell back from another subagent model, then its continuation requests home/m0. + const { sent, subagent } = await collapsedSubagentTurn("pinned-alias", { alias: "m0", firstModel: "home/m9" }); + const resumed = await subagent(bareContinuation); + expect(await resumed.text()).toContain("Rain today."); + expect(sent).toEqual(["backup", "backup"]); + }); + + test("a router-collapsed quota-only turn records its serving target when the Combo's flag is cleared during the turn", async () => { + const resolveAuth = coreAuth.resolveResponsesCodexAuth; + const { cfg, sent, subagent } = await collapsedSubagentTurn("admitted-quota-only", { + // Cleared after the pick was selected, while preparation awaits its credentials. + beforeFirstTurn: turnConfig => spyOn(coreAuth, "resolveResponsesCodexAuth").mockImplementationOnce(async (...args) => { + turnConfig.combos!.auto!.quotaOnlyFallback = false; + return resolveAuth(...args); + }), + }); + cfg.combos!.auto!.quotaOnlyFallback = true; + const resumed = await subagent(bareContinuation); + expect(await resumed.text()).toContain("Rain today."); + expect(sent).toEqual(["backup", "backup"]); + }); + + test("Claude Code resumes a quota-only tool turn using its Messages session header", async () => { + let attempts = 0; + const upstream = serve(async request => { + attempts++; + const body = await request.json() as { input: Item[] }; + return Response.json(responsesBody("m1", [ + body.input.at(-1)?.type === "function_call_output" ? answer("Rain today.") : issuedCall, + ])); + }); + const cfg = combo({ primary: provider("openai-responses", baseUrl(upstream)) }, [{ provider: "primary", model: "m1" }], + { quotaOnlyFallback: true, allowMeteredTargets: true }); + const first = { role: "user", content: "weather?" }; + const call = (messages: Item[]) => handleClaudeMessages(new Request("http://localhost/v1/messages", { + method: "POST", + headers: { "content-type": "application/json", "x-claude-code-session-id": "claude-tool-session" }, + body: JSON.stringify({ model: "combo/auto", messages, max_tokens: 32, stream: false, + tools: [{ name: "get_weather", input_schema: { type: "object" } }] }), + }), cfg, { model: "", provider: "" }, { + requestId: "fixture", start: Date.now(), admission: { kind: "loopback", source: "loopback" }, + }); + expect(await (await call([first])).text()).toContain("get_weather"); + const resumed = await call([ + first, { role: "assistant", content: [{ type: "tool_use", id: "call_1", name: "get_weather", input: {} }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "call_1", content: "rain" }] }, + ]); + const resumedText = await resumed.text(); + expect(resumed.status, resumedText).toBe(200); + expect(resumedText).toContain("Rain today."); + expect(attempts).toBe(2); + }); + + test("a quota-only continuation follows the quota of its redirected destination", async () => { + const sent: string[] = []; + const subscription = serve(() => { + sent.push("subscription"); + return Response.json(responsesBody("m1", [answer("wrong target")])); + }); + const mirror = serve(async request => { + sent.push("mirror"); + const body = await request.json() as { input: Item[] }; + return Response.json(responsesBody("m1", [ + body.input.at(-1)?.type === "function_call_output" ? answer("Rain today.") : issuedCall, + ])); + }); + const cfg = combo({ + subscription: provider("openai-responses", baseUrl(subscription)), + mirror: provider("openai-responses", baseUrl(mirror)), + }, [{ provider: "subscription", model: "m1" }], { quotaOnlyFallback: true, allowMeteredTargets: true }); + cfg.blockedModelRedirects = { "subscription/m1": "mirror/m1" }; + setCachedProviderQuotaForTests("subscription", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + const lane = { "thread-id": "redirected-destination-quota" }; + expect(await (await post(cfg, [userMessage("weather?")], lane)).text()).toContain("get_weather"); + expect(await (await post(cfg, bareContinuation, lane)).text()).toContain("Rain today."); + setCachedProviderQuotaForTests("mirror", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + const stopped = await post(cfg, bareContinuation, lane); + expect(stopped.status).toBe(429); + expect(await stopped.json()).toMatchObject({ error: { code: "combo_tool_target_quota_exhausted" } }); + expect(sent).toEqual(["mirror", "mirror"]); + }); + + const servingChanges: Record> = { + "send path": { responsesPath: "/moved/responses" }, + "model adapter": { modelAdapters: { m1: "openai-chat" } }, + "Vertex project": { project: "project-b" }, + "Vertex location": { location: "europe-west4" }, + }; + for (const [change, patch] of Object.entries(servingChanges)) { + test(`a quota-only continuation refuses its serving target once its ${change} changed`, async () => { + const paths: string[] = []; + const upstream = serve(async request => { + paths.push(new URL(request.url).pathname); + const body = await request.json() as { input: Item[] }; + return Response.json(responsesBody("m1", [ + body.input.at(-1)?.type === "function_call_output" ? answer("Rain today.") : issuedCall, + ])); + }); + const cfg = combo({ primary: provider("openai-responses", baseUrl(upstream)) }, [{ provider: "primary", model: "m1" }], + { quotaOnlyFallback: true, allowMeteredTargets: true }); + const lane = { "thread-id": `changed-${change}` }; + expect(await (await post(cfg, [userMessage("weather?")], lane)).text()).toContain("get_weather"); + const changed = { ...cfg, providers: { primary: { ...cfg.providers.primary!, ...patch } } }; + const refused = await post(changed, bareContinuation, lane); + expect(refused.status).toBe(409); + expect(await refused.json()).toMatchObject({ error: { code: "combo_tool_target_unavailable" } }); + expect(await (await post(cfg, bareContinuation, lane)).text()).toContain("Rain today."); + expect(paths).toEqual(["/v1/responses", "/v1/responses"]); + }); + } + + for (const [fallbackModel, allowed] of [["m2", false], ["m1", true]] as const) { + test(`a pinned continuation keeps the same-model guard when its target fails (${fallbackModel})`, async () => { + let primaryDown = false; + const sent: string[] = []; + const primary = serve(() => { + sent.push("primary"); + return primaryDown ? busy() : Response.json(responsesBody("m1", [issuedCall])); + }); + const other = serve(() => { + sent.push("other"); + return Response.json(responsesBody(fallbackModel, [answer("Rain today.")])); + }); + const cfg = combo({ + primary: provider("openai-responses", baseUrl(primary)), + other: provider("openai-responses", baseUrl(other)), + }, [{ provider: "primary", model: "m1" }, { provider: "other", model: fallbackModel }], { preserveFallbackModel: true }); + const lane = { "thread-id": `pinned-model-lock-${fallbackModel}` }; + expect(await (await post(cfg, [userMessage("weather?")], lane)).text()).toContain("get_weather"); + primaryDown = true; + const resumed = await post(cfg, bareContinuation, lane); + if (allowed) { + expect(await resumed.text()).toContain("Rain today."); + expect(sent.at(-1)).toBe("other"); + } else { + expect(resumed.status).toBe(409); + expect(await resumed.json()).toMatchObject({ error: { code: "combo_model_change_refused" } }); + expect(sent).not.toContain("other"); + } + }); + } + + for (const [label, withThird] of [["a target on the serving model", true], ["only a target on another model", false]] as const) { + test(`the model lock follows the serving model of a pinned continuation (${label})`, async () => { + let primaryDown = true; + let secondDown = false; + const sent: string[] = []; + const primary = serve(() => { + sent.push("primary"); + return primaryDown ? busy() : Response.json(responsesBody("m1", [answer("wrong model")])); + }); + const second = serve(() => { + sent.push("second"); + return secondDown ? busy() : Response.json(responsesBody("m2", [issuedCall])); + }); + const third = serve(() => { + sent.push("third"); + return Response.json(responsesBody("m2", [answer("Rain today.")])); + }); + const providers = { + primary: provider("openai-responses", baseUrl(primary)), + second: provider("openai-responses", baseUrl(second)), + third: provider("openai-responses", baseUrl(third)), + }; + const targets = [{ provider: "primary", model: "m1" }, { provider: "second", model: "m2" }, + ...(withThird ? [{ provider: "third", model: "m2" }] : [])]; + const lane = { "thread-id": `pinned-serving-model-${withThird}` }; + // The turn starts without the model lock while the first target is down, so the second + // target, on another model, issues the tool call. + expect(await (await post(combo(providers, targets), [userMessage("weather?")], lane)).text()).toContain("get_weather"); + primaryDown = false; + secondDown = true; + // With no target left on the serving model, the recovered first target is the next hop. + if (!withThird) clearComboTargetCooldowns("auto"); + const firstTurnSends = sent.length; + const resumed = await post(combo(providers, targets, { preserveFallbackModel: true }), bareContinuation, lane); + const continuationSends = sent.slice(firstTurnSends); + expect(continuationSends).not.toContain("primary"); + if (withThird) { + expect(await resumed.text()).toContain("Rain today."); + expect(continuationSends.at(-1)).toBe("third"); + } else { + expect(resumed.status).toBe(409); + expect(await resumed.json()).toMatchObject({ error: { code: "combo_model_change_refused" } }); + } + }); + } + + test("the model lock follows the serving model of a continuation whose serving target is already cooling", async () => { + let secondDown = false; + const sent: string[] = []; + const primary = serve(() => { sent.push("primary"); return Response.json(responsesBody("m1", [answer("wrong model")])); }); + const second = serve(() => { sent.push("second"); return secondDown ? busy() : Response.json(responsesBody("m2", [issuedCall])); }); + const providers = { primary: provider("openai-responses", baseUrl(primary)), second: provider("openai-responses", baseUrl(second)) }; + const targets = [{ provider: "primary", model: "m1" }, { provider: "second", model: "m2" }]; + const lane = { "thread-id": "cooling-serving-model" }; + // The first target's quota is spent, so the second target, on another model, issues the tool call. + setCachedProviderQuotaForTests("primary", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + expect(await (await post(combo(providers, targets), [userMessage("weather?")], lane)).text()).toContain("get_weather"); + // Another conversation cools the serving target, then the first target's quota recovers. + secondDown = true; + await (await post(combo(providers, targets), [userMessage("hello")], { "thread-id": "cooling-other-lane" })).text(); + clearCachedProviderQuotas(); + const sendsBefore = sent.length; + const resumed = await post(combo(providers, targets, { preserveFallbackModel: true }), bareContinuation, lane); + expect(resumed.status).toBe(409); + expect(await resumed.json()).toMatchObject({ error: { code: "combo_model_change_refused" } }); + expect(sent.slice(sendsBefore)).toEqual([]); + }); + + test("a pinned continuation resumes on a target whose configured model carries surrounding spaces", async () => { + const { cfg, sent } = singleTargetQuotaOnlyCombo(); + cfg.combos!.auto!.targets = [{ provider: "backup", model: " m2 " }]; + const lane = { "thread-id": "padded-target" }; + expect(await (await post(cfg, [userMessage("weather?")], lane)).text()).toContain("get_weather"); + expect(await (await post(cfg, bareContinuation, lane)).text()).toContain("Rain today."); + expect(sent).toEqual(["backup", "backup"]); + }); + + test("the model lock keeps the serving model when the serving target is disabled", async () => { + const sent: string[] = []; + const primary = serve(() => { sent.push("primary"); return Response.json(responsesBody("m1", [answer("wrong model")])); }); + const second = serve(() => { sent.push("second"); return Response.json(responsesBody("m2", [issuedCall])); }); + const providers = { primary: provider("openai-responses", baseUrl(primary)), second: provider("openai-responses", baseUrl(second)) }; + const targets = [{ provider: "primary", model: "m1" }, { provider: "second", model: "m2" }]; + const lane = { "thread-id": "disabled-serving-model" }; + // The first target's quota is spent, so the second target, on another model, issues the tool call. + setCachedProviderQuotaForTests("primary", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + expect(await (await post(combo(providers, targets), [userMessage("weather?")], lane)).text()).toContain("get_weather"); + clearCachedProviderQuotas(); + const cfg = combo(providers, targets, { preserveFallbackModel: true }); + cfg.providers.second!.disabled = true; + for (const attempt of ["first", "retry"]) { + const refused = await post(cfg, bareContinuation, lane); + expect(refused.status, attempt).toBe(409); + expect(await refused.json()).toMatchObject({ error: { code: "combo_model_change_refused" } }); + } + expect(sent).toEqual(["second"]); + }); + + test("the fallback policy of the provider a redirected Combo child used decides the next hop", async () => { + const sent: string[] = []; + const next = serve(() => { sent.push("next"); return Response.json(responsesBody("m2", [answer("from next")])); }); + const exhausted = serve(() => { + sent.push("elsewhere"); + return Response.json({ error: { code: "insufficient_quota", message: "Quota exhausted" } }, { status: 429 }); + }); + const cfg = combo({ + backup: provider("openai-responses", "http://127.0.0.1:9/v1"), + next: provider("openai-responses", baseUrl(next)), + elsewhere: provider("openai-responses", baseUrl(exhausted)), + }, [{ provider: "backup", model: "m2" }, { provider: "next", model: "m2" }], { quotaOnlyFallback: true, allowMeteredTargets: true }); + // Hops away from the provider that refused are forbidden, while hops away from the planned one are not. + cfg.fallback = { providers: { elsewhere: { provider: false } } }; + redirectWhileChildPrepares(cfg, "elsewhere/m2"); + const refused = await post(cfg, [userMessage("hello")], { "thread-id": "redirected-policy" }); + expect(await refused.json()).toMatchObject({ error: { code: "fallback_refused" } }); + expect(sent).toEqual(["elsewhere"]); + }); + + test("a pinned quota-only continuation keeps its pool target usable when another key is only rate-limited", async () => { + const sent: string[] = []; + let refusing = false; + const pool = serve(async request => { + const keyLabels: Record = { "Bearer key-one": "one", "Bearer key-two": "two" }; + const key = keyLabels[request.headers.get("authorization") ?? ""] ?? "unexpected"; + sent.push(key); + if (key === "unexpected") { + return Response.json({ error: { message: "unexpected credential", type: "invalid_request_error" } }, { status: 400 }); + } + const body = await request.json() as { input: Item[] }; + if (refusing) { + return key === "one" + ? Response.json({ error: { message: "Rate limit reached for requests per minute" } }, { status: 429 }) + : Response.json({ error: { code: "insufficient_quota", message: "Quota exhausted" } }, { status: 429 }); + } + return Response.json(responsesBody("m2", [ + body.input.at(-1)?.type === "function_call_output" ? answer("Rain today.") : issuedCall, + ])); + }); + const cfg = combo({ + backup: provider("openai-responses", baseUrl(pool), { + apiKey: "key-one", apiKeyPool: [{ id: "one", key: "key-one" }, { id: "two", key: "key-two" }], + }), + }, [{ provider: "backup", model: "m2" }], { quotaOnlyFallback: true, allowMeteredTargets: true }); + // Key rotation commits the next key to the persisted row, so the pool has to exist on disk. + saveConfig(cfg); + const lane = { "thread-id": "pinned-pool-rate-limit" }; + expect(await (await post(cfg, [userMessage("weather?")], lane)).text()).toContain("get_weather"); + refusing = true; + const sendsBefore = sent.length; + const stopped = await post(cfg, bareContinuation, lane); + expect(stopped.status).toBe(429); + await stopped.text(); + expect(sent.slice(sendsBefore)).toEqual(["one", "two"]); + // The rate limit passes, so the pool can serve the continuation again. + refusing = false; + clearKeyCooldowns(); + expect(await (await post(cfg, bareContinuation, lane)).text()).toContain("Rain today."); + }); + + test("the model lock keeps the model that issued the call when a redirect moves its target to another model", async () => { + const sent: string[] = []; + const backup = serve(() => { sent.push("backup"); return Response.json(responsesBody("m2", [issuedCall])); }); + const other = serve(() => { sent.push("other"); return Response.json(responsesBody("m3", [answer("wrong model")])); }); + const providers = { backup: provider("openai-responses", baseUrl(backup)), other: provider("openai-responses", baseUrl(other)) }; + const targets = [{ provider: "backup", model: "m2" }]; + const lane = { "thread-id": "redirected-lock" }; + expect(await (await post(combo(providers, targets, { preserveFallbackModel: true }), [userMessage("weather?")], lane)).text()) + .toContain("get_weather"); + // The selector that issued the call now resolves to another model. + const cfg = combo(providers, targets, { preserveFallbackModel: true }); + cfg.blockedModelRedirects = { "backup/m2": "other/m3" }; + const refused = await post(cfg, bareContinuation, lane); + expect(refused.status).toBe(409); + expect(await refused.json()).toMatchObject({ error: { code: "combo_model_change_refused" } }); + expect(sent).toEqual(["backup"]); + }); + + test("a quota refusal from a Combo child that settled on another provider is judged there, so the Combo advances", async () => { + const sent: string[] = []; + const answering = (name: string) => serve(() => { sent.push(name); return Response.json(responsesBody("m2", [answer(`from ${name}`)])); }); + const exhausted = serve(() => { + sent.push("elsewhere"); + return Response.json({ error: { code: "insufficient_quota", message: "Quota exhausted" } }, { status: 429 }); + }); + const cfg = combo({ + // A pool with two usable keys on the planned target, which alone would keep the Combo there. + backup: provider("openai-responses", baseUrl(answering("backup")), { + apiKey: "key-one", apiKeyPool: [{ id: "one", key: "key-one" }, { id: "two", key: "key-two" }], + }), + next: provider("openai-responses", baseUrl(answering("next"))), + elsewhere: provider("openai-responses", baseUrl(exhausted)), + }, [{ provider: "backup", model: "m2" }, { provider: "next", model: "m2" }], { quotaOnlyFallback: true, allowMeteredTargets: true }); + redirectWhileChildPrepares(cfg, "elsewhere/m2"); + expect(await (await post(cfg, [userMessage("hello")], { "thread-id": "redirected-pool" })).text()).toContain("from next"); + mock.restore(); + expect(await (await post(cfg, [userMessage("hello")], { "thread-id": "after-redirected-pool" })).text()).toContain("from backup"); + expect(sent).toEqual(["elsewhere", "next", "backup"]); + }); + + test("the model lock lets a continuation reach another target on its serving model when the serving target cools", async () => { + let secondDown = false; + const sent: string[] = []; + const primary = serve(() => { sent.push("primary"); return Response.json(responsesBody("m1", [answer("wrong model")])); }); + const second = serve(() => { sent.push("second"); return secondDown ? busy() : Response.json(responsesBody("m2", [issuedCall])); }); + const third = serve(() => { sent.push("third"); return Response.json(responsesBody("m2", [answer("Rain today.")])); }); + const providers = { + primary: provider("openai-responses", baseUrl(primary)), + second: provider("openai-responses", baseUrl(second)), + third: provider("openai-responses", baseUrl(third)), + }; + const targets = [{ provider: "primary", model: "m1" }, { provider: "second", model: "m2" }, { provider: "third", model: "m2" }]; + const lane = { "thread-id": "cooling-serving-model-third" }; + // The first target's quota stays spent, so the second target, on another model, issues the tool call. + setCachedProviderQuotaForTests("primary", { updatedAt: Date.now(), weeklyPercent: 100 } as ProviderQuota); + expect(await (await post(combo(providers, targets), [userMessage("weather?")], lane)).text()).toContain("get_weather"); + // Another conversation cools the serving target. + secondDown = true; + await (await post(combo(providers, targets), [userMessage("hello")], { "thread-id": "cooling-third-other-lane" })).text(); + const sendsBefore = sent.length; + const resumed = await post(combo(providers, targets, { preserveFallbackModel: true }), bareContinuation, lane); + expect(await resumed.text()).toContain("Rain today."); + expect(sent.slice(sendsBefore)).toEqual(["third"]); + }); + test("a pinned target that fails mid-loop fails over, and the strict target gets replayable history", async () => { let solFails = false; const sol = serve(() => solFails ? busy() : Response.json(responsesBody("gpt-6.1-sol", [issuedCall]))); diff --git a/tests/server/server-combo-zero-output-failover.test.ts b/tests/server/server-combo-zero-output-failover.test.ts index 5eb8d060491..3c54d222a1d 100644 --- a/tests/server/server-combo-zero-output-failover.test.ts +++ b/tests/server/server-combo-zero-output-failover.test.ts @@ -503,6 +503,25 @@ describe("combo zero-output bare Responses error failover", () => { expect(hits).toEqual(["a"]); }); + test("a quota refusal after visible stream output stays on its original target", async () => { + const sent: string[] = []; + customRunTurn = async (parsed, _incoming, emit) => { + sent.push(parsed.modelId); + emit({ type: "text_delta", text: "already delivered" }); + emit({ type: "error", status: 429, code: "insufficient_quota", message: "Quota exhausted" }); + }; + const config = comboConfig({ + a: provider("test-run-turn", "https://a.test/v1", "key-a"), + b: provider("test-run-turn", "https://b.test/v1", "key-b"), + }, undefined, { quotaOnlyFallback: true, allowMeteredTargets: true }); + const response = await handleResponses(new Request("http://localhost/v1/responses", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "combo/free", input: "hello", stream: true }), + }), config, { model: "", provider: "" }, { admission: { kind: "loopback", source: "loopback" } }); + expect(await response.text()).toContain("already delivered"); + expect(sent).toEqual(["m1"]); + }); + test("buffered undeclared tool call after text and replay-unsafe heartbeat never replays on backup", async () => { const hits: string[] = []; customRunTurn = async (parsed, _incoming, emit) => { From 206888ec1be5fbf5ad3ea97dece896caaf15fb3f Mon Sep 17 00:00:00 2001 From: JUN Date: Wed, 25 Nov 2026 15:37:08 +0900 Subject: [PATCH 39/60] feat(providers): persist API-key cooldowns across restarts (#9107) * feat(providers): persist API-key cooldowns across restarts (G-013) * fix(providers): keep cooldown rows per generation, persist clear markers, inline keys only * fix(providers): order cooldown clears with counters, bind persistence to the server lifecycle * fix(providers): drop local holds on a peer clear, track the restored home, coalesce pending holds * fix(providers): the final server release drops its in-memory holds * fix(providers): a flush adopting its own rebased clear keeps the holds recorded after it * test(providers): the cooldown file is private like config.json * docs(es): API-key cooldowns of inline keys survive a restart * fix(providers): keep cooldown clear counters for provider names that match Object.prototype members Provider names such as valueOf are valid, and a plain object lookup returned the inherited member instead of the provider's counter, so the hold was dropped on flush. The counter tables are null-prototype. * fix(providers): persist spent-quota evidence with a cooldown so a quota-only Combo still leaves a spent pool after restart Rows carry an optional quotaSpentUntil (bounded by the expiry). Coalesced pending holds, peer merges and restore keep the later spent-quota evidence alongside the later expiry. * docs(structure): name the persisted spent-quota evidence in the API-key cooldown file --------- Co-authored-by: r2b --- .../es/reference/configuration/providers.md | 2 +- .../docs/reference/configuration/providers.md | 2 +- scripts/test-layout/layout-providers.json | 3 +- src/lib/state-store-registrations.ts | 4 +- src/providers/api-key-cooldown-store.ts | 323 +++++++++++++ src/providers/api-key-cooldowns.ts | 114 ++++- src/providers/key-failover.ts | 10 +- src/server/background-lifecycle.ts | 6 + structure/providers-and-adapters.md | 2 +- tests/fixtures/test-layout-expected.json | 3 +- .../providers/api-key-cooldown-store.test.ts | 430 ++++++++++++++++++ 11 files changed, 880 insertions(+), 19 deletions(-) create mode 100644 src/providers/api-key-cooldown-store.ts create mode 100644 tests/providers/api-key-cooldown-store.test.ts diff --git a/docs-site/src/content/docs/es/reference/configuration/providers.md b/docs-site/src/content/docs/es/reference/configuration/providers.md index e497dd6420c..9b25a315fc0 100644 --- a/docs-site/src/content/docs/es/reference/configuration/providers.md +++ b/docs-site/src/content/docs/es/reference/configuration/providers.md @@ -392,7 +392,7 @@ Para múltiples entradas de grupo de claves API, opte por la distribución de so Esto admite como máximo diez solicitudes activas en todo el proveedor y una por referencia de credencial, con inicios en cada referencia con al menos cuatro segundos de diferencia. Estos son límites superiores locales, no una promesa de capacidad ascendente. Una configuración de RPM para todo el proveedor, cuando está presente, sigue siendo un límite agregado y no se multiplica con el recuento de claves. Los límites clave abarcan modelos; las reglas del modelo siguen siendo restricciones adicionales. Los proyectos que comparten cuota necesitan un límite agregado apropiado. El TPM y las cuotas diarias no se rastrean aquí. -Round-robin selecciona claves por solicitud sin guardar una nueva clave activa. Se omiten los tiempos de reutilización 401/429 conocidos; cuando ninguno sigue siendo elegible, las nuevas solicitudes reciben un 429 reintentable en lugar de enviarse repetidamente. El trabajo ya puesto en cola normalmente retiene su clave seleccionada y puede esperar detrás de esa clave incluso cuando otra está inactiva. Si esa selección se enfría o no es válida, la solicitud vuelve a seleccionar una clave elegible y vuelve a adquirir la admisión de estimulación; la cola limitada expira en lugar de esperar para siempre. La selección y el diagnóstico son locales de proceso, se restablecen al reiniciar y no igualan el uso o la facturación de tokens equilibrados. Comienza a contar las admisiones de ritmo, incluido el trabajo cancelado antes del envío. OAuth y las credenciales reenviadas mantienen su selección existente. El panel de control muestra los identificadores de teclas, los inicios, el trabajo en vuelo, el trabajo en cola y los tiempos de reutilización conocidos, nunca los valores de las claves secretas. Estos límites cubren el ejecutor de estimulación de inferencia, no la búsqueda directa del relé de imágenes independiente. +Round-robin selecciona claves por solicitud sin guardar una nueva clave activa. Se omiten los tiempos de reutilización 401/429 conocidos; cuando ninguno sigue siendo elegible, las nuevas solicitudes reciben un 429 reintentable en lugar de enviarse repetidamente. El trabajo ya puesto en cola normalmente retiene su clave seleccionada y puede esperar detrás de esa clave incluso cuando otra está inactiva. Si esa selección se enfría o no es válida, la solicitud vuelve a seleccionar una clave elegible y vuelve a adquirir la admisión de estimulación; la cola limitada expira en lugar de esperar para siempre. La selección y el diagnóstico son locales de proceso, se restablecen al reiniciar y no igualan el uso o la facturación de tokens equilibrados. Los tiempos de reutilización conocidos de las claves en línea son la excepción: una retención por un rechazo 401, 429 o de facturación se guarda en `api-key-cooldowns.json` en el directorio de configuración y sigue vigente tras un reinicio hasta que expira. Reemplazar la clave de esa entrada del grupo o borrarla desde la gestión de claves elimina la retención. Las claves indicadas como referencia de entorno o de llavero conservan sus tiempos de reutilización solo en memoria. Comienza a contar las admisiones de ritmo, incluido el trabajo cancelado antes del envío. OAuth y las credenciales reenviadas mantienen su selección existente. El panel de control muestra los identificadores de teclas, los inicios, el trabajo en vuelo, el trabajo en cola y los tiempos de reutilización conocidos, nunca los valores de las claves secretas. Estos límites cubren el ejecutor de estimulación de inferencia, no la búsqueda directa del relé de imágenes independiente. diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index b476d90119a..880b0c531e6 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -509,7 +509,7 @@ For multiple API-key pool entries, opt into normal-request distribution separate This admits at most ten active requests across the provider and one per credential reference, with starts on each reference at least four seconds apart. These are local upper bounds, not a promise of upstream capacity. A provider-wide RPM setting, when present, remains an aggregate limit and does not multiply with key count. Key limits span models; model rules remain additional restrictions. Projects sharing quota need an appropriate aggregate limit; TPM and daily quotas are not tracked here. -Round-robin selects keys per request without saving a new active key. Known 401/429 cooldowns are skipped; when none remains eligible, new requests receive a retryable 429 instead of repeatedly sending. Already queued work normally retains its selected key and may wait behind that key even when another is idle. If that selection becomes cooled or invalid, the request selects an eligible key again and reacquires pacing admission for it; the bounded queue expires rather than waiting forever. Selection and diagnostics are process-local, reset on restart, and do not equal balanced token usage or billing. Starts count pacing admissions, including work cancelled before dispatch. OAuth and forwarded credentials keep their existing selection. The dashboard shows key handles, starts, in-flight work, queued work and known cooldowns, never secret key values. These limits cover the inference pacing executor, not the standalone Images relay's direct fetch. +Round-robin selects keys per request without saving a new active key. Known 401/429 cooldowns are skipped; when none remains eligible, new requests receive a retryable 429 instead of repeatedly sending. Already queued work normally retains its selected key and may wait behind that key even when another is idle. If that selection becomes cooled or invalid, the request selects an eligible key again and reacquires pacing admission for it; the bounded queue expires rather than waiting forever. Selection and diagnostics are process-local, reset on restart, and do not equal balanced token usage or billing. Known cooldowns of inline keys are the exception: a hold from a 401, 429 or billing refusal is saved in `api-key-cooldowns.json` in the config directory and still applies after a restart until it expires. Replacing the key under that pool entry or clearing it from key management drops the hold. Keys given as an environment or keychain reference keep their cooldowns in memory only. Starts count pacing admissions, including work cancelled before dispatch. OAuth and forwarded credentials keep their existing selection. The dashboard shows key handles, starts, in-flight work, queued work and known cooldowns, never secret key values. These limits cover the inference pacing executor, not the standalone Images relay's direct fetch. ### Azure OpenAI model metadata discovery diff --git a/scripts/test-layout/layout-providers.json b/scripts/test-layout/layout-providers.json index a64f325f9c0..42c9a5ba0e9 100644 --- a/scripts/test-layout/layout-providers.json +++ b/scripts/test-layout/layout-providers.json @@ -27,5 +27,6 @@ "management-provider-model-discovery.test.ts": "server", "claude-cli-fixture-stdout-flush.test.ts": "providers", "alibaba-token-plan-developer-role.test.ts": "providers", - "provider-quota-probe-isolation.test.ts": "providers" + "provider-quota-probe-isolation.test.ts": "providers", + "api-key-cooldown-store.test.ts": "providers" } diff --git a/src/lib/state-store-registrations.ts b/src/lib/state-store-registrations.ts index 20121e6e894..22d2f7b22f7 100644 --- a/src/lib/state-store-registrations.ts +++ b/src/lib/state-store-registrations.ts @@ -45,6 +45,7 @@ import { configuredAnthropicInstance } from "../providers/anthropic-instance"; import { listLiveOAuthAccountKeys, reconcileOAuthReauthState } from "../oauth/store"; import { reconcileGuardianBackoff } from "../oauth/token-guardian"; import { sweepExpiredApiKeyCooldowns } from "../providers/key-failover"; +import { reconcileApiKeyCooldownGenerations } from "../providers/api-key-cooldowns"; import { reconcileProviderRequestPacing } from "../providers/request-pacing"; import { sweepAbandonedResponseStateTemps, sweepExpiredResponseStates, sweepOrphanedResponseSpills } from "../responses/state"; import { sweepExpiredAntigravityReplay } from "../adapters/google-antigravity-replay"; @@ -128,7 +129,8 @@ export function buildGenerationContext(): GenerationContext { export const STATE_STORE_REGISTRATIONS = [ { name: "subagent-model-health", sweepExpired: sweepExpiredSubagentModelHealth }, - { name: "api-key-cooldowns", sweepExpired: sweepExpiredApiKeyCooldowns }, + { name: "api-key-cooldowns", sweepExpired: sweepExpiredApiKeyCooldowns, + reconcileGeneration: () => reconcileApiKeyCooldownGenerations(liveServerConfig?.providers) }, { name: "provider-request-pacing", reconcileGeneration: reconcileProviderRequestPacing }, { name: "combo-target-cooldowns", diff --git a/src/providers/api-key-cooldown-store.ts b/src/providers/api-key-cooldown-store.ts new file mode 100644 index 00000000000..89212eb2d5c --- /dev/null +++ b/src/providers/api-key-cooldown-store.ts @@ -0,0 +1,323 @@ +/** + * Disk-backed rows for API-key cooldowns (`/api-key-cooldowns.json`). + * + * A confirmed quota or billing hold that lives only in memory is forgotten on restart, so a + * restarted proxy re-offers a key the upstream said to leave alone until its reset. Each row is + * `{provider, keyId, generation, cooldownUntil, epoch, allEpoch}` plus, for a refusal that proved + * the key's quota or credit spent, `quotaSpentUntil` (a quota-only Combo reads it to leave a spent + * pool), and nothing else; `generation` is a truncated fingerprint of the pool entry's key, so a key + * replaced under the same id is never held by an old row. + * + * Only inline keys are persisted. A value the key resolver reads from the environment (any value + * starting with `$`), a `keychain:` reference or a `gcp-sa:` marker names a secret that can change + * behind an unchanged value, so its holds stay in memory, as before. An inline key is already in + * `config.json` next to this file, so its fingerprint discloses nothing the directory lacks. + * + * Several proxies can share one home, so a flush re-reads the file under the config mutation lock + * and merges instead of replacing: + * - Rows are kept per generation. A peer still holding an old key's row cannot overwrite the + * current key's row; restore picks the row whose generation matches the configured key. + * - A manual clear increments a counter (per provider, or one for every provider) stored in the + * file. Each row carries the counters its process knew when it recorded the hold, and only rows + * carrying the current counters survive a flush or a load. A peer that recorded before learning + * of a clear, however late it flushes, therefore cannot revive the hold; at worst a hold it + * recorded just after a peer's clear is not persisted and stays in that process's memory. + * Within one process the counter orders a clear and a later hold exactly. + * - Among surviving rows of one provider, key id and generation the later expiry wins, and the + * later spent-quota evidence is kept with it. + * - A busy lock or I/O failure keeps everything pending and retries with bounded backoff. + * - Rows load once, at install, and only while unexpired and matching the current key. + */ +import { existsSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import { atomicWriteFile } from "../config/atomic-write"; +import { withConfigMutationLockSync } from "../config/mutation-lock"; +import { getConfigDir } from "../config/paths"; +import { registerOptionalShutdownHook } from "../lib/optional-shutdown-hooks"; +import type { OcxConfig } from "../types"; +import { GCP_CREDENTIAL_MARKER_PREFIX, isKeychainReference } from "./api-key-resolve"; +import { + apiKeyCooldownGeneration, + attachApiKeyCooldownPersistence, + resetLocalApiKeyCooldowns, + restoreApiKeyCooldowns, +} from "./api-key-cooldowns"; + +export interface ApiKeyCooldownHold { provider: string; keyId: string; generation: string; cooldownUntil: number; quotaSpentUntil?: number } +export interface ApiKeyCooldownRow extends ApiKeyCooldownHold { epoch: number; allEpoch: number } +export interface ApiKeyCooldownPersistence { + /** Whether a hold for this configured key value may be written to disk. */ + persists(credential: string): boolean; + record(hold: ApiKeyCooldownHold): void; + clear(provider?: string): void; +} +interface StoredState { rows: ApiKeyCooldownRow[]; epochs: Record; allEpoch: number } +/** Provider clear counters keyed by provider name; null-prototype, so a name like `valueOf` is an own key. */ +const epochTable = (): Record => Object.create(null) as Record; + +export const API_KEY_COOLDOWN_FILE = "api-key-cooldowns.json"; +const FLUSH_DELAY_MS = 250; +const MAX_FLUSH_DELAY_MS = 4_000; +const SHUTDOWN_ATTEMPTS = 5; +const SHUTDOWN_RETRY_MS = 200; + +const holdKey = (row: ApiKeyCooldownHold) => `${row.provider}\0${row.keyId}\0${row.generation}`; +const taggedKey = (row: ApiKeyCooldownRow) => `${holdKey(row)}\0${row.epoch}\0${row.allEpoch}`; +const isTime = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value); +const isCount = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0; + +/** + * Mirrors `resolveProviderApiKey`: a `keychain:` value reads the OS keychain and `resolveEnvValue` + * reads the environment for ANY value starting with `$`, so only a value matching neither is the + * credential itself. A `gcp-sa:` marker is excluded too. + */ +export function isInlineApiKey(credential: string): boolean { + return credential.length > 0 && !credential.startsWith("$") && !credential.startsWith(GCP_CREDENTIAL_MARKER_PREFIX) + && !isKeychainReference(credential); +} + +function errorCode(error: unknown): string | undefined { + return error && typeof error === "object" && "code" in error ? String((error as { code?: unknown }).code) : undefined; +} + +/** Valid content of the file. Missing file or unparsable JSON is empty; other read errors throw. */ +export function readApiKeyCooldownState(path: string): StoredState { + const empty: StoredState = { rows: [], epochs: epochTable(), allEpoch: 0 }; + let text: string; + try { + text = readFileSync(path, "utf8"); + } catch (error) { + if (errorCode(error) === "ENOENT") return empty; + throw error; + } + let parsed: unknown; + try { parsed = JSON.parse(text); } catch { return empty; } + const file = parsed as { version?: unknown; rows?: unknown; epochs?: unknown; allEpoch?: unknown } | null; + if (file?.version !== 1) return empty; + const state: StoredState = { rows: [], epochs: epochTable(), allEpoch: isCount(file.allEpoch) ? file.allEpoch : 0 }; + if (file.epochs && typeof file.epochs === "object" && !Array.isArray(file.epochs)) { + for (const [provider, epoch] of Object.entries(file.epochs as Record)) if (isCount(epoch)) state.epochs[provider] = epoch; + } + for (const value of Array.isArray(file.rows) ? file.rows : []) { + const row = value as Partial | null; + if (typeof row?.provider !== "string" || typeof row.keyId !== "string" || typeof row.generation !== "string") continue; + if (!isTime(row.cooldownUntil) || !isCount(row.epoch) || !isCount(row.allEpoch)) continue; + state.rows.push({ provider: row.provider, keyId: row.keyId, generation: row.generation, + cooldownUntil: row.cooldownUntil, epoch: row.epoch, allEpoch: row.allEpoch, + ...(isTime(row.quotaSpentUntil) && row.quotaSpentUntil > 0 ? { quotaSpentUntil: Math.min(row.quotaSpentUntil, row.cooldownUntil) } : {}) }); + } + return state; +} + +/** Two holds for one key and generation: the later expiry, keeping the later spent-quota evidence. */ +function mergeHold(prior: T | undefined, row: T, now: number): T { + const base = !prior || row.cooldownUntil > prior.cooldownUntil ? row : prior; + const quotaSpentUntil = Math.max(prior?.quotaSpentUntil ?? 0, row.quotaSpentUntil ?? 0); + const merged: T = { ...base }; + delete merged.quotaSpentUntil; + if (quotaSpentUntil > now) merged.quotaSpentUntil = quotaSpentUntil; + return merged; +} + +/** Rows that postdate every recorded clear and have not expired, one per provider/key/generation. */ +function liveRows(rows: Iterable, epochs: Record, allEpoch: number, now: number): ApiKeyCooldownRow[] { + const out = new Map(); + for (const row of rows) { + if (row.cooldownUntil <= now || row.allEpoch !== allEpoch || row.epoch !== (epochs[row.provider] ?? 0)) continue; + out.set(holdKey(row), mergeHold(out.get(holdKey(row)), row, now)); + } + return [...out.values()]; +} + +export class ApiKeyCooldownStore implements ApiKeyCooldownPersistence { + /** + * Pending holds, each tagged with the counters this process knew when it recorded them. One + * entry per provider, key, generation and counters (the longest expiry), so a write that keeps + * failing holds at most one entry per configured key. + */ + private readonly dirty = new Map(); + /** Whether counters were ever read from disk; a later increase is a peer's clear. */ + private adopted = false; + /** Counters as last read from disk, plus this process's own unwritten clears. */ + private readonly epochs = new Map(); + private allEpoch = 0; + private readonly bumped = new Set(); + private bumpedAll = false; + private timer: ReturnType | undefined; + private delayMs = FLUSH_DELAY_MS; + + constructor(readonly dir: string) {} + + get path(): string { return join(this.dir, API_KEY_COOLDOWN_FILE); } + + /** Pending holds not yet written (diagnostics and tests). */ + get pendingHolds(): number { return this.dirty.size; } + + /** Live rows on disk now, adopting the file's clear counters. Throws on a read error other than a missing file. */ + load(now = Date.now()): ApiKeyCooldownRow[] { + const state = readApiKeyCooldownState(this.path); + this.adopt(state); + return liveRows(state.rows, state.epochs, state.allEpoch, now); + } + + /** + * Take the file's counters. A counter that moved past what this process knew is another + * process's clear: this process's own in-memory holds for it are dropped too, so a later refusal + * starts a fresh hold instead of extending the cleared one. + */ + private adopt(state: StoredState, written?: { providers: ReadonlySet; all: boolean }): void { + // A counter this flush itself wrote is our own clear, possibly rebased above a peer's: the holds + // tagged with it were recorded after that clear and must stay. + if (written?.all) this.allEpoch = state.allEpoch; + else if (!this.bumpedAll) { + if (this.adopted && state.allEpoch > this.allEpoch) resetLocalApiKeyCooldowns(); + this.allEpoch = state.allEpoch; + } + for (const [provider, epoch] of Object.entries(state.epochs)) { + if (written?.providers.has(provider)) { this.epochs.set(provider, epoch); continue; } + if (this.bumped.has(provider)) continue; + if (this.adopted && epoch > (this.epochs.get(provider) ?? 0)) resetLocalApiKeyCooldowns(provider); + this.epochs.set(provider, epoch); + } + this.adopted = true; + } + + persists(credential: string): boolean { + return isInlineApiKey(credential); + } + + record(hold: ApiKeyCooldownHold): void { + const row: ApiKeyCooldownRow = { ...hold, epoch: this.epochs.get(hold.provider) ?? 0, allEpoch: this.allEpoch }; + this.dirty.set(taggedKey(row), mergeHold(this.dirty.get(taggedKey(row)), row, 0)); + this.schedule(); + } + + clear(provider?: string): void { + if (provider === undefined) { + this.allEpoch += 1; + this.bumpedAll = true; + this.dirty.clear(); + } else { + this.epochs.set(provider, (this.epochs.get(provider) ?? 0) + 1); + this.bumped.add(provider); + for (const [key, row] of this.dirty) if (row.provider === provider) this.dirty.delete(key); + } + this.schedule(); + } + + private pending(): boolean { + return this.bumpedAll || this.bumped.size > 0 || this.dirty.size > 0; + } + + private schedule(): void { + if (this.timer) return; + this.timer = setTimeout(() => { this.timer = undefined; this.flush(); }, this.delayMs); + (this.timer as { unref?: () => void }).unref?.(); + } + + /** Write pending changes now. Returns false, keeping them and rescheduling, if the write could not run. */ + flush(now = Date.now()): boolean { + if (!this.pending()) return true; + // A running server's config dir exists; a removed one (a test home) has nowhere to persist to. + if (!existsSync(this.dir)) { this.discardPending(); return true; } + const path = this.path; + let written: StoredState | undefined; + try { + withConfigMutationLockSync(() => { + const disk = readApiKeyCooldownState(path); + // A clear of ours lands strictly after every clear already on disk; holds we recorded after + // it move to the counter actually written. Anything else keeps the counter it was recorded with. + const allEpoch = this.bumpedAll ? Math.max(disk.allEpoch + 1, this.allEpoch) : disk.allEpoch; + const epochs = Object.assign(epochTable(), disk.epochs); + for (const provider of this.bumped) epochs[provider] = Math.max((disk.epochs[provider] ?? 0) + 1, this.epochs.get(provider) ?? 0); + const own = [...this.dirty.values()].map(row => ({ + ...row, + epoch: this.bumped.has(row.provider) && row.epoch === this.epochs.get(row.provider) ? epochs[row.provider]! : row.epoch, + allEpoch: this.bumpedAll && row.allEpoch === this.allEpoch ? allEpoch : row.allEpoch, + })); + const rows = liveRows([...disk.rows, ...own], epochs, allEpoch, now); + atomicWriteFile(path, JSON.stringify({ version: 1, rows, epochs, allEpoch })); + written = { rows, epochs, allEpoch }; + }, this.dir); + } catch { + // Lock held by another process or an I/O error: keep everything and retry later. + this.delayMs = Math.min(this.delayMs * 2, MAX_FLUSH_DELAY_MS); + this.schedule(); + return false; + } + const own = { providers: new Set(this.bumped), all: this.bumpedAll }; + this.discardPending(); + if (written) this.adopt(written, own); + return true; + } + + private discardPending(): void { + this.dirty.clear(); + this.bumped.clear(); + this.bumpedAll = false; + this.delayMs = FLUSH_DELAY_MS; + } + + /** Bounded final write for process shutdown; never blocks for more than about a second. */ + flushForShutdown(): void { + for (let attempt = 0; attempt < SHUTDOWN_ATTEMPTS; attempt += 1) { + if (this.timer) { clearTimeout(this.timer); this.timer = undefined; } + if (this.flush()) break; + if (attempt < SHUTDOWN_ATTEMPTS - 1) Bun.sleepSync(SHUTDOWN_RETRY_MS); + } + if (this.timer) { clearTimeout(this.timer); this.timer = undefined; } + } +} + +/** Keep only rows whose pool entry still exists and still carries the inline key the row was recorded for. */ +export function rowsMatchingCurrentKeys(rows: readonly T[], config: Pick): T[] { + return rows.filter(row => { + const entry = config.providers[row.provider]?.apiKeyPool?.find(candidate => candidate.id === row.keyId); + return entry !== undefined && isInlineApiKey(entry.key) + && apiKeyCooldownGeneration(row.provider, row.keyId, entry.key) === row.generation; + }); +} + +let installed: { store: ApiKeyCooldownStore; detach: () => void; detachShutdown: () => void } | undefined; + +/** + * Bind persistence to the running server's config dir and restore holds that are unexpired and + * still belong to the configured key. The server background lifecycle calls this when a server + * starts and `uninstallApiKeyCooldownPersistence` when the last one stops; repeat calls for the + * same dir are no-ops. Installing for another dir first drops the in-memory holds, which belong + * to the previous home. A failed read leaves the server running with in-memory cooldowns. + */ +export function installApiKeyCooldownPersistence(config: Pick, now = Date.now()): ApiKeyCooldownStore { + const dir = getConfigDir(); + if (installed?.store.dir === dir) return installed.store; + // Holds restored or recorded for another home are not this home's. + if (installed) uninstallApiKeyCooldownPersistence({ dropLocalHolds: true }); + const store = new ApiKeyCooldownStore(dir); + try { + restoreApiKeyCooldowns(rowsMatchingCurrentKeys(store.load(now), config), now); + } catch { + // An unreadable file restores nothing; later writes still try to persist. + } + installed = { + store, + detach: attachApiKeyCooldownPersistence(store), + detachShutdown: registerOptionalShutdownHook("api-key-cooldowns", () => uninstallApiKeyCooldownPersistence()), + }; + return store; +} + +/** + * Flush and detach the installed store. The final server release and a home change also drop the + * in-memory holds that home owned, so a server started later for another home inherits none; + * holds recorded after that belong to whichever home installs next. The process-exit hook keeps + * them, because turns still draining keep consulting them. + */ +export function uninstallApiKeyCooldownPersistence(options: { dropLocalHolds?: boolean } = {}): void { + if (!installed) return; + const current = installed; + installed = undefined; + current.detach(); + current.detachShutdown(); + current.store.flushForShutdown(); + if (options.dropLocalHolds === true) resetLocalApiKeyCooldowns(); +} diff --git a/src/providers/api-key-cooldowns.ts b/src/providers/api-key-cooldowns.ts index e5fe83af5f0..a2eee80325e 100644 --- a/src/providers/api-key-cooldowns.ts +++ b/src/providers/api-key-cooldowns.ts @@ -1,22 +1,58 @@ -/** Process-local cooldown state shared by selection validation and key failover. */ -const keyCooldowns = new Map(); +import { createHash } from "node:crypto"; +import type { ApiKeyCooldownHold, ApiKeyCooldownPersistence } from "./api-key-cooldown-store"; + +/** + * Cooldown state shared by selection validation and key failover. + * + * The map is the authority for every check. A running server attaches a persistence sink + * (`api-key-cooldown-store.ts`) so a confirmed hold survives a restart until it expires; without + * one (unit tests, detached tools) the state stays in memory. Expiry checks and sweeps only drop + * local rows: an expired local copy must never erase a row another process sharing the home extended. + */ +type KeyCooldown = { cooldownUntil: number; generation?: string; quotaSpentUntil?: number }; +const keyCooldowns = new Map(); +let persistence: ApiKeyCooldownPersistence | undefined; function cooldownKey(providerName: string, keyId: string): string { return `${providerName}\0${keyId}`; } +/** + * The persisted generation of one pool entry: a truncated hash of the entry's key, so a key + * replaced under the same id starts with no hold. It is unsalted on purpose; a per-file salt + * would race between processes sharing a home. A key fingerprint is the only generation an API + * key has (see `adapters/anthropic/per-message-effort.ts`). + */ +export function apiKeyCooldownGeneration(providerName: string, keyId: string, credential: string): string { + return createHash("sha256") + .update(`ocx-api-key-cooldown/v1\0${providerName}\0${keyId}\0${credential}`) + .digest("hex") + .slice(0, 24); +} + /** * `quotaSpent` marks a refusal that proved the key's quota or credit is spent. A rate limit leaves - * it unset, because that key serves again once the window passes. + * it unset, because that key serves again once the window passes. `credential` is the key that + * failed; it binds the hold to that key and lets a running server persist it. */ -export function setKeyCooldown(providerName: string, keyId: string, cooldownUntil: number, quotaSpent = false): void { +export function setKeyCooldown(providerName: string, keyId: string, cooldownUntil: number, quotaSpent = false, credential?: string): void { const key = cooldownKey(providerName, keyId); - const previous = keyCooldowns.get(key); - const quotaSpentUntil = Math.max(previous?.quotaSpentUntil ?? 0, quotaSpent ? cooldownUntil : 0); + const generation = credential === undefined ? undefined : apiKeyCooldownGeneration(providerName, keyId, credential); + const prior = keyCooldowns.get(key); + // A hold recorded against a different key under the same id belongs to that old key. + const sameKey = prior !== undefined && (generation === undefined || prior.generation === undefined || prior.generation === generation); + const until = sameKey ? Math.max(prior.cooldownUntil, cooldownUntil) : cooldownUntil; + const quotaSpentUntil = Math.max(sameKey ? prior.quotaSpentUntil ?? 0 : 0, quotaSpent ? cooldownUntil : 0); + const kept = generation ?? (sameKey ? prior.generation : undefined); keyCooldowns.set(key, { - cooldownUntil: Math.max(previous?.cooldownUntil ?? 0, cooldownUntil), + cooldownUntil: until, + ...(kept !== undefined ? { generation: kept } : {}), ...(quotaSpentUntil > 0 ? { quotaSpentUntil } : {}), }); + // Only a hold bound to the key that just failed is written, and only for a key the store accepts. + if (persistence && generation !== undefined && credential !== undefined && persistence.persists(credential)) { + persistence.record({ provider: providerName, keyId, generation, cooldownUntil: until, ...(quotaSpentUntil > 0 ? { quotaSpentUntil } : {}) }); + } } export function isKeyInCooldown(providerName: string, keyId: string, now = Date.now()): boolean { @@ -50,8 +86,9 @@ export function sweepExpiredApiKeyCooldowns(now = Date.now()): number { return removed; } -/** Manual key management clears this provider's cooldowns. */ +/** Manual key management clears this provider's cooldowns, on disk too so a restart cannot revive them. */ export function clearKeyCooldowns(providerName?: string): void { + persistence?.clear(providerName); if (!providerName) { keyCooldowns.clear(); return; @@ -61,3 +98,64 @@ export function clearKeyCooldowns(providerName?: string): void { if (key.startsWith(prefix)) keyCooldowns.delete(key); } } + +/** + * Forget holds in memory without writing: every hold when the config home changes, or one + * provider's (or every provider's) when another process sharing the home cleared them. + */ +export function resetLocalApiKeyCooldowns(providerName?: string): void { + if (providerName === undefined) { + keyCooldowns.clear(); + return; + } + const prefix = `${providerName}\0`; + for (const key of keyCooldowns.keys()) if (key.startsWith(prefix)) keyCooldowns.delete(key); +} + +/** Route later cooldown writes and clears to a store. Returns a detach that only removes this sink. */ +export function attachApiKeyCooldownPersistence(sink: ApiKeyCooldownPersistence): () => void { + persistence = sink; + return () => { if (persistence === sink) persistence = undefined; }; +} + +/** + * Adopt rows a store loaded; the caller has already matched their generation to the current keys, + * so a row replaces a local hold of any other generation and extends one of the same generation. + */ +export function restoreApiKeyCooldowns(rows: readonly ApiKeyCooldownHold[], now = Date.now()): number { + let restored = 0; + for (const row of rows) { + if (row.cooldownUntil <= now) continue; + const key = cooldownKey(row.provider, row.keyId); + const prior = keyCooldowns.get(key); + const sameKey = prior !== undefined && (prior.generation === undefined || prior.generation === row.generation); + const quotaSpentUntil = Math.max(sameKey ? prior.quotaSpentUntil ?? 0 : 0, row.quotaSpentUntil ?? 0); + if (sameKey && prior.cooldownUntil >= row.cooldownUntil && (prior.quotaSpentUntil ?? 0) >= quotaSpentUntil) continue; + keyCooldowns.set(key, { + cooldownUntil: sameKey ? Math.max(prior.cooldownUntil, row.cooldownUntil) : row.cooldownUntil, + generation: row.generation, + ...(quotaSpentUntil > now ? { quotaSpentUntil } : {}), + }); + restored += 1; + } + return restored; +} + +type KeyPools = Record } | undefined>; + +/** Drop holds whose pool entry is gone or now carries a different key. Local only. */ +export function reconcileApiKeyCooldownGenerations(providers: KeyPools | undefined): number { + if (!providers) return 0; + let removed = 0; + for (const [key, cooldown] of keyCooldowns) { + if (cooldown.generation === undefined) continue; + const separator = key.indexOf("\0"); + const providerName = key.slice(0, separator); + const keyId = key.slice(separator + 1); + const entry = providers[providerName]?.apiKeyPool?.find(candidate => candidate.id === keyId); + if (entry && apiKeyCooldownGeneration(providerName, keyId, entry.key) === cooldown.generation) continue; + keyCooldowns.delete(key); + removed += 1; + } + return removed; +} diff --git a/src/providers/key-failover.ts b/src/providers/key-failover.ts index 533b6f0dc6d..46e25398b9f 100644 --- a/src/providers/key-failover.ts +++ b/src/providers/key-failover.ts @@ -35,7 +35,7 @@ import { ProviderApiKeyPausedError } from "./api-key-pause-state"; import { cachedApiKeyQuota } from "./quota-key-accounts"; import { isDisplayOnlyQuota } from "./quota-types"; -// ---- cooldown state (in-memory, same as codex/routing.ts) ---- +// ---- cooldown state (api-key-cooldowns.ts; a running server persists it until expiry) ---- const DEFAULT_COOLDOWN_MS = 60_000; const MAX_COOLDOWN_MS = 10 * 60_000; // cap at 10 min for api-key rotation @@ -45,8 +45,8 @@ const MAX_COOLDOWN_MS = 10 * 60_000; // cap at 10 min for api-key rotation * ten-minute credential cap would hand a dead key back to rotation six times an hour. One hour * keeps it out of replacement and proactive selection while a funded sibling exists, and still * notices a top-up without a restart. When every key is held, requests keep using the active - * key and return Anthropic's original refusal. The hold is in memory; dashboard key management - * clears it. + * key and return Anthropic's original refusal. The hold survives a restart until it expires + * while the key is unchanged; dashboard key management clears it. */ export const ANTHROPIC_BILLING_COOLDOWN_MS = 60 * 60_000; @@ -840,7 +840,7 @@ export function recordDistributedKeyFailure( const delay = status === "billing" ? ANTHROPIC_BILLING_COOLDOWN_MS : status === 401 ? MAX_COOLDOWN_MS : quotaResetAt !== undefined ? Math.max(1, quotaResetAt - now) : parseRetryAfterMs(retryAfter, now) ?? DEFAULT_COOLDOWN_MS; for (const entry of provider.apiKeyPool ?? []) if (entry.key === failed.key) { - setKeyCooldown(providerName, entry.id, now + delay, status === "billing" || quotaExhausted); + setKeyCooldown(providerName, entry.id, now + delay, status === "billing" || quotaExhausted, entry.key); } sweepExpiredOnWrite(now); return true; @@ -940,7 +940,7 @@ function rotateKeyAfterFailure( : quotaResetAt !== undefined ? Math.max(quotaResetAt - now, 1) : parseRetryAfterMs(retryAfterHeader, now) ?? DEFAULT_COOLDOWN_MS; - setKeyCooldown(providerName, outcome.value.failedId, now + cooldownMs, failureStatus === "billing" || quotaExhausted); + setKeyCooldown(providerName, outcome.value.failedId, now + cooldownMs, failureStatus === "billing" || quotaExhausted, failedKey); sweepExpiredOnWrite(now); } if ("exhaustedCount" in outcome.value) { diff --git a/src/server/background-lifecycle.ts b/src/server/background-lifecycle.ts index 2ecc85fb2e1..53dcf588ddd 100644 --- a/src/server/background-lifecycle.ts +++ b/src/server/background-lifecycle.ts @@ -34,6 +34,7 @@ import { type MemoryWatchdog, } from "./memory-watchdog"; import { ensureQuotaPoolIdentity } from "../quota-pool/identity"; +import { installApiKeyCooldownPersistence, uninstallApiKeyCooldownPersistence } from "../providers/api-key-cooldown-store"; import { isTelemetryEnvOptOut } from "../telemetry/consent"; // The state module alone: the scheduler and its aggregation stay behind the dynamic import below. import { TELEMETRY_ENV_OPT_OUT_REFRESH_MS, endTelemetryEnvOptOut, recordTelemetryEnvOptOut } from "../telemetry/state"; @@ -218,6 +219,7 @@ function stopProcessLoops(): void { stopCatalogAutoRefresh(); setCatalogAutoRefreshClientFanout(null); setLivePolicyOwner(null); + uninstallApiKeyCooldownPersistence({ dropLocalHolds: true }); } async function stopStoragePolicyWorker(): Promise { @@ -279,6 +281,9 @@ export function acquireServerBackgroundLifecycle( // The quota-pool identity (homeId and the accountRef key) is minted here, per server and off // the request path, so GET /api/quota-pool only ever reads it. try { ensureQuotaPoolIdentity(); } catch { /* the read reports quota_pool_identity_unavailable */ } + // Confirmed API-key cooldowns survive a restart only for a running server: the first lease + // binds the config dir's file, and the final release (stopProcessLoops) detaches it. + installApiKeyCooldownPersistence(config); const owner: LeaseOwner = { token: Symbol("server-background-lifecycle"), @@ -297,6 +302,7 @@ export function acquireServerBackgroundLifecycle( } catch (error) { owner.lowQuota(); owner.resources.release(); + if (owners.length === 0) uninstallApiKeyCooldownPersistence({ dropLocalHolds: true }); throw error; } diff --git a/structure/providers-and-adapters.md b/structure/providers-and-adapters.md index a099f8c4b71..9e6fbd29b32 100644 --- a/structure/providers-and-adapters.md +++ b/structure/providers-and-adapters.md @@ -283,7 +283,7 @@ Cursor, one lease spans the whole turn: RunSSE and BidiAppend may overlap inside turns wait at the cap. Follow-up sends still obey start intervals. The turn owner returns its lease after `runTurn` settles, so RunSSE body completion cannot admit another turn early. A capped canonical Codex WebSocket turn uses HTTP/SSE because the socket has no response-body lifecycle. -Capacity waits use the same bounded queue and retryable queue-overload errors as interval waits. Optional `requestPacing.keys` adds a shared cross-model limit for each credential reference; duplicate references share capacity, but distinct references resolving to one upstream project do not imply separate quota. `keySelection: round-robin` assigns request-local healthy keys without mutating persisted selection, skips disabled entries (including keys paused by [permanent refusal auto-pause](account-auto-pause.md)) and known cooldowns, and refuses exhausted pools with retryable 429. Provider, model and key gates reserve atomically; key counters and the allocation cursor are process-local, not token or billing balances. OAuth and forwarded credentials retain their existing selection. Cooldown state is shared through the dependency-light `src/providers/api-key-cooldowns.ts` (retaining the longest outstanding expiry until explicit manual clearing) owner. Distributed selections are checked again at physical dispatch; a cooled queued key releases its old permit, selects a healthy sibling, and reacquires pacing before sending. Native Messages follows the same readmission rule. Native Responses, compact, Chat and Messages settle distributed refusals from immutable credential and destination metadata captured by `src/providers/api-key-response-ownership.ts` at physical fetch; successful same-key retry and unowned refusals do not cool keys. Failure ownership remains valid for a still-configured cooling key, so late in-flight rejections retain the longest cooldown without admitting another send. CLI-backed adapters check `IncomingMeta.beforePhysicalSend` after asynchronous setup and before spawn. An established distributed turn refuses later sends after its key cools instead of changing credentials mid-turn. +Capacity waits use the same bounded queue and retryable queue-overload errors as interval waits. Optional `requestPacing.keys` adds a shared cross-model limit for each credential reference; duplicate references share capacity, but distinct references resolving to one upstream project do not imply separate quota. `keySelection: round-robin` assigns request-local healthy keys without mutating persisted selection, skips disabled entries (including keys paused by [permanent refusal auto-pause](account-auto-pause.md)) and known cooldowns, and refuses exhausted pools with retryable 429. Provider, model and key gates reserve atomically; key counters and the allocation cursor are process-local, not token or billing balances. OAuth and forwarded credentials retain their existing selection. Cooldown state is shared through the dependency-light `src/providers/api-key-cooldowns.ts` (retaining the longest outstanding expiry until explicit manual clearing) owner. A running server persists those holds through `src/providers/api-key-cooldown-store.ts`: `acquireServerBackgroundLifecycle` installs it for the first live server and the final release detaches it (tests and tools that only adopt a config stay in memory). `/api-key-cooldowns.json` stores only provider, key id, expiry, clear counters, a truncated key fingerprint as the generation and, for a refusal that proved the key's quota or credit spent, `quotaSpentUntil` (bounded by the expiry), so a quota-only Combo still leaves a spent pool after a restart. Only inline keys are written; values the resolver reads from the environment (any `$` prefix), `keychain:` references and `gcp-sa:` markers keep their holds in memory, because the secret behind them can change under an unchanged value. Rows are kept per generation, so restore picks the configured key's row and the live reconcile drops a replaced key's hold; switching config homes drops the previous home's in-memory holds. Flushes merge with peer processes under the config mutation lock (same generation keeps the later expiry and the later spent-quota evidence). A manual clear increments a per-provider (or global) counter in the file, and only rows tagged with the current counters survive, so a peer's hold recorded before it learned of the clear never returns however late it flushes, and a process that reads a peer's newer counter drops its own in-memory holds for that provider. Pending holds coalesce per key, generation and counters while writes fail; expiry checks and sweeps never write. `tests/providers/api-key-cooldown-store.test.ts` covers restart, expiry, spent-quota evidence across restarts and peers, key replacement, references, clear ordering within and across processes, shared-home merges, home switches and the server lifecycle. Distributed selections are checked again at physical dispatch; a cooled queued key releases its old permit, selects a healthy sibling, and reacquires pacing before sending. Native Messages follows the same readmission rule. Native Responses, compact, Chat and Messages settle distributed refusals from immutable credential and destination metadata captured by `src/providers/api-key-response-ownership.ts` at physical fetch; successful same-key retry and unowned refusals do not cool keys. Failure ownership remains valid for a still-configured cooling key, so late in-flight rejections retain the longest cooldown without admitting another send. CLI-backed adapters check `IncomingMeta.beforePhysicalSend` after asynchronous setup and before spawn. An established distributed turn refuses later sends after its key cools instead of changing credentials mid-turn. Command Code effort defaults in `src/providers/command-code-efforts.ts` combine public-profile facts with the live API measurements from #5096. Both presets share the exact per-model rows; `xhigh` is preserved when accepted, and narrow ladders such as Laguna's `medium`-only row remain narrow. Rows without a verified profile URL still record rejected efforts but skip profile fetching. diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 805d38ac478..f73e47de83c 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1843,5 +1843,6 @@ "link-served-runtime-trust.test.ts": "clients", "link-ws-autobahn.test.ts": "clients", "routing-profile-types-reexport.test.ts": "config", - "provider-quota-probe-isolation.test.ts": "providers" + "provider-quota-probe-isolation.test.ts": "providers", + "api-key-cooldown-store.test.ts": "providers" } diff --git a/tests/providers/api-key-cooldown-store.test.ts b/tests/providers/api-key-cooldown-store.test.ts new file mode 100644 index 00000000000..951268ccca3 --- /dev/null +++ b/tests/providers/api-key-cooldown-store.test.ts @@ -0,0 +1,430 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmdirSync, statSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { setTimeout as wait } from "node:timers/promises"; +import { getConfigPath, saveConfig } from "../../src/config"; +import { + apiKeyCooldownGeneration, + clearKeyCooldowns, + getKeyCooldownUntil, + isKeyInCooldown, + isKeyQuotaSpent, + reconcileApiKeyCooldownGenerations, + resetLocalApiKeyCooldowns, + restoreApiKeyCooldowns, + setKeyCooldown, +} from "../../src/providers/api-key-cooldowns"; +import { + API_KEY_COOLDOWN_FILE, + ApiKeyCooldownStore, + installApiKeyCooldownPersistence, + isInlineApiKey, + uninstallApiKeyCooldownPersistence, + type ApiKeyCooldownHold, + type ApiKeyCooldownRow, +} from "../../src/providers/api-key-cooldown-store"; +import { rotateKeyOn429 } from "../../src/providers/key-failover"; +import { setLiveStateStoreConfig } from "../../src/lib/state-store-registrations"; +import { acquireServerBackgroundLifecycle } from "../../src/server/background-lifecycle"; +import type { OcxConfig, OcxProviderConfig } from "../../src/types"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +let home: string; +let previous: string | undefined; +const file = (dir = home) => join(dir, API_KEY_COOLDOWN_FILE); +const stored = () => JSON.parse(readFileSync(file(), "utf8")) as { rows: ApiKeyCooldownRow[]; epochs: Record; allEpoch: number }; +const hold = (keyId: string, key: string, cooldownUntil: number, provider = "p"): ApiKeyCooldownHold => + ({ provider, keyId, generation: apiKeyCooldownGeneration(provider, keyId, key), cooldownUntil }); +const row = (keyId: string, key: string, cooldownUntil: number, provider = "p"): ApiKeyCooldownRow => + ({ ...hold(keyId, key, cooldownUntil, provider), epoch: 0, allEpoch: 0 }); +const writeRows = (rows: ApiKeyCooldownRow[], dir = home) => writeFileSync(file(dir), JSON.stringify({ version: 1, rows })); +const keyIds = (rows: { keyId: string }[]) => rows.map(r => r.keyId).sort(); + +function config(keys: Record): OcxConfig { + return { + port: 0, + defaultProvider: "p", + providers: { + p: { + adapter: "openai-chat", + baseUrl: "https://api.example.com/v1", + apiKey: Object.values(keys)[0], + apiKeyPool: Object.entries(keys).map(([id, key], index) => ({ id, key, addedAt: index + 1 })), + } as OcxProviderConfig, + }, + } as OcxConfig; +} + +/** A restart: the process memory is gone, the file is not. */ +function restart(cfg: OcxConfig): ApiKeyCooldownStore { + uninstallApiKeyCooldownPersistence(); + resetLocalApiKeyCooldowns(); + return installApiKeyCooldownPersistence(cfg); +} + +beforeEach(() => { + previous = process.env.OPENCODEX_HOME; + home = mkdtempSync(join(tmpdir(), "ocx-key-cooldown-")); + process.env.OPENCODEX_HOME = home; + resetLocalApiKeyCooldowns(); +}); +afterEach(() => { + uninstallApiKeyCooldownPersistence(); + resetLocalApiKeyCooldowns(); + if (previous === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previous; + removeTreeWithRetry(home); +}); + +test("a key cooled before a restart stays cooled until its expiry", () => { + const cfg = config({ a: "sk-alpha-0001", b: "sk-beta-0002" }); + const store = installApiKeyCooldownPersistence(cfg); + const until = Date.now() + 60_000; + setKeyCooldown("p", "a", until, false, "sk-alpha-0001"); + expect(store.flush()).toBe(true); + expect(stored().rows).toEqual([row("a", "sk-alpha-0001", until)]); + expect(readFileSync(file(), "utf8")).not.toContain("sk-alpha"); + + restart(cfg); + expect(getKeyCooldownUntil("p", "a")).toBe(until); + expect(isKeyInCooldown("p", "b")).toBe(false); +}); + +test("a failover rotation records the failed key's row", () => { + const cfg = config({ k1: "key-alpha-000111222333", k2: "key-beta-444555666777" }); + saveConfig(cfg); + const store = installApiKeyCooldownPersistence(cfg); + const now = Date.now(); + expect(rotateKeyOn429(cfg, "p", "120", now)?.apiKey).toBe("key-beta-444555666777"); + expect(store.flush()).toBe(true); + expect(stored().rows).toEqual([row("k1", "key-alpha-000111222333", now + 120_000)]); +}); + +test.skipIf(process.platform === "win32")("the cooldown file is private like config.json and holds no key or fingerprint source", () => { + const cfg = config({ a: "sk-alpha-0001" }); + saveConfig(cfg); + const store = installApiKeyCooldownPersistence(cfg); + setKeyCooldown("p", "a", Date.now() + 60_000, false, "sk-alpha-0001"); + expect(store.flush()).toBe(true); + expect(statSync(file()).mode & 0o777).toBe(0o600); + expect(statSync(file()).mode & 0o777).toBe(statSync(getConfigPath()).mode & 0o777); + expect(readFileSync(file(), "utf8")).not.toContain("sk-alpha-0001"); +}); + +test("a provider named like an Object.prototype member keeps its holds across a restart", () => { + for (const name of ["valueOf", "toString"]) { + const cfg = config({ a: "sk-alpha-0001" }); + cfg.providers = { [name]: cfg.providers.p! }; + cfg.defaultProvider = name; + const store = restart(cfg); + const until = Date.now() + 60_000; + setKeyCooldown(name, "a", until, false, "sk-alpha-0001"); + expect(store.flush()).toBe(true); + restart(cfg); + expect(getKeyCooldownUntil(name, "a")).toBe(until); + } +}); + +test("expired and malformed rows are ignored at load", () => { + const now = Date.now(); + writeRows([row("a", "sk-alpha-0001", now - 1_000), row("b", "sk-beta-0002", now + 60_000)]); + installApiKeyCooldownPersistence(config({ a: "sk-alpha-0001", b: "sk-beta-0002" })); + expect(isKeyInCooldown("p", "a")).toBe(false); + expect(isKeyInCooldown("p", "b")).toBe(true); + + writeFileSync(file(), "{not json"); + restart(config({ a: "sk-alpha-0001", b: "sk-beta-0002" })); + expect(isKeyInCooldown("p", "b")).toBe(false); +}); + +test("a key replaced under the same id does not inherit the old key's hold", () => { + writeRows([row("a", "sk-old-0001", Date.now() + 60_000)]); + installApiKeyCooldownPersistence(config({ a: "sk-new-0002" })); + expect(isKeyInCooldown("p", "a")).toBe(false); + + // While running: a replaced key drops the hold at the next reconcile. + setKeyCooldown("p", "a", Date.now() + 60_000, false, "sk-new-0002"); + expect(reconcileApiKeyCooldownGenerations(config({ a: "sk-new-0002" }).providers)).toBe(0); + expect(reconcileApiKeyCooldownGenerations(config({ a: "sk-newer-0003" }).providers)).toBe(1); + expect(isKeyInCooldown("p", "a")).toBe(false); +}); + +test("a cooldown for a new key replaces a longer hold of the old key", () => { + const now = Date.now(); + setKeyCooldown("p", "a", now + 600_000, false, "sk-old-0001"); + setKeyCooldown("p", "a", now + 60_000, false, "sk-new-0002"); + expect(getKeyCooldownUntil("p", "a", now)).toBe(now + 60_000); + setKeyCooldown("p", "a", now + 30_000, false, "sk-new-0002"); + expect(getKeyCooldownUntil("p", "a", now)).toBe(now + 60_000); +}); + +test("a manual clear is persisted, so a restart does not revive the hold", () => { + const cfg = config({ a: "sk-alpha-0001" }); + const store = installApiKeyCooldownPersistence(cfg); + setKeyCooldown("p", "a", Date.now() + 60_000, false, "sk-alpha-0001"); + expect(store.flush()).toBe(true); + clearKeyCooldowns("p"); + expect(store.flush()).toBe(true); + expect(stored().rows).toEqual([]); + + restart(cfg); + expect(isKeyInCooldown("p", "a")).toBe(false); +}); + +test("a hold recorded right after a clear in the same process survives it", () => { + const cfg = config({ a: "sk-alpha-0001" }); + const store = installApiKeyCooldownPersistence(cfg); + const now = Date.now(); + setKeyCooldown("p", "a", now + 600_000, false, "sk-alpha-0001"); + // No time passes between these: ordering comes from the clear counter, not the clock. + clearKeyCooldowns("p"); + setKeyCooldown("p", "a", now + 60_000, false, "sk-alpha-0001"); + expect(store.flush(now)).toBe(true); + expect(stored().rows.map(r => r.cooldownUntil)).toEqual([now + 60_000]); + restart(cfg); + expect(getKeyCooldownUntil("p", "a", now)).toBe(now + 60_000); +}); + +test("a provider clear removes peer rows for that provider, and a global clear removes every row", () => { + const now = Date.now(); + writeRows([row("a", "sk-a", now + 60_000), row("x", "sk-x", now + 60_000, "q")]); + const store = new ApiKeyCooldownStore(home); + store.load(now); + store.clear("p"); + store.record(hold("b", "sk-b", now + 30_000)); + expect(store.flush(now)).toBe(true); + expect(keyIds(stored().rows)).toEqual(["b", "x"]); + store.clear(); + expect(store.flush(now)).toBe(true); + expect(stored().rows).toEqual([]); + expect(new ApiKeyCooldownStore(home).load(now)).toEqual([]); +}); + +test("a peer's pending holds from before a clear never come back, however late it flushes", () => { + const now = Date.now(); + const slow = new ApiKeyCooldownStore(home); + slow.load(now); + slow.record(hold("a", "sk-a", now + 600_000)); + const clearing = new ApiKeyCooldownStore(home); + clearing.load(now); + clearing.clear("p"); + expect(clearing.flush(now)).toBe(true); + // The slow peer has not seen the clear: a shorter hold it records now is still pre-clear evidence. + slow.record(hold("a", "sk-a", now + 60_000)); + expect(slow.flush(now)).toBe(true); + expect(stored().rows).toEqual([]); + // Having flushed, it knows the clear; its next hold persists. + slow.record(hold("a", "sk-a", now + 30_000)); + expect(slow.flush(now)).toBe(true); + expect(stored().rows.map(r => r.cooldownUntil)).toEqual([now + 30_000]); +}); + +test("two processes sharing a home merge their rows and never shorten a peer's hold", () => { + const now = Date.now(); + const first = new ApiKeyCooldownStore(home); + const second = new ApiKeyCooldownStore(home); + first.record(hold("a", "sk-a", now + 60_000)); + expect(first.flush(now)).toBe(true); + second.record(hold("b", "sk-b", now + 60_000)); + second.record(hold("a", "sk-a", now + 30_000)); + expect(second.flush(now)).toBe(true); + expect(stored().rows.sort((x, y) => x.keyId.localeCompare(y.keyId))) + .toEqual([row("a", "sk-a", now + 60_000), row("b", "sk-b", now + 60_000)]); +}); + +test("a peer flushing an old key's row last cannot displace the current key's row", () => { + const now = Date.now(); + const stale = new ApiKeyCooldownStore(home); + const current = new ApiKeyCooldownStore(home); + stale.record(hold("a", "sk-old", now + 600_000)); + current.record(hold("a", "sk-new", now + 60_000)); + expect(current.flush(now)).toBe(true); + expect(stale.flush(now)).toBe(true); + expect(stored().rows).toHaveLength(2); + + installApiKeyCooldownPersistence(config({ a: "sk-new" }), now); + expect(getKeyCooldownUntil("p", "a", now)).toBe(now + 60_000); +}); + +test("only inline keys are persisted; every value the resolver reads elsewhere stays in memory", () => { + for (const reference of ["${OCX_TEST_KEY}", "$OCX_TEST_KEY", "$KEY-NAME", "keychain:p/chain", "gcp-sa:p/acct"]) { + expect(isInlineApiKey(reference)).toBe(false); + } + expect(isInlineApiKey("sk-inline")).toBe(true); + const cfg = config({ env: "${OCX_TEST_KEY}", dash: "$KEY-NAME", chain: "keychain:p/chain", inline: "sk-inline" }); + const store = installApiKeyCooldownPersistence(cfg); + const until = Date.now() + 60_000; + for (const entry of cfg.providers.p!.apiKeyPool!) setKeyCooldown("p", entry.id, until, false, entry.key); + expect(store.flush()).toBe(true); + expect(keyIds(stored().rows)).toEqual(["inline"]); + expect(isKeyInCooldown("p", "dash")).toBe(true); + + // A row written for a referenced entry is never restored either. + writeRows([row("dash", "$KEY-NAME", until)]); + restart(cfg); + expect(isKeyInCooldown("p", "dash")).toBe(false); +}); + +test("switching homes drops the previous home's holds before restoring", () => { + const now = Date.now(); + installApiKeyCooldownPersistence(config({ a: "sk-one" }), now); + setKeyCooldown("p", "a", now + 600_000, false, "sk-one"); + const other = mkdtempSync(join(tmpdir(), "ocx-key-cooldown-other-")); + try { + process.env.OPENCODEX_HOME = other; + installApiKeyCooldownPersistence(config({ a: "sk-one" }), now); + expect(isKeyInCooldown("p", "a", now)).toBe(false); + uninstallApiKeyCooldownPersistence(); + + writeRows([row("a", "sk-one", now + 60_000)], other); + process.env.OPENCODEX_HOME = home; + installApiKeyCooldownPersistence(config({ a: "sk-one" }), now); + process.env.OPENCODEX_HOME = other; + installApiKeyCooldownPersistence(config({ a: "sk-one" }), now); + expect(getKeyCooldownUntil("p", "a", now)).toBe(now + 60_000); + } finally { + uninstallApiKeyCooldownPersistence(); + process.env.OPENCODEX_HOME = home; + removeTreeWithRetry(other); + } +}); + +test("only a live server binds the file, and its final release detaches it", async () => { + const cfg = config({ a: "sk-alpha-0001" }); + const until = Date.now() + 60_000; + writeRows([row("a", "sk-alpha-0001", until)]); + setLiveStateStoreConfig(cfg); + expect(isKeyInCooldown("p", "a")).toBe(false); + + const lease = acquireServerBackgroundLifecycle(() => {}, cfg); + expect(getKeyCooldownUntil("p", "a")).toBe(until); + await lease.release(); + expect(isKeyInCooldown("p", "a")).toBe(false); + + // After the last server stops, a cooldown and a clear stay in memory and leave the file alone. + const before = readFileSync(file(), "utf8"); + setKeyCooldown("p", "a", until + 60_000, false, "sk-alpha-0001"); + clearKeyCooldowns("p"); + await wait(400); + expect(readFileSync(file(), "utf8")).toBe(before); +}); + +test("a peer's clear also drops this process's in-memory hold, so a later refusal is not extended by it", () => { + const cfg = config({ a: "sk-alpha-0001" }); + const store = installApiKeyCooldownPersistence(cfg); + const now = Date.now(); + setKeyCooldown("p", "a", now + 600_000, false, "sk-alpha-0001"); + expect(store.flush(now)).toBe(true); + const peer = new ApiKeyCooldownStore(home); + peer.load(now); + peer.clear("p"); + expect(peer.flush(now)).toBe(true); + + // Recorded before this process learned of the clear: neither persisted nor kept as the old maximum. + setKeyCooldown("p", "a", now + 30_000, false, "sk-alpha-0001"); + expect(store.flush(now)).toBe(true); + expect(stored().rows).toEqual([]); + expect(isKeyInCooldown("p", "a", now)).toBe(false); + + setKeyCooldown("p", "a", now + 30_000, false, "sk-alpha-0001"); + expect(getKeyCooldownUntil("p", "a", now)).toBe(now + 30_000); + expect(store.flush(now)).toBe(true); + expect(stored().rows.map(r => r.cooldownUntil)).toEqual([now + 30_000]); +}); + +for (const scope of ["provider", "global"] as const) { + test(`a ${scope} clear rebased above a peer's keeps the hold recorded after it`, () => { + const cfg = config({ a: "sk-alpha-0001" }); + const store = installApiKeyCooldownPersistence(cfg); + const now = Date.now(); + const peer = new ApiKeyCooldownStore(home); + peer.load(now); + if (scope === "provider") peer.clear("p"); else peer.clear(); + expect(peer.flush(now)).toBe(true); + + // This process clears without having seen the peer's clear, then records a fresh refusal. + clearKeyCooldowns(scope === "provider" ? "p" : undefined); + setKeyCooldown("p", "a", now + 60_000, false, "sk-alpha-0001"); + expect(store.flush(now)).toBe(true); + expect(getKeyCooldownUntil("p", "a", now)).toBe(now + 60_000); + expect(stored().rows.map(r => r.cooldownUntil)).toEqual([now + 60_000]); + restart(cfg); + expect(getKeyCooldownUntil("p", "a", now)).toBe(now + 60_000); + }); +} + +test("a server for another home started after the last one stopped inherits no holds", () => { + const now = Date.now(); + installApiKeyCooldownPersistence(config({ a: "sk-one" }), now); + setKeyCooldown("p", "a", now + 600_000, false, "sk-one"); + // The final server release. + uninstallApiKeyCooldownPersistence({ dropLocalHolds: true }); + const other = mkdtempSync(join(tmpdir(), "ocx-key-cooldown-other-")); + try { + process.env.OPENCODEX_HOME = other; + installApiKeyCooldownPersistence(config({ a: "sk-one" }), now); + expect(isKeyInCooldown("p", "a", now)).toBe(false); + } finally { + uninstallApiKeyCooldownPersistence(); + process.env.OPENCODEX_HOME = home; + removeTreeWithRetry(other); + } +}); + +test("pending holds coalesce while writes keep failing", () => { + const now = Date.now(); + const store = new ApiKeyCooldownStore(home); + // A directory where the file belongs makes every write fail. + mkdirSync(file()); + for (let i = 1; i <= 500; i += 1) store.record(hold("a", "sk-a", now + i * 1_000)); + store.record(hold("b", "sk-b", now + 5_000)); + expect(store.flush(now)).toBe(false); + expect(store.flush(now)).toBe(false); + expect(store.pendingHolds).toBe(2); + rmdirSync(file()); + expect(store.flush(now)).toBe(true); + expect(stored().rows.map(r => [r.keyId, r.cooldownUntil]).sort()).toEqual([["a", now + 500_000], ["b", now + 5_000]]); +}); + +test("a store whose home was removed drops its pending rows", () => { + const gone = join(home, "gone"); + const store = new ApiKeyCooldownStore(gone); + store.record(hold("a", "sk-a", Date.now() + 60_000)); + expect(store.flush()).toBe(true); + expect(existsSync(gone)).toBe(false); +}); + +test("a spent-quota hold stays spent across a restart, so a quota-only Combo can leave a spent pool", () => { + const cfg = config({ a: "sk-alpha-0001", b: "sk-beta-0002" }); + const store = installApiKeyCooldownPersistence(cfg); + const until = Date.now() + 600_000; + setKeyCooldown("p", "a", until, true, "sk-alpha-0001"); + setKeyCooldown("p", "b", until, true, "sk-beta-0002"); + expect(store.flush()).toBe(true); + restart(cfg); + // The predicate core-combo-failure uses: every enabled key refused with a spent quota. + expect(["a", "b"].every(id => isKeyQuotaSpent("p", id))).toBe(true); + expect(isKeyInCooldown("p", "a")).toBe(true); +}); + +test("a longer ordinary hold keeps the shorter spent-quota evidence, on restore and across peers", () => { + const cfg = config({ a: "sk-alpha-0001" }); + const now = Date.now(); + const generation = apiKeyCooldownGeneration("p", "a", "sk-alpha-0001"); + setKeyCooldown("p", "a", now + 60_000, true, "sk-alpha-0001"); + restoreApiKeyCooldowns([{ provider: "p", keyId: "a", generation, cooldownUntil: now + 600_000 }], now); + expect(getKeyCooldownUntil("p", "a", now)).toBe(now + 600_000); + expect(isKeyQuotaSpent("p", "a", now)).toBe(true); + + resetLocalApiKeyCooldowns(); + const spentPeer = new ApiKeyCooldownStore(home); + const ordinaryPeer = new ApiKeyCooldownStore(home); + spentPeer.record({ ...hold("a", "sk-alpha-0001", now + 60_000), quotaSpentUntil: now + 60_000 }); + ordinaryPeer.record(hold("a", "sk-alpha-0001", now + 600_000)); + expect(spentPeer.flush()).toBe(true); + expect(ordinaryPeer.flush()).toBe(true); + expect(stored().rows).toEqual([{ ...row("a", "sk-alpha-0001", now + 600_000), quotaSpentUntil: now + 60_000 }]); + restart(cfg); + expect(getKeyCooldownUntil("p", "a")).toBe(now + 600_000); + expect(isKeyQuotaSpent("p", "a")).toBe(true); +}); From a3e2c70b362557322ccc5d1672452d30ebd2a74b Mon Sep 17 00:00:00 2001 From: Arthur tinseau <65445747+atinseau@users.noreply.github.com> Date: Wed, 25 Nov 2026 07:40:32 +0100 Subject: [PATCH 40/60] feat(combos): manage quota-only failover from the API and CLI (#9090) Manage quota-only Combo failover from the management API and the CLI (set, partial update and preview), with the Combo guides describing the quota-only consent refusal. Co-authored-by: JUN --- .../src/content/docs/es/guides/combos.md | 35 ++++++++++--- .../src/content/docs/fr/guides/combos.md | 24 +++++++++ docs-site/src/content/docs/guides/combos.md | 49 ++++++++++++++++--- .../references/01_surface_agents-routing.md | 4 +- src/cli/capabilities-agents-routing.ts | 4 +- src/cli/combo-input.ts | 20 ++++++-- src/cli/combo-result.ts | 3 +- src/cli/combo.ts | 9 ++++ src/server/management/combo-routes.ts | 46 ++++++++++++++--- tests/cli/cli-combo-partial-update.test.ts | 11 +++++ tests/routing/combo-management-api.test.ts | 18 +++++++ 11 files changed, 193 insertions(+), 30 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/combos.md b/docs-site/src/content/docs/es/guides/combos.md index 2dc307a0fdb..b101bca8b09 100644 --- a/docs-site/src/content/docs/es/guides/combos.md +++ b/docs-site/src/content/docs/es/guides/combos.md @@ -12,6 +12,24 @@ Esto es útil cuando usted quiere: Los combos se evalúan antes del enrutamiento normal de proveedores. Consulta primero [Enrutamiento de modelos](/es/guides/model-routing/) si aún no conoces los selectores `provider/model`. +## Fallback al agotarse la cuota + +**Cambiar solo cuando se agote la cuota** (`quotaOnlyFallback`) avanza tras confirmar que se agotó +la cuota o el saldo. Un destino con varias claves de API avanza cuando cada clave activa informa +una cuota o un saldo agotados. Los destinos fuera de una suscripción reconocida o una ruta local explícita de +loopback requieren consentimiento, incluidas las claves personalizadas y las redirecciones. Un destino +sin autorización devuelve `combo_metered_consent_required`. Si no se puede recuperar el destino de +una llamada a herramienta, la continuación devuelve `409 combo_tool_target_unavailable`. El límite +de tokens de salida deja el modelo disponible para el turno siguiente. + +**Mantener el mismo modelo** (`preserveFallbackModel`) exige el mismo identificador de modelo +resuelto, incluso entre proveedores. Si cambia, devuelve `409 combo_model_change_refused`. + +```bash +ocx combo set openai-first --quota-only-fallback on +ocx combo set exact-model --preserve-fallback-model on +``` + ## Consentimiento de fallback medido @@ -21,18 +39,22 @@ Marque un objetivo combinado de pago por uso con `"metered": true` cuando siga l - **Local Claude Code o Codex:** en un proxy solo loopback, establezca `"allowMeteredTargets": true` en el combo o ejecute `ocx combo set --allow-metered-targets on`. Esto permite explícitamente a las personas que llaman locales usar sus objetivos marcados. El valor predeterminado es falso; `off` borra el consentimiento. La autenticación de loopback no lee las claves API. - **Llamadas en red o vinculadas:** la entrada `apiKeys[]` configurada por el llamante debe tener `"allowMeteredComboTargets": true`. Un proxy con un oyente que no es loopback ignora la bandera combinada, incluso en su oyente de loopback secundario. Las personas que llaman vinculadas también retienen su requisito de consentimiento de clave configurada cuando el oyente principal es loopback. El token de entorno nunca califica. -Los encabezados de solicitud no pueden otorgar consentimiento. Los alcances de modelo/proveedor todavía se aplican. Esto cubre la selección inicial, la conmutación por error y la recuperación a través de estrategias combinadas, compactación, Messages, Chat Completions y WebSocket, y un modelo de subagente alternativo que nombra un alias combinado. Una reserva colapsada intenta un objetivo no medido utilizable antes de rechazarlo. Los objetivos no marcados conservan el comportamiento existente; el operador declara la medición en lugar de detectarla automáticamente. +Los encabezados de solicitud no pueden otorgar consentimiento. Los alcances de modelo/proveedor todavía se aplican. Esto cubre la selección inicial, la conmutación por error y la recuperación a través de estrategias combinadas, compactación, Messages, Chat Completions y WebSocket, y un modelo de subagente alternativo que nombra un alias combinado. Fuera del modo de cuota, una reserva colapsada intenta un objetivo no medido utilizable antes de rechazarlo. Un combo colapsado con cambio solo por cuota se detiene en el primer destino de pago sin consentimiento con `combo_metered_consent_required`. Fuera del modo de cuota, solo la marca `metered` del operador hace que un objetivo necesite consentimiento. En el modo de cuota, un objetivo no marcado también lo necesita cuando su destino está fuera de una suscripción reconocida o de una ruta local explícita de loopback. Una solicitud vuelve a comprobar el consentimiento y el alcance de modelos de su clave justo antes de cada envío de pago: la llamada de decisión de JEV y cada intento de destino, incluidos la conmutación por error, los reintentos y los envíos fijados. Por eso, retirar el consentimiento o reducir el alcance de una clave detiene los envíos que la solicitud aún no ha hecho. Se omite el destino que ya no cumple los requisitos y otro destino elegible puede atender la solicitud; si no queda ninguno, la solicitud -termina con el `combo_unavailable` habitual o con el rechazo por alcance. Los demás cambios del combo, +termina con el `combo_unavailable` habitual o con el rechazo por alcance. Un combo con cambio solo por +cuota no omite un destino que perdió el consentimiento. Devuelve `403 combo_metered_consent_required`, +igual que una continuación de herramienta fijada a ese destino. Los demás cambios del combo, como las capacidades, el Vision Sidecar, los ajustes de protocolo o la lista de destinos, se aplican a -partir de la siguiente solicitud. Una solicitud en curso conserva la configuración con la que empezó. +partir de la siguiente solicitud. Una solicitud en curso conserva la configuración con la que empezó. Una continuación de herramienta +fijada de un combo con cambio solo por cuota vuelve a comprobar antes del envío que su destino sigue en el +combo y que su ruta no cambió. -Por ejemplo, una cadena de fallback puede probar Anthropic OAuth, después Cursor y finalmente `{ "provider": "anthropic-apikey", "model": "claude-opus-5-5", "metered": true }`. Sin consentimiento, al agotar los destinos se devuelve el último error de un objetivo no medido, con las excepciones de [desbordamiento de contexto confirmado](#context-window-refusals) y de cuota: un rechazo anterior 429 o 402 tiene prioridad sobre un 400, 401 o 403 posterior. Si la suscripción devuelve 429 y Cursor luego rechaza con 401 o 403, se devuelve el 429 porque explica el agotamiento de la suscripción. Los guardados del dashboard conservan la medición de objetivos y el consentimiento del combo cuando se omiten; `false` explícito los elimina. Estos ajustes se configuran en el archivo o la API; la bandera del combo también está disponible en la CLI, pero el dashboard no la expone. +Por ejemplo, una cadena de fallback puede probar Anthropic OAuth, después Cursor y finalmente `{ "provider": "anthropic-apikey", "model": "claude-opus-5-5", "metered": true }`. En un combo de conmutación ordinario sin consentimiento, al agotar los destinos se devuelve el último error de un objetivo no medido, con las excepciones de [desbordamiento de contexto confirmado](#context-window-refusals) y de cuota: un rechazo anterior 429 o 402 de un destino enviado tiene prioridad sobre un 400, 401 o 403 posterior. Un combo con cambio solo por cuota que llega a un destino de pago sin consentimiento devuelve `403 combo_metered_consent_required`. Si la suscripción devuelve 429 y Cursor luego rechaza con 401 o 403, se devuelve el 429 porque explica el agotamiento de la suscripción. Los guardados del dashboard conservan la medición de objetivos y el consentimiento del combo cuando se omiten; `false` explícito los elimina. Estos ajustes se configuran en el archivo o la API; la bandera del combo también está disponible en la CLI, pero el dashboard no la expone. @@ -518,7 +540,8 @@ terminal incompleto puede poner ese destino en enfriamiento para la siguiente so puede aparecer en el evento terminal o en su instantánea `response`. Un rechazo en cualquiera de los dos tiene prioridad. `upstream_stall_timeout` aplica un enfriamiento de 60 segundos. `max_output_tokens` aplica uno de 10 minutos si el intento alcanza el límite de salida conocido -del modelo y el turno termina sin pausa. +del modelo y el turno termina sin pausa. Un combo con `quotaOnlyFallback` no aplica este enfriamiento, así +que el objetivo sigue disponible para el turno siguiente. El preajuste de Devin requiere que el límite de salida se configure explícitamente en el proveedor para aplicar este enfriamiento. Si ya hay un enfriamiento con un vencimiento posterior, ese vencimiento se conserva. @@ -589,7 +612,7 @@ Un combo también puede avanzar después de un HTTP 400 `invalid_request_error` Cuando un modelo le pide a su cliente que ejecute una herramienta, la solicitud que devuelve el resultado de la herramienta finaliza el mismo turno de asistente. OpenCodex envía esa solicitud al objetivo que emitió la llamada a la herramienta, siempre que el objetivo aún esté habilitado, aún en el combo y fuera del tiempo de reutilización. Esto se aplica a todas las estrategias, incluido JEV, que omite su decisión para esa solicitud. El siguiente mensaje de usuario elige un destino normalmente. -El seguimiento utiliza el hilo o el identificador de sesión del cliente, por lo que un cliente que no envía ninguno recibe una selección normal. Si el objetivo original no está disponible o falla, el combo falla como de costumbre, y el nuevo objetivo recibe las llamadas a la herramienta anterior de la forma que acepta. DeepSeek modelos de pensamiento obtienen un marcador de posición de razonamiento de un espacio para una llamada de herramienta que otro modelo emitió sin razonamiento. Gemini obtiene el marcador de posición de firma documentado de Google. Anthropic recibe una simple llamada de herramienta y resultado. Las versiones anteriores podían enviar DeepSeek una llamada de herramienta desnuda aquí y fallar con `The reasoning_text in the +El seguimiento utiliza el hilo o el identificador de sesión del cliente, por lo que un cliente que no envía ninguno recibe una selección normal. Si el objetivo original no está disponible o falla, el combo falla como de costumbre, y el nuevo objetivo recibe las llamadas a la herramienta anterior de la forma que acepta. Con `quotaOnlyFallback`, la continuación se queda en ese objetivo: un fallo vuelve al cliente, y un objetivo que no puede atenderla devuelve `409 combo_tool_target_unavailable`, o `429 combo_tool_target_quota_exhausted` cuando agotó su cuota. DeepSeek modelos de pensamiento obtienen un marcador de posición de razonamiento de un espacio para una llamada de herramienta que otro modelo emitió sin razonamiento. Gemini obtiene el marcador de posición de firma documentado de Google. Anthropic recibe una simple llamada de herramienta y resultado. Las versiones anteriores podían enviar DeepSeek una llamada de herramienta desnuda aquí y fallar con `The reasoning_text in the thinking mode must be passed back to the API`. diff --git a/docs-site/src/content/docs/fr/guides/combos.md b/docs-site/src/content/docs/fr/guides/combos.md index 12bfa5a240f..636d3117010 100644 --- a/docs-site/src/content/docs/fr/guides/combos.md +++ b/docs-site/src/content/docs/fr/guides/combos.md @@ -15,6 +15,30 @@ Ceci est utile lorsque vous souhaitez : Les combos interviennent en amont du routage normal des fournisseurs. Consultez d’abord [Routage des modèles](/fr/guides/model-routing/) si vous ne connaissez pas encore les sélecteurs `provider/model`. +## Basculer quand le quota est épuisé + +**Basculer uniquement si le quota est épuisé** (`quotaOnlyFallback`) suit l’ordre déclaré après +confirmation d’un quota ou d’un crédit épuisé. Quand la cible essayée échoue sur une limite temporaire, un +quota inconnu, une erreur d’authentification ou une requête incompatible, la chaîne s’arrête là. Une cible +sans relevé de quota est quand même essayée dans l’ordre déclaré. Les règles de bascule, la rotation des comptes, les limites d’envoi et l’autorisation des appels +payants continuent de s’appliquer. Une cible servie par plusieurs clés API bascule une fois que +chaque clé active signale un quota ou un crédit épuisé. La bascule par quota exige un consentement pour toute destination +hors abonnement reconnu ou route locale explicite en boucle locale. Les clés personnalisées, la +facturation inconnue et les redirections sont couvertes. Un appel refusé renvoie +`combo_metered_consent_required`. Si la cible retenue pour la conversation, celle de son dernier tour servi par la Combo, est +inconnue ou indisponible, la continuation d’un appel d’outil renvoie `409 combo_tool_target_unavailable`. Un plafond de sortie laisse le modèle +disponible au tour suivant. + +**Garder le même modèle lors de la bascule** (`preserveFallbackModel`) exige le même identifiant de +modèle résolu entre deux cibles, même lorsque le fournisseur change. Un changement de modèle +renvoie `409 combo_model_change_refused`. Laissez cette option décochée +pour basculer entre familles de modèles. + +```bash +ocx combo set openai-first --quota-only-fallback on +ocx combo set exact-model --preserve-fallback-model on +``` + ## Démarrage rapide en 60 secondes Cet exemple crée `combo/main`, avec Anthropic en premier et OpenAI en second. Les deux fournisseurs doivent diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index 6d0aec50f28..18cf53e14df 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -15,6 +15,29 @@ This is useful when you want either: Combos sit in front of normal provider routing. Read [Model Routing](/guides/model-routing/) first if `provider/model` selectors are new to you. +## Fallback when quota runs out + +**Switch only when quota runs out** (`quotaOnlyFallback`) follows the declared order after confirmed +quota or billing exhaustion. When the attempted target fails with a temporary limit, an +unknown quota state, an invalid credential or an incompatible request, the chain stops there. A target +without a quota reading is still tried in declared order. Scoped fallback rules, account rotation, send limits and paid-call consent +continue to apply. A target backed by several API keys advances once every enabled key reports a +spent quota or credit. In quota-only mode, every destination outside a recognized subscription or an +explicit local loopback route requires consent. The policy covers custom API keys, unknown billing, +and redirects. An unauthorized step stops with `combo_metered_consent_required`. The client may +have its own admission key settings. A tool continuation with an unavailable or unrecognized serving +target stops with `409 combo_tool_target_unavailable`. Reaching a model's output ceiling leaves it +available for the next turn. + +**Keep the same model on fallback** (`preserveFallbackModel`) requires the same resolved model ID +across a hop, including between providers. A model change returns `409 combo_model_change_refused`. +Leave the setting off for a route that changes model families. + +```bash +ocx combo set openai-first --quota-only-fallback on +ocx combo set exact-model --preserve-fallback-model on +``` + ## Metered fallback consent Mark a pay-per-use combo target with `"metered": true` when it follows subscription targets. Omitted or false consent denies metered dispatch. Choose consent for your deployment: @@ -22,17 +45,20 @@ Mark a pay-per-use combo target with `"metered": true` when it follows subscript - **Local Claude Code or Codex:** on a loopback-only proxy, set `"allowMeteredTargets": true` on the combo, or run `ocx combo set --allow-metered-targets on`. This explicitly permits local callers to use its marked targets. The default is false; `off` clears consent. Loopback authentication does not read API keys. - **Network or linked callers:** the caller's configured `apiKeys[]` entry must have `"allowMeteredComboTargets": true`. A proxy with a non-loopback listener ignores the combo flag, including on its secondary loopback listener. Linked callers also retain their configured-key consent requirement when the primary listener is loopback. The environment token never qualifies. -Request headers cannot grant consent. Model/provider scopes still apply. This covers initial selection, failover and recovery across combo strategies, compaction, Messages, Chat Completions and WebSocket requests, and a subagent model fallback naming a combo alias. A collapsed fallback tries a usable unmetered target before refusing. Unmarked targets retain existing behavior; metering is declared by the operator rather than detected automatically. +Request headers cannot grant consent. Model/provider scopes still apply. This covers initial selection, failover and recovery across combo strategies, compaction, Messages, Chat Completions and WebSocket requests, and a subagent model fallback naming a combo alias. Outside quota-only mode, a collapsed fallback tries a usable unmetered target before refusing. A collapsed quota-only Combo stops at the first paid target without consent with `combo_metered_consent_required`. Outside quota-only mode, only the operator's `metered` flag makes a target need consent. In quota-only mode, an unmarked target also needs consent when its destination is outside a recognized subscription or an explicit local loopback route. A request rechecks consent and its key's model scope immediately before each paid send: the JEV decision call and every target attempt, including failover, retries and pinned sends. Revoking consent or narrowing a key's scope therefore stops sends the request has not made yet. A target that no longer qualifies is skipped and another eligible target may serve the request; when none remains, -the request ends with the usual `combo_unavailable` or scope refusal. Other combo edits, such as +the request ends with the usual `combo_unavailable` or scope refusal. A quota-only Combo does not +skip a target that lost consent. It returns `403 combo_metered_consent_required`, and so does a +quota-only tool continuation whose pinned target lost consent. Other combo edits, such as capabilities, the Vision Sidecar, protocol settings or the target list, apply from the next request. -A request already in progress keeps the settings it started with. +A request already in progress keeps the settings it started with. A pinned quota-only tool continuation +still rechecks its target's Combo membership and route before it sends. -For example, a failover chain can target Anthropic OAuth, then Cursor, then `{ "provider": "anthropic-apikey", "model": "claude-opus-5-5", "metered": true }`. Without consent, exhaustion returns the last unmetered error, with exceptions for [confirmed context overflow](#context-window-refusals) and quota refusals: an earlier 429 or 402 quota refusal takes precedence over a later 400, 401 or 403. If the subscription target returns 429 and Cursor then refuses with 401 or 403, the caller receives the subscription's 429, because the spent subscription explains the failure and Cursor's credential refusal does not. Dashboard saves retain omitted target metering and combo consent; explicitly setting either to false clears it. These consent fields are configured through the config file or API; the combo flag is also available through the CLI, while the dashboard does not expose it. +For example, a failover chain can target Anthropic OAuth, then Cursor, then `{ "provider": "anthropic-apikey", "model": "claude-opus-5-5", "metered": true }`. In an ordinary failover Combo without consent, exhaustion returns the last unmetered error, with exceptions for [confirmed context overflow](#context-window-refusals) and quota refusals: an earlier 429 or 402 quota refusal from a dispatched target takes precedence over a later 400, 401 or 403. A quota-only Combo that reaches a paid target without consent returns `403 combo_metered_consent_required` instead. If the subscription target returns 429 and Cursor then refuses with 401 or 403, the caller receives the subscription's 429, because the spent subscription explains the failure and Cursor's credential refusal does not. Dashboard saves retain omitted target metering and combo consent; explicitly setting either to false clears it. These consent fields are configured through the config file or API; the combo flag is also available through the CLI, while the dashboard does not expose it. ## 60-second quickstart @@ -803,7 +829,8 @@ After a Responses combo stream commits output, an incomplete terminal can cool t next request. The reason can appear on the terminal event or its `response` snapshot. A refusal on either carrier takes precedence. `upstream_stall_timeout` cools for 60 seconds. `max_output_tokens` cools for 10 minutes when the serving attempt reaches the routed model's known output ceiling and -the turn is unpaused. +the turn is unpaused. A Combo with `quotaOnlyFallback` skips this output-limit cooldown, so the target +stays available for the next turn. Devin's preset has no output ceiling, so this output-limit cooldown requires an explicit ceiling in the provider configuration. An existing longer cooldown keeps its expiry. @@ -943,8 +970,16 @@ strategy, including JEV, which skips its decision for that request. The next use target normally. Tracking uses the client's thread or session id, so a client that sends neither gets a normal pick. -If the original target is unavailable or fails, the combo fails over as usual, and the new target -receives the earlier tool calls in a form it accepts. DeepSeek thinking models get a one-space +With `quotaOnlyFallback`, such a client cannot be pinned, and its tool continuation answers +`409 combo_tool_target_unavailable`. +Without `quotaOnlyFallback`, if the original target is unavailable or fails, the combo fails over as +usual, and the new target receives the earlier tool calls in a form it accepts. With +`quotaOnlyFallback`, the continuation of a Combo you request directly stays on the original serving +target and never fails over. A failure returns to the client, and a target that cannot serve the continuation answers +`409 combo_tool_target_unavailable`, or `429 combo_tool_target_quota_exhausted` once its quota is +spent. A target that lost paid-call consent answers `403 combo_metered_consent_required`. A Combo +reached through another route, such as a subagent fallback alias, keeps its serving +target the same way. DeepSeek thinking models get a one-space reasoning placeholder for a tool call that another model issued without reasoning. Gemini gets Google's documented signature placeholder. Anthropic gets a plain tool call and result. Earlier versions could send DeepSeek a bare tool call here and fail with `The reasoning_text in the diff --git a/skills/ocx/references/01_surface_agents-routing.md b/skills/ocx/references/01_surface_agents-routing.md index 566e1a4a8b3..60404113422 100644 --- a/skills/ocx/references/01_surface_agents-routing.md +++ b/skills/ocx/references/01_surface_agents-routing.md @@ -1000,7 +1000,7 @@ State-changing: no. JSON mode: `payload`. ### `ocx combo set` -Usage: `ocx combo set [--targets | --targets-file ] [--strategy ] [--sticky <1-100|->] [--cooldown-reprobe ] [--cooldown-reprobe-interval ] [--effort ] [--effort-mode ] [--alias ] [--native-alias [on|off]] [--allow-metered-targets ] [--display-name ] [--description ] [--decision-provider | --decision-model ] [--decision-timeout ] [--decision-quota-signals ] [--decision-quota-tiers ] [--session-pin ] [--session-pin-effort ] [--rename-from ] [--image-input ] [--reasoning-effort-mode ] [--jev-effort-mode ] [--json]` +Usage: `ocx combo set [--targets | --targets-file ] [--strategy ] [--sticky <1-100|->] [--cooldown-reprobe ] [--cooldown-reprobe-interval ] [--effort ] [--effort-mode ] [--alias ] [--native-alias [on|off]] [--allow-metered-targets ] [--quota-only-fallback ] [--preserve-fallback-model ] [--display-name ] [--description ] [--decision-provider | --decision-model ] [--decision-timeout ] [--decision-quota-signals ] [--decision-quota-tiers ] [--session-pin ] [--session-pin-effort ] [--rename-from ] [--image-input ] [--reasoning-effort-mode ] [--jev-effort-mode ] [--json]` Create, update or rename a combo. @@ -1013,6 +1013,8 @@ State-changing: yes. JSON mode: `payload`. | Flag | Value | Meaning | |---|---|---| +| `--quota-only-fallback` | string | on limits ordered fallback to confirmed quota or billing exhaustion. | +| `--preserve-fallback-model` | string | on holds the resolved model ID across ordered fallback hops. | | `--allow-metered-targets` | string | on grants operator consent to metered targets only on a loopback-only proxy; off clears it. | | `--targets` | string | Ordered provider/model[:weight] list; required for creation. | | `--strategy` | string | Routing strategy. | diff --git a/src/cli/capabilities-agents-routing.ts b/src/cli/capabilities-agents-routing.ts index f1c96299c45..81f5f25b9d0 100644 --- a/src/cli/capabilities-agents-routing.ts +++ b/src/cli/capabilities-agents-routing.ts @@ -411,10 +411,10 @@ export const AGENT_ROUTING_CAPABILITIES: readonly Capability[] = [ }, { command: ["combo","set"], - usage: "ocx combo set [--targets | --targets-file ] [--strategy ] [--sticky <1-100|->] [--cooldown-reprobe ] [--cooldown-reprobe-interval ] [--effort ] [--effort-mode ] [--alias ] [--native-alias [on|off]] [--allow-metered-targets ] [--display-name ] [--description ] [--decision-provider | --decision-model ] [--decision-timeout ] [--decision-quota-signals ] [--decision-quota-tiers ] [--session-pin ] [--session-pin-effort ] [--rename-from ] [--image-input ] [--reasoning-effort-mode ] [--jev-effort-mode ] [--json]", + usage: "ocx combo set [--targets | --targets-file ] [--strategy ] [--sticky <1-100|->] [--cooldown-reprobe ] [--cooldown-reprobe-interval ] [--effort ] [--effort-mode ] [--alias ] [--native-alias [on|off]] [--allow-metered-targets ] [--quota-only-fallback ] [--preserve-fallback-model ] [--display-name ] [--description ] [--decision-provider | --decision-model ] [--decision-timeout ] [--decision-quota-signals ] [--decision-quota-tiers ] [--session-pin ] [--session-pin-effort ] [--rename-from ] [--image-input ] [--reasoning-effort-mode ] [--jev-effort-mode ] [--json]", summary: "Create, update or rename a combo.", routes: [{"method":"GET","path":"/api/combos"},{"method":"PUT","path":"/api/combos"}], - flags: [{"name":"--allow-metered-targets","value":"string","summary":"on grants operator consent to metered targets only on a loopback-only proxy; off clears it."},{"name":"--targets","value":"string","summary":"Ordered provider/model[:weight] list; required for creation."},{"name":"--strategy","value":"string","summary":"Routing strategy."},{"name":"--sticky","value":"string","summary":"Round-robin limit 1-100; - resets."},{"name":"--cooldown-reprobe","value":"string","summary":"Opt into one recovery pass when all eligible targets cool; off by default."},{"name":"--cooldown-reprobe-interval","value":"string","summary":"Minimum interval between recovery passes in ms (1000..86400000); default 300000."},{"name":"--effort","value":"string","summary":"Default effort; - clears."},{"name":"--effort-mode","value":"string","summary":"fallback or force; - resets to fallback."},{"name":"--alias","value":"string","summary":"Alias; - clears."},{"name":"--display-name","value":"string","summary":"Label; - clears."},{"name":"--description","value":"string","summary":"Catalog row description; - clears."},{"name":"--decision-provider","value":"string","summary":"JEV provider; - clears."},{"name":"--decision-model","value":"string","summary":"JEV route; - clears; exclusive with provider."},{"name":"--decision-timeout","value":"string","summary":"JEV deadline 1000-120000 ms; - clears."},{"name":"--decision-quota-signals","value":"string","summary":"JEV advisory quota on/off; - clears."},{"name":"--decision-quota-tiers","value":"string","summary":"Partial JSON thresholds; - clears."},{"name":"--session-pin","value":"string","summary":"JEV session pin idle window 1m-24h (90s, 20m, 1h); - clears."},{"name":"--session-pin-effort","value":"string","summary":"pinned reuses the pinned effort; per-turn asks JEV for the pinned target's effort each turn."},{"name":"--rename-from","value":"string","summary":"Existing combo ID to rename."},{"name":"--json","value":"boolean","summary":"Emit structured JSON."},{"name":"--native-alias","value":"string","summary":"Bare legacy flag means on; explicit on/off preserves presence, including false."},{"name":"--targets-file","value":"string","summary":"Bounded ordered target JSON array, exclusive with --targets; preserves effort/profile/last-resort metadata."},{"name":"--image-input","value":"string","summary":"auto or disabled; explicit auto clears the previous disabled choice."},{"name":"--reasoning-effort-mode","value":"string","summary":"strict or adaptive, distinct from --effort-mode fallback/force."},{"name":"--jev-effort-mode","value":"string","summary":"JEV wire-effort owner: decide (default) applies the decision effort; client keeps its target and leaves effort to combo policy."}], + flags: [{"name":"--quota-only-fallback","value":"string","summary":"on limits ordered fallback to confirmed quota or billing exhaustion."},{"name":"--preserve-fallback-model","value":"string","summary":"on holds the resolved model ID across ordered fallback hops."},{"name":"--allow-metered-targets","value":"string","summary":"on grants operator consent to metered targets only on a loopback-only proxy; off clears it."},{"name":"--targets","value":"string","summary":"Ordered provider/model[:weight] list; required for creation."},{"name":"--strategy","value":"string","summary":"Routing strategy."},{"name":"--sticky","value":"string","summary":"Round-robin limit 1-100; - resets."},{"name":"--cooldown-reprobe","value":"string","summary":"Opt into one recovery pass when all eligible targets cool; off by default."},{"name":"--cooldown-reprobe-interval","value":"string","summary":"Minimum interval between recovery passes in ms (1000..86400000); default 300000."},{"name":"--effort","value":"string","summary":"Default effort; - clears."},{"name":"--effort-mode","value":"string","summary":"fallback or force; - resets to fallback."},{"name":"--alias","value":"string","summary":"Alias; - clears."},{"name":"--display-name","value":"string","summary":"Label; - clears."},{"name":"--description","value":"string","summary":"Catalog row description; - clears."},{"name":"--decision-provider","value":"string","summary":"JEV provider; - clears."},{"name":"--decision-model","value":"string","summary":"JEV route; - clears; exclusive with provider."},{"name":"--decision-timeout","value":"string","summary":"JEV deadline 1000-120000 ms; - clears."},{"name":"--decision-quota-signals","value":"string","summary":"JEV advisory quota on/off; - clears."},{"name":"--decision-quota-tiers","value":"string","summary":"Partial JSON thresholds; - clears."},{"name":"--session-pin","value":"string","summary":"JEV session pin idle window 1m-24h (90s, 20m, 1h); - clears."},{"name":"--session-pin-effort","value":"string","summary":"pinned reuses the pinned effort; per-turn asks JEV for the pinned target's effort each turn."},{"name":"--rename-from","value":"string","summary":"Existing combo ID to rename."},{"name":"--json","value":"boolean","summary":"Emit structured JSON."},{"name":"--native-alias","value":"string","summary":"Bare legacy flag means on; explicit on/off preserves presence, including false."},{"name":"--targets-file","value":"string","summary":"Bounded ordered target JSON array, exclusive with --targets; preserves effort/profile/last-resort metadata."},{"name":"--image-input","value":"string","summary":"auto or disabled; explicit auto clears the previous disabled choice."},{"name":"--reasoning-effort-mode","value":"string","summary":"strict or adaptive, distinct from --effort-mode fallback/force."},{"name":"--jev-effort-mode","value":"string","summary":"JEV wire-effort owner: decide (default) applies the decision effort; client keeps its target and leaves effort to combo policy."}], mutates: true, json: "payload", details: ["create and update are aliases of set. Existing fields are read before writing; --targets replaces targets. Without --strategy an existing combo keeps its stored strategy and JEV policy; a new combo defaults to failover.","force overrides valid client effort and may increase cost and latency.","Only the implemented target grammar is supported; full GUI target metadata and routing-profile writes are separate tasks.","New file/flag conflicts refuse before transport. Partial edits preserve target metadata; explicit false/default values override server carry. Turning a native alias off may also require clearing its incompatible alias.","Read/merge/write uses one target and remains an upsert without revision CAS. Saved-but-incomplete catalog outcomes return nonzero with their receipt."], diff --git a/src/cli/combo-input.ts b/src/cli/combo-input.ts index efba4b065fa..8dffb2d6f20 100644 --- a/src/cli/combo-input.ts +++ b/src/cli/combo-input.ts @@ -10,6 +10,8 @@ type ComboInput = { jevEffortMode?: "decide" | "client"; nativeAlias?: boolean; allowMeteredTargets?: boolean; + quotaOnlyFallback?: boolean; + preserveFallbackModel?: boolean; }; const TARGET_KEYS = new Set(["provider", "model", "weight", "reasoningEfforts", "modelProfile", "lastResort", "metered"]); @@ -69,6 +71,13 @@ function takeNativeAlias(args: string[]): boolean | undefined { return next === "on"; } +function takeOnOff(args: string[], flag: string): boolean | undefined { + const option = takeOptionWithSyntax(args, flag); + if (!option) return undefined; + if (option.value !== "on" && option.value !== "off") throw new CliUsageError(`${flag} must be on or off`); + return option.value === "on"; +} + /** Consume only extension options, before the parent set flow resolves a target or reads HTTP. */ export async function prepareComboInput(args: string[], deps: RuntimeApiDeps = {}): Promise { const file = takeOptionWithSyntax(args, "--targets-file")?.value; @@ -76,10 +85,9 @@ export async function prepareComboInput(args: string[], deps: RuntimeApiDeps = { const reasoning = takeOptionWithSyntax(args, "--reasoning-effort-mode")?.value; const jevEffort = takeOptionWithSyntax(args, "--jev-effort-mode")?.value; const nativeAlias = takeNativeAlias(args); - const metered = takeOptionWithSyntax(args, "--allow-metered-targets")?.value; - if (metered !== undefined && metered !== "on" && metered !== "off") { - throw new CliUsageError("--allow-metered-targets must be on or off"); - } + const metered = takeOnOff(args, "--allow-metered-targets"); + const quotaOnlyFallback = takeOnOff(args, "--quota-only-fallback"); + const preserveFallbackModel = takeOnOff(args, "--preserve-fallback-model"); if (file !== undefined && args.some(arg => arg === "--targets" || arg.startsWith("--targets="))) { throw new CliUsageError("--targets-file cannot be combined with --targets"); } @@ -98,6 +106,8 @@ export async function prepareComboInput(args: string[], deps: RuntimeApiDeps = { ...(reasoning === undefined ? {} : { reasoningEffortMode: reasoning }), ...(jevEffort === undefined ? {} : { jevEffortMode: jevEffort }), ...(nativeAlias === undefined ? {} : { nativeAlias }), - ...(metered === undefined ? {} : { allowMeteredTargets: metered === "on" }), + ...(metered === undefined ? {} : { allowMeteredTargets: metered }), + ...(quotaOnlyFallback === undefined ? {} : { quotaOnlyFallback }), + ...(preserveFallbackModel === undefined ? {} : { preserveFallbackModel }), }; } diff --git a/src/cli/combo-result.ts b/src/cli/combo-result.ts index 494322dcf0c..c04369cc11c 100644 --- a/src/cli/combo-result.ts +++ b/src/cli/combo-result.ts @@ -53,7 +53,8 @@ function publicCombo(value: unknown): Record { if (!pin) invalid(); result[key] = pin; continue; - } else if (key === "nativeAlias" || key === "allowMeteredTargets" || key === "decisionQuotaSignals") { + } else if (key === "nativeAlias" || key === "allowMeteredTargets" || key === "decisionQuotaSignals" + || key === "quotaOnlyFallback" || key === "preserveFallbackModel") { if (typeof child !== "boolean") invalid(); } else invalid(); result[key] = child; diff --git a/src/cli/combo.ts b/src/cli/combo.ts index 9e2088ff991..59addf90cbb 100644 --- a/src/cli/combo.ts +++ b/src/cli/combo.ts @@ -28,6 +28,8 @@ const USAGE = `Usage: [--effort ] [--effort-mode ] (force overrides valid client effort and can increase cost/latency) [--alias ] [--native-alias [on|off]] [--allow-metered-targets ] [--display-name ] + [--quota-only-fallback ] [--preserve-fallback-model ] + (quota-only mode requires consent for any paid target, including the first target) [--description ] [--image-input ] [--reasoning-effort-mode ] [--jev-effort-mode ] @@ -174,6 +176,9 @@ async function set(argv: string[], deps: RuntimeApiDeps): Promise { // Flags that belong to one strategy. An explicit --strategy is checked before any request; an // omitted one is the stored strategy, so it is checked once the row has been read. const requireStrategyFlags = (strategy: string): void => { + if (strategy !== "failover" && (additional.quotaOnlyFallback === true || additional.preserveFallbackModel === true)) { + throw new CliUsageError("Enabling quota-only fallback or model preservation requires the failover strategy", USAGE); + } if (stickyLimit !== undefined && strategy !== "round-robin") throw new CliUsageError("--sticky applies only to round-robin", USAGE); if (strategy === "jev") return; if (decisionModel !== undefined && decisionModel !== "-") throw new CliUsageError("--decision-model applies only to the jev strategy", USAGE); @@ -216,6 +221,10 @@ async function set(argv: string[], deps: RuntimeApiDeps): Promise { if (alias !== undefined) combo.alias = alias === "-" ? "" : alias; if (additional.nativeAlias !== undefined) combo.nativeAlias = additional.nativeAlias; if (additional.allowMeteredTargets !== undefined) combo.allowMeteredTargets = additional.allowMeteredTargets; + for (const key of ["quotaOnlyFallback", "preserveFallbackModel"] as const) { + if (strategy !== "failover") delete combo[key]; + else if (additional[key] !== undefined) combo[key] = additional[key]; + } if (additional.imageInput !== undefined) combo.imageInput = additional.imageInput; if (additional.reasoningEffortMode !== undefined) combo.reasoningEffortMode = additional.reasoningEffortMode; if (additional.jevEffortMode !== undefined) combo.jevEffortMode = additional.jevEffortMode; diff --git a/src/server/management/combo-routes.ts b/src/server/management/combo-routes.ts index c7a2eb88bee..d5538c6896a 100644 --- a/src/server/management/combo-routes.ts +++ b/src/server/management/combo-routes.ts @@ -185,15 +185,45 @@ export async function handleComboRoutes(ctx: ManagementContext): Promise 64 || selectors.some(selector => selector.length > 512)) { + return jsonResponse({ error: "Too many or oversized fallback targets" }, 400); + } + const { routeConcreteModel } = await import("../../router"); + const { comboTargetRequiresConsent } = await import("../responses/combo-admission-snapshot"); + const routes = Object.fromEntries([...new Set(selectors)].map(selector => { + const slash = selector.indexOf("/"); + const provider = selector.slice(0, slash); + const model = selector.slice(slash + 1); + if (slash < 1 || !model || !Object.hasOwn(config.providers, provider) || config.providers[provider]?.disabled) return [selector, null]; + try { + const route = routeConcreteModel(config, selector); + return [selector, { + provider: route.providerName, model: route.modelId, + requiresConsent: comboTargetRequiresConsent(config, { provider, model }, true, route), + }]; + } catch { + return [selector, null]; + } + })); + return jsonResponse({ routes }); + } const { comboPublicModelId, getCombo, listComboIds } = await import("../../combos"); - return jsonResponse({ combos: listComboIds(config).map(id => { - const combo = getCombo(config, id)!; - return { - id, - model: comboPublicModelId(id, combo), - ...sparseComboConfig(combo), - }; - }) }); + const { configuredComboProviderBilling } = await import("../../combos/billing"); + return jsonResponse({ + combos: listComboIds(config).map(id => { + const combo = getCombo(config, id)!; + return { + id, + model: comboPublicModelId(id, combo), + ...sparseComboConfig(combo), + }; + }), + // The dashboard labels targets with the billing class the quota-only dispatcher applies. + providerBilling: Object.fromEntries(Object.entries(config.providers) + .map(([name, provider]) => [name, configuredComboProviderBilling({ ...provider, name })])), + }); } if (url.pathname === "/api/combos" && req.method === "PUT") { diff --git a/tests/cli/cli-combo-partial-update.test.ts b/tests/cli/cli-combo-partial-update.test.ts index c73aa1b3660..85ee1440223 100644 --- a/tests/cli/cli-combo-partial-update.test.ts +++ b/tests/cli/cli-combo-partial-update.test.ts @@ -190,3 +190,14 @@ test("loopback metered consent is explicit on/off, survives partial edits and re expect(r.requests).toEqual([]); } }); + +test("quota-only and same-model options are explicit on/off and failover-only", async () => { + quiet(); + const saved = { ...original, strategy: "failover", quotaOnlyFallback: true, preserveFallbackModel: true }; + const updated = runtime(saved); + expect(await handleComboCommand(["set", "auto", "--quota-only-fallback=off", "--preserve-fallback-model", "off"], updated.deps)).toBe(0); + expect(updated.body()?.combo).toMatchObject({ quotaOnlyFallback: false, preserveFallbackModel: false }); + const rejected = runtime(saved); + expect(await handleComboCommand(["set", "auto", "--strategy", "random", "--quota-only-fallback", "on"], rejected.deps)).toBe(2); + expect(rejected.requests).toEqual([]); +}); diff --git a/tests/routing/combo-management-api.test.ts b/tests/routing/combo-management-api.test.ts index 3f4b687983c..e500ab9320f 100644 --- a/tests/routing/combo-management-api.test.ts +++ b/tests/routing/combo-management-api.test.ts @@ -320,6 +320,24 @@ describe("combo management API", () => { }); }); + test("a draft preview resolves redirects with the same billing policy as dispatch", async () => { + const config = baseConfig({ blockedModelRedirects: { "a/m1": "b/m2" } }); + config.providers.a = { ...config.providers.a!, authMode: "local", baseUrl: "http://127.0.0.1:19012" }; + const response = await comboApi(config, "GET", "/api/combos?fallbackTarget=a%2Fm1&fallbackTarget=missing%2Fm"); + expect(await responseJson(response)).toEqual({ routes: { + "a/m1": { provider: "b", model: "m2", requiresConsent: true }, + "missing/m": null, + } }); + }); + + test("the Combo list reports each provider's billing class for the dashboard", async () => { + const config = baseConfig(); + config.providers.b = { ...config.providers.b!, authMode: "local", baseUrl: "http://127.0.0.1:19012/v1" }; + const listed = await responseJson(await comboApi(config, "GET", "/api/combos")); + expect(listed.providerBilling).toEqual({ a: "consent", b: "local", c: "consent" }); + expect(listed.combos.map((combo: { id: string }) => combo.id)).toEqual(["free"]); + }); + test("quota-only and same-model options survive a partial PUT and can be cleared", async () => { await withTempHome(async () => { const config = baseConfig({ combos: undefined }); From 3c0ed3bc680a62257eb1cdaf4f4e6e1c399f7fb9 Mon Sep 17 00:00:00 2001 From: Stanislas Date: Wed, 25 Nov 2026 07:41:52 +0100 Subject: [PATCH 41/60] Fix checked stop on localized Windows Task Scheduler states (#9041) * Read numeric Task Scheduler state for unrecognized Windows locales * Verify scheduler wrapper identity when CIM owner enrichment times out * fix(service): keep this PR to the numeric Task Scheduler state read Revert the snapshot-owner fallback in windows-process-evidence.ts and windows-process-native.ts to dev: #9027 carries the native ownership proof for a missing CIM owner sample, and two fallbacks for the same evidence would disagree. Document the Schedule.Service TASK_STATE fallback for unrecognized locales. * test(service): bound the numeric Scheduler state read by the time the CSV query left --------- Co-authored-by: JUN --- src/service/windows-checked-stop-live.ts | 12 ++++---- structure/ops/windows-checked-stop.md | 2 +- .../windows/windows-checked-stop-live.test.ts | 29 ++++++++++++++++++- 3 files changed, 36 insertions(+), 7 deletions(-) diff --git a/src/service/windows-checked-stop-live.ts b/src/service/windows-checked-stop-live.ts index aba2d04c3f3..7bd3cd7fe30 100644 --- a/src/service/windows-checked-stop-live.ts +++ b/src/service/windows-checked-stop-live.ts @@ -179,7 +179,8 @@ export const liveWindowsStopCommandRunner: WindowsStopCommandRunner = (program, * resources, and the PowerShell fallback cannot start inside Part A's 1 s manager-state cap on a * cold machine (#8863), so the words observed from shipped resources are read here: zh-CN, ja-JP * and ko-KR from their System32 locale directories, ko-KR running/ready also from two machines. - * Any other word stays unknown and falls back to Get-ScheduledTask's locale-independent State enum. + * Any other word stays unknown here and falls back to the numeric TASK_STATE read through the + * Schedule.Service COM object, which is locale-independent and imports no module. */ // A queued instance can launch after Part A. Only ready and disabled prove inactivity. const TASK_CSV_ACTIVE = new Set(["running", "queued", "正在运行", "已排队", "실행 중", "대기", "実行中", "キューに登録済み"]); @@ -413,14 +414,15 @@ export function windowsCheckedStopLiveDeps(options: WindowsCheckedStopLiveOption const csv = await run("schtasks", ["/query", "/tn", TASK, "/fo", "CSV", "/nh"], timeoutMs); const parsed = csv.status === 0 ? parseTaskCsvState(csv.stdout) : "unknown"; if (parsed !== "unknown") return parsed; - // A localized status word: ask Get-ScheduledTask, whose State is an enum name. + // Query TASK_STATE directly: importing ScheduledTasks can exhaust the one-second state budget. const left = timeoutMs - (Date.now() - started); if (left <= 0) return "unknown"; const ps = await run("powershell", ["-NoProfile", "-NoLogo", "-NonInteractive", "-Command", - "(Get-ScheduledTask -TaskName '" + TASK + "' -TaskPath '\\' -ErrorAction Stop).State"], left); + `$ErrorActionPreference = 'Stop'; $s = New-Object -ComObject Schedule.Service; $s.Connect(); $s.GetFolder('\\').GetTask('${TASK}').State`], left); + if (ps.timedOut || ps.status !== 0) return "unknown"; const state = ps.stdout.trim(); - if (/^(running|queued)$/i.test(state)) return "running"; - if (/^(ready|disabled)$/i.test(state)) return "not-running"; + if (state === "2" || state === "4") return "running"; // queued or running + if (state === "1" || state === "3") return "not-running"; // disabled or ready return "unknown"; }, async winswStop(timeoutMs) { diff --git a/structure/ops/windows-checked-stop.md b/structure/ops/windows-checked-stop.md index 64186822d47..02174cba40d 100644 --- a/structure/ops/windows-checked-stop.md +++ b/structure/ops/windows-checked-stop.md @@ -183,7 +183,7 @@ objects. The final manager-state probe treats both running and queued tasks as a The task's running state is read from `schtasks /query /fo CSV`. The status words observed from shipped zh-CN, ko-KR, and ja-JP resources are recognized there, because a cold `Get-ScheduledTask` takes -1.6 s to 4.9 s (#8863) and cannot finish inside the 1 s cap. Any other localized word still falls back to it. +1.6 s to 4.9 s (#8863) and cannot finish inside the 1 s cap. Any other localized word (French `Prêt`, for example) falls back to the numeric `TASK_STATE` read through the `Schedule.Service` COM object, which needs no module import (about 0.3 s including PowerShell startup on the reporting host): 2 and 4 (queued, running) are active, 1 and 3 (disabled, ready) are stopped, and a failed, timed-out or other value stays unknown. The instance stop maps an access-denied HRESULT to `denied`. A running WinSW service is only this home's manager when `sc qc` shows a `BINARY_PATH_NAME` naming this installation's WinSW executable, the same proof the guarded manager path uses: the service ID is fixed, so a successful `sc query` alone diff --git a/tests/windows/windows-checked-stop-live.test.ts b/tests/windows/windows-checked-stop-live.test.ts index 0b8766b113e..193807b923d 100644 --- a/tests/windows/windows-checked-stop-live.test.ts +++ b/tests/windows/windows-checked-stop-live.test.ts @@ -102,7 +102,7 @@ describe("capped command answers", () => { const programs: string[] = []; const deps = windowsCheckedStopLiveDeps({ run: async program => { programs.push(program); - if (program === "powershell") return result(0, "Queued\r\n"); + if (program === "powershell") return result(0, "2\r\n"); const word = status === "PowerShell" ? "Wird ausgeführt" : status; return result(0, `"\\opencodex-proxy","N/A","${word}"\r\n`); } }); @@ -110,6 +110,33 @@ describe("capped command answers", () => { expect(programs).toEqual(status === "PowerShell" ? ["schtasks", "powershell"] : ["schtasks"]); }); + test.each([ + [result(0, "1"), "not-running"], [result(0, "3"), "not-running"], + [result(0, "4"), "running"], [result(0, "0"), "unknown"], + [result(1, "3"), "unknown"], [result(0, "3", "", true), "unknown"], + ] as const)("reads the numeric scheduler state for an unrecognized CSV label", async (probe, expected) => { + const deps = windowsCheckedStopLiveDeps({ run: async program => program === "schtasks" + ? result(0, '"\\opencodex-proxy","N/A","Prêt"') : probe }); + expect(await deps.taskState(1_000)).toBe(expected); + }); + + test("the numeric state read gets only the time the CSV query left, and none once it is spent", async () => { + let now = 1_000_000; + const clock = spyOn(Date, "now").mockImplementation(() => now); + try { + for (const [csvMs, expectedTimeout, expected] of [[900, 100, "not-running"], [1_000, null, "unknown"]] as const) { + const calls: Array<[string, number]> = []; + const deps = windowsCheckedStopLiveDeps({ run: async (program, _args, timeout) => { + calls.push([program, timeout]); + if (program === "schtasks") { now += csvMs; return result(0, '"\\opencodex-proxy","N/A","Prêt"'); } + return result(0, "3"); + } }); + expect(await deps.taskState(1_000)).toBe(expected); + expect(calls).toEqual(expectedTimeout === null ? [["schtasks", 1_000]] : [["schtasks", 1_000], ["powershell", expectedTimeout]]); + } + } finally { clock.mockRestore(); } + }); + test("the #3064 launcher survives the task stop proof round trip", async () => { const previousHome = process.env.OPENCODEX_HOME; const sid = "S-1-5-21-100-200-300-1001"; From 04fdc4c7b443410051bdfdcaf8b238d1d1f5107c Mon Sep 17 00:00:00 2001 From: Epinephrine Date: Wed, 25 Nov 2026 15:54:56 +0900 Subject: [PATCH 42/60] fix(link): restore guarded stop cleanup with native Windows owner proof (#8933) * fix(link): restore stop cleanup with bounded native Windows proof Restore the guarded file-route drain and exact stop ownership boundaries from #8803 after its Windows timeout revert. Replace repeated CIM owner probes with same-handle native creation/SID evidence, preserve Windows argv semantics, retain apply exclusion during recycle, and retry only closed, unpublished rollback listeners within a shared remaining budget. Native Windows acceptance remains pending; no CI policy or budget changes. * ci: refresh measured test durations Apply the identical generated timing table from lidge-jun/opencodex#8940 (d190515a19cef9cc391d5a68e901d538bbe07f44). Completed primary-file samples update scheduling weights only; test coverage, five-shard execution, time limits, and workflow policy remain unchanged. * ci: record reviewed timing table in release evidence Preserve the 26 historical evidence snapshots and append the current CI fingerprint set with the independently reviewed timing table blob. Keep every workflow, job requirement, shard count, and timeout unchanged. Validation: 69 release evidence/history/dispatch/resume/docs tests pass; release-evidence policy-check passes. * test: keep stop-owner registration independent of the service-stop follow-up * test(link): report recovery phases when the Windows watchdog expires * fix(link): defer periodic sync for a fenced listener generation * test(link): bind the scheduler to the generation stamped at publication * test(link): isolate stop fixtures from other services and client profiles * test(link): keep unreadable process identities unverified The recovery fixture now sends a missing creation-time sample through the same ownership decision used by normal samples. A missing identity must keep recovery fenced. A matching or mismatching observed identity retains its old result. Windows x64 with Bun 1.4.4: five isolated decisions checked before and after, and typecheck passed. The parent-unverified integration fixture reached its unchanged 15-second parent deadline during file-route setup, before the observer ran. Its Windows integration result remains open. --------- Co-authored-by: luvs01 <27862058+luvs01@users.noreply.github.com> Co-authored-by: JUN --- .../docs/es/reference/cli/lifecycle.md | 2 +- .../content/docs/reference/cli/lifecycle.md | 8 +- scripts/test-layout/layout-clients.json | 3 + src/client/runtime-recycle.ts | 29 ++++ src/client/runtime-rollback.ts | 29 ++++ src/client/runtime.ts | 104 +++++++++------ src/client/stop-teardown-owner.ts | 51 ++++--- src/client/sync-runtime.ts | 8 ++ src/integrations/route-intent-tick.ts | 7 + src/service/windows-process-native.ts | 56 +++++--- structure/INDEX.md | 2 + structure/manifest.json | 2 + structure/ops/windows-checked-stop.md | 2 +- structure/remote-link.md | 12 +- tests/cli/cli-client-start-fence.test.ts | 2 +- .../clients/client-link-stop-recovery.test.ts | 53 +++++++- .../clients/client-recycle-exclusion.test.ts | 67 ++++++++++ .../client-restart-rollback-lock.test.ts | 44 ++++++ .../clients/route-intent-runtime-stop.test.ts | 32 ++++- tests/clients/route-intent-scheduler.test.ts | 45 +++++++ .../client-link-stop-recovery-runner.ts | 73 +++++++--- tests/fixtures/client-link-stop-runner.ts | 34 ++++- tests/fixtures/parent-stop-runner.ts | 21 ++- tests/fixtures/test-layout-expected.json | 5 +- tests/helpers/client-link-stop.ts | 5 +- tests/helpers/client-stop-fixture-home.ts | 15 +++ .../windows-stop-owner-identity.test.ts | 125 ++++++++++++++++++ 27 files changed, 713 insertions(+), 123 deletions(-) create mode 100644 src/client/runtime-recycle.ts create mode 100644 src/client/runtime-rollback.ts create mode 100644 tests/clients/client-recycle-exclusion.test.ts create mode 100644 tests/clients/client-restart-rollback-lock.test.ts create mode 100644 tests/helpers/client-stop-fixture-home.ts create mode 100644 tests/windows/windows-stop-owner-identity.test.ts diff --git a/docs-site/src/content/docs/es/reference/cli/lifecycle.md b/docs-site/src/content/docs/es/reference/cli/lifecycle.md index 85c95422fcd..53b6a27e795 100644 --- a/docs-site/src/content/docs/es/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/es/reference/cli/lifecycle.md @@ -127,7 +127,7 @@ Si OpenCodex no puede confirmar que un envoltorio terminó porque no dispone de de objeto de proceso (handle), como puede ocurrir en ARM64, compruébalo en el Administrador de tareas desde la sesión de su propietario, detenlo si sigue en ejecución y vuelve a intentarlo. -Si no puede demostrarse que el servicio se detuvo, `ocx stop` no envía una solicitud de parada al proxy, deja intacta la configuración del cliente y falla. Con `--json`, el resumen conserva `outcome: "failed"` y `proxy: "unknown"`, y añade `serviceStopReason`: +Si no puede demostrarse que el servicio se detuvo, `ocx stop` no envía una solicitud de parada al proxy ni continúa con la restauración nativa compartida. En un Child de Remote Link, el prevuelo puede haber eliminado ya las integraciones de archivos propiedad del Link y pausado la sincronización; repara la parada del servicio y vuelve a ejecutar `ocx stop`. El comando falla. Con `--json`, el resumen conserva `outcome: "failed"` y `proxy: "unknown"`, y añade `serviceStopReason`: | `serviceStopReason` | Significado | Qué hacer | |---|---|---| diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index 2cea913f521..a2567b88b82 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -198,9 +198,11 @@ eligible for termination, stop it from its owning Windows session using Task Man If OpenCodex cannot confirm a wrapper's exit without a process handle, as can happen on ARM64, check it in Task Manager from its owning session, stop it if it is still running, and retry. -When the service cannot be proven stopped, `ocx stop` sends no stop request to the proxy, leaves -your client configuration alone, and fails. With `--json` the summary keeps `outcome: "failed"` -and `proxy: "unknown"`, and adds `serviceStopReason`: +When the service cannot be proven stopped, `ocx stop` sends no stop request to the proxy and +does not proceed to shared native restoration. On a Remote Link Child, preflight may already have +removed Link-owned file integrations and paused sync; repair the service stop and retry `ocx stop`. +The command fails. With `--json` the summary keeps `outcome: "failed"` and `proxy: "unknown"`, +and adds `serviceStopReason`: | `serviceStopReason` | Meaning | What to do | |---|---|---| diff --git a/scripts/test-layout/layout-clients.json b/scripts/test-layout/layout-clients.json index 4a4eda1f781..3c2d9e34d62 100644 --- a/scripts/test-layout/layout-clients.json +++ b/scripts/test-layout/layout-clients.json @@ -179,6 +179,9 @@ "client-link-runtime.test.ts": "clients", "client-link-stop.test.ts": "clients", "client-link-stop-recovery.test.ts": "clients", + "windows-stop-owner-identity.test.ts": "windows", + "client-recycle-exclusion.test.ts": "clients", + "client-restart-rollback-lock.test.ts": "clients", "client-link-stop-sibling.test.ts": "clients", "link-routes.test.ts": "clients", "client-link-state.test.ts": "clients", diff --git a/src/client/runtime-recycle.ts b/src/client/runtime-recycle.ts new file mode 100644 index 00000000000..e0fb65498b3 --- /dev/null +++ b/src/client/runtime-recycle.ts @@ -0,0 +1,29 @@ +import { withConfigMutationLockSync } from "../config"; +import type { OcxClientConnectionConfig } from "../types"; +import { withLinkApply } from "./link-home"; +import { clientConnectionEnded } from "./runtime-restart"; +import { pendingClientConnectMayOwnToken, readClientConnectionStateWithEvidence } from "./state"; + +/** + * Called outside L: Link apply exclusion is outermost in the apply -> N -> L -> C order. + * Once admitted, keep it through all teardown awaits; a new connect cannot commit halfway. + */ +export async function runClientRecycleWithAdmission( + served: OcxClientConnectionConfig, + allowed: () => boolean, + teardown: () => Promise, +): Promise { + let admitted = false; + try { + return await withLinkApply(async () => { + admitted = withConfigMutationLockSync(() => allowed() && !pendingClientConnectMayOwnToken() + && clientConnectionEnded(served, readClientConnectionStateWithEvidence())); + if (!admitted) return false; + await teardown(); + return true; + }); + } catch (error) { + if (admitted) throw error; // A started teardown must not masquerade as an admission refusal. + return false; + } +} diff --git a/src/client/runtime-rollback.ts b/src/client/runtime-rollback.ts new file mode 100644 index 00000000000..f2e0380377b --- /dev/null +++ b/src/client/runtime-rollback.ts @@ -0,0 +1,29 @@ +import { ConfigMutationLockError } from "../config"; +import { CLIENT_RESTART_REBIND_WAIT_MS } from "../lib/system-restart-contract"; + +export type ClientRollbackAttempt = "published" | "busy" | "refused"; + +export function retryableClientRollbackLock(error: unknown): boolean { + if (error && typeof error === "object" && "code" in error && error.code === "client_lifecycle_busy") return true; + const cause = error instanceof ConfigMutationLockError ? error.cause : undefined; + const code = cause && typeof cause === "object" && "code" in cause ? cause.code : undefined; + return code === "SQLITE_BUSY" || code === "SQLITE_LOCKED"; +} + +/** Each busy attempt must close its unpublished listener before this helper may yield. */ +export async function retryClientRollback( + attempt: (remainingMs: number) => Promise, + io: { now?: () => number; sleep?: (ms: number) => Promise; budgetMs?: number } = {}, +): Promise { + const now = io.now ?? (() => performance.now()); + const deadline = now() + (io.budgetMs ?? CLIENT_RESTART_REBIND_WAIT_MS); + while (now() < deadline) { + const result = await attempt(Math.max(0, deadline - now())); + if (result === "published") return true; + if (result !== "busy") return false; + const remaining = deadline - now(); + if (remaining <= 0) return false; + await (io.sleep ?? Bun.sleep)(Math.min(50, remaining)); + } + return false; +} diff --git a/src/client/runtime.ts b/src/client/runtime.ts index dde66d08d9d..ace5c261520 100644 --- a/src/client/runtime.ts +++ b/src/client/runtime.ts @@ -15,7 +15,6 @@ import { createLocalAttestationSecret } from "../lib/local-management-attestatio import { loadServiceTokenFromFile, serviceApiTokenFingerprint } from "../lib/service-secrets"; import { handledSignalExitCode } from "../lib/handled-signal-exit"; import { - CLIENT_RESTART_REBIND_WAIT_MS, DESKTOP_RESTART_EXIT_CODE, DESKTOP_SUPERVISED_ENV, DESKTOP_SUPERVISED_PORT_WAIT_MS, @@ -39,9 +38,11 @@ import { createLinkParityReporter, type LinkParityReporter } from "./link-parity import { restoreLinkClientRoutingBeforeExit } from "./stop-routing"; import { observeClientStopOwner } from "./stop-teardown-owner"; import { SUPERVISOR_MARKER_ENVS } from "../lib/supervisor-markers"; -import { markClientRuntimeStopping, markClientRuntimeStoppingWithRetry } from "./sync-runtime"; +import { isPublishedRuntimeStopping, markClientRuntimeStopping, markClientRuntimeStoppingWithRetry } from "./sync-runtime"; import { startRouteIntentTick, type RouteIntentTick } from "../integrations/route-intent-tick"; import { startRouteIntentWatch, type RouteIntentRuntimeWatch } from "./route-intent-watch"; +import { runClientRecycleWithAdmission } from "./runtime-recycle"; +import { retryClientRollback, retryableClientRollbackLock, type ClientRollbackAttempt } from "./runtime-rollback"; let activeServer: Server | null = null; let activePort: number | null = null; @@ -60,6 +61,7 @@ let clientStopping = false; let explicitClientStopRequested: boolean | undefined; let explicitClientStopOwner: ClientStopOwner | undefined; let standaloneRecycleAllowed = () => !clientStopping; +let activeLinkForRecycle: OcxClientConnectionConfig | undefined; /** * When this runtime's process started (OCX-6, P5): what `/healthz` reports as `startedAt` and the @@ -90,6 +92,8 @@ const LINK_BIND_ATTEMPTS = 3; export interface ClientRuntimeIo { /** Link-mode port budget; defaults to {@link LINK_PORT_WAIT_MS}. */ portWaitMs?: number; + /** Rollback bind attempts share one deadline instead of restarting the port wait. */ + bindDeadlineAt?: number; startListener?: typeof startMachineListener; /** Which supervisor owns this process for a bound restart; tests replace the production check. */ restartSupervisor?: () => Promise<"service" | "desktop" | null>; @@ -200,27 +204,36 @@ export async function recycleStandalone( const exit = io.exitProcess ?? ((code: number) => { process.exit(code); }); // Capture the one-use sibling handoff before this process removes its runtime record. const serviceSupervised = (io.serviceSupervised ?? (() => process.env.OCX_SERVICE === "1"))(); - const replacementEnv = port && !serviceSupervised - ? withSiblingMarker(standaloneRecycleEnv(process.env, disconnectedTokenFingerprint), issueSiblingHandoff) - : null; - activeCredentialObservation?.stop(); activeCredentialObservation = null; - activeHubRelayRefresh?.stop(); activeHubRelayRefresh = null; - activeReporter?.stop(); activeReporter = null; - activeRouteWatch?.stop(); activeRouteWatch = null; - activeRouteSync?.stop(); activeRouteSync = null; - try { - await activeSupervisor?.stop(); - } catch (error) { - console.warn(`[client] link supervisor stop failed: ${error instanceof Error ? error.message : String(error)}`); - } - activeSupervisor = null; - try { - activeServer?.stop(true); - } catch (error) { - console.warn(`[client] listener stop failed: ${error instanceof Error ? error.message : String(error)}`); - } - cleanup(); - await flushLinkDiagnostics(); + let replacementEnv: NodeJS.ProcessEnv | null = null; + const teardown = async () => { + replacementEnv = port && !serviceSupervised + ? withSiblingMarker(standaloneRecycleEnv(process.env, disconnectedTokenFingerprint), issueSiblingHandoff) + : null; + activeCredentialObservation?.stop(); activeCredentialObservation = null; + activeHubRelayRefresh?.stop(); activeHubRelayRefresh = null; + activeReporter?.stop(); activeReporter = null; + activeRouteWatch?.stop(); activeRouteWatch = null; + activeRouteSync?.stop(); activeRouteSync = null; + try { + await activeSupervisor?.stop(); + } catch (error) { + console.warn(`[client] link supervisor stop failed: ${error instanceof Error ? error.message : String(error)}`); + } + activeSupervisor = null; + try { + await activeServer?.stop(true); + } catch (error) { + console.warn(`[client] listener stop failed: ${error instanceof Error ? error.message : String(error)}`); + } + cleanup(); + await flushLinkDiagnostics(); + }; + if (activeLinkForRecycle) { + if (!(await runClientRecycleWithAdmission(activeLinkForRecycle, standaloneRecycleAllowed, teardown))) { + recycleScheduled = false; + return; + } + } else await teardown(); // Recycling back to standalone after `ocx disconnect` must actually bring a standalone // proxy back, under every launch shape. // @@ -289,17 +302,19 @@ export async function bindClientListener( ): Promise<{ server: Server; port: number }> { const { linkMode } = request; const portWaitMs = io.portWaitMs ?? (linkMode ? linkPortWaitMs() : LINK_PORT_WAIT_MS); - const deadline = Date.now() + portWaitMs; + const deadline = io.bindDeadlineAt ?? Date.now() + portWaitMs; + const remaining = () => Math.max(0, deadline - Date.now()); const busy = (cause: unknown) => new Error( `link mode needs port ${request.configuredPort}; free it or change port`, { cause }, ); let port: number; try { + if (io.bindDeadlineAt !== undefined && remaining() <= 0) throw busy("rollback deadline expired"); if (linkMode) { const { reclaimListenPort } = await import("../server/port-reclaim"); await reclaimListenPort(request.configuredPort, "127.0.0.1", { - timeoutMs: portWaitMs, + timeoutMs: io.bindDeadlineAt === undefined ? portWaitMs : Math.min(portWaitMs, remaining()), intervalMs: 100, scanIntervalMs: 500, killOcxHolders: false, @@ -307,7 +322,8 @@ export async function bindClientListener( }); } port = await findAvailablePort(request.preferred, "127.0.0.1", { - preferRetryMs: request.explicitPort ? PINNED_PREFER_RETRY_MS : 750, + preferRetryMs: Math.min(request.explicitPort ? PINNED_PREFER_RETRY_MS : 750, + io.bindDeadlineAt === undefined ? Infinity : remaining()), preferRetryIntervalMs: 50, allowEphemeralFallback: linkMode ? false : !request.explicitPort, }); @@ -318,6 +334,7 @@ export async function bindClientListener( const startListener = io.startListener ?? startMachineListener; for (let attempt = 1; ; attempt += 1) { try { + if (io.bindDeadlineAt !== undefined && remaining() <= 0) throw busy("rollback deadline expired"); const server = startListener(port, { state: request.state, machineApi: { scheduleStandaloneRecycle }, @@ -332,8 +349,8 @@ export async function bindClientListener( } catch (error) { // Check-then-bind: the port can be taken between the probe and Bun.serve. if (!linkMode || !isAddrInUse(error)) throw error; - const waitMs = Math.max(1_000, deadline - Date.now()); - if (attempt >= LINK_BIND_ATTEMPTS + const waitMs = io.bindDeadlineAt === undefined ? Math.max(1_000, remaining()) : remaining(); + if (attempt >= LINK_BIND_ATTEMPTS || waitMs <= 0 || !(await waitForPortAvailable(port, "127.0.0.1", { timeoutMs: waitMs, intervalMs: 100 }))) { throw busy(error); } @@ -384,7 +401,7 @@ export async function startClientRuntime( && (!explicitClientStopOwner || observeClientStopOwner(explicitClientStopOwner) !== "confirmed-stale"); }; // An unpublishable rollback closes the new listener before the caller considers a recycle. - const serve = async (rollback?: { port: number; portWaitMs: number }): Promise => { + const serve = async (rollback?: { port: number; portWaitMs: number }): Promise => { const supervisor = supervised ? createClientLinkSupervisor({ diagnostic: recordLinkDiagnostic, @@ -413,17 +430,20 @@ export async function startClientRuntime( ...(linkReadiness ? { linkReadiness } : {}), ...(supervisor ? { linkConnectionGeneration: () => supervisor.connectionGeneration() } : homeInitiated && link ? { linkConnectionGeneration: () => verifiedHomeConnection(link.linkId) } : {}), - }, rollback === undefined ? io : { ...io, portWaitMs: rollback.portWaitMs }); + }, rollback === undefined ? io : { ...io, portWaitMs: rollback.portWaitMs, bindDeadlineAt: Date.now() + rollback.portWaitMs }); + let servingGeneration: string; const publishRecord = (): void => { // A parent stop can arrive after restart admission. Never clear its fence on rollback; // a fresh process has another attestation identity and cannot inherit this request. if (rollback) observeExplicitStop(); writePid(process.pid); // A new generation refuses commits from syncs admitted before the failed restart. - writeRuntimePort({ ...clientRuntimeRecord(process.pid, boundPort, attestationSecret), servingGeneration: randomUUID(), + servingGeneration = randomUUID(); + writeRuntimePort({ ...clientRuntimeRecord(process.pid, boundPort, attestationSecret), servingGeneration, clientLinkOwner }); }; const activate = (): void => { + activeLinkForRecycle = linkMode ? state.value : undefined; activeServer = server; activePort = boundPort; servedPort = boundPort; @@ -437,7 +457,10 @@ export async function startClientRuntime( if (linkMode && state.value.link && linkKey) { activeReporter = createLinkParityReporter({ connection: state.value, linkKey, runtimeStartedAt: CLIENT_RUNTIME_STARTED_AT }); activeReporter.start(); - const scheduler = startRouteIntentTick(state.value, { onApplied: () => activeReporter?.requestReport() }); + const scheduler = startRouteIntentTick(state.value, { + deferPeriodic: () => isPublishedRuntimeStopping({ pid: process.pid, port: boundPort, attestationSecret, servingGeneration }), + onApplied: () => activeReporter?.requestReport(), + }); activeRouteSync = scheduler; activeRouteWatch = startRouteIntentWatch(state.value, linkKey, { requestSync: () => scheduler.requestSync() }); } @@ -445,7 +468,7 @@ export async function startClientRuntime( if (!rollback) { publishRecord(); activate(); - return true; + return "published"; } // Admission and publication are synchronous after bind. A busy lock must close the // rebound listener before yielding. Link takes C to preserve an explicit stop fence. @@ -454,15 +477,16 @@ export async function startClientRuntime( publishRecord(); return true; }; - let published = false; + let published = false, busy = false; try { published = withClientLifecycleSync(() => linkMode ? withConfigMutationLockSync(publishIfOwned) : publishIfOwned()); - } catch { /* failed admission */ } + } catch (error) { busy = retryableClientRollbackLock(error); } if (published) activate(); else { - try { await server.stop(true); } catch { /* never published */ } + // Do not retain an unrecorded listener across the contention retry's await. + await server.stop(true); } - return published; + return published ? "published" : busy ? "busy" : "refused"; }; // Stop everything this process serves, giving in-flight requests up to `drainMs`. @@ -553,7 +577,11 @@ export async function startClientRuntime( await recycleAfterRollback(); return; } - if (!(await serve({ port: servedPort, portWaitMs: CLIENT_RESTART_REBIND_WAIT_MS }))) { + if (!(await retryClientRollback(async remainingMs => { + observeExplicitStop(); + if (clientRestartRollbackAction(state.value, readClientConnectionState()) === "recycle") return "refused"; + return serve({ port: servedPort, portWaitMs: remainingMs }); + }))) { await recycleAfterRollback(); } }, diff --git a/src/client/stop-teardown-owner.ts b/src/client/stop-teardown-owner.ts index e0c3085e814..f1ae8cc87ed 100644 --- a/src/client/stop-teardown-owner.ts +++ b/src/client/stop-teardown-owner.ts @@ -1,21 +1,46 @@ -import { execFileSync } from "node:child_process"; import { readlinkSync, statSync } from "node:fs"; import { isAbsolute, join, resolve } from "node:path"; import { NODE_LAUNCH_PROOF_PREFIX } from "../cli/launcher-context"; import { parseStopApproval } from "../cli/stop-approval"; -import { tokenizeCommandLine } from "../codex/app-server-processes"; import { readProcessCommandLine, type ClientStopOwner } from "../config/process-state"; import { readBoundedRegularFileSync } from "../lib/bounded-file-read"; -import { resolveTrustedWindowsPowerShellExe } from "../lib/windows-elevation"; -import { windowsProcessNative, windowsProcessPlatform, windowsProcessPlatformSimulated } from "../service/windows-process-native"; +import { windowsProcessNative, windowsProcessPlatform } from "../service/windows-process-native"; import { readDarwinStopArgv, readDarwinStopCwd, readDarwinStopEnvironment, readDarwinStopStart } from "./stop-darwin-process"; const basename = (value: string) => value.toLowerCase().replace(/\\/g, "/").split("/").pop() ?? ""; +/** Windows native argv rules: apostrophes are literal; only double quotes group arguments. */ +function windowsArgv(commandLine: string): string[] { + if (commandLine.length > 64 * 1024 || /[\0\r\n]/.test(commandLine)) return []; + const argv: string[] = []; + let offset = 0; + while (offset < commandLine.length) { + while (/[ \t]/.test(commandLine[offset] ?? "")) offset++; + if (offset === commandLine.length) break; + let value = "", quoted = false; + while (offset < commandLine.length) { + const character = commandLine[offset]!; + if (!quoted && /[ \t]/.test(character)) break; + // argv[0] is a pathname: its backslashes are literal, including before a closing quote. + if (argv.length > 0 && character === "\\") { + let count = 0; + while (commandLine[offset] === "\\") { count++; offset++; } + if (commandLine[offset] !== '"') { value += "\\".repeat(count); continue; } + value += "\\".repeat(Math.floor(count / 2)); + if (count % 2) { value += '"'; offset++; continue; } + } else if (character !== '"') { value += character; offset++; continue; } + if (argv.length > 0 && quoted && commandLine[offset + 1] === '"') { value += '"'; offset += 2; } + else { quoted = !quoted; offset++; } + } + argv.push(value); + } + return argv; +} + /** Recognize the invocation that sets the native Child's explicit-stop fence, not any ocx. */ export function isClientStopCommandLine(commandLine: string): boolean { if (commandLine.length > 64 * 1024) return false; - return isClientStopArgv(tokenizeCommandLine(commandLine)); + return isClientStopArgv(windowsArgv(commandLine)); } export function isClientStopArgv(argv: readonly string[]): boolean { @@ -25,7 +50,7 @@ export function isClientStopArgv(argv: readonly string[]): boolean { export function isLegacyWindowsStartCommandLine(commandLine: string): boolean { if (commandLine.length > 64 * 1024) return false; - const argv = tokenizeCommandLine(commandLine); + const argv = windowsArgv(commandLine); const command = ocxCommandIndex(argv); return command !== undefined && argv[command] === "start"; } @@ -62,18 +87,8 @@ export function readClientStopProcessStart(pid: number): string | undefined { if (ticks && /^\d+$/.test(ticks) && /^[a-f0-9-]{36}$/.test(boot)) return `linux:${boot}:${ticks}`; } if (platform === "win32") { - const native = windowsProcessNative(); - if (native) { - const identity = native.sameUserIdentity(pid); - return identity ? `win32:${identity.ticks}` : undefined; - } - if (windowsProcessPlatformSimulated()) return; - // The fallback also binds the SID to this incarnation by refreshing CreationDate. - const script = `$ErrorActionPreference='Stop'; $p=Get-CimInstance Win32_Process -Filter "ProcessId=${pid}"; $owner=Invoke-CimMethod -InputObject $p -MethodName GetOwnerSid; if ($owner.ReturnValue -eq 0 -and $owner.Sid -eq [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value -and $p.CreationDate) { $after=Get-CimInstance -InputObject $p; if ($after.CreationDate -eq $p.CreationDate) { $p.CreationDate.ToUniversalTime().Ticks } }`; - const ticks = execFileSync(resolveTrustedWindowsPowerShellExe(), ["-NoProfile", "-NoLogo", "-NonInteractive", "-Command", script], { - encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 3000, maxBuffer: 1024, windowsHide: true, - }).trim(); - if (/^\d{1,20}$/.test(ticks)) return `win32:${ticks}`; + const ticks = windowsProcessNative()?.sameUserIdentity(pid)?.ticks; + if (typeof ticks === "bigint" && ticks > 0n && ticks <= 3155378975999999999n) return `win32:${ticks}`; } } catch { /* unreadable ownership cannot authorize a native restoration handoff */ } } diff --git a/src/client/sync-runtime.ts b/src/client/sync-runtime.ts index 8aca45421ec..ab9500e0eeb 100644 --- a/src/client/sync-runtime.ts +++ b/src/client/sync-runtime.ts @@ -24,6 +24,14 @@ export function readSyncRuntime(): RuntimePortState | null { } catch { throw new ClientSyncRuntimeError("client_runtime_unverified"); } } +export function isPublishedRuntimeStopping( + expected: Required>, +): boolean { + const current = readSyncRuntime(); + return current?.clientStopping === true && current.pid === expected.pid && current.port === expected.port + && current.attestationSecret === expected.attestationSecret && current.servingGeneration === expected.servingGeneration; +} + /** Capture and recheck under C. Proven no-runtime sync keeps its existing offline behavior. */ export function clientSyncRuntimeGuard(): () => void { const expected = readSyncRuntime(); diff --git a/src/integrations/route-intent-tick.ts b/src/integrations/route-intent-tick.ts index 3469351c00f..69b2376bc88 100644 --- a/src/integrations/route-intent-tick.ts +++ b/src/integrations/route-intent-tick.ts @@ -3,6 +3,8 @@ import type { OcxClientConnectionConfig } from "../types"; export interface RouteIntentTickDeps { sync?: () => Promise; onApplied?: () => void | Promise; + /** True when this listener's stop fence already rules out a periodic apply. */ + deferPeriodic?: () => boolean; setTimer?: (callback: () => void, ms: number) => unknown; clearTimer?: (timer: unknown) => void; } @@ -32,6 +34,11 @@ export function startRouteIntentTick(connection: OcxClientConnectionConfig, deps do { queued = false; const batch = waiters.splice(0); + if (batch.length === 0 && deps.deferPeriodic) { + let deferred = false; + try { deferred = deps.deferPeriodic(); } catch { /* Let normal sync check uncertain state. */ } + if (deferred) { delay = 5_000; continue; } + } try { const result = await sync(); await deps.onApplied?.(); diff --git a/src/service/windows-process-native.ts b/src/service/windows-process-native.ts index 94658ff1a56..797bae67c22 100644 --- a/src/service/windows-process-native.ts +++ b/src/service/windows-process-native.ts @@ -88,6 +88,29 @@ export function fileTimeToEpochMs(fileTime: bigint): number | null { return ms > BigInt(Number.MAX_SAFE_INTEGER) ? null : Number(ms); } +/** Keep owner, lifetime and creation evidence on one process handle; never cache a PID proof. */ +export function readSameUserWindowsStart(pid: number, io: { + open: (pid: number) => number | bigint; + close: (handle: number | bigint) => void; + fileTime: (handle: number | bigint) => bigint | null; + exited: (handle: number | bigint) => boolean | null; + ownerSid: (handle: number | bigint) => string; + currentSid: () => string; +}): bigint | null { + if (!Number.isInteger(pid) || pid <= 0 || pid > 0x7fffffff) return null; + const handle = io.open(pid); + if (!handle) return null; + try { + const created = io.fileTime(handle); + if (created === null || created <= FILETIME_UNIX_EPOCH || io.exited(handle) !== false) return null; + const owner = io.ownerSid(handle); + if (!/^S-1-\d+(?:-\d+)+$/.test(owner) || owner !== io.currentSid() || io.exited(handle) !== false) return null; + // Preserve the creation identity already stored by the CIM-based stop owner protocol. + return (created + FILETIME_DOTNET_EPOCH) / 10n * 10n; + } catch { return null; } + finally { io.close(handle); } +} + /** Decode SERVICE_STATUS_PROCESS: the PID only while the service reports RUNNING. */ export function decodeServiceStatusProcess(buffer: Uint8Array): number | null { if (buffer.byteLength < SERVICE_STATUS_PROCESS_BYTES) return null; @@ -224,21 +247,24 @@ function loadNativeApi(): WindowsProcessNativeApi | null { } }, sameUserIdentity(pid, withCommandLine, expectedUserSid) { - const handle = k.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid); - if (!handle) return null; - try { - const fileTime = handleFileTime(handle); - if (fileTime === null) return null; - const userSid = handleUserSid(handle); - if (userSid !== handleUserSid(k.GetCurrentProcess()) || (expectedUserSid !== undefined && userSid !== expectedUserSid)) return null; - const commandLine = withCommandLine ? readWindowsProcessCommandLineFromHandle(handle) : undefined; - if (handleExited(handle) !== false) return null; - return { ticks: fileTimeToCimTicks(fileTime), commandLine }; - } catch { - return null; - } finally { - k.CloseHandle(handle); - } + let commandLine: string | undefined; + const ticks = readSameUserWindowsStart(pid, { + open: target => k.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, target), + close: handle => { k.CloseHandle(handle); }, + fileTime: handle => { + const created = handleFileTime(handle); + if (withCommandLine) commandLine = readWindowsProcessCommandLineFromHandle(handle); + return created; + }, + exited: handleExited, + ownerSid: handleUserSid, + // #9027: a caller that names the account requires exactly that account as well as the caller's. + currentSid: () => { + const current = handleUserSid(k.GetCurrentProcess()); + return expectedUserSid === undefined || expectedUserSid === current ? current : ""; + }, + }); + return ticks === null ? null : { ticks, commandLine }; }, terminate(pid, boundStartTime) { const handle = k.OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION | SYNCHRONIZE, 0, pid); diff --git a/structure/INDEX.md b/structure/INDEX.md index ecd299a0e70..b51f1fa798c 100644 --- a/structure/INDEX.md +++ b/structure/INDEX.md @@ -304,7 +304,9 @@ A source area can be described by more than one doc, because these docs are orga | `src/client/link-management-relay.ts` | [`usage-client-attribution.md`](usage-client-attribution.md) | | `src/client/link-parity-reporter.ts` | [`remote-link.md`](remote-link.md) | | `src/client/machine-listener.ts` | [`remote-link.md`](remote-link.md) | +| `src/client/runtime-recycle.ts` | [`remote-link.md`](remote-link.md) | | `src/client/runtime-restart.ts` | [`remote-link.md`](remote-link.md) | +| `src/client/runtime-rollback.ts` | [`remote-link.md`](remote-link.md) | | `src/clients/` | [`clients/integrations.md`](clients/integrations.md)
    [`clients/qoder.md`](clients/qoder.md)
    [`clients/client-support-matrix.md`](clients/client-support-matrix.md)
    [`clients/t3code.md`](clients/t3code.md) | | `src/clients/config-export.ts` | [`transports/timeouts.md`](transports/timeouts.md)
    [`clients/export-model-names.md`](clients/export-model-names.md)
    [`clients/omo-export-dialect.md`](clients/omo-export-dialect.md) | | `src/clients/config-export/` | [`clients/export-model-names.md`](clients/export-model-names.md) | diff --git a/structure/manifest.json b/structure/manifest.json index 2e14b6b2bf2..89416290a4c 100644 --- a/structure/manifest.json +++ b/structure/manifest.json @@ -1569,7 +1569,9 @@ "src/client/machine-listener.ts", "src/client/link-home.ts", "src/client/link-parity-reporter.ts", + "src/client/runtime-recycle.ts", "src/client/runtime-restart.ts", + "src/client/runtime-rollback.ts", "src/cli/link-apply-restart.ts", "src/cli/status-codex-settings.ts", "src/cli/status-link.ts", diff --git a/structure/ops/windows-checked-stop.md b/structure/ops/windows-checked-stop.md index 02174cba40d..1e1a38ee209 100644 --- a/structure/ops/windows-checked-stop.md +++ b/structure/ops/windows-checked-stop.md @@ -28,7 +28,7 @@ lazily, caches a failed load as unavailable, and closes every handle in a `final - an exit watch: a handle opened at bind time and polled with `WaitForSingleObject(handle, 0)`; - the Task Scheduler service host PID through `QueryServiceStatusEx` on `Schedule`, only while it runs. -Link stop reads a live process’s creation time and token user through one handle. To verify a stop owner, it also reads the command line through that handle using `src/config/windows-process-command-line.ts`. The creation time uses .NET ticks truncated to CIM’s microsecond precision so existing receipts and runtime records still match. If the native API is unavailable, a bounded CIM probe refreshes the creation time after reading the SID. A failed native read leaves the identity unverified. Forced Link termination requires the native handle and compares the saved creation time and token user on that handle before ending the process. +The Link Child reads its live same-user creation proof in-process on one native handle, using `GetProcessTimes` and the token user SID; stop-owner argv is read through that same handle by `src/config/windows-process-command-line.ts`. It preserves the existing .NET tick identity at microsecond precision without spawning PowerShell or caching a PID proof. The process fallback compares that identity on the same handle used for termination. Unavailable native identity or handle binding refuses promptly; it does not fall back to repeated CIM subprocesses. `tests/windows/windows-stop-owner-identity.test.ts` covers handle ownership, stale identities and an actual-Windows-only repeated-read budget. Windows ARM64, other platforms and any test that simulates a platform get no native API. `src/service/windows-process-evidence.ts` is the facade the operations use. Its process snapshot is diff --git a/structure/remote-link.md b/structure/remote-link.md index 151eb9c6d9c..a129e65454e 100644 --- a/structure/remote-link.md +++ b/structure/remote-link.md @@ -13,13 +13,15 @@ Signal fencing uses the configuration mutation lock (`C`), yielding 50 ms betwee `src/client/sync-runtime.ts` fences Link sync against the local runtime record. Signal shutdown marks its own PID/port/attestation generation as `clientStopping` under C before restoration, and retains that mark through its last await. Sync captures the record at admission and rechecks it under C before catalog, injection, settings-record and cache commits. A stopping, replaced, removed or unreadable record refuses the write; a stale operation cannot reinject after the Child exits. Failure to mark the runtime refuses restoration while service, Desktop and sibling preservation retain their own exclusions; a native teardown receipt never waives the file-route fence. No-runtime sync remains an explicit offline operation: it reapplies routing even though no Child listener is serving it. A stale stopping record is reconciled by the existing start/stop recovery paths, not by guessing PID ownership. A bound restart marks the record the same way before it drains the listener, and abandons the restart with the runtime still serving when the mark cannot be written; and every publication of the runtime record carries a fresh `servingGeneration`, so a sync admitted before a restart whose replacement failed is refused by the record the rollback publishes, while syncs admitted afterwards proceed (`tests/clients/client-restart-sync-fence.test.ts`). The separate-process catalog/settings-response holds in `tests/clients/client-link-stop.test.ts` cover late commits, fresh sync during shutdown and the completed-sync control. -Orderly signals in an unsupervised Link Child await file-route cleanup in `src/client/stop-routing.ts` before releasing the listener, then reuse native Codex config/catalog/history restoration and managed Grok removal. The saved connection and credentials remain. `src/client/restore-ownership.ts` optionally binds each write under C to the immutable served connection, including selection and rotation state. Only `catalogFingerprint` and `catalogSyncedAt`, updated by normal catalog sync, are excluded from this restore-specific comparison; `priorCatalog` remains guarded and the shared full-snapshot CAS for asynchronous connection work is unchanged. A changed owner, pending transition or unverified journal refuses remaining writes. Service/desktop supervision, sibling ownership and accepted restart/recycle handoff preserve integrations for their existing owners. Native teardown receipts never skip unsupervised file-route cleanup or the sync fence. `src/client/stop-native-handoff.ts` defers native Codex/Grok only when a bounded, no-follow receipt names the exact loopback endpoint, the current PID/port/attestation record binds its nonce to the PID and creation identity of a distinct live same-user stop invocation, and the receipt names that same owner. `src/client/stop-teardown-owner.ts` reads Linux NUL-separated argv and uses `src/client/stop-darwin-process.ts` for native macOS argv and microsecond process creation time. On Windows x64 it binds the creation time, token SID and argv to one live process handle. It accepts the supported compiled, source and npm stop forms, including installation paths containing spaces. Update workers launch a separate stop child. The Child rechecks the receipt bytes and runtime identity after inspecting the owner. The current claim can coexist with stale exact claims for this endpoint and quarantined obligations. For other endpoints, the current claim must carry the digest of the exact receipt bytes verified by the parent. A missing or changed snapshot, a malformed receipt or a guessed endpoint refuses signal deferral. Without that current owner, outstanding or unreadable receipt evidence refuses native restoration and retains the listener. Unreadable owner evidence blocks restart and recycle, as does a verified active stop. Both rollback paths that would recycle use the same admission check as scheduled recycle and bound restart. Signal shutdown waits for an accepted restart to hand off or finish rolling back; a pending admission owns no routing. It refuses new or pending restart admission with `409 runtime_stopping`; normal bound restart remains unchanged. After an ordinary unsupervised stop, start alone does not reapply routing; the operator steps live in the public CLI lifecycle reference. Coverage: `tests/clients/client-link-stop.test.ts`, `tests/clients/client-runtime-restart.test.ts`. +Orderly signals in an unsupervised Link Child await file-route cleanup in `src/client/stop-routing.ts` before releasing the listener, then reuse native Codex config/catalog/history restoration and managed Grok removal. The saved connection and credentials remain. `src/client/restore-ownership.ts` optionally binds each write under C to the immutable served connection, including selection and rotation state. Only `catalogFingerprint` and `catalogSyncedAt`, updated by normal catalog sync, are excluded from this restore-specific comparison; `priorCatalog` remains guarded and the shared full-snapshot CAS for asynchronous connection work is unchanged. A changed owner, pending transition or unverified journal refuses remaining writes. Service/desktop supervision, sibling ownership and accepted restart/recycle handoff preserve integrations for their existing owners. Native teardown receipts never skip unsupervised file-route cleanup or the sync fence. `src/client/stop-native-handoff.ts` defers native Codex/Grok only when a bounded, no-follow receipt names the exact loopback endpoint, the current PID/port/attestation record binds its nonce to the PID and creation identity of a distinct live same-user stop invocation, and the receipt names that same owner. `src/client/stop-teardown-owner.ts` reads Linux NUL-separated argv and uses `src/client/stop-darwin-process.ts` for native macOS argv and microsecond process creation time. On Windows x64, the same-user creation proof uses `GetProcessTimes`, the process token and stop-owner argv on one live native handle, without PowerShell/CIM subprocesses or cached PID proofs; unavailable native evidence refuses promptly. The stored .NET tick identity retains its existing microsecond precision. Windows command lines follow native double-quote/backslash rules and treat apostrophes literally. It accepts the supported compiled, source and npm stop forms, including installation paths containing spaces. Update workers launch a separate stop child. The Child rechecks the receipt bytes and runtime identity after inspecting the owner. The current claim can coexist with stale exact claims for this endpoint and quarantined obligations. For other endpoints, the current claim must carry the digest of the exact receipt bytes verified by the parent. A missing or changed snapshot, a malformed receipt or a guessed endpoint refuses signal deferral. Without that current owner, outstanding or unreadable receipt evidence refuses native restoration and retains the listener. Unreadable owner evidence blocks restart and recycle, as does a verified active stop. Both rollback paths that would recycle use the same admission check as scheduled recycle and bound restart. Signal shutdown waits for an accepted restart to hand off or finish rolling back; a pending admission owns no routing. It refuses new or pending restart admission with `409 runtime_stopping`; normal bound restart remains unchanged. After an ordinary unsupervised stop, start alone does not reapply routing; the operator steps live in the public CLI lifecycle reference. Coverage: `tests/clients/client-link-stop.test.ts`, `tests/clients/client-runtime-restart.test.ts`. -`src/client/stop-file-routing.ts` shares the receipt-driven file cleanup in `src/integrations/route-intent-disconnect.ts` without disconnecting the Child. It removes only Link-created file integrations, preserves pre-link standalone integrations and local opt-outs, and retains connection/recovery records. After the runtime fence, strict receipt and on-disk absence inspection may prove no file cleanup is needed without acquiring L or requiring a token; the connection, configured port and runtime boundary are still checked. Each actual writer acquires L and repeats the immutable connection, configured port and physical token checks under C immediately before committing; a partial cleanup invalidates the earlier Home apply proof. A conflicting file, changed owner or unverified receipt refuses cleanup without overwriting the conflict. Signal shutdown keeps the listener bound with sync fenced and background watchers stopped; another signal or `ocx stop` retries after repair. For an explicit stop, `src/cli/stop-restore.ts` requires the runtime's attested Link fence capability, exact PID/port/runtime generation and the serving Link ownership fingerprint. The fingerprint must match the saved connection, and the configured port must match the serving port. Invalid or mismatched connection state refuses before manager or process mutation. Saved client state, Link receipts, a live client runtime record, an attested Link fence or client-role health trigger preflight. It requires the protected runtime record and attested health for both tracked and discovered live targets before service-manager mutation. Missing or unreadable identity refuses those targets even if saved state reads disconnected. Standalone stop uses the ordinary manager and restore path. Link stop captures the same-user OS creation identity before attestation, checks the pinned runtime record afterwards, and rechecks the process identity at mutation boundaries. The fenced record and connection are checked before manager or process stop, including escalation and port reclaim. Linux requires a verified pidfd for both TERM and KILL. Windows checks creation time on the same handle used to terminate. macOS sends one orderly SIGTERM and returns a refusal if the Child stays up. That signal targets a numeric PID, so a same-user replacement can still receive it if the PID is reused between the final creation-time check and the signal syscall. Preflight checks the bounded inherited-teardown snapshot captured by `src/cli/index.ts`. Malformed/unscannable or guessed inherited evidence refuses before any manager or process stop. An exact receipt for this attested endpoint may be settled by this stop. For a different endpoint, the parent must prove absence and bind that receipt snapshot to its own claim. The parent still probes the inherited endpoints after shutdown before restoring or discharging receipts. Quarantine-only evidence and live concurrent/self-owned claims retain their existing recovery exclusions. The inherited-receipt scan reuses the owner observation for receipts naming the same PID and creation identity. Preflight marks the sync fence and drains these files before any service-manager stop, new teardown receipt or kill fallback. Each busy-lock retry takes a fresh guard and verifies the exact runtime inside C. The CLI revalidates the fenced record and connection immediately before invoking the manager or stopping the process, including forced fallback. A failed preflight returns without stopping a process. When all known concrete endpoints are dead and the manager is inactive, preflight returns `already-stopped`. For a saved Link on Linux with an unreadable manager, the offline path requires `lstat` to report `ENOENT` for the installer unit and every service installation record path. It runs without runtime attestation, fencing or file cleanup; the later parent restoration path attempts file cleanup. A surviving Link receipt without a matching saved Link refuses post-stop restoration and retains the evidence. An attested legacy native listener with saved Link ownership and neither a published owner nor a fence is refused with the ordered transition in the CLI lifecycle reference. The initial absence of file routes never skips the fence: an already-admitted Home update can enable its first file integration. Failure to establish the fence retains an unsupervised signal listener too. During unsupervised signal cleanup, a native Codex/Grok restoration refusal after file cleanup also retains the listener and sync fence. During explicit stop, native restoration is attempted by the parent after the Child exits; refusal retains recovery evidence and reports incomplete restoration with the listener already stopped. Successful native restoration and the supervised/sibling/handoff exclusions keep their existing owners. Coverage: `tests/clients/client-link-stop.test.ts` (file writers, listener release and late materializer commits) and `tests/clients/client-link-stop-sibling.test.ts` (CLI stop ordering, process identity and native handoff). +`src/client/stop-file-routing.ts` shares the receipt-driven file cleanup in `src/integrations/route-intent-disconnect.ts` without disconnecting the Child. It removes only Link-created file integrations, preserves pre-link standalone integrations and local opt-outs, and retains connection/recovery records. After the runtime fence, strict receipt and on-disk absence inspection may prove no file cleanup is needed without acquiring L or requiring a token; the connection, configured port and runtime boundary are still checked. Each actual writer acquires L and repeats the immutable connection, configured port and physical token checks under C immediately before committing; a partial cleanup invalidates the earlier Home apply proof. A conflicting file, changed owner or unverified receipt refuses cleanup without overwriting the conflict. Signal shutdown keeps the listener bound with sync fenced and background watchers stopped; another signal or `ocx stop` retries after repair. For an explicit stop, `src/cli/stop-restore.ts` requires the runtime's attested Link fence capability, exact PID/port/runtime generation and the serving Link ownership fingerprint. The fingerprint must match the saved connection, and the configured port must match the serving port. Invalid or mismatched connection state refuses before manager or process mutation. Saved client state, Link receipts, a live client runtime record, an attested Link fence or client-role health trigger preflight. It requires the protected runtime record and attested health for both tracked and discovered live targets before service-manager mutation. Missing or unreadable identity refuses those targets even if saved state reads disconnected. Standalone stop uses the ordinary manager and restore path. Link stop captures the same-user OS creation identity before attestation, checks the pinned runtime record afterwards, and rechecks process identity at mutation boundaries. The fenced record and connection are checked before manager or process stop, including escalation and port reclaim. Linux requires a verified pidfd for both TERM and KILL. Windows checks creation time on the same handle used to terminate. macOS sends one orderly SIGTERM and returns a refusal if the Child stays up. That signal targets a numeric PID, so a same-user replacement can still receive it if the PID is reused between the final creation-time check and the signal syscall. Preflight checks the bounded inherited-teardown snapshot captured by `src/cli/index.ts`. Malformed/unscannable or guessed inherited evidence refuses before any manager or process stop. An exact receipt for this attested endpoint may be settled by this stop. For a different endpoint, the parent must prove absence and bind that receipt snapshot to its own claim. The parent still probes the inherited endpoints after shutdown before restoring or discharging receipts. Quarantine-only evidence and live concurrent/self-owned claims retain their existing recovery exclusions. The inherited-receipt scan reuses the owner observation for receipts naming the same PID and creation identity. Preflight marks the sync fence and drains these files before any service-manager stop, new teardown receipt or kill fallback. Each busy-lock retry takes a fresh guard and verifies the exact runtime inside C. The CLI revalidates the fenced record and connection immediately before invoking the manager or stopping the process, including forced fallback. A failed preflight returns without stopping a process. When all known concrete endpoints are dead and the manager is inactive, preflight returns `already-stopped`. For a saved Link on Linux with an unreadable manager, the offline path requires `lstat` to report `ENOENT` for the installer unit and every service installation record path. It runs without runtime attestation, fencing or file cleanup; the later parent restoration path attempts file cleanup. A surviving Link receipt without a matching saved Link refuses post-stop restoration and retains the evidence. An attested legacy native listener with saved Link ownership and neither a published owner nor a fence is refused with the ordered transition in the CLI lifecycle reference. The initial absence of file routes never skips the fence: an already-admitted Home update can enable its first file integration. Failure to establish the fence retains an unsupervised signal listener too. During unsupervised signal cleanup, a native Codex/Grok restoration refusal after file cleanup also retains the listener and sync fence. During explicit stop, native restoration is attempted by the parent after the Child exits; refusal retains recovery evidence and reports incomplete restoration with the listener already stopped. Successful native restoration and the supervised/sibling/handoff exclusions keep their existing owners. Coverage: `tests/clients/client-link-stop.test.ts` (file writers, listener release and late materializer commits) and `tests/clients/client-link-stop-sibling.test.ts` (CLI stop ordering, process identity and native handoff). A discovery miss requires independent standalone proof or a matching manager registration bound to the PID. The [standalone stop rules](runtime.md#lifecycle) describe the runtime-record fallback. With neither proof, `ocx stop` refuses before the service stop and signal ladder, preserving the Child's ability to refuse an unsafe shutdown. -An explicit parent stop sets `clientStopRequested: true` and writes its nonce, owner PID and process creation identity in the same exact-runtime C transaction. A deferred-teardown receipt with that nonce and creation identity must be written before manager or process stop. `src/config/process-state.ts` accepts both boolean values only with `clientStopping: true`. Before releasing its ownership mutation lease, the CLI finalizer clears only the matching request and retains the sync fence. A finalization refusal keeps the fence and preserves the original stop result. The runtime observes it only for its own PID/port/attestation, rejects further restart admission and the pre-fence stage of an already-admitted restart, and preserves both active and finished states under C when publishing a failed-restart rollback. A retained fence blocks unchanged, pending, new or unverified connections. Only a validated disconnected config and a complete disconnect receipt for the served owner and token, checked together under C with no pending connect, admit a serialized standalone recycle after the parent stop finishes. A verified active or unverified parent stop blocks recovery, as does signal shutdown. Only a dead PID or a positively different creation identity is confirmed stale. A malformed identity or an unrecognized invocation at the same incarnation is unverified. A receipt whose owner cannot be verified remains outstanding and blocks parent recovery. The check covers a previously scheduled timer and a restart awaiting its final supervisor check. After a completed disconnect, a finished request or confirmed-stale owner permits recovery. Signal shutdown cancels a pending recycle timer and frees its scheduling slot for eligible recovery if the listener is retained. Shutdown still waits for a recycle already in flight. A fresh process has a new attestation and does not inherit a stale request. The owning runtime passes `linkStopFence: true` to `src/client/machine-listener.ts`, which advertises it in attested health. Link preflight requires that capability before writing the marker or files; older or unknown running builds refuse with supervisor update/restart guidance. A Hub stop does not require the Link fence. A native listener that does not report a Link fence must publish its Hub identity and still have a saved Hub connection. Older native listeners without a published owner refuse until updated and restarted through their supervisor. Ordinary restart has no explicit-stop marker, so a failed replacement still publishes a new generation and admits fresh sync. Rollback holds the rebound listener during bounded config-lock retries and starts the tunnel supervisor and credential observer after publication. The overlap and ordinary-rollback control use real runtime records and file writers in `tests/clients/client-link-stop-recovery.test.ts`. +An explicit parent stop sets `clientStopRequested: true` and writes its nonce, owner PID and process creation identity in the same exact-runtime C transaction. A deferred-teardown receipt with that nonce and creation identity must be written before manager or process stop. `src/config/process-state.ts` accepts both boolean values only with `clientStopping: true`. Before releasing its ownership mutation lease, the CLI finalizer clears only the matching request and retains the sync fence. A finalization refusal keeps the fence and preserves the original stop result. The runtime observes it only for its own PID/port/attestation, rejects further restart admission and the pre-fence stage of an already-admitted restart, and preserves both active and finished states under C when publishing a failed-restart rollback. A retained fence blocks unchanged, pending, new or unverified connections. Only a validated disconnected config and a complete disconnect receipt for the served owner and token, checked together under C with no pending connect, admit a serialized standalone recycle after the parent stop finishes. A verified active or unverified parent stop blocks recovery, as does signal shutdown. Only a dead PID or a positively different creation identity is confirmed stale. A malformed identity or an unrecognized invocation at the same incarnation is unverified. A receipt whose owner cannot be verified remains outstanding and blocks parent recovery. The check covers a previously scheduled timer and a restart awaiting its final supervisor check. After a completed disconnect, a finished request or confirmed-stale owner permits recovery. Signal shutdown cancels a pending recycle timer and frees its scheduling slot for eligible recovery if the listener is retained. Shutdown still waits for a recycle already in flight. A fresh process has a new attestation and does not inherit a stale request. The owning runtime passes `linkStopFence: true` to `src/client/machine-listener.ts`, which advertises it in attested health. Link preflight requires that capability before writing the marker or files; older or unknown running builds refuse with supervisor update/restart guidance. A Hub stop does not require the Link fence. A native listener that does not report a Link fence must publish its Hub identity and still have a saved Hub connection. Older native listeners without a published owner refuse until updated and restarted through their supervisor. Ordinary restart has no explicit-stop marker, so a failed replacement still publishes a new generation and admits fresh sync. Rollback closes an unpublished rebound listener before yielding on lifecycle/configuration lock contention, retries within one shared rebind deadline, and rechecks connection ownership and explicit-stop evidence before each new bind and publication. It starts the tunnel supervisor and credential observer only after publication. The overlap and ordinary-rollback control use real runtime records and file writers in `tests/clients/client-link-stop-recovery.test.ts`. + +`src/client/runtime-recycle.ts` holds the Link apply exclusion from admission through listener drain and routing cleanup. Admission rechecks the served connection and explicit-stop policy under the configuration mutation lock; a pending transition, unchanged connection or retained stop obligation refuses teardown. The exclusion is released before replacement startup. `src/client/runtime-rollback.ts` retries only proven lifecycle or SQLite lock contention, with at most 50 ms between attempts and one remaining-time budget shared with listener rebinding. Coverage: `tests/clients/client-recycle-exclusion.test.ts`, `tests/clients/client-restart-rollback-lock.test.ts`, and the rollback controls in `tests/clients/client-link-stop-recovery.test.ts`. `src/link/ssh-argv.ts` and `src/link/remote-windows.ts` build every gated Child command through `remoteGatedOcxArgv` and `windowsGatedOcxArgv`: the script selects one executable, reads its version inside the remote script, refuses below the command's minimum with a named `ocx-fanout:` marker and exit 121, and only then runs the arguments. Every gated script exports `OCX_NO_DESKTOP_HANDOFF=1` before the version probe and the run, so a package launcher answers for itself and a Desktop handoff cannot pass the gate on behalf of an older launcher. The pinned sync is the 2.93.0 instance and executes `sync --expect-link`; the Home adds `--restart-app-server-only` or `--restart-codex` only for a restarting sync (the Child operation runners below and `ocx sync --restart-children`), never on Windows (the builder refuses it, `unsupported:windows-restart`) or for a link recorded as `ocx-child`, and withholds it for a link whose relayed model traffic is in flight (`src/cli/sync-fanout.ts`, `src/link/sync-then-restart.ts`). A link whose `childKind` is not recorded can receive the flag on that second sync, which is how the selected-kind marker reports `ocx-child`; `ocx-child` ignores it. The update builders in `src/link/child-gated-ocx.ts` require 2.97.0 inside the script, so the Home never sends `update` to an ocx that reports an older version; they refuse a selected `ocx-child` by file name (`ocx-fanout:child-ocx-ephemeral`) and on POSIX report `ocx-fanout:entry:pair|binary` (Windows reads no census, so its script prints no entry marker and the Home infers `binary`); the plan probe also reports the Child's clock, and the shipped builders refuse Windows apply. A Windows command that would exceed the encoded command-line budget throws `windows-command-too-long`; the plan probe fits a Home version of at least 40 characters. `src/link/child-update-contract.ts` is the Home's own strict copy of the Child's `update.orchestrated/1` plan and result documents and maps every apply exit to a closed verdict. `src/link/child-observations.ts` keeps a tolerant per-link cache in `/link/child-observations.json` beside the strict `links.json`: it drops unknown keys, prunes removed links on write and reads damage as empty. The per-Child sync classifier lives in `src/link/sync-fanout-classify.ts`. The plan probe is wired to the observe operation (`src/link/child-observe.ts`, below), which always passes the resolved platform to `classifyUpdatePlanProbe`; the apply builder and the sync restart flag are called from the Child operation runners (below) and `ocx sync --restart-children`; nothing runs on a timer except the Child-ops scheduler (below), which submits no-restart `sync` jobs and restarts app-servers only for idle Children under `childCodexRestart: "app-server-when-idle"`. The relay, not `onAuthenticatedCatalog` (which fires on admission and keeps driving the supervisor and the enrollment wait), records each Child's catalog pulls. Coverage: `tests/clients/link-gated-ocx-argv.test.ts`, `tests/clients/link-child-update-contract.test.ts`, `tests/clients/link-child-observations.test.ts`. Fan-out platform discovery in `src/link/remote-platform.ts` accepts a Windows marker on any stdout line or one framed uname line, so login-shell output cannot decide the platform. The Home requires one valid selection marker on stderr and one stdout delimiter, and classifies only the text after that delimiter; login-shell output before them is ignored. Oversized version probes are skipped. POSIX version capture and watchdog readiness use a private temporary directory, removed before execution or on refusal. The Home's `src/cli/sync-command.ts` fans out only after its catalog is current; the Child may still restart its own OpenCodex client runtime after applying changed Home settings. With `--overwrite-conflict` the pinned sync gate requires 2.100.0 and refuses ephemeral Children before executing; explicit client selection is forwarded. Known ephemeral links receive plain catalog sync. Coverage: `tests/clients/link-pinned-sync-overwrite.test.ts`, `tests/cli/cli-sync-fanout-ephemeral.test.ts`. @@ -337,7 +339,7 @@ When sync preserves an external Codex provider without applying configuration, i `ocx status --json` reports `appliedCodexSettingsDigest` on every device (a Child's record, or a Home's own projection, which is what it serves), and on a Child `lastApplyAt` and `runtimeStartedAt` as epoch ms (`src/cli/status-codex-settings.ts`). The client runtime's `/healthz` reports `startedAt`. After `ocx sync` records an apply, `src/cli/link-apply-restart.ts` restarts the client runtime through `handleProxyRestart`, the `ocx restart` path, only when the live client runtime started before `appliedAt` or reports no start; its start callback starts nothing unless an accepted restart left no runtime, which takes the ordinary recovery start. An explicit Desktop or service supervised refusal defers that restart without failing the applied sync; the notice directs Desktop users to Quit from the tray menu and reopen OpenCodex, or service users to `ocx service restart`. The next sync retries until the runtime starts after the apply. Other restart failures remain failures, and any earlier sync error is retained. The Child's JSON shape stays unchanged so existing Home fan-out parsers accept the successful result. -The client listener serves that bound restart (`src/client/machine-listener.ts`, `src/client/runtime-restart.ts`). `/healthz` answers the attestation challenge with the secret the runtime publishes in `runtime-port.json` and advertises `restartCapability: "v1"`; `POST /api/system/restart` admits only the HMAC capability bound to this pid and port, never a dashboard session, admin token or link key. If the relaunch command cannot be identified, `src/client/runtime.ts` omits it from the runtime record; update admission treats the identity as unproven, while client startup and shutdown continue. Under the desktop app or a viable service it answers `409 restart_supervised` naming the supervisor and keeps serving, because handing off to a supervisor means exiting before the replacement is proven; the CLI reports "not performed, runtime kept". That refusal applies only while the durable connection is still the one the runtime serves: after `ocx disconnect` or a newer connect there is nothing to keep, so the restart is accepted and hands off to the standalone recycle (desktop exit 75, a viable service exit 1, otherwise a spawned replacement carrying no supervisor marker). "Ended" needs evidence (`readClientConnectionStateWithEvidence`, one snapshot of config.json): a saved file that validates and records no client, or another connection; missing, unreadable or invalid is invalid. Ownership and relaunch are separate (`classifyClientRestartSupervisor`): manager-launched evidence is the current markers in the environment only (`isMarkedSupervisedServiceChild`: the managed marker or the Windows wrapper marker); a legacy Windows registration recognised only from its parent's command line counts as a bare OCX_SERVICE=1; relaunch needs the service diagnostic to be viable and running. Manager-launched without that is `service-unproven`. `service-unproven` keeps the runtime and is refused at admission even when the connection ended; on this PR's recycle path only a process whose owner is proven to be none detaches, carrying no supervisor marker. A bare OCX_SERVICE=1 is outside that path and is always refused as `legacy-flag` (#8545, owner decision 2026-11-16): its owner is never inferred, not from the service diagnostic and not from the parent's command line, so nothing is stopped, replaced or recycled. A marker proves only that the process was started with it, so no supervisor marker may reach a process that supervisor did not launch: `src/lib/supervisor-markers.ts` holds the one list, and every detached runtime launch (companions, recycle, replacement, detached and post-update starts) and every shell a runtime hands to a tool clears it. The ended-connection recycle needs positive ownership evidence (`restartOwnerProven`: the desktop app, a manager's marker, or no OCX_SERVICE at all). A bare OCX_SERVICE=1 (a service registered before v2.49, or the proxy of ocx claude, ocx codex or ocx opencode) cannot be told apart, so its client runtime refuses `ocx restart` with 409 `restart_supervised` and supervisor `legacy-flag` whatever the service state and whether or not the connection ended, and records `restartOwner: legacy-flag`. The refusal text (`LEGACY_FLAG_OWNER_ADVICE` in `src/cli/restart-failure.ts`) tells the user to re-register the service once with `ocx service repair`, which writes the current ownership marker, or, for a companion's proxy, to `ocx stop` and start it again; `ocx sync` defers with the same text. `ocx disconnect` restarts only a runtime whose record states an owner it handles (`restartOwner`: desktop, service-manager or none); for `legacy-flag` it sends no restart request, prints the advice on stderr and exits 0, because the disconnect itself completed and a later `ocx restart` refuses with the same advice. A runtime started before this field existed, or an unknown value, gets origin/dev's disconnect: no restart request, exit 0. An inconclusive liveness probe or an unreadable record still exits 1 before any request, the one deliberate difference from origin/dev (no runtime is stopped, and the Home's leave stops before its own `ocx restart`). Owner evidence for those runtimes is a separate design (follow-up issue). `ocx disconnect` (`src/cli/disconnect-runtime.ts`) runs that restart itself when a client runtime is still live, bound to the runtime generation it observed: it captures that runtime's record (pid, port, per-process attestation secret) and the bound restart attests and derives its capability from the captured record, so another process at a reused pid is refused. It reads the client state once after its observation; when no runtime or a non-client runtime answered, that read decides alone (exit 0 only if disconnected). When it restarted a client runtime, it reads the state again after the restart: exit 0 needs that read to be disconnected and a live non-client runtime answering, and every exit-1 outcome takes its advice from one function (`recoveryAdvice`) given the state read at that point and whether the captured runtime, a different one or nothing answers: a plain restart is advised only for the captured runtime under a disconnected state (or a start when nothing answers), and a connected or unreadable state gets `ocx status` inspection only. Every other outcome exits 1, so a Home-driven leave stops before its own `ocx restart`. No read fences a process that runs after the command has exited. Each `ocx disconnect` attempt holds its own lock D (`withClientDisconnectAttempt` in `src/client/lifecycle-lock.ts`, outermost and taken by nothing else), so a second attempt refuses with `client_disconnect_busy` instead of sharing the first one's receipt while Codex is restored outside L. A disconnect refused before its receipt reaches `desktop_restored` (in practice, by the Codex journal restore, which keeps Codex's own later edits through `preserveConfigEdits`) removes that `prepared` receipt (and an otherwise empty `desktop-remote/` folder) when this attempt wrote it, or when an earlier run's receipt finds the Desktop store with no restore started (`absent`, `active` or `legacy_current_connection`); otherwise the receipt is kept, because that run may have stopped inside the Desktop restore. On a link Child the route-intent drain has already run by then; the rollback leaves it, and the runtime's next route-intent apply restores the routed file integrations. A pending receipt makes client startup refuse with `client_disconnect_pending`; that startup refusal names `ocx disconnect` as the way to finish or roll back (`src/client/connect.ts`, `src/client/state.ts`). `inspectRemoteDesktopStore` reports which step failed and the path it read, and `src/client/desktop-refusal.ts` turns that into the refusal. Coverage: `tests/clients/client-disconnect-recovery.test.ts`, `tests/clients/client-disconnect-desktop-refusals.test.ts`. Right after its connection commits, `connectClient` (and each connected `ocx sync` injection) takes over a Codex journal another owner wrote (`adoptJournalForClient` in `src/codex/journal.ts`), keeping the original snapshot; before the commit the journal stays its live writer's, so a runtime starting mid-connect leaves it alone, and after it a supervisor relaunch does not read the standalone owner as a crashed session and restore native Codex. Only a disconnected state or a different committed connection counts as ended for a supervised restart; unreadable or mismatched state keeps the refusal, and the controller rechecks after its supervisor lookup, immediately before recycling, handing the recycle the same supervisor verdict (a service only when viable). Otherwise one budget (`CLIENT_RESTART_BUDGET_MS`, 90 s from acceptance) covers a 20 s listener drain, a replacement `ocx start` that must answer by 70 s (`spawnReplacementStart` with `notReady: "terminate"`, which stops an unready replacement and returns only after its exit is observed), and a rollback that binds the port again with a 10 s wait, builds a fresh tunnel supervisor (a stopped one cannot restart) and republishes the same attestation secret and start time. Before binding, and again under the client lifecycle lock right before it publishes, it checks that the durable connection is still the one it served; Link rollback takes C inside the lifecycle lock to preserve any explicit stop fence. Ownership change, lock contention or publication failure closes the rebound listener in the binding turn, before the existing recycle admission check. `requestBoundSystemRestart` sends the request to a client target only while `CLIENT_RESTART_REQUEST_MIN_REMAINING_MS` remains, so a rollback always ends before the CLI's replacement observation and its recovery start. Coverage: `tests/clients/client-runtime-restart.test.ts`, `tests/server/restart-replacement-not-ready.test.ts`, `tests/cli/link-apply-restart.test.ts`. +The client listener serves that bound restart (`src/client/machine-listener.ts`, `src/client/runtime-restart.ts`). `/healthz` answers the attestation challenge with the secret the runtime publishes in `runtime-port.json` and advertises `restartCapability: "v1"`; `POST /api/system/restart` admits only the HMAC capability bound to this pid and port, never a dashboard session, admin token or link key. If the relaunch command cannot be identified, `src/client/runtime.ts` omits it from the runtime record; update admission treats the identity as unproven, while client startup and shutdown continue. Under the desktop app or a viable service it answers `409 restart_supervised` naming the supervisor and keeps serving, because handing off to a supervisor means exiting before the replacement is proven; the CLI reports "not performed, runtime kept". That refusal applies only while the durable connection is still the one the runtime serves: after `ocx disconnect` or a newer connect there is nothing to keep, so the restart is accepted and hands off to the standalone recycle (desktop exit 75, a viable service exit 1, otherwise a spawned replacement carrying no supervisor marker). "Ended" needs evidence (`readClientConnectionStateWithEvidence`, one snapshot of config.json): a saved file that validates and records no client, or another connection; missing, unreadable or invalid is invalid. Ownership and relaunch are separate (`classifyClientRestartSupervisor`): manager-launched evidence is the current markers in the environment only (`isMarkedSupervisedServiceChild`: the managed marker or the Windows wrapper marker); a legacy Windows registration recognised only from its parent's command line counts as a bare OCX_SERVICE=1; relaunch needs the service diagnostic to be viable and running. Manager-launched without that is `service-unproven`. `service-unproven` keeps the runtime and is refused at admission even when the connection ended; on this PR's recycle path only a process whose owner is proven to be none detaches, carrying no supervisor marker. A bare OCX_SERVICE=1 is outside that path and is always refused as `legacy-flag` (#8545, owner decision 2026-11-16): its owner is never inferred, not from the service diagnostic and not from the parent's command line, so nothing is stopped, replaced or recycled. A marker proves only that the process was started with it, so no supervisor marker may reach a process that supervisor did not launch: `src/lib/supervisor-markers.ts` holds the one list, and every detached runtime launch (companions, recycle, replacement, detached and post-update starts) and every shell a runtime hands to a tool clears it. The ended-connection recycle needs positive ownership evidence (`restartOwnerProven`: the desktop app, a manager's marker, or no OCX_SERVICE at all). A bare OCX_SERVICE=1 (a service registered before v2.49, or the proxy of ocx claude, ocx codex or ocx opencode) cannot be told apart, so its client runtime refuses `ocx restart` with 409 `restart_supervised` and supervisor `legacy-flag` whatever the service state and whether or not the connection ended, and records `restartOwner: legacy-flag`. The refusal text (`LEGACY_FLAG_OWNER_ADVICE` in `src/cli/restart-failure.ts`) tells the user to re-register the service once with `ocx service repair`, which writes the current ownership marker, or, for a companion's proxy, to `ocx stop` and start it again; `ocx sync` defers with the same text. `ocx disconnect` restarts only a runtime whose record states an owner it handles (`restartOwner`: desktop, service-manager or none); for `legacy-flag` it sends no restart request, prints the advice on stderr and exits 0, because the disconnect itself completed and a later `ocx restart` refuses with the same advice. A runtime started before this field existed, or an unknown value, gets origin/dev's disconnect: no restart request, exit 0. An inconclusive liveness probe or an unreadable record still exits 1 before any request, the one deliberate difference from origin/dev (no runtime is stopped, and the Home's leave stops before its own `ocx restart`). Owner evidence for those runtimes is a separate design (follow-up issue). `ocx disconnect` (`src/cli/disconnect-runtime.ts`) runs that restart itself when a client runtime is still live, bound to the runtime generation it observed: it captures that runtime's record (pid, port, per-process attestation secret) and the bound restart attests and derives its capability from the captured record, so another process at a reused pid is refused. It reads the client state once after its observation; when no runtime or a non-client runtime answered, that read decides alone (exit 0 only if disconnected). When it restarted a client runtime, it reads the state again after the restart: exit 0 needs that read to be disconnected and a live non-client runtime answering, and every exit-1 outcome takes its advice from one function (`recoveryAdvice`) given the state read at that point and whether the captured runtime, a different one or nothing answers: a plain restart is advised only for the captured runtime under a disconnected state (or a start when nothing answers), and a connected or unreadable state gets `ocx status` inspection only. Every other outcome exits 1, so a Home-driven leave stops before its own `ocx restart`. No read fences a process that runs after the command has exited. Each `ocx disconnect` attempt holds its own lock D (`withClientDisconnectAttempt` in `src/client/lifecycle-lock.ts`, outermost and taken by nothing else), so a second attempt refuses with `client_disconnect_busy` instead of sharing the first one's receipt while Codex is restored outside L. A disconnect refused before its receipt reaches `desktop_restored` (in practice, by the Codex journal restore, which keeps Codex's own later edits through `preserveConfigEdits`) removes that `prepared` receipt (and an otherwise empty `desktop-remote/` folder) when this attempt wrote it, or when an earlier run's receipt finds the Desktop store with no restore started (`absent`, `active` or `legacy_current_connection`); otherwise the receipt is kept, because that run may have stopped inside the Desktop restore. On a link Child the route-intent drain has already run by then; the rollback leaves it, and the runtime's next route-intent apply restores the routed file integrations. A pending receipt makes client startup refuse with `client_disconnect_pending`; that startup refusal names `ocx disconnect` as the way to finish or roll back (`src/client/connect.ts`, `src/client/state.ts`). `inspectRemoteDesktopStore` reports which step failed and the path it read, and `src/client/desktop-refusal.ts` turns that into the refusal. Coverage: `tests/clients/client-disconnect-recovery.test.ts`, `tests/clients/client-disconnect-desktop-refusals.test.ts`. Right after its connection commits, `connectClient` (and each connected `ocx sync` injection) takes over a Codex journal another owner wrote (`adoptJournalForClient` in `src/codex/journal.ts`), keeping the original snapshot; before the commit the journal stays its live writer's, so a runtime starting mid-connect leaves it alone, and after it a supervisor relaunch does not read the standalone owner as a crashed session and restore native Codex. Only a disconnected state or a different committed connection counts as ended for a supervised restart; unreadable or mismatched state keeps the refusal, and the controller rechecks after its supervisor lookup, immediately before recycling, handing the recycle the same supervisor verdict (a service only when viable). Otherwise one budget (`CLIENT_RESTART_BUDGET_MS`, 90 s from acceptance) covers a 20 s listener drain, a replacement `ocx start` that must answer by 70 s (`spawnReplacementStart` with `notReady: "terminate"`, which stops an unready replacement and returns only after its exit is observed), and a rollback that binds the port again with a 10 s wait, builds a fresh tunnel supervisor (a stopped one cannot restart) and republishes the same attestation secret and start time. Before binding, and again under the client lifecycle lock right before it publishes, it checks that the durable connection is still the one it served; Link rollback takes C inside the lifecycle lock to preserve any explicit stop fence. An unsuccessful publication closes the rebound listener in the binding turn. Only proved lifecycle or config SQLite contention retries, yielding with that listener closed and rechecking the durable owner and stop fence before a fresh bind/publication. All attempts share the existing 10 s rollback budget; ownership, storage and other failures do not retry. Link recycle takes the outer apply exclusion before its final C-protected owner/stop-receipt/pending-connect admission, outside L, and retains it through supervisor stop, listener closure, record cleanup and diagnostic drain. Once teardown begins it finishes under that exclusion instead of abandoning a partially stopped runtime. `requestBoundSystemRestart` sends the request to a client target only while `CLIENT_RESTART_REQUEST_MIN_REMAINING_MS` remains, so a rollback always ends before the CLI's replacement observation and its recovery start. Coverage: `tests/clients/client-runtime-restart.test.ts`, `tests/server/restart-replacement-not-ready.test.ts`, `tests/cli/link-apply-restart.test.ts`. The Home learns a Child's apply from the Child (`src/link/child-parity.ts`, `src/client/link-parity-reporter.ts`). The linked client runtime POSTs `{linkId, lastApplyAt, runtimeStartedAt, appliedCodexSettingsDigest, sequence}` to `/v1/link-management/child-parity` through the connection-bound relay, shortly after start with backoff and then once a minute; a 404 stops it. On the Home the hub-link listener admits exactly that POST beside the read table, and `src/server/index/link-management.ts` handles it before the passive-read dispatch: the admitting key must own the named link, the body is capped at 8 KiB and 5 s, the parse is strict, and the only effect is an in-memory entry pruned to current links. Entries are ordered by `runtimeStartedAt`, then by `sequence` (process-wide, so a rollback keeps counting), and an older report is ignored, so a late POST from a replaced runtime or an earlier send never moves the row backward. `GET /api/link/status` and `ocx link status --json` carry `lastApplyAt`, `runtimeStartedAt`, `appliedCodexSettingsDigest` and `reportedAt` (epoch ms) on every link row, null without a report; the CLI accepts their absence from an older runtime. Coverage: `tests/server/link-child-parity.test.ts`, `tests/clients/link-parity-reporter.test.ts`. @@ -398,7 +400,7 @@ The authenticated `GET /v1/link-management/route-intent` is separate from the ma `src/server/index/route-intent-watch.ts` adds optional closed headers on that same GET: `x-ocx-route-intent-watch: 1` and an optional `x-ocx-route-intent-after` lowercase SHA-256 digest. A differing or absent digest returns immediately. A matching digest waits for a Home notification or at most 30 seconds, then repeats the listener's link-key admission against current policy (`serve-options.ts` passes a `readmit` callback; a key revoked during the wait is refused with 403 `link_key_required`), rechecks current link ownership and projects fresh policy. Successful reads advertise watch support in the same watch header; watch responses identify `changed`, `notified` or `timeout` in `x-ocx-route-intent-wake`. An unchanged timeout needs no apply, but an explicit notification and a changed digest still request sync. A peer without the new response header retains the previous conservative behavior. `src/link/route-intent-watch.ts` holds at most one waiter per link and 256 total in process memory; duplicate/capacity admission refuses, cancellation removes the waiter, and notification neither persists state nor acknowledges an apply. Home device mutations notify that link, default mutations notify every linked device, and Child-initiated explicit sync notifies an active waiter while returning `pending`; without a watcher it directs the caller to the Child or the next periodic tick. Conflict overwrite still requires explicit local Child authority. -`src/client/route-intent-watch.ts` exposes `startRouteIntentWatch(connection, key, { requestSync })` and `stop()`. Each GET uses the existing connection-bound relay, resolves a key getter afresh for rotation, pins the starting connection identity, refuses redirects and consumes at most 64 KiB with an 8 KiB response-header bound and a 40-second total read budget. A Home without watch support leaves reconciliation to the existing periodic tick. Failed reads retry after five seconds; immediately returning supported peers cannot create a tight loop. Watch notifications retain one pending apply while `requestSync` is busy and retry rejected applies. The runtime owner supplies the same serialized scheduler used by periodic sync, reports successful applies through the existing parity reporter, and stops the watcher with the runtime. Standalone recycle also stops the reporter, watch and tick before listener shutdown or replacement handoff; watch cancellation releases the outstanding Home read. The watch itself writes no client files or receipts and adds no Child-to-Home mutation endpoint. The periodic tick (`src/integrations/route-intent-tick.ts`) runs a full `syncConnectedClient` every 60 seconds even when nothing changed. Each apply first clears the Home proof record and writes a withdrawn receipt, because a failed or interrupted apply must not leave an earlier proof current, then rewrites both; unchanged writers make no client-file change, but the receipt and record are rewritten, and a parity report sent during that window carries the withdrawal until the next report. Avoiding the rewrite would mean knowing an apply changes nothing before running it, which the withdraw-first rule forbids. Native switches on a Child follow the Home: a local `ocx restore` is reverted by the next tick unless the person records `ocx route to codex off --local`. A tick can change the saved `selectedClients`, so `/api/machine/clients` reports the saved selection while it still belongs to the served connection (`src/client/machine-api.ts`). The tick does not restart the runtime after it applies changed Home Codex settings: the parity report keeps the runtime's real start time, so status shows that the runtime predates the apply, and `ocx sync` (or the Home fan-out) restarts it as before. +`src/client/route-intent-watch.ts` exposes `startRouteIntentWatch(connection, key, { requestSync })` and `stop()`. Each GET uses the existing connection-bound relay, resolves a key getter afresh for rotation, pins the starting connection identity, refuses redirects and consumes at most 64 KiB with an 8 KiB response-header bound and a 40-second total read budget. A Home without watch support leaves reconciliation to the existing periodic tick. A periodic tick defers for five seconds when its own published listener is marked stopping. Home-requested syncs still enter the normal queue and receive the result of the guarded sync. Failed reads retry after five seconds; immediately returning supported peers cannot create a tight loop. Watch notifications retain one pending apply while `requestSync` is busy and retry rejected applies. The runtime owner supplies the same serialized scheduler used by periodic sync, reports successful applies through the existing parity reporter, and stops the watcher with the runtime. Standalone recycle also stops the reporter, watch and tick before listener shutdown or replacement handoff; watch cancellation releases the outstanding Home read. The watch itself writes no client files or receipts and adds no Child-to-Home mutation endpoint. The periodic tick (`src/integrations/route-intent-tick.ts`) runs a full `syncConnectedClient` every 60 seconds even when nothing changed. Each apply first clears the Home proof record and writes a withdrawn receipt, because a failed or interrupted apply must not leave an earlier proof current, then rewrites both; unchanged writers make no client-file change, but the receipt and record are rewritten, and a parity report sent during that window carries the withdrawal until the next report. Avoiding the rewrite would mean knowing an apply changes nothing before running it, which the withdraw-first rule forbids. Native switches on a Child follow the Home: a local `ocx restore` is reverted by the next tick unless the person records `ocx route to codex off --local`. A tick can change the saved `selectedClients`, so `/api/machine/clients` reports the saved selection while it still belongs to the served connection (`src/client/machine-api.ts`). The tick does not restart the runtime after it applies changed Home Codex settings: the parity report keeps the runtime's real start time, so status shows that the runtime predates the apply, and `ocx sync` (or the Home fan-out) restarts it as before. The served roster a connected Child materializes from is the Home's own `GET /v1/models` list, so `loadConnectedRouteModels` (`src/integrations/route-intent-connected.ts`) reads each row's capability fields there — `capabilities.input_modalities`, `capabilities.context_length`/`max_output_tokens`, `supports_reasoning`, `supports_thinking_toggle`, `supports_reasoning_effort`, `default_thinking_enabled`, the `reasoning_effort` ladder (bare values or Grok's `{value, default}` options) and the top-level `context_window`/`context_length`/`max_output_tokens` mirrors — and maps them into `ExportModel`, the same projection `toExportModel` makes for `/api/models`. The row is remote input, so every value is validated: an integer window, a boolean axis, a modality from the exporters' vocabulary or a declared effort, with malformed entries dropped individually and nothing synthesized for a field the row omits. Without this the file integrations a Child materializes from Home intent (Pi, OpenCode and the rest) fell back to text-only with no reasoning controls. Fields the served row does not carry — `maxInputTokens`, `supports_reasoning_summaries` and `supports_tools` — stay absent and the exporters apply their own rules. The Grok adapter carries the ladder and its declared default into the Grok config, and the Desktop adapter passes each routed window, which decides `supports1m`. A combo row the route catalog does not list is accepted only as an expanded selector of a listed one, `--fast` or `--` as the Home's `/v1/models` publishes them, and takes that base's canonical key; an expanded selector whose base is unlisted is left out on its own, while any other unlisted combo still rejects the roster. Coverage: `tests/clients/route-intent-connected-capabilities.test.ts`. diff --git a/tests/cli/cli-client-start-fence.test.ts b/tests/cli/cli-client-start-fence.test.ts index 59902fa4319..872ca1ce09d 100644 --- a/tests/cli/cli-client-start-fence.test.ts +++ b/tests/cli/cli-client-start-fence.test.ts @@ -141,7 +141,7 @@ describe("connected-client start ownership fence", () => { // released only once the first serve() returned, i.e. after publication. const serve = runtime.slice(runtime.indexOf("const serve = async"), runtime.indexOf("const stopServing")); // Each publication also stamps a fresh servingGeneration (restart sync fence, #8416). - expect(serve).toMatch(/writePid\(process\.pid\);\s*\n(?:\s*\/\/[^\n]*\n)*\s*writeRuntimePort\(\{ \.\.\.clientRuntimeRecord\(process\.pid, boundPort, attestationSecret\), servingGeneration: randomUUID\(\),\s+clientLinkOwner \}\);/); + expect(serve).toMatch(/writePid\(process\.pid\);\s*\n(?:\s*\/\/[^\n]*\n)*\s*servingGeneration = randomUUID\(\);\s*writeRuntimePort\(\{ \.\.\.clientRuntimeRecord\(process\.pid, boundPort, attestationSecret\), servingGeneration,\s+clientLinkOwner \}\);/); expect(runtime).toMatch(/await serve\(\);\s*\n\s*options\.afterPublish\?\.\(\);/); }); }); diff --git a/tests/clients/client-link-stop-recovery.test.ts b/tests/clients/client-link-stop-recovery.test.ts index de7c39807c6..8cab87d947f 100644 --- a/tests/clients/client-link-stop-recovery.test.ts +++ b/tests/clients/client-link-stop-recovery.test.ts @@ -5,18 +5,49 @@ import { join } from "node:path"; import { fixturePath, repoPath } from "../helpers/repo-root"; import { removeTreeWithRetry } from "../helpers/remove-tree"; import { runStop } from "../helpers/client-link-stop"; +import { stopFixtureEnv, unavailableFixtureHome } from "../helpers/client-stop-fixture-home"; -async function runRecovery(mode: string, scheduled = false, env = process.env) { +test("stop fixtures keep Home traffic and integration state separate across children", async () => { + const first = unavailableFixtureHome(), second = unavailableFixtureHome(); + try { + expect(first.port).not.toBe(second.port); + for (const home of [first, second]) { + expect(home.url.hostname).toBe("127.0.0.1"); + expect((await fetch(home.url)).status).toBe(503); + } + const root = join(tmpdir(), "fixture-child"); + const inherited = { ...process.env, GROK_HOME: "suite-grok", CLAUDE_CONFIG_DIR: "suite-claude", + XDG_CONFIG_HOME: "suite-config", OCX_OWNER_REGISTRY_DIR: "suite-registry", OCX_SERVICE: "1" }; + expect(stopFixtureEnv(root, inherited)).toMatchObject({ GROK_HOME: join(root, ".grok"), + CLAUDE_CONFIG_DIR: join(root, ".claude"), XDG_CONFIG_HOME: join(root, ".config"), + OCX_OWNER_REGISTRY_DIR: join(root, "ocx", "ocx-homes"), OCX_SERVICE: "" }); + } finally { await Promise.all([first.stop(true), second.stop(true)]); } +}); + +async function runRecovery(mode: string, scheduled = false, env = process.env, attempt = 0): Promise> { const root = mkdtempSync(join(tmpdir(), "ocx-link-stop-recovery-")); const child = Bun.spawn([process.execPath, fixturePath("client-link-stop-recovery-runner.ts")], { cwd: repoPath(), stdin: new Blob([JSON.stringify({ mode, scheduled })]), stdout: "pipe", stderr: "pipe", - env: { ...env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: join(root, "ocx"), CODEX_HOME: join(root, "codex"), - OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR: join(root, "claude-desktop"), OCX_SERVICE: "", OCX_SERVICE_MANAGED: "0" }, + env: stopFixtureEnv(root, env), }); - const timeout = setTimeout(() => child.kill("SIGKILL"), 15_000); + let parentDeadlineReached = false; + const timeout = setTimeout(() => { + if (child.exitCode !== null) return; + parentDeadlineReached = true; + child.kill("SIGKILL"); + }, 15_000); try { const [exit, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); - expect(exit, stderr).toBe(0); + if (exit === 75 && stderr.trim() === "fixture-port-collision") { + if (attempt >= 2) throw new Error("recovery fixture port collided three times"); + return runRecovery(mode, scheduled, env, attempt + 1); + } + if (exit !== 0) { + const phases = stdout.split(/\r?\n/).filter(line => line.startsWith("recovery phase ")); + const status = parentDeadlineReached ? "parent requested termination at its 15s deadline" : "child exited"; + throw new Error([`Link recovery (${mode}): ${status}, exit ${exit}`, + ...(phases.length ? phases : ["no fixture phase reported"]), stderr.trimEnd()].filter(Boolean).join("\n")); + } expect(stderr).not.toContain("uncaughtException"); const line = stdout.split("\n").find(line => line.startsWith("{")); expect(line, stdout + stderr).toBeDefined(); @@ -64,7 +95,7 @@ test("a stale stop owner cannot block completed disconnect recovery", async () = test("a refused signal stop can reschedule a canceled recycle after disconnect recovery", async () => { const result = await runRecovery("signal-pending-recycle"); - expect(result).toMatchObject({ firstRecycleTimers: 1, beforeRecoveryAdmission: 409, recoveryRecycleTimers: 1, + expect(result).toMatchObject({ firstRecycleTimers: 1, firstRecycleCanceled: true, beforeRecoveryAdmission: 409, recoveryRecycleTimers: 1, role: "standalone", spawned: 1, file: { userSetting: "keep" }, state: "disconnected", phase: "complete", runtimePresent: false }); }, 20_000); @@ -103,6 +134,16 @@ test("restart rollback closes its unpublished listener in the binding turn when expect(report.fileAfter.pi).not.toContain("127.0.0.1"); }, 20_000); +for (const retryRollbackPublication of ["lifecycle", "config", "owner-changed"] as const) { + test("restart rollback rechecks its owner after " + retryRollbackPublication + " contention", async () => { + const report = await runStop({ mode: "file-restart-overlap", preserve: "restart-rollback", fileClients: ["pi"], retryRollbackPublication }); + const resumed = retryRollbackPublication !== "owner-changed"; + expect(report.result).toEqual({ preflight: null, closedBeforeYield: true, published: resumed, bound: resumed, + rollbackBinds: resumed ? 2 : 1, replacementAttempts: 1, stopping: true, explicitStop: true }); + expect(report.fileAfter.pi).not.toContain("127.0.0.1"); + }, 20_000); +} + test("ordinary restart rollback keeps file routes and admits fresh sync", async () => { const report = await runStop({ mode: "file-restart-control", preserve: "restart-rollback", fileClients: ["pi"] }); expect(report.result).toEqual({ rolledBack: true, bound: true, stopping: false, explicitStop: false, sync: "accepted" }); diff --git a/tests/clients/client-recycle-exclusion.test.ts b/tests/clients/client-recycle-exclusion.test.ts new file mode 100644 index 00000000000..34359c711b7 --- /dev/null +++ b/tests/clients/client-recycle-exclusion.test.ts @@ -0,0 +1,67 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Database } from "bun:sqlite"; +import { writeFileSync } from "node:fs"; +import { getDefaultConfig, saveConfig } from "../../src/config"; +import { prepareConfigMutationDatabasePathForWrite } from "../../src/config/mutation-lock"; +import { LinkApplyBusyError, withLinkApply } from "../../src/client/link-home"; +import { markClientConnectPending } from "../../src/client/state"; +import { runClientRecycleWithAdmission } from "../../src/client/runtime-recycle"; +import type { OcxClientConnectionConfig } from "../../src/types"; +import { createTempHome, type TempHome } from "../helpers/temp-home"; + +const served: OcxClientConnectionConfig = { + serverUrl: "http://127.0.0.1:34567", managementUrl: "http://127.0.0.1:34567", managementTransport: "direct", transport: "link", + link: { tunnelPort: 34567, linkId: "lnk_0123456789abcdef" }, selectedClients: [], tokenEnv: "OPENCODEX_API_AUTH_TOKEN", + apiKeyId: "fixture-client", tokenFingerprint: "c".repeat(64), protocolVersion: 1, connectedAt: "2026-10-01T00:00:00.000Z", +}; +let home: TempHome; +beforeEach(() => { home = createTempHome("recycle-exclusion-"); saveConfig(getDefaultConfig()); }); +afterEach(() => home.remove()); + +test("an in-flight Link apply refuses recycle before any teardown", async () => { + let stopped = 0; + await withLinkApply(async () => { + expect(await runClientRecycleWithAdmission(served, () => true, async () => { stopped++; })).toBe(false); + }); + expect(stopped).toBe(0); +}); + +test("recycle retains apply exclusion through every teardown await", async () => { + let entered!: () => void, release!: () => void; + const ready = new Promise(resolve => { entered = resolve; }); + const held = new Promise(resolve => { release = resolve; }); + let admissions = 0, completed = false; + const flight = runClientRecycleWithAdmission(served, () => { admissions++; return true; }, async () => { + entered(); await held; + await expect(withLinkApply(async () => {})).rejects.toBeInstanceOf(LinkApplyBusyError); + completed = true; + }); + await ready; + try { await expect(withLinkApply(async () => {})).rejects.toBeInstanceOf(LinkApplyBusyError); } + finally { release(); } + expect(await flight).toBe(true); + expect({ admissions, completed }).toEqual({ admissions: 1, completed: true }); + await withLinkApply(async () => {}); +}); + +for (const state of ["same-connection", "unreadable", "pending-connect", "stop-refused", "config-busy"] as const) { + test("recycle rechecks " + state + " inside apply exclusion", async () => { + let stopped = 0; + let lock: Database | undefined; + if (state === "same-connection") { + const config = getDefaultConfig(); config.runtimeRole = "client"; config.client = served; saveConfig(config); + } + if (state === "unreadable") writeFileSync(home.path("config.json"), "{"); + if (state === "pending-connect") markClientConnectPending("d".repeat(64)); + if (state === "config-busy") { lock = new Database(prepareConfigMutationDatabasePathForWrite()); lock.exec("BEGIN IMMEDIATE"); } + try { + expect(await runClientRecycleWithAdmission(served, () => state !== "stop-refused", async () => { stopped++; })).toBe(false); + expect(stopped).toBe(0); + } finally { lock?.close(); } + }); +} + +test("a failure after teardown begins is propagated instead of reported as an admission refusal", async () => { + await expect(runClientRecycleWithAdmission(served, () => true, async () => { throw new LinkApplyBusyError(); })) + .rejects.toBeInstanceOf(LinkApplyBusyError); +}); diff --git a/tests/clients/client-restart-rollback-lock.test.ts b/tests/clients/client-restart-rollback-lock.test.ts new file mode 100644 index 00000000000..50d1bc7807d --- /dev/null +++ b/tests/clients/client-restart-rollback-lock.test.ts @@ -0,0 +1,44 @@ +import { expect, test } from "bun:test"; +import { ConfigMutationLockError } from "../../src/config"; +import { retryClientRollback, retryableClientRollbackLock } from "../../src/client/runtime-rollback"; + +test("rollback retries only known lifecycle or configuration contention", () => { + expect(retryableClientRollbackLock({ code: "client_lifecycle_busy" })).toBe(true); + for (const code of ["SQLITE_BUSY", "SQLITE_LOCKED"]) { + expect(retryableClientRollbackLock(new ConfigMutationLockError("busy", { cause: { code } }))).toBe(true); + } + for (const error of [undefined, new Error("busy"), { code: "SQLITE_BUSY" }, { code: "client_lifecycle_lock_failed" }, + new ConfigMutationLockError("unavailable", { cause: { code: "SQLITE_CORRUPT" } })]) { + expect(retryableClientRollbackLock(error)).toBe(false); + } +}); + +test("rollback closes each busy attempt before yielding and keeps one remaining budget", async () => { + let clock = 0, calls = 0, listener = false; + const remaining: number[] = []; + expect(await retryClientRollback(async budget => { + remaining.push(budget); calls++; listener = true; clock += 10; + if (calls === 3) return "published"; + listener = false; return "busy"; + }, { budgetMs: 200, now: () => clock, sleep: async ms => { + expect(listener).toBe(false); clock += ms; + } })).toBe(true); + expect(remaining).toEqual([200, 140, 80]); + expect(listener).toBe(true); +}); + +test("rollback contention exhaustion never extends its budget", async () => { + let clock = 0, calls = 0; + expect(await retryClientRollback(async () => { calls++; clock += 20; return "busy"; }, { + budgetMs: 100, now: () => clock, sleep: async ms => { clock += ms; }, + })).toBe(false); + expect({ clock, calls }).toEqual({ clock: 100, calls: 2 }); +}); + +test("a changed owner or non-contention refusal stops rollback retries immediately", async () => { + let clock = 0, calls = 0; + expect(await retryClientRollback(async () => ++calls === 1 ? "busy" : "refused", { + now: () => clock, sleep: async ms => { clock += ms; }, + })).toBe(false); + expect(calls).toBe(2); +}); diff --git a/tests/clients/route-intent-runtime-stop.test.ts b/tests/clients/route-intent-runtime-stop.test.ts index 6de8b64e092..e68820f96b3 100644 --- a/tests/clients/route-intent-runtime-stop.test.ts +++ b/tests/clients/route-intent-runtime-stop.test.ts @@ -13,7 +13,7 @@ test("runtime recycle cancels its watch and tick before replacement handoff", () writeFileSync(fixture, ` import { test, expect, spyOn } from 'bun:test'; test('isolated recycle', async () => { - const { writeFileSync } = await import('node:fs'); + const { readFileSync, writeFileSync, unlinkSync } = await import('node:fs'); const { join } = await import('node:path'); const configApi = await import(${JSON.stringify(repoPath("src/config.ts"))}); const { serviceApiTokenFingerprint } = await import(${JSON.stringify(repoPath("src/lib/service-secrets.ts"))}); @@ -38,6 +38,8 @@ test("runtime recycle cancels its watch and tick before replacement handoff", () }), })); const runtime = await import(${JSON.stringify(repoPath("src/client/runtime.ts"))}); + const { clearClientConnection } = await import(${JSON.stringify(repoPath("src/client/state.ts"))}); + const { withLinkApply } = await import(${JSON.stringify(repoPath("src/client/link-home.ts"))}); const probe = Bun.serve({hostname:'127.0.0.1',port:0,fetch:()=>new Response(null)}); const port = probe.port; await probe.stop(true); const token = 'ocx_data_'+'c'.repeat(40); @@ -49,15 +51,41 @@ test("runtime recycle cancels its watch and tick before replacement handoff", () configApi.saveConfig(config); writeFileSync(join(process.env.OPENCODEX_HOME,'service-api-token'), token); try { await runtime.startClientRuntime({block:false}, {restartSupervisor:async()=>null, - startListener: port => ({port,stop(){events.push('listener-stop');}})}); + startListener: port => ({port,async stop(){ + events.push('listener-stop'); + await withLinkApply(async()=>{events.push('apply-entered-during-stop');}) + .catch(error=>{if(error.code==='link_apply_busy')events.push('apply-blocked-during-stop');else throw error;}); + }})}); for(let i=0;i<100&&!active;i++)await Bun.sleep(5); expect(active).toBe(true); + const deferPeriodic = tick.mock.calls[0][1].deferPeriodic; + const file = join(process.env.OPENCODEX_HOME, 'runtime-port.json'); + const original = readFileSync(file); + const published = JSON.parse(original.toString()); + const stopping = { ...published, clientStopping: true }; + try { + expect(deferPeriodic()).toBe(false); + writeFileSync(file, JSON.stringify(stopping)); + expect(deferPeriodic()).toBe(true); + for (const change of [{ pid: published.pid + 1 }, { port: port === 1 ? 2 : 1 }, + { attestationSecret: 'A'.repeat(43) }, { servingGeneration: 'other' }, { servingGeneration: undefined }]) { + writeFileSync(file, JSON.stringify({ ...stopping, ...change })); + expect(deferPeriodic()).toBe(false); + } + writeFileSync(file, '{'); + expect(deferPeriodic).toThrow('client_runtime_unverified'); + unlinkSync(file); + expect(deferPeriodic()).toBe(false); + } finally { writeFileSync(file, original); } + expect(clearClientConnection(config.client)).toBe('committed'); await runtime.recycleStandalone(serviceApiTokenFingerprint(token), { isDesktopSupervised:()=>false, spawnReplacement:async()=>{expect(active).toBe(false);events.push('replacement');}, exitProcess:code=>events.push('exit:'+code), }); expect(events.indexOf('watch-cancelled')).toBeGreaterThanOrEqual(0); + expect(events).toContain('apply-blocked-during-stop'); + expect(events).not.toContain('apply-entered-during-stop'); expect(events.indexOf('tick-stop')).toBeGreaterThanOrEqual(0); expect(events.filter(event => event === 'credential-observation-stop')).toHaveLength(1); expect(events.indexOf('watch-cancelled')).toBeLessThan(events.indexOf('listener-stop')); diff --git a/tests/clients/route-intent-scheduler.test.ts b/tests/clients/route-intent-scheduler.test.ts index 7e98bb09103..2df566bcdc7 100644 --- a/tests/clients/route-intent-scheduler.test.ts +++ b/tests/clients/route-intent-scheduler.test.ts @@ -42,6 +42,51 @@ test("busy applies reject the request and retry on the short cadence without ove scheduler.stop(); }); +test("a retained stop defers periodic sync while Home requests keep their original result", async () => { + const timers: Array<{ run: () => void; ms: number }> = []; + let fenced = true, checks = 0, calls = 0, reports = 0; + const refusal = new Error("link_apply_busy"); + const scheduler = startRouteIntentTick(connection, { + deferPeriodic: () => { checks++; return fenced; }, + sync: async () => { calls++; if (fenced) throw refusal; }, + onApplied: () => { reports++; }, + setTimer: (run, ms) => { const timer = { run, ms }; timers.push(timer); return timer; }, + clearTimer: timer => { const i = timers.findIndex(entry => entry === timer); if (i >= 0) timers.splice(i, 1); }, + }); + const first = timers.shift()!; + expect(first.ms).toBe(2_000); + first.run(); await flush(); + expect([checks, calls, reports]).toEqual([1, 0, 0]); + expect(timers.map(timer => timer.ms)).toEqual([5_000]); + + await expect(scheduler.requestSync()).rejects.toBe(refusal); + await flush(); + expect([checks, calls, reports]).toEqual([1, 1, 0]); + expect(timers.map(timer => timer.ms)).toEqual([5_000]); + + fenced = false; + timers.shift()!.run(); await flush(); + expect([checks, calls, reports]).toEqual([2, 2, 1]); + expect(timers.map(timer => timer.ms)).toEqual([60_000]); + scheduler.stop(); + expect(timers).toHaveLength(0); +}); + +test("an inconclusive periodic fence check falls through to sync", async () => { + const timers: Array<{ run: () => void; ms: number }> = []; + let calls = 0, reports = 0; + const scheduler = startRouteIntentTick(connection, { + deferPeriodic: () => { throw new Error("runtime record unavailable"); }, + sync: async () => { calls++; }, + onApplied: () => { reports++; }, + setTimer: (run, ms) => { timers.push({ run, ms }); return timers.length; }, clearTimer: () => {}, + }); + timers.shift()!.run(); await flush(); + expect([calls, reports]).toEqual([1, 1]); + expect(timers.map(timer => timer.ms)).toEqual([60_000]); + scheduler.stop(); +}); + test("machine clients reports the saved selection a scheduled sync changed, only for the served connection", async () => { const { handleMachineApi } = await import("../../src/client/machine-api"); const state = { serverUrl: "http://127.0.0.1:22001", managementUrl: "http://127.0.0.1:22001", managementTransport: "direct" as const, diff --git a/tests/fixtures/client-link-stop-recovery-runner.ts b/tests/fixtures/client-link-stop-recovery-runner.ts index 6f831e890cf..1ecdac7d906 100644 --- a/tests/fixtures/client-link-stop-recovery-runner.ts +++ b/tests/fixtures/client-link-stop-recovery-runner.ts @@ -1,7 +1,8 @@ /** Real file recovery and bound restart; only replacement process launch is a loopback fixture. */ import { mock, spyOn } from "bun:test"; -import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, unlinkSync, writeFileSync, writeSync } from "node:fs"; import { dirname, join } from "node:path"; +import { unavailableFixtureHome } from "../helpers/client-stop-fixture-home"; import { getDefaultConfig, saveConfig } from "../../src/config"; import { serviceApiTokenFingerprint, writeServiceApiTokenFile, readServiceApiTokenState } from "../../src/lib/service-secrets"; import { readRuntimePort, type ClientStopOwner } from "../../src/config/process-state"; @@ -13,6 +14,13 @@ import { createSystemRestartCapability, SYSTEM_RESTART_CAPABILITY_HEADER, SYSTEM SYSTEM_RESTART_NONCE_HEADER, SYSTEM_RESTART_PATH } from "../../src/lib/system-restart-contract"; const options = JSON.parse(readFileSync(0, "utf8")) as { mode: string; scheduled?: boolean }; +let phase: string; +function enterPhase(name: string): void { + phase = name; + // Flush before synchronous filesystem work so a parent timeout retains the last transition. + writeSync(1, `recovery phase ${Math.round(performance.now())}ms: ${name}\n`); +} +enterPhase("fixture setup"); const home = process.env.OPENCODEX_HOME!; mkdirSync(home, { recursive: true }); const lifecycle = await import("../../src/client/lifecycle-lock"); @@ -26,10 +34,11 @@ mock.module("../../src/client/lifecycle-lock", () => ({ ...lifecycle, async function main() { const token = `ocx_data_${"c".repeat(40)}`; const probe = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response(null) }); + const fixtureHome = unavailableFixtureHome(); const config = getDefaultConfig(); config.port = probe.port!; config.runtimeRole = "client"; - config.client = { serverUrl: "http://127.0.0.1:34567", managementUrl: "http://127.0.0.1:34567", managementTransport: "direct", transport: "link", - link: { tunnelPort: 34567, linkId: "lnk_0123456789abcdef" }, selectedClients: ["pi"], tokenEnv: "OPENCODEX_API_AUTH_TOKEN", + config.client = { serverUrl: fixtureHome.url.origin, managementUrl: fixtureHome.url.origin, managementTransport: "direct", transport: "link", + link: { tunnelPort: fixtureHome.port!, linkId: "lnk_0123456789abcdef" }, selectedClients: ["pi"], tokenEnv: "OPENCODEX_API_AUTH_TOKEN", apiKeyId: "fixture-client", tokenFingerprint: serviceApiTokenFingerprint(token), protocolVersion: 1, connectedAt: "2026-10-01T00:00:00.000Z" }; saveConfig(config); writeServiceApiTokenFile(token); const expected = structuredClone(config.client); @@ -42,6 +51,7 @@ async function main() { const document = { version: 1 as const, home: { name: "fixture", version: "1" }, clients: Object.fromEntries(ROUTE_CLIENT_IDS.map(id => [id, { enabled: id === "pi" }])), sources: Object.fromEntries(ROUTE_CLIENT_IDS.map(id => [id, "default"])) } as import("../../src/link/route-intent").HomeRouteIntentDocument; + enterPhase("applying the file route"); const applied = await applyConnectedRouteIntent(expected, token, { document, stale: false, fetchedAt: "2026-11-16T00:00:00.000Z" }, { onlyClients: ["pi"], lifecycleLockDeps }, { fetchImpl: (async () => Response.json({ data: [{ id: "fixture/home-model" }] })) as typeof fetch }); if (applied?.outcomes.find(row => row.client === "pi")?.outcome !== "current") throw new Error("fixture apply failed"); @@ -72,6 +82,7 @@ async function main() { const replacement = await import("../../src/server/restart-replacement"); mock.module("../../src/server/restart-replacement", () => ({ ...replacement, spawnReplacementStart: async (request: { port: number }) => { spawned++; + enterPhase("binding the replacement listener"); // A successful bind proves the real Child listener released its port. No native coordinator, // provider request or external process participates in this replacement seam. const server = Bun.serve({ hostname: "127.0.0.1", port: request.port, fetch: () => Response.json({ role: "standalone" }) }); @@ -88,27 +99,48 @@ async function main() { const observeOwner = owner.observeClientStopOwner; mock.module("../../src/client/stop-teardown-owner", () => ({ ...owner, observeClientStopOwner: (proof: ClientStopOwner) => { - if (options.mode === "parent-unverified") return "unverified"; if (proof.nonce === "malformed" || proof.startTime === "malformed") return observeOwner(proof); - return owner.readClientStopProcessStart(proof.pid) === proof.startTime ? "active" : "confirmed-stale"; + const observedStart = options.mode === "parent-unverified" ? undefined : owner.readClientStopProcessStart(proof.pid); + if (observedStart === undefined) return "unverified"; + return observedStart === proof.startTime ? "active" : "confirmed-stale"; }, })); const { startClientRuntime, scheduleStandaloneRecycle } = await import("../../src/client/runtime"); + const { startMachineListener } = await import("../../src/client/machine-listener"); + const { isAddrInUse } = await import("../../src/server/ports"); + enterPhase("starting the Child listener"); // Keep the selected port reserved while preparing the fixture and loading the runtime. await probe.stop(true); - await startClientRuntime({ block: false }, { restartSupervisor: async () => null }); - // The parent watchdog bounds total time, including fixture setup. Give the - // stop and disconnect operations their own phase deadline once the Child serves. - let phase = "observing the refused stop"; + try { + await startClientRuntime({ block: false }, { restartSupervisor: async () => null, + startListener: (port, deps) => { + try { return startMachineListener(port, deps); } + catch (error) { + // Only a proven bind collision requests a fresh, fully owned fixture from the parent. + if (isAddrInUse(error)) throw new Error("fixture-port-collision"); + throw error; + } + }, + }); + } catch (error) { + if (error instanceof Error && error.message === "fixture-port-collision") { + console.error("fixture-port-collision"); process.exit(75); + } + throw error; + } + // The parent bounds setup; the existing phase watchdog starts only once the Child serves. setTimeout(() => { - console.error(`recovery fixture timed out (${options.mode}: ${phase})`); + console.error(`recovery fixture timed out 10s after listener startup (${options.mode}: ${phase})`); process.exit(1); }, 10_000).unref(); const pendingRecycle = options.mode === "signal-pending-recycle"; + let lastRecycleTimer: ReturnType | undefined; const scheduleAndCountTimers = () => { const timer = spyOn(globalThis, "setTimeout"); try { scheduleStandaloneRecycle(expected.tokenFingerprint); + const index = timer.mock.calls.findIndex(([, delay]) => delay === 50); + lastRecycleTimer = index < 0 ? undefined : timer.mock.results[index]!.value; return timer.mock.calls.filter(([, delay]) => delay === 50).length; } finally { timer.mockRestore(); } }; @@ -120,13 +152,24 @@ async function main() { [SYSTEM_RESTART_EXPECTED_PID_HEADER]: String(process.pid), [SYSTEM_RESTART_NONCE_HEADER]: nonce, [SYSTEM_RESTART_CAPABILITY_HEADER]: createSystemRestartCapability(runtime.attestationSecret!, nonce, "POST", SYSTEM_RESTART_PATH, process.pid, config.port), } }); - await response.arrayBuffer(); return response.status; + await response.arrayBuffer(); + if (response.status === 202) enterPhase("restart request accepted"); + return response.status; }; let finishStop: () => Promise = async () => {}; + enterPhase("observing the refused stop"); if (options.mode.startsWith("signal")) { // Queue and signal in one turn so the first timer is still pending at shutdown. - if (pendingRecycle) observations.firstRecycleTimers = scheduleAndCountTimers(); - process.emit("SIGTERM", "SIGTERM"); + if (pendingRecycle) { + observations.firstRecycleTimers = scheduleAndCountTimers(); + const original = lastRecycleTimer; + if (original === undefined) throw new Error("fixture did not create the first recycle timer"); + const cancel = spyOn(globalThis, "clearTimeout"); + try { + process.emit("SIGTERM", "SIGTERM"); + observations.firstRecycleCanceled = cancel.mock.calls.some(([timer]) => timer === original); + } finally { cancel.mockRestore(); } + } else process.emit("SIGTERM", "SIGTERM"); await (options.mode === "signal-active" ? entered : refused); } else { const { preflightConnectedClientStop } = await import("../../src/cli/stop-restore"); @@ -145,7 +188,7 @@ async function main() { } observations.beforeRecoveryAdmission = await restart(); observations.finishedMarker = readRuntimePort(process.pid)?.clientStopRequested; - phase = "disconnecting the Child"; + enterPhase("disconnecting the Child"); const { disconnectClient } = await import("../../src/client/connect"); await disconnectClient({ recoverConfig: true }, { lifecycleLockDeps }); const receiptPath = storePaths().disconnect; @@ -160,7 +203,7 @@ async function main() { if (options.mode === "missing-config") unlinkSync(join(home, "config.json")); if (options.mode === "new-connection") { config.client!.connectedAt = "2026-11-16T01:00:00.000Z"; saveConfig(config); } if (options.mode === "pending-connect") markClientConnectPending("b".repeat(64)); - phase = "observing restart or recycle after disconnect"; + enterPhase("observing restart or recycle after disconnect"); if (pendingRecycle) { observations.recoveryRecycleTimers = scheduleAndCountTimers(); if (observations.recoveryRecycleTimers === 0) { diff --git a/tests/fixtures/client-link-stop-runner.ts b/tests/fixtures/client-link-stop-runner.ts index 4a13bd8955d..0f55b317e81 100644 --- a/tests/fixtures/client-link-stop-runner.ts +++ b/tests/fixtures/client-link-stop-runner.ts @@ -3,6 +3,7 @@ import { mock } from "bun:test"; import { Database } from "bun:sqlite"; import { existsSync, mkdirSync, readFileSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"; import { dirname, join } from "node:path"; +import { unavailableFixtureHome } from "../helpers/client-stop-fixture-home"; import { getDefaultConfig, prepareConfigMutationDatabasePathForWrite, saveConfig } from "../../src/config"; import { CODEX_CONFIG_PATH, CODEX_HOME, CODEX_PROFILE_PATH, DEFAULT_CATALOG_PATH } from "../../src/codex/paths"; import { JOURNAL_PATH, markJournalInjectedState, writeJournal } from "../../src/codex/journal"; @@ -46,6 +47,7 @@ const options = JSON.parse(readFileSync(0, "utf8")) as { danglingServiceRecord?: boolean; busyStopFence?: boolean; busyRollbackPublication?: boolean; + retryRollbackPublication?: "lifecycle" | "config" | "owner-changed"; terminationPlatform?: "linux" | "darwin"; siblingEscalation?: "stopping" | "different-generation"; removeToken?: boolean; @@ -72,14 +74,15 @@ mock.module("../../src/client/lifecycle-lock", () => ({ ...lifecycle, const token = `ocx_data_${"c".repeat(40)}`; const config = getDefaultConfig(); const probe = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response(null) }); +const fixtureHome = options.transport === "hub" ? undefined : unavailableFixtureHome(); config.port = probe.port!; await probe.stop(true); config.runtimeRole = "client"; config.client = { - serverUrl: options.transport === "hub" ? "https://hub.example.test" : "http://127.0.0.1:34567", - managementUrl: options.transport === "hub" ? "https://hub.example.test" : "http://127.0.0.1:34567", + serverUrl: fixtureHome?.url.origin ?? "https://hub.example.test", + managementUrl: fixtureHome?.url.origin ?? "https://hub.example.test", managementTransport: "direct", transport: options.transport ?? "link", - ...(options.transport === "hub" ? {} : { link: { tunnelPort: 34567, linkId: "lnk_0123456789abcdef" } }), + ...(fixtureHome ? { link: { tunnelPort: fixtureHome.port!, linkId: "lnk_0123456789abcdef" } } : {}), selectedClients: ["codex", ...(options.deferFileApply ? [] : options.fileClients ?? [])], tokenEnv: "OPENCODEX_API_AUTH_TOKEN", apiKeyId: "fixture-client", tokenFingerprint: serviceApiTokenFingerprint(token), protocolVersion: 1, connectedAt: "2026-10-01T00:00:00.000Z", }; @@ -337,6 +340,7 @@ if (options.mode === "retry") { } })); } let replacementAttempts = 0; + let rollbackBinds = 0, publicationHeld = false; let observeRollback!: (closed: boolean) => void; const rollbackTurn = new Promise(resolve => { observeRollback = resolve; }); let restartSettled: (() => Promise) | undefined; @@ -345,7 +349,7 @@ if (options.mode === "retry") { saveConfig(config); protectedBefore = protectedPaths.map(path => readFileSync(path, "utf8")); }; - if (options.failedRollback) { + if (options.failedRollback || options.retryRollbackPublication) { const controller = await import("../../src/client/runtime-restart"); const create = controller.createClientRestartController; mock.module("../../src/client/runtime-restart", () => ({ ...controller, createClientRestartController: (...args: Parameters) => { @@ -371,19 +375,25 @@ if (options.mode === "retry") { const restartStopping = new Promise(resolve => { restartStopEntered = resolve; }); const restartRelease = new Promise(resolve => { releaseRestartStop = resolve; }); await startClientRuntime({ block: false }, { restartSupervisor: () => options.preserve?.startsWith("restart-rollback") ? Promise.resolve(null) : new Promise(() => {}), startListener: (port, deps) => { + if (replacementAttempts === 1) rollbackBinds++; requestRestart = deps?.restart?.request; if (options.failedRollback === "during-rebind" && replacementAttempts === 1) replaceSavedConnection(); const server = startMachineListener(port, options.oldStopCapability && deps?.restart ? { ...deps, restart: { ...deps.restart, linkStopFence: undefined } } : deps); - if (options.busyRollbackPublication && replacementAttempts === 1) { - const lock = new Database(prepareConfigMutationDatabasePathForWrite()); + if ((options.busyRollbackPublication || options.retryRollbackPublication) && replacementAttempts === 1 && !publicationHeld) { + publicationHeld = true; + const lock = new Database(options.retryRollbackPublication === "lifecycle" + ? lifecycleLockDeps.lockPath : prepareConfigMutationDatabasePathForWrite()); lock.exec("BEGIN IMMEDIATE"); const stop = server.stop.bind(server); let closed = false; server.stop = ((force: boolean) => { const result = stop(force); closed = force; return result; }) as typeof server.stop; // The bind and failed admission complete before the next event-loop turn. Keep C // held until the observation, so a retry cannot publish in the meantime. - setImmediate(() => { observeRollback(closed); lock.close(); }); + setImmediate(() => { + observeRollback(closed); lock.close(); + if (options.retryRollbackPublication === "owner-changed") replaceSavedConnection(); + }); return server; } const stop = server.stop.bind(server); @@ -414,6 +424,16 @@ if (options.mode === "retry") { report({ preflight, closedBeforeYield, published: readRuntimePort(process.pid)?.servingGeneration !== before.servingGeneration, replacementAttempts }); process.exit(0); } + if (options.retryRollbackPublication) { + const closedBeforeYield = await rollbackTurn; + await restartSettled!(); + const after = readRuntimePort(process.pid)!; + const published = after.servingGeneration !== before.servingGeneration; + const bound = published && (await fetch(`http://127.0.0.1:${config.port}/healthz`)).ok; + report({ preflight, closedBeforeYield, published, bound, rollbackBinds, replacementAttempts, + stopping: after.clientStopping, explicitStop: after.clientStopRequested }); + process.exit(0); + } if (options.failedRollback) { await restartSettled!(); report({ preflight, replacementAttempts, runtimePresent: readRuntimePort(process.pid) !== null, diff --git a/tests/fixtures/parent-stop-runner.ts b/tests/fixtures/parent-stop-runner.ts index b220365cfac..0142e73eeb9 100644 --- a/tests/fixtures/parent-stop-runner.ts +++ b/tests/fixtures/parent-stop-runner.ts @@ -75,8 +75,8 @@ const options = JSON.parse(readFileSync(0, "utf8")) as { windowsPartAReject?: boolean; }; if (options.legacyWindowsEvidence) { - // Fake Windows command output at the OS boundary. The production SID, argv - // and listener readers and the standalone proof all run in this subprocess. + // Fake Windows process evidence at the OS boundary. The production argv/listener + // readers and standalone proof run here without touching the host's process table. const evidence = options.legacyWindowsEvidence; const record = { pid: 4242, port: 10100, hostname: "127.0.0.1", ...(evidence === "client-role" ? { role: "client" as const } : {}), @@ -84,9 +84,19 @@ if (options.legacyWindowsEvidence) { }; const { proveStandaloneStopRecord } = await import("../../src/cli/stop-restore"); const { setProcessCommandLinePlatformForTests } = await import("../../src/config/process-state"); - const { setWindowsProcessNativeForTests } = await import("../../src/service/windows-process-native"); - setWindowsProcessNativeForTests(null); // Exercise the mocked CIM fallback on Windows too. setProcessCommandLinePlatformForTests("win32"); + const { readSameUserWindowsStart, setWindowsProcessNativeForTests } = await import("../../src/service/windows-process-native"); + setWindowsProcessNativeForTests({ creationTime: () => null, terminate: () => ({ status: "unavailable" }), + openWatch: () => ({ status: "unavailable" }), scheduleServicePid: () => null, + sameUserIdentity: pid => { + const ticks = readSameUserWindowsStart(pid, { + open: target => target === record.pid ? 1 : 0, close: () => {}, + fileTime: () => 134_088_768_000_000_000n, exited: () => false, + ownerSid: () => evidence === "foreign-sid" ? "S-1-5-21-2" : "S-1-5-21-1", currentSid: () => "S-1-5-21-1", + }); + return ticks === null ? null : { ticks }; + }, + }); const windows = await import("../../src/lib/windows-elevation"); mock.module("../../src/lib/windows-elevation", () => ({ ...windows, resolveTrustedWindowsSystemDirectory: () => "system", @@ -100,9 +110,6 @@ if (options.legacyWindowsEvidence) { const port = evidence === "wrong-port" ? record.port + 1 : record.port; return `TCP ${host}:${port} 0.0.0.0:0 LISTENING ${pid}\r\n`; } - if (args.at(-1)?.includes("GetOwnerSid")) { - return evidence === "foreign-sid" ? "" : "639000000000000000\r\n"; - } if (file.endsWith("WMIC.exe")) { const verb = evidence === "wrong-argv" ? 'status "start"' : "start"; return `CommandLine="C:\\Program Files\\Bun\\bun.exe" run "C:\\work tree\\src\\cli\\index.ts" ${verb}\r\n`; diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index f73e47de83c..17bd14d024f 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1636,6 +1636,7 @@ "windows-atomic-replace.test.ts": "windows", "windows-codex-cli-job-store.test.ts": "windows", "windows-deploy-close-regressions.test.ts": "windows", + "windows-stop-owner-identity.test.ts": "windows", "windows-elevation-spawn.test.ts": "windows", "windows-elevation.test.ts": "windows", "windows-guarded-manager.test.ts": "windows", "windows-checked-stop.test.ts": "windows", "windows-stop-binding.test.ts": "windows", "windows-checked-stop-live.test.ts": "windows", "windows-service-stop-wiring.test.ts": "windows", @@ -1709,7 +1710,9 @@ "grok-47-build-fast-metadata.test.ts": "providers/xai", "grok-47-fast-model.test.ts": "providers/xai", "grok-47-fast-model-wire.test.ts": "providers/xai", "client-link-connect.test.ts": "clients", "client-link-relay.test.ts": "clients", "client-link-runtime.test.ts": "clients", "client-link-stop.test.ts": "clients", - "client-link-stop-recovery.test.ts": "clients", "client-link-stop-sibling.test.ts": "clients", + "client-link-stop-recovery.test.ts": "clients", + "client-recycle-exclusion.test.ts": "clients", + "client-restart-rollback-lock.test.ts": "clients", "client-link-stop-sibling.test.ts": "clients", "link-routes.test.ts": "clients", "client-link-state.test.ts": "clients", "client-link-status.test.ts": "clients", "client-link-teardown.test.ts": "clients", "client-disconnect-recovery.test.ts": "clients", "client-disconnect-desktop-refusals.test.ts": "clients", "client-link-tunnel.test.ts": "clients", "link-ports.test.ts": "clients", diff --git a/tests/helpers/client-link-stop.ts b/tests/helpers/client-link-stop.ts index 3559a871037..bc4084fe100 100644 --- a/tests/helpers/client-link-stop.ts +++ b/tests/helpers/client-link-stop.ts @@ -4,13 +4,12 @@ import { tmpdir } from "node:os"; import { dirname, join } from "node:path"; import { fixturePath, repoPath } from "./repo-root"; import { removeTreeWithRetry } from "./remove-tree"; +import { stopFixtureEnv } from "./client-stop-fixture-home"; export async function runStop(options: Record) { const root = mkdtempSync(join(tmpdir(), "ocx-link-stop-")); const home = join(root, "ocx"); - const env = { ...process.env, HOME: root, USERPROFILE: root, OPENCODEX_HOME: home, - CODEX_HOME: join(root, "codex"), OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR: join(root, "claude-desktop"), - OCX_SERVICE: "", OCX_SERVICE_MANAGED: "0" }; + const env = stopFixtureEnv(root); let owner: Bun.Subprocess<"pipe", "pipe", "ignore"> | undefined; let child: Bun.Subprocess | undefined; const timeout = setTimeout(() => { diff --git a/tests/helpers/client-stop-fixture-home.ts b/tests/helpers/client-stop-fixture-home.ts new file mode 100644 index 00000000000..ce6cb4cdf70 --- /dev/null +++ b/tests/helpers/client-stop-fixture-home.ts @@ -0,0 +1,15 @@ +import { join } from "node:path"; + +export function stopFixtureEnv(root: string, inherited = process.env) { + return { ...inherited, HOME: root, USERPROFILE: root, OPENCODEX_HOME: join(root, "ocx"), CODEX_HOME: join(root, "codex"), + OPENCODEX_CLAUDE_DESKTOP_CONFIG_DIR: join(root, "claude-desktop"), CLAUDE_CONFIG_DIR: join(root, ".claude"), + GROK_HOME: join(root, ".grok"), XDG_CONFIG_HOME: join(root, ".config"), OCX_OWNER_REGISTRY_DIR: join(root, "ocx", "ocx-homes"), + OCX_SERVICE: "", OCX_SERVICE_MANAGED: "0" }; +} + +export function unavailableFixtureHome() { + const home = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: () => new Response(null, { status: 503 }) }); + // Runtime watch requests stay inside this fixture. The Home must not keep its child process alive. + home.unref(); + return home; +} diff --git a/tests/windows/windows-stop-owner-identity.test.ts b/tests/windows/windows-stop-owner-identity.test.ts new file mode 100644 index 00000000000..448f0ac80c0 --- /dev/null +++ b/tests/windows/windows-stop-owner-identity.test.ts @@ -0,0 +1,125 @@ +import { expect, spyOn, test } from "bun:test"; +import { readSameUserWindowsStart, setWindowsProcessNativeForTests, setWindowsProcessPlatformForTests } from "../../src/service/windows-process-native"; +import { isClientStopCommandLine, isLegacyWindowsStartCommandLine, observeClientStopOwner, readClientStopProcessStart } from "../../src/client/stop-teardown-owner"; + +const fileTime = 133_000_000_000_000_007n; +const ticks = 637_911_232_000_000_000n; +const sid = "S-1-5-21-100-200-300-1001"; + +function nativeRead(overrides: Partial[1]> = {}) { + const handles: Array = [], closed: Array = []; + const result = readSameUserWindowsStart(42, { + open: pid => { expect(pid).toBe(42); return 101n; }, + close: handle => { closed.push(handle); }, + fileTime: handle => { handles.push(handle); return fileTime; }, + exited: handle => { handles.push(handle); return false; }, + ownerSid: handle => { handles.push(handle); return sid; }, + currentSid: () => sid, + ...overrides, + }); + return { result, handles, closed }; +} + +test("Windows stop creation and same-user evidence use one live handle and preserve protocol precision", () => { + const result = nativeRead(); + expect(result.result).toBe(ticks); + expect(result.handles).toEqual([101n, 101n, 101n, 101n]); + expect(result.closed).toEqual([101n]); +}); + +test("Windows stop owner evidence fails closed and closes every opened handle", () => { + for (const overrides of [ + { fileTime: () => null }, + { exited: () => true }, + { exited: () => null }, + { ownerSid: () => "S-1-5-21-100-200-300-1002" }, + { ownerSid: () => "", currentSid: () => "" }, + { ownerSid: () => { throw new Error("access denied"); } }, + { currentSid: () => { throw new Error("token unreadable"); } }, + ]) { + const result = nativeRead(overrides); + expect(result.result).toBeNull(); + expect(result.closed).toEqual([101n]); + } + expect(nativeRead({ open: () => 0 }).closed).toEqual([]); + let reads = 0; + expect(nativeRead({ exited: () => ++reads === 1 ? false : true }).result).toBeNull(); +}); + +test("a reused PID gets a fresh handle and cannot inherit a prior creation proof", () => { + let opens = 0; + const io = { + open: () => ++opens, + close: () => {}, + fileTime: (handle: number | bigint) => fileTime + BigInt(handle) * 10n, + exited: () => false, + ownerSid: () => sid, + currentSid: () => sid, + }; + expect(readSameUserWindowsStart(42, io)).toBe(ticks + 10n); + expect(readSameUserWindowsStart(42, io)).toBe(ticks + 20n); + for (const pid of [0, -1, 1.5, 0x80000000]) expect(readSameUserWindowsStart(pid, io)).toBeNull(); + expect(opens).toBe(2); +}); + +test("native Windows owner observation binds argv to the same identity and refuses unavailable proof", () => { + const pid = process.pid + 1; + const owner = { pid, startTime: `win32:${ticks}`, nonce: "a".repeat(32) }; + const reads: Array<[number, boolean | undefined]> = []; + let identity = { ticks, commandLine: "C:\\Users\\O'Neil\\ocx.exe stop" }; + const alive = spyOn(process, "kill").mockImplementation(() => true); + setWindowsProcessPlatformForTests("win32"); + setWindowsProcessNativeForTests({ + creationTime: () => null, + sameUserIdentity: (target, withCommandLine) => { reads.push([target, withCommandLine]); return identity; }, + terminate: () => ({ status: "unavailable" }), + openWatch: () => ({ status: "unavailable" }), + scheduleServicePid: () => null, + }); + try { + expect(observeClientStopOwner(owner)).toBe("active"); + expect(reads).toEqual([[pid, true]]); + identity = { ...identity, ticks: ticks + 10n }; + expect(observeClientStopOwner(owner)).toBe("confirmed-stale"); + identity = { ticks, commandLine: "ocx.exe start" }; + expect(observeClientStopOwner(owner)).toBe("unverified"); + setWindowsProcessNativeForTests(null); + expect(readClientStopProcessStart(pid)).toBeUndefined(); + expect(observeClientStopOwner(owner)).toBe("unverified"); + } finally { + alive.mockRestore(); + setWindowsProcessPlatformForTests(null); + setWindowsProcessNativeForTests(undefined); + } +}); + +test("Windows stop and legacy start recognize apostrophes without shell quoting", () => { + for (const command of [ + "C:\\Users\\O'Neil\\ocx.exe stop", + '"C:\\Users\\O\'Neil\\Program Files\\ocx.exe" stop --json', + 'bun.exe "C:\\Users\\O\'Neil\\app\\src\\cli\\index.ts" stop --deadline-ms 5000', + '"C:\\Program Files\\ocx.exe"\tstop\t--json', + ]) expect(isClientStopCommandLine(command), command).toBe(true); + expect(isLegacyWindowsStartCommandLine("C:\\Users\\O'Neil\\ocx.exe start")).toBe(true); + expect(isLegacyWindowsStartCommandLine('bun.exe "C:\\Users\\O\'Neil\\app\\src\\cli.ts" start')).toBe(true); + for (const command of [ + "'C:\\Program Files\\ocx.exe' stop", "ocx.exe 'stop'", 'ocx.exe "stop --json"', + 'ocx.exe "st\\"op"', 'ocx.exe "st""op"', 'ocx.exe stop\0 --json', "ocx.exe start stop", + ]) expect(isClientStopCommandLine(command), command).toBe(false); +}); + +test("Windows stop approval preserves quoted backslashes and embedded quote boundaries", () => { + const approved = 'ocx.exe stop --json --expect-pid 12 --expect-port 10100 --expect-hostname 127.0.0.1 ' + + '--expect-config-home "C:\\Users\\O\'Neil\\Home Folder\\\\" --expect-cli-version 1.0.0 ' + + '--expect-compatibility-token ' + "a".repeat(64); + expect(isClientStopCommandLine(approved)).toBe(true); + expect(isClientStopCommandLine(approved.replace('Home Folder\\\\"', 'Home Folder\\"'))).toBe(false); +}); + +test.skipIf(process.platform !== "win32" || process.arch !== "x64")("Windows repeated stop proofs stay in-process and within the fixture budget", () => { + const expected = readClientStopProcessStart(process.pid); + expect(expected).toMatch(/^win32:\d+$/); + const started = performance.now(); + for (let attempt = 0; attempt < 30; attempt++) expect(readClientStopProcessStart(process.pid)).toBe(expected); + expect(performance.now() - started).toBeLessThan(3000); +}); From ab13a77f356235b40cc703ad1b5efaa804c18aa3 Mon Sep 17 00:00:00 2001 From: Federico <114950442+federicorv25@users.noreply.github.com> Date: Wed, 25 Nov 2026 02:56:30 -0400 Subject: [PATCH 43/60] feat(i18n): add Spanish dashboard and README (#8706) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds Spanish (Español) to the browser and Desktop dashboards, including the classic edition, adds a Spanish README, and polishes the Spanish documentation reported in #8378. Closes #8378. --- README.md | 25 +- .../010_plan.md | 22 + .../src/content/docs/es/guides/claude-code.md | 2 +- .../docs/es/guides/codex-integration.md | 14 +- .../src/content/docs/es/guides/remote-link.md | 6 +- .../content/docs/es/guides/web-dashboard.md | 25 +- .../src/content/docs/es/reference/adapters.md | 2 +- .../content/docs/es/reference/cli/agents.md | 2 +- .../docs/es/reference/cli/lifecycle.md | 18 +- .../es/reference/configuration/providers.md | 51 +- .../es/reference/configuration/routing.md | 2 +- .../docs/es/reference/proxy-formats.md | 12 +- .../content/docs/guides/codex-integration.md | 2 +- .../src/content/docs/guides/web-dashboard.md | 9 +- .../content/docs/reference/cli/lifecycle.md | 14 +- .../docs/reference/configuration/providers.md | 11 +- gui/classic/index.html | 3 + gui/index.html | 3 + gui/scripts/sync-locale-keys.mjs | 31 +- gui/src/components/QuotaBars.tsx | 2 + .../ProviderCapacityQuota.tsx | 1 + gui/src/i18n/account-probe-copy.ts | 112 +- gui/src/i18n/catalogs.ts | 2 + gui/src/i18n/codex-cli-update-copy.ts | 118 +- gui/src/i18n/connections-copy.ts | 92 +- gui/src/i18n/desktop-compatibility-copy.ts | 94 +- gui/src/i18n/es.ts | 4627 +++++++++++++++++ gui/src/i18n/gateway-clients-copy.ts | 83 +- gui/src/i18n/getting-started-copy.ts | 22 +- gui/src/i18n/lab-translations.ts | 65 +- gui/src/i18n/log-guard-labels.ts | 27 + gui/src/i18n/log-guard-operation-labels.ts | 12 + gui/src/i18n/log-guard-state-labels.ts | 5 + gui/src/i18n/models-overall-copy.ts | 26 +- gui/src/i18n/native-main-translations.ts | 56 +- gui/src/i18n/remote-link-child-copy.ts | 18 +- gui/src/i18n/remote-link-diagnostics-copy.ts | 44 +- gui/src/i18n/routing-compatibility-labels.ts | 5 + gui/src/i18n/shared.ts | 5 +- gui/src/i18n/shell-v2-copy.ts | 187 +- gui/src/i18n/v2-pages/accounts-copy.ts | 29 +- gui/src/i18n/v2-pages/connect-copy.ts | 13 +- gui/src/i18n/v2-pages/copy-table.ts | 8 +- gui/src/i18n/v2-pages/logs-copy.ts | 32 +- gui/src/i18n/v2-pages/models-copy.ts | 15 +- gui/src/i18n/v2-pages/proxy-copy.ts | 140 +- gui/src/i18n/v2-pages/startup-copy.ts | 29 +- gui/src/i18n/v2-pages/subagents-copy.ts | 36 +- .../i18n/v2-pages/telemetry-profile-copy.ts | 76 +- gui/src/i18n/v2-pages/usage-copy.ts | 100 +- gui/src/i18n/vision-reasoning-labels.ts | 1 + gui/src/status-codes.ts | 22 +- ...claude-native-passthrough-setting.test.tsx | 1 + gui/tests/es-localization.test.ts | 193 + gui/tests/i18n-language-switch.test.tsx | 25 + gui/tests/locale-parity.test.ts | 21 +- gui/tests/logs-cost-plain-dollar.test.ts | 1 + gui/tests/subagent-surface-warning.test.tsx | 3 +- gui/tests/usage-app-breakdown.test.tsx | 5 +- readme/README.es.md | 446 ++ readme/README.fr.md | 26 +- readme/README.ja.md | 26 +- readme/README.ko.md | 24 +- readme/README.ru.md | 27 +- readme/README.tr.md | 28 +- readme/README.zh-CN.md | 24 +- readme/README.zh-TW.md | 23 +- readme/i18n-manifest.json | 20 +- scripts/file-size-ratchet.ts | 1 + structure/dashboard-and-usage.md | 6 +- tests/ci-workflows/docs-gpt61-terra.test.ts | 7 +- tests/ci-workflows/docs-link-targets.test.ts | 23 +- .../docs-readme-memory-inventory.test.ts | 8 + .../docs-spanish-localization.test.ts | 13 + tests/ci-workflows/file-size-ratchet.test.ts | 1 + .../codex-quota-window-conflict.test.ts | 10 +- tests/fixtures/file-size-baseline.json | 1 + tests/usage/request-outcome-agreement.test.ts | 5 +- 78 files changed, 6508 insertions(+), 818 deletions(-) create mode 100644 devlog/_plan/261113_spanish_dashboard_readme/010_plan.md create mode 100644 gui/src/i18n/es.ts create mode 100644 gui/tests/es-localization.test.ts create mode 100644 readme/README.es.md diff --git a/README.md b/README.md index cf3b4b23655..2590d14cfaf 100644 --- a/README.md +++ b/README.md @@ -79,7 +79,7 @@ Sol drives the session and calls a Kimi K3 subagent.

    - English · Français · 한국어 · 简体中文 · 繁體中文 · Русский · 日本語 · Türkçe · 📖 Full documentation → + English · Français · 한국어 · 简体中文 · 繁體中文 · Русский · 日本語 · Türkçe · Español · 📖 Full documentation →

    opencodex is a lightweight local gateway between your coding tools and your model providers. It @@ -110,11 +110,11 @@ Connect the tool you already use: | Tool | How to connect | |---|---| -| Codex | Turn on the Codex switch on the dashboard's **Connect** page, then run `codex` as usual. On a local listener this points Codex's built-in provider at the proxy. From the terminal, run `ocx init` before adding providers in the dashboard and accept its Codex prompt. | +| Codex | Turn on the Codex switch on the dashboard's **Route** page, then run `codex` as usual. On a local listener this points Codex's built-in provider at the proxy. From the terminal, run `ocx init` before adding providers in the dashboard and accept its Codex prompt. | | Claude Code | With the `claude` CLI installed, run `ocx claude`. It starts the proxy if needed and launches Claude Code through it. | | Claude Desktop | Run `ocx claude desktop`. On a new install it sets up the gateway profile for the whole app; an existing first-party setup is kept, and `ocx claude desktop apply --gateway` switches explicitly. See the [Claude Code guide](https://opencodex.me/guides/claude-code/). Fully quit and reopen Claude Desktop after a switch. | | Grok Build | On a local listener with Grok integration enabled, `ocx start` registers the models when `~/.grok` exists; pick an `ocx-*` model in Grok Build. Remote setups: see the [Grok Build guide](https://opencodex.me/guides/grok-build/). After adding providers, restart the proxy (or run `ocx ensure` when Codex autostart is enabled) to refresh the list. | -| Tools with a managed integration | Use the dashboard **Connect** page, or `ocx integration client enable --client `. | +| Tools with a managed integration | Use the dashboard **Route** page, or `ocx integration client enable --client `. | | Any other tool | Set a custom OpenAI-compatible base URL of `http://localhost:10100/v1`, or an Anthropic base URL of `http://localhost:10100`. | The [client support page](https://opencodex.me/reference/client-support/) lists which path each tool has @@ -258,9 +258,12 @@ ocx start # or `ocx service` ocx init # interactive setup: writes ~/.opencodex/config.json and wires Codex ``` -`ocx init` never starts the proxy; start it first (or after — either order works, but headless -commands like `ocx provider add` and `ocx combo set` talk to the **live** proxy and exit nonzero -when it is unreachable). `ocx status` / `ocx doctor` / `ocx health` report the running state. +You can start the proxy before or after `ocx init`; `ocx init` never starts it for you. +`ocx provider add` saves local configuration without a running proxy. With `--sync`, +it saves first and then needs a running proxy to sync models to Codex. If the proxy is +unavailable, the provider stays saved, but the command exits nonzero; run `ocx sync` +once the proxy is up. `ocx provider add --live` and `ocx combo set` require a running +proxy. `ocx status` / `ocx doctor` / `ocx health` report the running state. > **Agents installing or running opencodex:** read > [`AGENTS_INSTALL.md`](./AGENTS_INSTALL.md). An interactive `ocx start` may ask once whether to @@ -429,10 +432,12 @@ npm uninstall -g @bitkyc08/opencodex ## Remote access -By default opencodex binds to `127.0.0.1` and needs no extra authentication. Binding beyond -loopback (`"hostname": "0.0.0.0"`) **requires** a bearer token — the proxy refuses to start -without `OPENCODEX_API_AUTH_TOKEN`, and every client request must carry it as -`x-opencodex-api-key`. Details: [configuration reference](https://opencodex.me/reference/configuration/). +By default, opencodex binds to `127.0.0.1` and needs no extra data-plane authentication. +A non-loopback bind (for example, `"hostname": "0.0.0.0"`) **requires a configured client +API key or a shared data token**. The shared token is resolved from `OPENCODEX_API_AUTH_TOKEN`, +`OCX_API_TOKEN_FILE`, or the installed owner-only `service-api-token`. Inference clients +send an accepted credential in `x-opencodex-api-key`. Management uses a separate admin +credential. See the [configuration reference](https://opencodex.me/reference/configuration/). ## Advanced usage diff --git a/devlog/_plan/261113_spanish_dashboard_readme/010_plan.md b/devlog/_plan/261113_spanish_dashboard_readme/010_plan.md new file mode 100644 index 00000000000..16965e1c870 --- /dev/null +++ b/devlog/_plan/261113_spanish_dashboard_readme/010_plan.md @@ -0,0 +1,22 @@ +# Spanish dashboard and README follow-up + +This is one follow-up to the Spanish website and documentation in #7559 +(original request: #1551). It brings forward the dashboard and README prepared +after #7406 as separate commits in this pull request. The base includes the +subsequent Spanish documentation parity fixes, including #8648. + +- Add neutral Spanish to the dashboard shared by browsers and OpenCodex + Desktop, including the current shell and per-page copy tables. +- Reuse the same client-side preference and catalog contract, including + language initialization for the classic entry. Native shell and CLI messages + are separate from the dashboard. +- Publish a Spanish README with current install, integration and privacy + guidance, linked alongside the other README translations. +- Document the existing Remote Link readiness reason in its Spanish status + list, and fix the specific Spanish wording issues in the dashboard and + Codex guides. + +Validate with the locale, GUI and documentation tests, the GUI and docs builds, +and root checks. Browser screenshots use synthetic data and are attached to +the PR outside the source branch. See the PR's Verification section for the +commands, results and any environment limitations. diff --git a/docs-site/src/content/docs/es/guides/claude-code.md b/docs-site/src/content/docs/es/guides/claude-code.md index 70f1e17d6af..79d3466d82b 100644 --- a/docs-site/src/content/docs/es/guides/claude-code.md +++ b/docs-site/src/content/docs/es/guides/claude-code.md @@ -577,7 +577,7 @@ Un catálogo mixto que contiene un puente Codex `exec_command` o `shell_command` ## Esfuerzo de razonamiento -En las solicitudes traducidas Messages → Responses, Claude Code `/effort` Configuración de mapas de la siguiente manera: +Al traducir solicitudes de Messages a Responses, se asigna el valor de `/effort` de Claude Code así: | Formato de protocolo | Mapeo | | --- | --- | diff --git a/docs-site/src/content/docs/es/guides/codex-integration.md b/docs-site/src/content/docs/es/guides/codex-integration.md index c6f4c7d1672..eec1821211c 100644 --- a/docs-site/src/content/docs/es/guides/codex-integration.md +++ b/docs-site/src/content/docs/es/guides/codex-integration.md @@ -31,7 +31,7 @@ Los duplicados existentes se conservan, pero no pueden seleccionarse como una se OpenCodex serializa su configuración Codex. En Windows, un archivo mantenido temporalmente abierto por otro proceso obtiene un breve reintento limitado. Si el acceso permanece ocupado, vuelva a intentar la operación en breve; OpenCodex conserva la evidencia de bloqueo existente y no utiliza ese fallo de acceso para hacerse cargo de la cerradura de otro escritor. -`ocx init`, `ocx start`, y `ocx sync` Llame al inyector. En el enlace de bucle predeterminado, se mantiene Codex incorporado `openai` ID de proveedor y apunta a ese proveedor en opencodex: +`ocx init`, `ocx start` y `ocx sync` ejecutan la inyección de configuración. Con la dirección de loopback predeterminada, OpenCodex conserva el identificador del proveedor integrado de Codex, `openai`, y dirige ese proveedor al proxy: ```toml # root keys, before the first table @@ -621,7 +621,7 @@ La presente política solo maneja `/backend-api/wham/usage` y su punto final `/s Codex Pool puede proteger opcionalmente las cuentas de grupo almacenadas a un umbral de uso semanal o de 5 horas seleccionado. La cuenta de escritorio/principal mantiene su bloqueo separado del 98%. Establezca `codexPool.lowQuotaProtection` en configuración para pausar cuentas, registrar una alerta de registro y API o ambas; vea [configuración de enrutamiento](/es/reference/configuration/routing/#codex-pool-low-quota-protection). Una pausa tiene efecto para la siguiente selección inmediatamente, mientras que guardarla en el disco se aplaza. Las respuestas de cuota Pool pueden autorizar una pausa solo con el uso válido y una credencial capturada que todavía está actualizada. Una respuesta sin esa prueba puede actualizar el uso mostrado sin pausar una cuenta. Compruebe el historial de `GET /api/codex-auth/low-quota-events` autenticado de este servidor para alertas `logged` o errores de guardado. El reanudación manual permanece en vigor para el episodio de cuota actual. La alerta por defecto solo llega al log y API. Añadir `actions.desktop: true` para mostrar también una notificación macOS o Linux en la máquina que ejecuta el proxy; Windows permanece solo registro. -Cuando se agote la cuota de ChatGPT de 5 horas, Codex puede ofrecer un modelo de reserva de reserva (`gpt-reserve` / Luna Reserve). Mientras que ese estado está activo, el selector de modelos Codex puede hacer **cualquier otra entrada no seleccionable, incluidos los modelos enrutados opencodex**, a pesar de que se ejecutan en proveedores independientes y credenciales y no consumen ninguna de las cuotas agotadas. +Cuando se agota la cuota de 5 horas de ChatGPT, Codex puede ofrecer un modelo de reserva (`gpt-reserve` / Luna Reserve). Mientras ese estado esté activo, el selector de Codex puede **impedir elegir cualquier otro modelo, incluidos los que enruta OpenCodex**, aunque usen proveedores y credenciales independientes y no consuman la cuota agotada. **Este es un comportamiento del cliente Codex que el enrutamiento proxy de modelo ordinario no puede cambiar.** El estado de reserva llega desde el backend ChatGPT en la propia conexión autenticada del cliente, no a través del proxy. La aplicación de escritorio sondea `backend-api/wham/usage` y trata la reserva como activa cuando la respuesta lleva `rate_limit_upsell.banner_type = "luna_reserve"`, el `rate_limit.allowed` primario es `false`, y `additional_rate_limits[]` contiene una entrada con `limit_name = "gpt-reserve"` que todavía está permitida. Mientras eso se mantiene, la aplicación fuerza la configuración del modelo de la conversación a `gpt-reserve` y reescribe cualquier otra elección de nuevo a ella - el selector se contrae a la entrada de reserva por el cliente, y un valor `model =` en `config.toml` se anula de la misma manera. Nada de esto consulta el catálogo de modelos, por lo que ninguna representación de nuestra parte participa en la decisión. opencodex no tiene un concepto de reserva para ajustar, y la alternativa - informar mal su propia cuota a su propio cliente - sería un error peor que el que encubrió. @@ -703,7 +703,7 @@ Con la opción activada o desactivada, una solicitud con bearer propio registra `codexPool.startIdleWindows` es un booleano opcional y por defecto a `false`. Cuando se habilita, una nueva solicitud real no vinculada puede colocarse en una cuenta elegible cuya ventana de cuota corta observada es del 0% con evidencia de que su reloj de cinco horas no ha comenzado. Esta verificación se ejecuta después de la conversación y la afinidad familiar, por lo que un enlace existente sigue siendo autorizado; también gana un pin de cuenta explícito o una preferencia de cuenta manual. Se omiten los ámbitos de cuota de modelo independientes y el cursor activo compartido permanece sin cambios. Después de la opción de ventana inactiva, la selección de estrategia normal se reanuda para otras conversaciones. -La observación no debe ser mayor de cinco minutos, y la ventana corta debe ser explícitamente de 18.000 segundos. Su restablecimiento debe observarse dentro de los 60 segundos de `observation + 5h` (en lugar de un restablecimiento ya realizado o transcurrido). Una reserva local de proceso sincrónica evita selecciones duplicadas para la misma cuenta y ventana. El plazo de reserva es de al menos 5 horas más un minuto después de la selección; se requiere una nueva observación después de ese plazo antes de que la misma cuenta pueda ser dirigida nuevamente. Las reservas se borran cuando se reinicia el proceso proxy y nunca se mantienen en el disco. +La observación debe tener como máximo 5 minutos de antigüedad y la ventana corta debe durar explícitamente 18 000 segundos. El restablecimiento debe quedar a no más de 60 segundos de `observation + 5h`; una ventana que ya está corriendo o que terminó no cumple esta condición. Una reserva síncrona local al proceso evita seleccionar dos veces la misma cuenta para la misma ventana. La reserva dura al menos 5 horas y 1 minuto desde la selección. Después, se necesita una observación nueva para volver a elegir esa cuenta. Las reservas se borran al reiniciar el proxy y nunca se guardan en el disco. Habilitarlo en su configuración existente: @@ -772,7 +772,7 @@ Cuando un almacén de historial afectado admite registros paginados, una transic Al volver al formulario de anulación de raíz, OpenCodex conserva una definición `[model_providers.opencodex]` existente antes de confirmar la configuración, incluso si el historial de pre-vuelo pasa actualmente. Esto hace que las conversaciones más antiguas de `opencodex` se puedan resolver si Codex migra el historial después de esa confirmación o mientras se inicia el trabajador en segundo plano. Las nuevas conversaciones aún usan el proveedor raíz seleccionado; la restauración explícita mantiene sus protectores de eliminación separados. -`ocx restore`, `ocx stop` y `ocx uninstall` Ya no se niegan a `history_paginated_requires_native_writer`. Toman cada clave de enrutamiento raíz OpenCodex y mantienen la `[model_providers.opencodex]` definición en el disco, por lo que las conversaciones cuyas filas todavía nombran ese proveedor siguen resolviendo mientras se `codex` Deja de apuntar al proxy. El resultado se informa como una restauración parcial que nombra las líneas retenidas, y `ocx restore --remove-codex-provider-table` También los elimina, después de lo cual esas conversaciones dejan de abrirse. +`ocx restore`, `ocx stop` y `ocx uninstall` ya no rechazan la operación al encontrar `history_paginated_requires_native_writer`. Quitan las claves de enrutamiento que OpenCodex añadió en la raíz de la configuración, por lo que `codex` deja de usar el proxy de forma predeterminada. Conservan la definición `[model_providers.opencodex]` para que las conversaciones asociadas a ese proveedor sigan teniendo un proveedor que existe. Codex 0.166 y posteriores solo abren esas conversaciones mientras `opencodex` es el proveedor actual, así que después de la restauración solo se vuelven a abrir cuando se selecciona `opencodex` de nuevo como proveedor. Si la URL de esa tabla sigue apuntando al proxy, el proxy debe estar accesible para enviar solicitudes nuevas desde esas conversaciones. El resultado indica una restauración parcial y enumera las líneas conservadas. `ocx restore --remove-codex-provider-table` también quita esas líneas; después, las conversaciones asociadas dejan de abrirse. Habilitar la integración en su formulario de tabla de proveedores en una casa cuyas `openai` conversaciones etiquetadas Codex ya se han paginado solía ser rechazado por completo con `history_paginated_openai_requires_native_writer`: no se escribió nada y la integración se mantuvo inhabilitada. OpenCodex ahora completa esa transición manteniendo la raíz administrada `openai_base_url` al lado de la tabla `[model_providers.opencodex]`. Codex fusiona la anulación en su proveedor `openai` incorporado, por lo que esas conversaciones siguen llegando al proxy sin ser reetiquetadas y no se toca ningún byte de despliegue o fila de hilos. Solo un formulario de enrutamiento que requiere la cabecera de admisión `x-opencodex-api-key` todavía se niega, porque el proveedor incorporado de Codex no puede llevar esa cabecera; su mensaje nombra las dos configuraciones que lo resuelven: la ruta Codex a través del oyente de bucle de retorno para que la anulación pueda conservarse, o establece `syncResumeHistory` a `false` para aceptar que esas conversaciones se reanuden contra el propio punto final OpenAI de Codex. @@ -857,7 +857,7 @@ Los resultados de la herramienta paralela se ponen en cola y se envían un fotog Cuando el servidor rechaza una inyección con `response_already_completed`, use sus salidas guardadas devueltas en **Un cliente enviado** `response.create` con el `previous_response_id` completado, modelo/configuración sin cambios y el mismo carril. Incluya cada resultado sobresaliente exactamente una vez; no incluya resultados ya aceptados. El relé mantiene esa continuación en la cuenta / socket original y conserva el ritmo normal de la solicitud. Nunca ejecuta la herramienta de nuevo o crea una solicitud de recuperación en sí. Otras fallas permanecen visibles para que el cliente las maneje. -Un acuse de recibo faltante o una entrega de medios de desconexión puede ser **Desconocido**. No vuelva a enviar un resultado automáticamente, reinicie una herramienta o cambie de cuenta para volver a intentarlo. La cola pendiente está limitada a 32 tramas y 8 MiB, con 1.024 llamadas de función anunciadas, un diario de reproducción de 32 MiB y como máximo 128 respuestas por conexión propia. Los diarios de inyección comparten el presupuesto de memoria fijado y el techo agregado de 128 MiB con los diarios de dirección; véase [límites de memoria de dirección](#steering-confirmation-deadlines-and-retained-context). El límite de cuerpo ascendente configurado se comprueba antes de que un resultado entre en la cola, incluso mientras otro resultado espera el acuse de recibo. Un rechazo `outbound_body_too_large` deja la conexión utilizable para un resultado corregido sin volver a ejecutar su herramienta. Cada inyección enviada tiene un plazo de confirmación de 90 segundos que la salida no relacionada no puede extender; una espera de resultado guardado está limitada a 30 minutos. Los límites de marco existentes y los tiempos muertos todavía se aplican. +Un acuse de recibo faltante o una entrega de medios de desconexión puede ser **Desconocido**. No vuelva a enviar un resultado automáticamente, reinicie una herramienta o cambie de cuenta para volver a intentarlo. La cola pendiente está limitada a 32 tramas y 8 MiB, con 1024 llamadas de función anunciadas, un diario de reproducción de 32 MiB y como máximo 128 respuestas por conexión propia. Los diarios de inyección comparten el presupuesto de memoria fijado y el techo agregado de 128 MiB con los diarios de dirección; véase [límites de memoria de dirección](#steering-confirmation-deadlines-and-retained-context). El límite de cuerpo ascendente configurado se comprueba antes de que un resultado entre en la cola, incluso mientras otro resultado espera el acuse de recibo. Un rechazo `outbound_body_too_large` deja la conexión utilizable para un resultado corregido sin volver a ejecutar su herramienta. Cada inyección enviada tiene un plazo de confirmación de 90 segundos que la salida no relacionada no puede extender; una espera de resultado guardado está limitada a 30 minutos. Los límites de marco existentes y los tiempos muertos todavía se aplican. Los proveedores traducidos, las puertas de enlace personalizadas, las rutas Combo / sidecar y el retroceso HTTP no obtienen soporte de inyección. Los intentos no soportados devuelven un error explícito en lugar de desaparecer. La opción permanece desactivada por defecto; las pruebas de transporte sintético no son una certificación de compatibilidad en vivo. Ajuste `codexNativeInjection` a `false` y reinicie para retroceder. No es necesario eliminar ningún archivo de cuenta o conversación. @@ -868,7 +868,7 @@ Los proveedores traducidos, las puertas de enlace personalizadas, las rutas Comb Con `codexNativeInjection` habilitado, un cliente-enviado `response.create` en la misma conexión de propiedad ahora puede devolver **no enviado** resultados de función/personalizados que contienen texto, imagen o partes de archivo después de `response.completed`. Suministre el `previous_response_id` de la respuesta completada, el mismo carril y el mismo modelo / configuración sin cambios. Incluya cada resultado sobresaliente o aprobación solicitada exactamente una vez; omita los resultados inyectados ya aceptados. El proxy reenvía esta continuación enviada por el llamante usando la cuenta original y el socket con las comprobaciones de envío existentes. -Los elementos de continuación admitidos son `function_call_output`, `custom_tool_call_output` y `mcp_approval_response`. La salida de la herramienta puede ser una cadena o una matriz de `input_text`, `input_image` y `input_file` partes. Las piezas de imagen requieren `detail` (`auto`, `low`, `high` o `original`); el detalle del archivo es opcional (`auto`, `low`, `high`). Utilice exactamente una fuente de imagen / archivo. Los datos de archivo en línea requieren un nombre de archivo. Se conserva la opción `prompt_cache_breakpoint: { "mode": "explicit" }`. Los campos no admitidos son rechazados, no eliminados. Las referencias no se descargan ni se vuelven a cargar por el proxy. Cada resultado tiene como máximo 1.024 partes de contenido dentro del límite de solicitud de 8 MiB existente. Una persona que llama al programa suministrado debe coincidir con la llamada anunciada; no puede hacerse pasar por otra herramienta o agente. El orden del contenido, las referencias de archivos y la ortografía original sobreviven. +Los elementos de continuación admitidos son `function_call_output`, `custom_tool_call_output` y `mcp_approval_response`. La salida de la herramienta puede ser una cadena o una matriz de `input_text`, `input_image` y `input_file` partes. Las piezas de imagen requieren `detail` (`auto`, `low`, `high` o `original`); el detalle del archivo es opcional (`auto`, `low`, `high`). Utilice exactamente una fuente de imagen / archivo. Los datos de archivo en línea requieren un nombre de archivo. Se conserva la opción `prompt_cache_breakpoint: { "mode": "explicit" }`. Los campos no admitidos son rechazados, no eliminados. Las referencias no se descargan ni se vuelven a cargar por el proxy. Cada resultado tiene como máximo 1024 partes de contenido dentro del límite de solicitud de 8 MiB existente. Una persona que llama al programa suministrado debe coincidir con la llamada anunciada; no puede hacerse pasar por otra herramienta o agente. El orden del contenido, las referencias de archivos y la ortografía original sobreviven. Para un `mcp_approval_request` emitido por el servidor, pase su ID como `approval_request_id` y un `approve: true` o `approve: false` explícito. La denegación se envía sin cambios. El proxy no decide, por defecto, aprueba automáticamente ni ejecuta la herramienta solicitada. Se rechaza una decisión faltante o no relacionada. Las acciones alojadas `multi_agent_call` y otras herramientas de ejecución de servidor son **no** funciones de desarrollador: sus eventos, salidas y mensajes de agente cifrados se conservan, nunca se ejecutan o se inyectan antes de OpenCodex. @@ -907,7 +907,7 @@ Para una comparación de suscripción, la URL directa es `wss://chatgpt.com/back Solo después de revisar el plan, suministre `STEERING_DIRECT_TOKEN` y `STEERING_PROXY_TOKEN` a través de su entorno de shell y agregue **ambos** `--live` y `--allow-model-requests`. Una conexión directa ChatGPT puede necesitar adicionalmente `STEERING_DIRECT_ACCOUNT_ID`; ese encabezado nunca se copia al público API o al proxy. No ponga credenciales en argumentos de comando, registros, capturas de pantalla o solicitudes de extracción (PR). El script no lee el inicio de sesión Codex guardado, actualiza tokens o cambia la configuración. -La ejecución en vivo envía cuatro solicitudes iniciales sintéticas (dos escenarios por ruta), más cualquier sucesor resultante o continuación de resultado requerido, y **puede consumir el uso del modelo**. Un escenario comprueba un sucesor automático; el otro devuelve un resultado sintético fijo solo para la función anunciada del propio script y cambia el razonamiento/verbosidad en su continuación explícita. No se ejecuta ninguna herramienta externa y no se infiere ninguna aprobación. No hay reintentos ni solicitudes de recuperación automática. Cada escenario está limitado a 120 segundos, 5.000 eventos y 2 MiB de datos recibidos. +La ejecución en vivo envía cuatro solicitudes iniciales sintéticas (dos escenarios por ruta), más cualquier sucesor resultante o continuación de resultado requerido, y **puede consumir el uso del modelo**. Un escenario comprueba un sucesor automático; el otro devuelve un resultado sintético fijo solo para la función anunciada del propio script y cambia el razonamiento/verbosidad en su continuación explícita. No se ejecuta ninguna herramienta externa y no se infiere ninguna aprobación. No hay reintentos ni solicitudes de recuperación automática. Cada escenario está limitado a 120 segundos, 5000 eventos y 2 MiB de datos recibidos. El informe JSON contiene solo resultados, tiempos y puntos de control booleanos. Un pase requiere una aceptación en cola, un sucesor creado y el marcador sintético en su salida completada. Las confirmaciones ausentes son `unknown`; si el modelo nunca entra en la ruta de entrada requerida, el resultado es `not_exercised`. Ninguno de los dos cuenta como pase. El proceso sale con 0 solo si pasan los cuatro escenarios en vivo, con 1 en caso contrario y con 2 para argumentos no válidos o credenciales ausentes. Se trata de un **diagnóstico del protocolo**, no de una prueba de interfaz de extremo a extremo de Codex App/CLI, una certificación en vivo ni una instrucción para habilitar la función experimental para el trabajo de producción. diff --git a/docs-site/src/content/docs/es/guides/remote-link.md b/docs-site/src/content/docs/es/guides/remote-link.md index e492d96b955..11fcc2fa067 100644 --- a/docs-site/src/content/docs/es/guides/remote-link.md +++ b/docs-site/src/content/docs/es/guides/remote-link.md @@ -89,7 +89,9 @@ Si las solicitudes siguen fallando, ejecuta `ocx link check --link-id ` en H Un enlace fallido no cambia silenciosamente a un proveedor local. Si el túnel ya falló, está detenido o no está supervisado antes de iniciar el reenvío, el Child devuelve un `503` reintentable sin enviar la clave de enlace ni la solicitud. Un fallo posterior al inicio del reenvío es distinto: el Home puede haber recibido o procesado la solicitud; comprueba ese resultado incierto antes de reintentar. También mantiene la clave local cuando otro proceso posee el puerto del túnel; libre ese puerto para que el túnel SSH del Child pueda enlazarlo. -En un Child, `GET /healthz` solo indica que OpenCodex se está ejecutando. `GET /readyz` y `ocx ready` también comprueban si el enlace puede transportar una solicitud. Si no puede, la respuesta es `503` con `Retry-After: 1`, `"status": "pending"` y un objeto `link`, por ejemplo `{ "state": "unavailable", "reason": "home_unreachable" }`. Si puede, responde `200`, `"status": "ready"` y `{ "state": "available" }`. Los motivos posibles son `tunnel_connecting`, `tunnel_failed`, `tunnel_idle`, `tunnel_unavailable`, `sidecar_invalid`, `home_unreachable`, `home_unauthorized`, `link_auth_failed`, `link_credential_unavailable` y `link_unverified`. Un Child enlazado desde su propio dashboard consulta su túnel. Si el Home añadió el Child, este no tiene un túnel propio que inspeccionar: consulta al Home por el túnel con la misma comprobación sin credenciales que precede a cada solicitud reenviada, como máximo una vez cada cinco segundos. Si el Home no responde en medio segundo, informa `link_unverified`. +En un Child, `GET /healthz` solo indica que OpenCodex se está ejecutando. `GET /readyz` y `ocx ready` también comprueban si el enlace puede transportar una solicitud. Si no puede, la respuesta es `503` con `Retry-After: 1`, `"status": "pending"` y un objeto `link`, por ejemplo `{ "state": "unavailable", "reason": "home_unreachable" }`. Si puede, responde `200`, `"status": "ready"` y `{ "state": "available" }`. Los motivos posibles son `tunnel_connecting`, `tunnel_failed`, `tunnel_idle`, `tunnel_unavailable`, `sidecar_invalid`, `home_unreachable`, `home_unauthorized`, `link_auth_failed`, `link_credential_unavailable`, `link_unverified` y `client_state_changed`. Un Child enlazado desde su propio dashboard consulta su túnel. Si el Home añadió el Child, este no tiene un túnel propio que inspeccionar: consulta al Home por el túnel con la misma comprobación sin credenciales que precede a cada solicitud reenviada, como máximo una vez cada cinco segundos. Si el Home no responde en medio segundo, informa `link_unverified`. + +El motivo `client_state_changed` indica que falta la conexión guardada del Child en ejecución o que ahora identifica otro propietario u otro enlace. Los endpoints de estado del equipo y del enlace también devuelven `503` con este motivo. Detén o reinicia el Child y comprueba su conexión antes de volver a enlazarlo. Este resultado de disponibilidad no desconecta el relay. Para confirmar qué Home atiende a un Child, compara el encabezado `x-opencodex-served-by` de `GET /v1/models` del Child con `instanceId` de `GET /healthz` del Home. El Child retransmite el encabezado sin cambios, por lo que los valores coinciden mientras el enlace funciona. Es un identificador opaco, nunca un nombre de equipo; consulta [Identidad del Home y encabezado served-by](/es/reference/management-api/#home-identity-and-the-served-by-header). @@ -373,7 +375,7 @@ En un Child cuyo enlace inició Home, `ocx link status` informa el rol `child`, El Home requiere OpenCodex 2.66.0 o posterior; el Child también si inicia el enlace o usa una instalación completa. Un host SSH vacío puede recibir `ocx-child` verificado sin Node, Bun ni OpenCodex previo. npm y Desktop no incluyen ese binario: consulta [Children efímeros](#ephemeral-child-machines-ocx-child). Confirma la huella antes de **Conectar Child** o **Instalar agente ligero y conectar**. -Home reintenta cada minuto los túneles que inició tras un timeout o error de reenvío. Un Child que inició su enlace duplica la espera de uno hasta cinco minutos. Ambos esperan cinco minutos ante errores de autenticación; nunca reintentan una huella cambiada. `client_state_changed` significa que la conexión guardada falta o identifica otro propietario o enlace; los endpoints de estado también devuelven `503`. Detén o reinicia el Child y comprueba su conexión antes de enlazarlo otra vez; este resultado no desconecta el relay. +Home reintenta cada minuto los túneles que inició tras un timeout o error de reenvío. Un Child que inició su enlace duplica la espera de uno hasta cinco minutos. Ambos esperan cinco minutos ante errores de autenticación; nunca reintentan una huella cambiada. `ocx connect status` muestra `Link tunnel:` con `up`, `down ()` o `unknown`. Las causas de este último son `runtime_not_running`, `runtime_unreadable` y `link_unverified`. `--json` lo incluye en `linkTunnel`. `Connection: connected` solo confirma el vínculo: puede coexistir con `Link tunnel: down (home_unreachable)` hasta reconectar. diff --git a/docs-site/src/content/docs/es/guides/web-dashboard.md b/docs-site/src/content/docs/es/guides/web-dashboard.md index eee4f7e2452..d5858695c17 100644 --- a/docs-site/src/content/docs/es/guides/web-dashboard.md +++ b/docs-site/src/content/docs/es/guides/web-dashboard.md @@ -93,9 +93,9 @@ El dashboard en `localhost` obtiene su propia sesión y no debería pedir un tok ## Dashboard clásico -El diseño nuevo abre Inicio y agrupa páginas en **Uso diario**, **Configuración** y **Ajustes avanzados**. El anterior sigue en `/classic/`, por ejemplo `http://127.0.0.1:10100/classic/`. +El panel actual abre **Inicio**. La barra lateral agrupa las páginas en **Uso diario** y **Ajustes avanzados**. **Enrutamiento** abre las integraciones de clientes y tiene una pestaña de configuración. El panel anterior sigue en `/classic/`, por ejemplo `http://127.0.0.1:10100/classic/`. -- Cambia mediante el reloj **Dashboard clásico** al pie de la barra lateral; allí **Nuevo dashboard** permite volver. +- Cambia mediante el reloj **Panel clásico** al pie de la barra lateral; allí **Panel nuevo** permite volver. - El navegador recuerda la elección; abrir `/` y Desktop la respetan. El desplegable de bandeja siempre usa el nuevo. - El clásico modifica las mismas opciones del proxy, pero las páginas y opciones posteriores al rediseño solo existen en el nuevo. @@ -142,8 +142,8 @@ La parte superior de cada página, salvo Inicio, muestra en una línea el uso de | **Codex autostart** | Permitir que se ejecute una shim de lanzador Codex ya instalada `ocx ensure`. Este conmutador no instala un servicio de shim o de fondo. | | **Telemetría** | En **Detalles del proxy** (`#proxy-telemetry`), activa o desactiva compartir estadísticas anónimas y consulta la vista previa JSON. El aviso inicial solo guarda al pulsar **Continuar** (`PUT /api/telemetry`); cerrarlo no registra nada. Consulta [Telemetría y privacidad](/es/guides/telemetry/). | | **Proveedores** | Añade, edita, habilita, deshabilita y elimina proveedores; solo los habilitados pueden ser predeterminados. Gestiona grupos de cuentas OAuth y de claves API cuando se admiten. Si eliminas el proveedor predeterminado, se selecciona el primer proveedor habilitado restante; si no hay ninguno, se rechaza la eliminación y se conserva el actual. Los ajustes del proveedor permiten desactivar el descubrimiento en vivo cuando su catálogo `/models` no existe, tarda demasiado o es demasiado grande. En Claude (Anthropic) OAuth, cada cuenta conectada muestra sus propias barras de cuota de cinco horas y semanal: el uso corresponde a cada credencial. Si falla una consulta, se conservan las últimas barras válidas y se marcan como no disponibles hasta que una actualización tenga éxito. La actualización de cuotas omite las cuentas OAuth en pausa y las claves API deshabilitadas; las filas omitidas sin una lectura en caché siguen sin estar disponibles, pero no afectan al resultado de la actualización. La actualización informa de un fallo si una cuenta OAuth sin pausar o una clave API habilitada que admita consultas de cuota tiene una lectura no disponible. Cuando no hay un proveedor seleccionado, la vista general ofrece **Actualizar todas las cuotas**, que fuerza una nueva consulta del servidor para cada proveedor configurado. Si falla la consulta a un proveedor, se conserva su última fila válida. El estado informa de que la comprobación terminó, sin afirmar que todos los valores sean nuevos; la antigüedad de cada fila indica la vigencia de sus datos. | -| **Añadir proveedor** | Una búsqueda por encima de las pestañas llega a los cuatro a la vez — Cuentas, Gratis, Local, Pagado. Mientras una consulta está en vivo, los resultados se agrupan por pestaña con un recuento de cada uno, y la pestaña seleccionada se mantiene en lugar de saltar. Presione ArrowDown en el cuadro de búsqueda para enfocar la primera acción de resultado disponible, omitiendo los botones desactivados; si no hay ninguna acción disponible, el enfoque permanece en el cuadro de búsqueda. Los tiempos de ejecución locales (Ollama, vLLM, LM Studio, LitelLM) tienen su propia pestaña, y una larga nota del proveedor se fija a dos líneas con el texto completo a un clic de distancia. Claude Code CLI (suscripción) se encuentra bajo Pagado con una suscripción CLI insignia, y al seleccionarlo advierte que se factura la suscripción iniciada a través de Claude `claude -p` y nunca usa una clave API (usar `anthropic-apikey` ej., para facturación de claves). | -| **Codex Autonomía** | Agregue cuentas de grupo ChatGPT/Codex, seleccione la cuenta de la siguiente sesión, actualice las cuotas de 5h / semanal / 30d, habilite o deshabilite el cambio automático de cuota, establezca su umbral 1–100% y configure la conmutación por error de transitorios. | +| **Añadir proveedor** | La búsqueda abarca las cuatro pestañas: Cuentas, Gratis, Local y De pago. Los resultados se agrupan por pestaña con su recuento, y la pestaña seleccionada se mantiene. Presiona ArrowDown en el cuadro de búsqueda para enfocar la primera acción disponible de los resultados. Se omiten los botones desactivados. Si no hay acciones disponibles, el foco permanece en el cuadro. Las herramientas que se ejecutan localmente (Ollama, vLLM, LM Studio y LiteLLM) tienen su propia pestaña. Las notas largas se muestran en dos líneas y se pueden ampliar con un clic. Claude Code CLI (suscripción) aparece en De pago con la indicación de suscripción de CLI. Al seleccionarlo, el panel aclara que `claude -p` usa la suscripción de Claude con la que iniciaste sesión. Para facturar por clave API, usa `anthropic-apikey`. | +| **Autenticación de Codex** | Añade cuentas al grupo de ChatGPT/Codex, elige la cuenta de la próxima sesión y actualiza las cuotas de 5 horas, 1 semana y 30 días. Puedes activar o desactivar el cambio de cuenta por cuota, elegir un umbral de entre 1 y 100 % y configurar el cambio de cuenta ante fallos transitorios. | | **Subagentes** | Define las primeras cinco prioridades de `spawn_agent` mediante `subagentModels`, con modelos nativos sin prefijo o modelos enrutados con espacio de nombres. No es una lista de permitidos: las posiciones libres pueden completarse con filas visibles del catálogo. El panel **Límites del flujo de trabajo para subagentes** controla los turnos simultáneos, las solicitudes al modelo y los subagentes distintos permitidos por tarea en cada ventana de 10 minutos. Consulta [Límites del flujo de trabajo](/es/reference/configuration/server/#workflow-limits). | | **Modelos** | Alternar GPT nativo y modelos enrutados, establecer listas de proveedores y límites de contexto, elegir v1/base/v2 y configurar el límite de hilos v2. La página distingue un catálogo guardado en el concentrador, un catálogo obtenido por este cliente y la activación en un cliente en ejecución. Una marca de tiempo fetch no prueba que incluya la última función de guardado del concentrador, y la activación en entorno de ejecución se muestra como no verificada. Los proveedores configurados permanecen visibles como grupos de modelo cero cuando la detección está desactivada o no devuelve filas. | | **Registros** | Actualizar automáticamente las solicitudes recientes con tokens, el esfuerzo solicitado y (cuando esté disponible) el esfuerzo de salida efectivo, el modelo resuelto, el proveedor, el estado, la identificación de la solicitud, la duración y los detalles del error. La vista de detalle incluye el campo exacto del cable de razonamiento cuando el adaptador emite uno. Filtrar por ID de conversación/sesión opaca (cuando el cliente envía uno) a tokens total y costo de lista-precio estimado para el anillo de registros cargado actualmente. | @@ -183,15 +183,16 @@ Si el proxy observó ambos extremos, divide los tokens de salida entre la duraci Los filtros activos muestran el recuento correspondiente del total cargado. Restablecer filtros restaura todo filas y devuelve el foco del teclado al control de toda la superficie; “Sin solicitudes coincidentes” difiere de un anillo de registro vacío. Utilice las teclas de flecha o Home/End en el selector de superficie. Estos controles no consultan registros históricos más allá del anillo cargado. -El selector de idioma incluye **Portugués** (Portugués brasileño, `pt-BR`) Los idiomas del navegador portugués lo seleccionan automáticamente a menos que ya se guarde una preferencia de idioma compatible. +El selector de idioma incluye **Português** (portugués brasileño, `pt-BR`). El navegador lo selecciona automáticamente si está configurado en portugués y aún no guardaste otro idioma compatible. + +**Español** usa español neutro. Si el navegador está configurado en una variante como `es-BO`, `es-MX` o `es-ES`, el panel la detecta, salvo que ya tengas un idioma compatible guardado en `ocx-lang`. El idioma del documento es `es` y las fechas de restablecimiento de cuotas usan el formato regional español. ### Vincular a una sección -Hay un solo diseño, por lo que no hay ningún interruptor de diseño para configurar. Las secciones del panel son direccionable en su lugar: `#dashboard` abre Vista general, y `#dashboard/providers` y -`#dashboard/models` Abre los otros dos. Recargar, marcar y Atrás todos mantienen la sección que estabas encendido. **Registros** Funciona de la misma manera con `#logs` y `#logs/debug`. Un viejo `#providers/workspace` -Marcador ahora aterriza en `#providers`. +Las secciones del panel tienen enlaces directos: `#dashboard` abre Vista general, y `#dashboard/providers` y +`#dashboard/models` abren las otras dos secciones. Al recargar, usar un marcador o volver atrás se conserva la sección. **Registros** funciona de la misma manera con `#logs` y `#logs/debug`. Los marcadores antiguos a `#providers/workspace` ahora abren `#providers`. Valores de costos en **Registros** y **Uso** son equivalentes de lista-precio de API calculados a partir de tokens notificado. Para un intervalo de uso personalizado, el servidor debe confirmar las horas de inicio y fin solicitadas. Si un proxy de ejecución anterior no admite esos límites, el panel de control y CLI rechazan su informe; Actualizar y reiniciar ese proxy antes de volver a intentarlo. Restablecer un precio de modelo manual afecta solo a modelo, conservando otras tasas ahorradas independientemente. Los **Uso** Las tablas de resumen y Modelos/Proveedores muestran el rendimiento de salida de extremo a extremo del historial de uso para el rango y los filtros seleccionados: salida sumada tokens dividida por segundos de reloj de pared sumados, no un promedio de tasas individuales. El recuento de muestras se mide por intentos (o solicitudes de filas heredadas sin intentos); se excluyen las muestras que carecen de salida finita positiva tokens o duración. Un guión significa que no hay muestra calificada o el servidor devolvió una tasa inutilizable. Esto incluye la espera de predecodificación y no es una velocidad de decodificación estimada. @@ -338,14 +339,14 @@ La GUI es un cliente ligero de la API JSON de administración del proxy. Algunos | `GET /api/models` · `PUT /api/disabled-models` | Enumera filas de modelos nativos/enrutados y actualiza el conjunto de modelos deshabilitados compartidos. | | `GET /api/selected-models` · `PUT /api/model-visibility` | Lea las listas de proveedores y cambie atómicamente la visibilidad final de un modelo o grupo de proveedores. | | `GET /api/key-providers` · `GET /api/oauth/providers` | Lea los catálogos de proveedores API y OAuth. | -| `GET /api/oauth/accounts?provider=..."a=1` · `GET /api/providers/keys?name=..."a=1` | Lea cada cuenta o cuota de clave donde sea compatible, sin cambiar la credencial activa. Añadir `refresh=1` para omitir la caché de cuota establecida; se puede compartir una lectura de la misma credencial en vuelo. Omita `quota=1` para una lista local barata con cada fila de `quotaMode`: `probe`, `passive`, o `unsupported`. Las lecturas pasivas devuelven las observaciones existentes sin una sonda de red. Ninguna lectura es lo mismo que el 0% utilizado, y las cuotas para múltiples claves no se suman. | +| `GET /api/oauth/accounts?provider=..."a=1` · `GET /api/providers/keys?name=..."a=1` | Lea cada cuenta o cuota de clave donde sea compatible, sin cambiar la credencial activa. Añadir `refresh=1` para omitir la caché de cuota establecida; se puede compartir una lectura de la misma credencial en vuelo. Omita `quota=1` para una lista local barata con cada fila de `quotaMode`: `probe`, `passive`, o `unsupported`. Las lecturas pasivas devuelven las observaciones existentes sin una sonda de red. Que no haya una lectura no significa que el uso sea del 0 %. Las cuotas de varias claves no se suman. | | `POST /api/oauth/login` · `GET /api/oauth/status` | Inicie un flujo de proveedores OAuth y realice una encuesta para su finalización. | -| `GET /api/codex-auth/accounts?refresh=1` | Listar cuentas principales y de grupo, forzar la actualización de cuotas e informar la cuenta principal `hasCredential` / terminal `needsReauth` Estado. | +| `GET /api/codex-auth/accounts?refresh=1` | Enumera la cuenta principal y las del grupo, fuerza la actualización de cuotas e informa si la cuenta principal tiene credencial (`hasCredential`) o debe volver a autenticarse (`needsReauth`). | | `PUT /api/codex-auth/active` · `PUT /api/codex-auth/auto-switch` · `PUT /api/codex-auth/failover` | Seleccione la cuenta para la siguiente solicitud y configure el enrutamiento del grupo. | -| `GET /api/codex-auth/active` · `PUT /api/codex-auth/accounts/priority` | Lea la cuenta efectiva (incluyendo `pinned` ¿Cuál es la cuenta `pinnedAccountId`y establecer el orden de selección de una cuenta. | +| `GET /api/codex-auth/active` · `PUT /api/codex-auth/accounts/priority` | Consulta la cuenta efectiva, incluidos el indicador `pinned` y la cuenta identificada en `pinnedAccountId`, y establece el orden de selección de una cuenta. | | `POST /api/codex-auth/login` · `GET /api/codex-auth/login-status` | Agregar una cuenta de grupo a través del inicio de sesión del navegador. | | `GET /api/logs?tail=50&limit=20&offset=0&provider=...&status=5xx` | Lea los metadatos de las solicitudes recientes con filtros opcionales de cola, proveedor y estado exacto/clase. Con `limit`/`offset`, paging camina hacia atrás desde la fila más reciente (`offset=0` devuelve la última página). Forma de respuesta: `{ timeZone, generatedAt, total, logs }` donde `total` es el recuento de filas filtradas antes de la paginación. | -| `GET` / `PUT /api/subagent-models` | Leer o establecer los cinco destacados `spawn_agent` Anule los modelos. | +| `GET` / `PUT /api/subagent-models` | Consulta o configura los cinco modelos destacados que tienen prioridad para `spawn_agent`. | | `POST /api/stop` | Detenga el proxy/servicio, restaure el Codex nativo y salga. Rechazado con `respawnable_service` en el Backend del Programador de Tareas Windows, con `self_unload_service` cuando este proxy es en sí mismo el trabajo instalado de lanzamiento / sistema, y con `service_state_unknown` cuando no se puede leer el estado del Programador de tareas; nada cambia en ninguno de esos casos. Una sesión de dashboard también es rechazada, con `desktop_supervised`Mientras que la aplicación de escritorio OpenCodex ejecuta el proxy. | La parada vuelve a comprobar quién controla la conexión antes de restaurar la configuración. Una conexión nueva al hub conserva su enrutamiento, catálogo y configuración de Grok. Si el control aún está cambiando o no se puede confirmar, la API devuelve HTTP 409 con `sharedTeardown: "refused"` y sigue atendiendo solicitudes; deja que termine la operación de conexión y reintenta. Consulta el [flujo de parada de Remote Link](/es/guides/remote-link/). diff --git a/docs-site/src/content/docs/es/reference/adapters.md b/docs-site/src/content/docs/es/reference/adapters.md index 78b2a743551..a93f8b973de 100644 --- a/docs-site/src/content/docs/es/reference/adapters.md +++ b/docs-site/src/content/docs/es/reference/adapters.md @@ -338,7 +338,7 @@ login` completa el propio inicio de sesión PKCE del CLI y escribe un `devin-ses - Las definiciones de herramienta se codifican en la solicitud y los eventos de llamada de herramienta se decodifican a partir del flujo de respuesta. Cognition impone un límite de longitud por herramienta-descripción (6998 caracteres) y una lista de bloques de frases exactas; el adaptador desinfecta los disparadores conocidos y trunca las descripciones demasiado largas antes de codificar. Las reescrituras de disparadores conocidos también se aplican al prompt de sistema inicial (campo #2 de la solicitud). - `OPENCODEX_DEVIN_SANITIZE_DATA_SURFACES` está desactivada por defecto y solo se activa con el valor exacto `"1"`; una variable sin definir o cualquier otro valor deja los datos del historial fuera del desinfectante. Activada, también reescribe el texto de mensajes unido (#3), los `arguments_json` de las llamadas de herramienta (#6.3), los pies de imagen (#10.3) y el razonamiento repetido (#11). Los nombres de herramienta, los ID de llamadas de herramienta y los bytes de imagen no se tocan. Esto cambia el historial literal que recibe el modelo, incluido el contenido de archivos citado y los argumentos de herramientas. Si una reescritura cambia el razonamiento, ese prompt envía el texto #11 reescrito sin su firma #12 original ni el tipo de firma #18. El razonamiento sin cambios conserva ambos campos de firma byte a byte, aunque cambie otro campo de datos; la repetición solo de firma también queda intacta. Por tanto, el razonamiento reescrito usa una repetición sin firma, lo que puede debilitar la continuidad del razonamiento firmado en ese turno. Esta opción no garantiza que el upstream la acepte. - Las claves API de Devin/Cognition no tienen punto final de actualización. Si Cognition rechaza una clave almacenada con 401, OpenCodex marca esa cuenta para la reautenticación y puede usar otra cuenta de inicio de sesión para El turno. Correr `ocx login devin` de nuevo para una clave de inicio de sesión del navegador revocada. Una cuenta importada por CLI Puede seguir un `devin auth login` rotación de teclas solo cuando su ID de cuenta o correo electrónico almacenados coincide con la identidad CLI acuñada. Importaciones sin una identidad almacenada requieren un - `ocx login devin` Después de la rotación. Un legado `devin-cli` slot para esa misma cuenta ya puede Mantenga la nueva clave; una cuenta diferente que la mantenga bloquea la adopción. Si el archivo CLI es temporalmente ilegible o la verificación de identidad no está disponible, reintente después de que se recupere. Una cuenta en pausa permanece en pausa durante esta recuperación y devuelve 403. + `ocx login devin` después de la rotación. Una entrada antigua de `devin-cli` para la misma cuenta puede tener ya la clave nueva. Si la clave pertenece a otra cuenta, se bloquea su adopción. Si no se puede leer temporalmente el archivo de la CLI o no está disponible la verificación de identidad, vuelve a intentarlo cuando se recupere. Una cuenta en pausa sigue en pausa durante la recuperación y devuelve 403. - Solo la credencial es local cuando se usa la ruta de importación CLI. El turno en sí mismo va a Cognition de cualquier manera, por lo que las rutas de inicio de sesión de importación y navegador no difieren en nada más que de dónde vino la credencial. Instale el CLI con `curl -fsSL https://cli.devin.ai/install.sh | bash` o `brew install --cask devin-cli`, ejecute `devin auth login` una vez y luego agregue el proveedor. - Una compilación anterior envió un segundo adaptador bajo el id `devin-cli` que ejecutó el turno como una sesión de Protocolo de cliente de agente contra un proceso secundario local `devin acp`. Se ha ido. Una configuración guardada que todavía nombra ese adaptador se reescribe a `devin` al iniciarse, incluida una fila con nombre personalizado como `"devin-acp"`. - La solicitud de chat está calibrada, no adivinada. Tres cosas lo unen: la credencial es el token de sesión duplicado y unido en un encabezado `Authorization: Basic`, mientras que el cuerpo del protobuf mantiene una copia, la envolvente de la solicitud sube sin comprimir y `Metadata` #31 lleva una huella digital del dispositivo de 732 caracteres cuya longitud, no valor, el servicio verifica. En el interior `CompletionConfiguration`, el campo #2 es el límite de salida y el campo #3 es `max_newlines`, enviado a un valor fijo grande; intercambiar esos dos hace que cada turno falle con un `invalid_argument` opaco. Sin límite de llamadas o configurado, el límite de salida es el propio techo del modelo seleccionado del catálogo, y 8192 solo cuando el catálogo no está disponible. Se rechaza una temperatura de exactamente 0, por lo que se fija al valor aceptado más pequeño. diff --git a/docs-site/src/content/docs/es/reference/cli/agents.md b/docs-site/src/content/docs/es/reference/cli/agents.md index c6d7791f25b..c6704b2f782 100644 --- a/docs-site/src/content/docs/es/reference/cli/agents.md +++ b/docs-site/src/content/docs/es/reference/cli/agents.md @@ -925,7 +925,7 @@ de la CLI seleccionada. Nunca detiene sesiones de Codex existentes: si hay proce conoce su estado, rechaza la actualización. Windows admite prefijos compartidos con ACL verificadas y sin rutas con puntos de reanálisis. -La observación incluye paquetes y shims ajenos, con límites de 4,096 entradas, 512 MiB en total +La observación incluye paquetes y shims ajenos, con límites de 4096 entradas, 512 MiB en total y 384 MiB por archivo. Deben conservarse sus bytes e identidades. Los prefijos mayores o inseguros, ARM64, la reparación de shims, las aplicaciones nativas y otros gestores de instalación siguen sin admitirse. Si no se conoce la duración de los hijos o la limpieza de handles queda incompleta, diff --git a/docs-site/src/content/docs/es/reference/cli/lifecycle.md b/docs-site/src/content/docs/es/reference/cli/lifecycle.md index 53b6a27e795..1287d547a3d 100644 --- a/docs-site/src/content/docs/es/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/es/reference/cli/lifecycle.md @@ -445,12 +445,22 @@ ocx catalog pull https://proxy.example.com/v1/catalog \ --auth-env OPENCODEX_CATALOG_AUTH_TOKEN ``` -El valor se envía como un token de portador, pero nunca se acepta como un valor de argv. Las redirecciones son rechazadas, por lo que la autorización no puede cruzar orígenes. Las escrituras de catálogo y caché utilizan el bloqueo de catálogo Codex compartido y el escritor atómico. Una recuperación, validación, adquisición de bloqueos, escritura de catálogo o reconstrucción de caché fallida conserva los últimos archivos buenos conocidos. Si los bytes del catálogo son idénticos, la operación no cambia nada: conserva los mtimes y no modifica los procesos. `--restart-codex`, `--restart-app-server-only` y el alias `--restart-desktop-app` en desuso significan lo mismo aquí que en `ocx sync` y `ocx sync-cache`, y se aplican solo después de una escritura real. +El valor se envía como token Bearer, pero no se acepta como argumento en argv. El comando +rechaza las redirecciones para que la autorización no se envíe a otro origen. Las escrituras +del catálogo y de la caché usan el bloqueo compartido del catálogo de Codex y el mecanismo +de escritura atómica. Si falla la descarga, la validación, la adquisición del bloqueo o la +escritura del catálogo o de la caché, se conservan los últimos archivos válidos. +`--restart-codex`, `--restart-app-server-only` y el alias en desuso `--restart-desktop-app` +seleccionan los mismos procesos que en `ocx sync` y `ocx sync-cache`. Al usar `ocx catalog pull`, +solo se aplican si se escribe el catálogo. La URL debe nombrar `/v1/catalog` en la raíz del host. Este comando no admite un proxy inverso que sirva el punto final bajo un prefijo de ruta. -El comando descarga el catálogo completo y compara bytes localmente en lugar de emitir un `ETag` / -`If-None-Match` Solicitud condicional. Los bytes idénticos se tratan como un no-op completo, por lo que Codex casa cuyo catálogo es correcto, pero cuya `models_cache.json` falta o es rancio no reparado por este comando; usar `ocx sync-cache` Por eso. +El comando descarga el catálogo completo y compara sus bytes localmente en vez de enviar una +solicitud condicional con `ETag` / `If-None-Match`. Si los bytes del catálogo coinciden, el +archivo se conserva sin cambios. El comando sí repara `models_cache.json` si falta o está +desactualizado. En ese caso, el resultado puede indicar `status: "unchanged"` junto con +`cacheSynced: true`. Si ambos archivos ya coinciden, mantienen sus fechas de modificación. `--json` emite un sobre estable en stdout. `schemaVersion`, `ok`, `status`, `catalogWritten`, `cacheSynced` y `codexRestarted` están siempre presentes. `codexRestarted` todavía significa solo servidores de aplicaciones. `desktopAppRestarted` está presente solo cuando se solicitó un reinicio del escritorio, y es `true` solo cuando se inició el relanzamiento; un traspaso no es un éxito. `status` es `updated`, `unchanged`, o `failed`. Un tirón exitoso agrega `modelCount`; un fallo agrega `code`, que es el campo en el que se ramifica un script: @@ -682,7 +692,7 @@ ocx codex-shim uninstall Después de desinstalar Unix, elimine la línea de origen del archivo de inicio de shell y reinicie el shell o elimine la entrada de bin privado de su PATH. La desinstalación elimina el envoltorio, el archivo de entorno de shell y el estado propios; deja intacto el lanzador del administrador de paquetes. Se libera una shim Unix más antigua en el lugar utilizando sus datos de restauración registrados. :::note[Entorno del token en Windows] -Windows CMD y las shims PowerShell recientemente generadas restauran el número de la persona que llama `OPENCODEX_API_AUTH_TOKEN` Después de la ejecución. Codex y sus procesos secundarios aún pueden heredar el token. +Los shims nuevos de CMD y PowerShell en Windows restauran al terminar el valor de `OPENCODEX_API_AUTH_TOKEN` que tenía el proceso que los llamó. Codex y sus procesos secundarios aún pueden heredar el token. Después de actualizar OpenCodex, vuelva a crear una shim Windows existente con `ocx codex-shim uninstall` seguido por `ocx codex-shim install` para obtener este comportamiento. Una actualización ordinaria no reescribe una shim Windows saludable. ::: diff --git a/docs-site/src/content/docs/es/reference/configuration/providers.md b/docs-site/src/content/docs/es/reference/configuration/providers.md index 9b25a315fc0..2ea92474d2a 100644 --- a/docs-site/src/content/docs/es/reference/configuration/providers.md +++ b/docs-site/src/content/docs/es/reference/configuration/providers.md @@ -29,13 +29,13 @@ Solo se suben imágenes de mensajes `user` y `developer`, y las imágenes de res ## GPT-6.1 Terra -[GPT-6.1 Terra](https://openai.com/index/introducing-gpt-6-1-terra/) se publicó el 26 de octubre de 2026 como sucesor de GPT-5.6 Terra. `gpt-6.1-terra` está disponible junto a `gpt-5.6-terra`; no cambian el modelo predeterminado ni la lista de subagentes. GitHub Copilot usa Responses; OpenRouter enumera `openai/gpt-6.1-terra` con 1,050,000 de contexto y $1.00 de entrada / $5.00 de salida por millón de tokens. +[GPT-6.1 Terra](https://openai.com/index/introducing-gpt-6-1-terra/) se publicó el 26 de octubre de 2026 como sucesor de GPT-5.6 Terra. `gpt-6.1-terra` está disponible junto a `gpt-5.6-terra`; no cambian el modelo predeterminado ni la lista de subagentes. GitHub Copilot usa Responses; OpenRouter enumera `openai/gpt-6.1-terra` con una ventana de 1 050 000 tokens y tarifas de 1,00 USD de entrada y 5,00 USD de salida por millón de tokens. -En Codex nativo: contexto predeterminado de 500,000 y máximo de contexto largo de 872,000; esfuerzo predeterminado `low` y niveles `low`, `medium`, `high`, `xhigh`, `max`, `ultra`. El `ultra` nativo se envía como `max`. La fila nativa solo ofrece Fast. +En Codex nativo: contexto predeterminado de 500 000 y máximo de contexto largo de 872 000; esfuerzo predeterminado `low` y niveles `low`, `medium`, `high`, `xhigh`, `max`, `ultra`. El `ultra` nativo se envía como `max`. La fila nativa solo ofrece Fast. -En la [API de OpenAI](https://developers.openai.com/api/docs/models/gpt-6.1-terra): contexto de 1,050,000 y salida máxima de 128,000; entrada de texto e imágenes y salida de texto; conocimiento hasta 2026-06-01. Los esfuerzos son `none`, `low`, `medium` (predeterminado), `high`, `xhigh` y `max`. Los endpoints son `v1/responses` y `v1/chat/completions`; las llamadas a herramientas requieren Responses. +En la [API de OpenAI](https://developers.openai.com/api/docs/models/gpt-6.1-terra): contexto de 1 050 000 y salida máxima de 128 000; entrada de texto e imágenes y salida de texto; conocimiento hasta 2026-06-01. Los esfuerzos son `none`, `low`, `medium` (predeterminado), `high`, `xhigh` y `max`. Los endpoints son `v1/responses` y `v1/chat/completions`; las llamadas a herramientas requieren Responses. -Por millón de tokens: $1.00 de entrada, $0.05 de entrada en caché, $1.25 de escritura de caché durante 30 minutos y $5.00 de salida. Con más de 272,000 tokens de entrada, toda la solicitud usa el doble para entrada y caché y 1,5 veces para salida: $2.00 / $0.10 / $2.50 / $7.50, respectivamente. El modo Fast cuesta el doble. +Por millón de tokens: 1,00 USD de entrada, 0,05 USD de entrada en caché, 1,25 USD de escritura de caché durante 30 minutos y 5,00 USD de salida. Si la entrada supera los 272 000 tokens, se aplican a toda la solicitud el doble de las tarifas de entrada y caché y 1,5 veces la tarifa de salida: 2,00 / 0,10 / 2,50 / 7,50 USD, respectivamente. El modo Fast cuesta el doble. @@ -142,11 +142,11 @@ El control del panel de control Codex Auth posee mapas que tienen un campo expl ### GPT-6 Astra, Sol y Luna -`gpt-6-astra` usa la ruta de inicio de sesión de Codex; `openai-apikey/gpt-6-astra` usa su clave API. La disponibilidad sigue dependiendo de la cuenta aguas arriba. Astra nativo conserva los valores predeterminados que envía Codex: 272.000 de contexto, razonamiento `low` y la escalera `low` / `medium` / `high` / `xhigh` / `max` / `ultra`. Su descripción de Fast en el catálogo es **2x velocidad**; no es el multiplicador de facturación. +`gpt-6-astra` usa la ruta de inicio de sesión de Codex; `openai-apikey/gpt-6-astra` usa su clave API. La disponibilidad sigue dependiendo de la cuenta aguas arriba. Astra nativo conserva los valores predeterminados que envía Codex: 272 000 de contexto, razonamiento `low` y la escalera `low` / `medium` / `high` / `xhigh` / `max` / `ultra`. Su descripción de Fast en el catálogo es **2x velocidad**; no es el multiplicador de facturación. Establecer `providerContextCaps.openai` a `922000` para optar por el grupo nativo en contexto largo; Astra se detiene en su propio techo **872,000**. Los modelos `providers.openai.modelContextWindows` y `modelAutoCompactTokenLimits` pueden reducir su ventana y su presupuesto de compactación suave. Por ejemplo, `modelAutoCompactTokenLimits: { "gpt-6-astra": 700000 }` reduce el valor predeterminado de la ventana larga de 784.800. Un límite de proveedor explícito más pequeño o límite de destino aún gana, incluidos los combos de alias nativos. -Sin un límite rígido configurado, el catálogo nativo mantiene el `max_context_window` anunciado separado del `context_window` predeterminado (para Astra, 872,000 frente a 272,000). La compactación sigue utilizando la ventana por defecto efectiva. Para dar un modelo 500.000 tokens y los otros 300.000, establece `providers.openai.contextWindow` a `300000` y `providers.openai.modelContextWindows` a `{ "gpt-6.1-sol": 500000 }`. El valor por modelo anula la ventana del proveedor; `providerContextCaps.openai`, cuando está habilitado, sigue siendo un techo para cada modelo nativo y debe ser al menos `500000` para este ejemplo. La capacidad de cada modelo limita el resultado. +Sin un límite rígido configurado, el catálogo nativo mantiene el `max_context_window` anunciado separado del `context_window` predeterminado (para Astra, 872 000 frente a 272 000). La compactación usa la ventana predeterminada efectiva. Para asignar 500 000 tokens a un modelo y 300 000 a los demás, establece `providers.openai.contextWindow` a `300000` y `providers.openai.modelContextWindows` a `{ "gpt-6.1-sol": 500000 }`. El valor por modelo anula la ventana del proveedor; `providerContextCaps.openai`, cuando está habilitado, sigue siendo un techo para cada modelo nativo y debe ser al menos `500000` para este ejemplo. La capacidad de cada modelo limita el resultado. La fila API tiene 1.050.000 contextos, 922.000 entradas máximas, 128.000 salidas máximas, entradas de texto/imagen y API esfuerzos de razonamiento a través de `max`. El control Ultra sintético enrutado de OpenCodex conserva su mapeo de esfuerzo de cable existente; no es un esfuerzo adicional de API. No hay alias Astra `-pro`. Utilice la configuración `fastMode` existente, o Codex `service_tier = "fast"` con `[features].fast_mode = true`; API `fast` y `priority` se aceptan ortografía rápida. @@ -154,8 +154,8 @@ La fila API tiene 1.050.000 contextos, 922.000 entradas máximas, 128.000 salida | Modelo | Contexto predeterminado | Techo opt-in | Esfuerzo predeterminado | Razonamiento escalera | | --- | ---: | ---: | --- | --- | -| `gpt-6-sol` | 272,000 | 872,000 | `medium` | `low` hasta `ultra` | -| `gpt-6-luna` | 272,000 | 872,000 | `medium` | `low` a `max` (n.o `ultra`) | +| `gpt-6-sol` | 272 000 | 872 000 | `medium` | `low` hasta `ultra` | +| `gpt-6-luna` | 272 000 | 872 000 | `medium` | `low` a `max` (n.o `ultra`) | [GPT-6.2 Sol](https://developers.openai.com/api/docs/models/gpt-6.2-sol) y [GPT-6.2 Astra](https://developers.openai.com/api/docs/models/gpt-6.2-astra) están disponibles como modelos @@ -169,9 +169,9 @@ y el valor predeterminado es `low`. En la API, va de `low` a `max`. | Modelo | Contexto predeterminado | Techo opt-in | Esfuerzo predeterminado | Razonamiento escalera | | --- | ---: | ---: | --- | --- | -| `gpt-6.1-sol` | 500,000 | 872,000 | `low` | `low` hasta `ultra` | +| `gpt-6.1-sol` | 500 000 | 872 000 | `low` | `low` hasta `ultra` | -OpenAI elevó el contexto predeterminado de GPT-6.1 Sol en Codex y Work de 272,000 a 500,000 tokens el 11 de octubre de 2026, por lo que la fila nativa ahora se establece en 500,000 y se compacta en 450,000. OpenCodex aplica 500.000 tokens a partir de la entrada histórica de 272.000. Una ventana configurada o tapa del proveedor todavía lo baja, y el opt-in de ventana larga todavía se detiene en 872,000: OpenAI describe el máximo del modelo como 1M sin decir cómo se mapea en los límites de ventana y entrada de Codex, por lo que opencodex no anuncia más que el techo que puede verificar. +OpenAI elevó el contexto predeterminado de GPT-6.1 Sol en Codex y Work de 272 000 a 500 000 tokens el 11 de octubre de 2026. La entrada nativa ahora usa 500 000 tokens y compacta a los 450 000. OpenCodex aplica 500 000 tokens a partir de la entrada histórica de 272 000. La ventana configurada o el límite del proveedor aún pueden reducirlo. La ventana larga opcional sigue limitada a 872 000 tokens: OpenAI describe el máximo del modelo como 1M sin decir cómo se mapea en los límites de ventana y entrada de Codex, por lo que opencodex no anuncia más que el techo que puede verificar. Las mismas palancas `providerContextCaps.openai`, `modelContextWindows` y `modelAutoCompactTokenLimits` se aplican como para Astra. En el OpenAI API (`openai-apikey`), `gpt-6.1-sol` tiene 1.050.000 contextos, 922.000 entradas máximas, 128.000 salidas máximas y esfuerzos `low` a `max`, con un precio de $2 entradas, $0.10 entradas en caché y $10 salidas por 1 millón de tokens (provoca más de 272K billetes a la tasa de contexto largo). GitHub Copilot, OpenRouter, Vercel AI Gateway, Kilo y OpenCode Zen también lo enumeran. @@ -190,7 +190,7 @@ Cuando OpenAI envía un modelo GPT que esta versión aún no conoce, agréguelo } ``` -Cada una de las `gpt-*` id listadas allí en el proveedor de inicio de sesión Codex aparece como un modelo nativo (aquí **GPT-6-Nova**) con la escalera de razonamiento, el esfuerzo predeterminado y las modalidades de Sol GPT-6.1, un contexto predeterminado de 272,000 tokens y un techo de aceptación de 872,000 tokens. Elevar o estrechar con `modelContextWindows`, por ejemplo `"modelContextWindows": { "gpt-6-nova": 872000 }`. Nunca está cerrado por cuenta: si su cuenta no puede usar el modelo, la solicitud aún se apaga y verá el error de subida. Los identificadores que ya están incorporados se ignoran, y al eliminar un id de la lista se elimina el modelo. Un combo `nativeAlias` no puede apuntar a un identificador configurado. +Cada una de las `gpt-*` id listadas allí en el proveedor de inicio de sesión Codex aparece como un modelo nativo (aquí **GPT-6-Nova**) con la escalera de razonamiento, el esfuerzo predeterminado y las modalidades de Sol GPT-6.1, un contexto predeterminado de 272 000 tokens y un límite de aceptación de 872 000 tokens. Elevar o estrechar con `modelContextWindows`, por ejemplo `"modelContextWindows": { "gpt-6-nova": 872000 }`. Nunca está cerrado por cuenta: si su cuenta no puede usar el modelo, la solicitud aún se apaga y verá el error de subida. Los identificadores que ya están incorporados se ignoran, y al eliminar un id de la lista se elimina el modelo. Un combo `nativeAlias` no puede apuntar a un identificador configurado. `gpt-6-astra-minor` (**GPT-6-Astra-Minor**) es una variante inédita de Astra. Está cerrado por cuenta: permanece oculto y las solicitudes se rechazan localmente, hasta que una lista autenticada de Codex para su cuenta lo enumera. Cuando aparece utiliza el contexto, la escalera y las modalidades de Astra. @@ -297,7 +297,7 @@ Los proveedores pueden exponer una abreviatura incorporada, como `agy` para `goo | `modelPreferHostedTools?` | `Record` | Opción de modelo exacto para puertas de enlace Responses no directas que reservan un espacio de nombres de herramienta alojada. Actualmente solo acepta `["image_generation"]`; un modelo coincidente debe usar el `openai-responses` cable y soporte de esa herramienta alojada. Elimina el cliente en colisión `image_gen` declaraciones y reescribe sus selectores para preservar la elección de la herramienta de llamadas. Para OpenAI virtual API `-pro` modelos, el ID público seleccionado se empareja primero y el ID de modelo de cable base resuelto es un respaldo. `modelAdapters` primero resuelve el ID público, luego el ID base; la segunda resolución determina el cable final. Otros modelos conservan el comportamiento normal de alias. | | `annotateEmptyToolOutputs?` | `boolean` | Reemplace un resultado de herramienta presente pero vacío con un marcador corto antes de que llegue al modelo, de modo que un resultado en blanco no se lea como faltante. Se aplica a cadenas en blanco y matrices de partes de solo texto; nunca se tocan imágenes, archivos y partes cifradas. Predetermina a `true` para DeepSeek desde el registro integrado y no se establece de otro modo. Establecer `false` para excluir a un proveedor - un `false` explícito se conserva en ediciones posteriores que omiten el campo. `PATCH /api/providers?name=` acepta `true`, `false` o `null` para borrar la anulación y volver al comportamiento predeterminado del registro. | | `promoteAdditionalTools?` | `boolean` | Controla si los elementos `additional_tools` de Codex Desktop se convierten en declaraciones `tools` de nivel superior y se retira su envoltorio de `input`. Se activa automáticamente para OpenCode Go y xAI (`api.x.ai` y `cli-chat-proxy.grok.com`), salvo con `authMode: "forward"`, donde requiere `true` explícito. Otros gateways estrictos de terceros compatibles con OpenAI que devuelvan HTTP 422 por tipos de elemento desconocidos en `input` pueden activarlo aquí. `PATCH /api/providers?name=` acepta un booleano o `null` para borrar la opción. | -| `unsupportedHostedTools?` | `string[]` | La herramienta alojada declara que este destino Responses rechaza, por lo que se eliminan de `tools`, desde el cliente-cargado `additional_tools`, y desde `tool_choice` En lugar de ser reenviado y rechazado de origen. Utilícelo para una puerta de enlace compatible con OpenAI con un conjunto de capacidades más estrecho — que acepte solicitudes simples Responses y `function` herramientas, pero devuelve HTTP 400 para alojado `web_search` — para que un mensaje de solo texto no falle por una capacidad que nunca necesitó. Acepta solo nombres de tipo de herramienta alojados (`web_search`, `web_search_preview`, `file_search`, `computer_use_preview`, `computer_use`, `code_interpreter`, `image_generation`, `image_gen`, `mcp`, `tool_search`, `local_shell`, `x_search`); un nombre no reconocido es rechazado en lugar de silenciosamente ignorado. Las variantes de ortografía de una capacidad se aliased, así que `["web_search"]` También niega `web_search_preview`. Un proveedor no puede negar una herramienta alojada aquí y preferirla en `modelPreferHostedTools`. Xiaomi MiMo Responses destinos (`xiaomimimo.com` y sus subdominios, incluyendo `api.xiaomimimo.com` y `token-plan-cn.xiaomimimo.com`) automáticamente tira `web_search` y `web_search_preview` conservando las herramientas de función; no se necesita ninguna declaración para estos hosts. Esto es independiente de `supportsResponsesCustomTools`; establece ambos para una puerta de enlace que también rechaza las herramientas personalizadas nativas. `PATCH /api/providers?name=` Acepta una matriz o `null` No lo puedo evitar. | +| `unsupportedHostedTools?` | `string[]` | La herramienta alojada declara que este destino Responses rechaza, por lo que se eliminan de `tools`, desde el cliente-cargado `additional_tools`, y desde `tool_choice` En lugar de ser reenviado y rechazado de origen. Utilícelo para una puerta de enlace compatible con OpenAI con un conjunto de capacidades más estrecho — que acepte solicitudes simples Responses y `function` herramientas, pero devuelve HTTP 400 para alojado `web_search` — para que un mensaje de solo texto no falle por una capacidad que nunca necesitó. Acepta solo nombres de tipo de herramienta alojados (`web_search`, `web_search_preview`, `file_search`, `computer_use_preview`, `computer_use`, `code_interpreter`, `image_generation`, `image_gen`, `mcp`, `tool_search`, `local_shell`, `x_search`); un nombre no reconocido es rechazado en lugar de silenciosamente ignorado. Las variantes de un mismo nombre se tratan como equivalentes, así que `["web_search"]` también excluye `web_search_preview`. Un proveedor no puede negar una herramienta alojada aquí y preferirla en `modelPreferHostedTools`. Xiaomi MiMo Responses destinos (`xiaomimimo.com` y sus subdominios, incluyendo `api.xiaomimimo.com` y `token-plan-cn.xiaomimimo.com`) automáticamente tira `web_search` y `web_search_preview` conservando las herramientas de función; no se necesita ninguna declaración para estos hosts. Esto es independiente de `supportsResponsesCustomTools`; establece ambos para una puerta de enlace que también rechaza las herramientas personalizadas nativas. `PATCH /api/providers?name=` acepta una lista o `null` para borrar el valor. | | `unsupportedHostedToolsWithClientTools?` | `string[]` | Herramientas alojadas que se eliminan solo si hay herramientas del cliente en la misma solicitud: `function`, `custom` o `namespace` con miembros, en `tools`, `additional_tools` o un resultado `tool_search_output`. Se retiran de esos campos y de `tool_choice` como con `unsupportedHostedTools`; forzar una eliminada pasa a `"none"`. Las solicitudes con solo herramientas alojadas las conservan. Úsalo para gateways que rechazan HTTP 400 al combinar funciones y búsqueda alojada, por ejemplo `Please enable tool_config.include_server_side_tool_invocations to use Built-in tools with Function calling.`. Admite los mismos nombres y alias que `unsupportedHostedTools`; rechaza desconocidos. Esa lista siempre prevalece y tampoco puede preferirse aquí una herramienta mediante `modelPreferHostedTools`. Ausente o `[]` no cambia nada; `PATCH /api/providers?name=` acepta lista o `null`. | | `reasoningEffortMap?` | `Record` | Alias de cable de todo el proveedor para etiquetas de razonamiento. Asignar una etiqueta a `"__omit__"` para eliminar el campo de razonamiento de la solicitud aguas arriba por completo: `reasoning_effort` en un cable compatible con OpenAI, y el campo nativo `think` de Ollama en el adaptador nativo Ollama (#2356). | | `modelReasoningEffortMap?` | `Record>` | Alias de cable por modelo para etiquetas de razonamiento. Asignar una etiqueta a `"__omit__"` para eliminar por completo el campo de razonamiento de la solicitud ascendente. | @@ -1236,12 +1236,27 @@ Para un selector nativo-primero, incluya los identificadores nativos en `modelPi ## Mensajes de agentes enrutados -Con el [`openai-responses` adaptador](/es/reference/adapters/#openai-responses), Codex -`agent_message` Los elementos que contienen matrices no vacías de partes de texto plano admitidas se convierten en mensajes de usuario cuando `authMode` no es `"forward"` -(Por ejemplo, `"key"`) Proveedores que utilizan `authMode: "forward"` mantener estos elementos sin cambios. -`agent_message` es privado al backend ChatGPT Codex, y los destinos enrutados reportado hasta el momento responder a toda la solicitud con -`422 unknown item type "agent_message"`; Codex reproduce el historial de subagentes en cada giro posterior, por lo que el hilo sigue fallando hasta que se convierte el elemento. El autor y el destinatario siguen siendo metadatos de texto explícito, y se conservan las partes del contenido. Para HTTPS `api.x.ai` y `cli-chat-proxy.grok.com` en el puerto estándar, no hacia adelante El despacho Responses también acepta un resultado hijo de cadena no en blanco y lo convierte en uno -`input_text` parte. La cadena original, incluyendo el espacio en blanco y las líneas nuevas, se conserva. Otros destinos mantienen sin cambios los mensajes de agente con valor de cadena. Vacío o Las cadenas de solo espacio en blanco permanecen sin cambios, al igual que las formas incompletas y mezcladas cifradas/desconocidas. El contenido encriptado y desconocido no está normalizado; las tareas encriptadas nativas aún requieren el opt-in separado [recuperación de tareas](/es/reference/configuration/agents/#encrypted-v2-task-recovery). +Con el [adaptador `openai-responses`](/es/reference/adapters/#openai-responses), los elementos +`agent_message` de Codex se convierten en mensajes de usuario si contienen una lista no vacía +de partes admitidas (`input_text`, `input_image` o `input_file`) y `authMode` no es `"forward"` +(por ejemplo, `"key"`). +Los proveedores que usan `authMode: "forward"` conservan estos elementos sin cambios. +`agent_message` es un tipo privado del backend de ChatGPT Codex. Los destinos enrutados +observados hasta ahora rechazan toda la solicitud con `422 unknown item type "agent_message"`. +Como Codex reproduce el historial de subagentes en cada turno, el hilo sigue fallando hasta +que se convierte el elemento. Se conservan las partes del contenido, y el autor y el +destinatario siguen siendo metadatos de texto explícitos. + +Para `api.x.ai`, `us.api.x.ai` y `cli-chat-proxy.grok.com` por HTTPS en el puerto estándar, el envío de +Responses sin reenvío de autenticación también convierte un resultado de subagente que sea +una cadena con contenido en una sola parte `input_text`. La cadena original conserva sus +espacios y saltos de línea. Los demás destinos mantienen los mensajes con valor de cadena +sin cambios. Las cadenas vacías o con solo espacios en blanco se conservan tal como llegan, +igual que las listas de contenido vacías y las que mezclan partes cifradas o desconocidas. Una +lista no vacía cuyas partes usan todas un tipo admitido se convierte tal como llega, aunque a +una parte le falte su campo esperado. El contenido +cifrado o desconocido no se normaliza; las tareas cifradas nativas siguen requiriendo activar +por separado la [recuperación de tareas](/es/reference/configuration/agents/#encrypted-v2-task-recovery). Con la recuperación de tareas habilitada, los elementos `NEW_TASK`, `MESSAGE`, `FOLLOWUP_TASK` y `FINAL_ANSWER` reutilizan una asignación en caché solo después de validar el llamador y coincidir con el alcance del subproceso principal. La restauración de reproducción no realiza una nueva solicitud de recuperación ni extiende la caducidad de la caché. El texto cifrado caducado o no visto no se reemplaza. Los nuevos elementos cifrados `NEW_TASK`, `MESSAGE`, `FOLLOWUP_TASK` y `FINAL_ANSWER` utilizan la misma ruta de recuperación opt-in, incluida la entrega `send_message` de padres nativos. El tipo de mensaje, el remitente, el destinatario, el alcance principal y las credenciales del llamante siguen siendo parte de la validación o la identidad de caché. Un `FINAL_ANSWER` sin una línea `Task name` no tiene ninguna dirección de cabecera para verificar, pero su destinatario todavía explora la caché. diff --git a/docs-site/src/content/docs/es/reference/configuration/routing.md b/docs-site/src/content/docs/es/reference/configuration/routing.md index 73fd6b2bf0e..0eb7fff19aa 100644 --- a/docs-site/src/content/docs/es/reference/configuration/routing.md +++ b/docs-site/src/content/docs/es/reference/configuration/routing.md @@ -269,7 +269,7 @@ Ambos son espacios de nombres virtuales con alias y validación de colisión; di El combo puede seguir disponible por su identificador aunque quede fuera de `ocx sync`, `/v1/models` o del selector de Codex. Para publicarlo se requieren: -- un `contextWindow` positivo, a partir de metadatos activos, sugerencias de registro, proveedor `modelContextWindows` / `contextWindow`, un `maxInputTokens` positivo conocido en la fila de miembros, o - cuando el proveedor es conocido y habilitado pero cada fuente aún omite una ventana - una reserva conservadora de 128,000 tokens (fijada por `providerContextCaps` cuando se establece); y +- un `contextWindow` positivo, a partir de metadatos activos, sugerencias de registro, proveedor `modelContextWindows` / `contextWindow`, un `maxInputTokens` positivo conocido en la fila de miembros, o - cuando el proveedor es conocido y habilitado pero cada fuente aún omite una ventana - una reserva conservadora de 128 000 tokens (fijada por `providerContextCaps` cuando se establece); y - una intersección `inputModalities` no vacía, tratando un valor de miembro omitido como `["text"]`. Un combo con `capabilityPolicy: "union"` requiere una unión publicada no vacía y excluye el vídeo. Consulta [Capacidades de unión](/es/guides/combos/#union-capabilities-capabilitypolicy). diff --git a/docs-site/src/content/docs/es/reference/proxy-formats.md b/docs-site/src/content/docs/es/reference/proxy-formats.md index 9c272a0f37c..bc646a9d9a6 100644 --- a/docs-site/src/content/docs/es/reference/proxy-formats.md +++ b/docs-site/src/content/docs/es/reference/proxy-formats.md @@ -628,8 +628,16 @@ La historia también se maneja, y de manera diferente, porque perder un mensaje Un elemento de razonamiento repetido lleva `encrypted_content` que solo el proveedor y la credencial que lo produjo pueden leer. Cuando opencodex sabe que la conversación fue atendida por última vez por un proveedor diferente, elimina esa mancha antes de enviarla y guarda el resumen del artículo. Si ese proveedor también usó un punto final o una credencial diferente, el identificador `rs_…` del elemento también se elimina, porque nombra un elemento que el nuevo destino no puede buscar. Cuando no puede saber, por ejemplo después de un reinicio proxy, el nuevo destino rechaza el blob en su lugar: OpenAI y Azure OpenAI responden `400 invalid_encrypted_content`. opencodex luego reenvía la solicitud una vez sin el estado de razonamiento del proveedor anterior. El blob se va, y también lo hace el id `rs_…` del elemento de razonamiento, porque ese id nombra un elemento que el proveedor anterior almacenó y el nuevo destino respondería `Item with id 'rs_…' not found`. -Esta recuperación se aplica a todos los adaptadores que hablan el cable Responses, así `openai-responses` y -`azure-openai` Comportarse de la misma manera. Después de una recuperación exitosa, los giros posteriores de esa conversación en el mismo destino, deje caer el estado extranjero antes del primer envío para los próximos cinco minutos, sin otro viaje rechazado. El reenvío cuenta con el presupuesto de envío normal de la solicitud. Un ordinario 400 y un 429 nunca se vuelven a intentar de esta manera, y tampoco lo es un 5xx, con una estrecha. excepción: un 502 cuyo cuerpo es la herramienta encriptada exacta descifra el rechazo, enviado para una solicitud que lleva la salida de la herramienta cifrada, obtiene el mismo reenvío único. Un segundo rechazo llega a cliente sin cambios. Si eso sucede, inicie una nueva conversación en el proveedor de destino. +Esta recuperación se aplica a todos los adaptadores que usan el protocolo Responses, +incluidos `openai-responses` y `azure-openai`. Si la recuperación funciona, durante los +siguientes cinco minutos el proxy elimina el estado del proveedor anterior antes del +primer envío de cada turno de esa conversación al mismo destino. Así evita otro rechazo. +El reenvío cuenta dentro del límite habitual de envíos de la solicitud. Las respuestas +400 comunes, 429 y 5xx no se reintentan de esta manera, salvo un caso: si una solicitud +lleva una salida de herramienta cifrada y recibe un 502 cuyo cuerpo coincide exactamente +con el rechazo de descifrado de esa salida, se hace el mismo reenvío único. Un segundo +rechazo se entrega al cliente sin cambios. Si ocurre, inicia una nueva conversación en +el proveedor de destino. diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md index 47eec96a7b0..1e54553e9f4 100644 --- a/docs-site/src/content/docs/guides/codex-integration.md +++ b/docs-site/src/content/docs/guides/codex-integration.md @@ -1548,7 +1548,7 @@ When an affected history store supports paginated records, a provider transition When returning to the root-override form, OpenCodex retains an existing `[model_providers.opencodex]` definition before committing the configuration, even if history preflight currently passes. This keeps older `opencodex` conversations resolvable if Codex migrates history after that commit or while the background worker starts. New conversations still use the selected root provider; explicit restore keeps its separate removal guards. -`ocx restore`, `ocx stop` and `ocx uninstall` no longer refuse on `history_paginated_requires_native_writer`. They take every OpenCodex root routing key out and keep the `[model_providers.opencodex]` definition on disk, so conversations whose rows still name that provider keep resolving while plain `codex` stops pointing at the proxy. The result is reported as a partial restore that names the retained lines, and `ocx restore --remove-codex-provider-table` removes them too, after which those conversations stop opening. +`ocx restore`, `ocx stop` and `ocx uninstall` no longer refuse on `history_paginated_requires_native_writer`. They remove OpenCodex's root routing keys, so `codex` stops using the proxy by default. They keep the `[model_providers.opencodex]` definition so conversations that still name it keep a provider that exists. Codex 0.166 and later open such a conversation only while `opencodex` is the current provider, so after the restore it reopens only once `opencodex` is selected as the provider again. If the retained table still points to the proxy, sending new requests from those conversations still requires the proxy to be reachable. The result is reported as a partial restore that names the retained lines, and `ocx restore --remove-codex-provider-table` removes them too, after which those conversations stop opening. Enabling the integration in its provider-table form on a home whose `openai`-tagged conversations Codex has already paginated used to be refused outright with `history_paginated_openai_requires_native_writer`: nothing was written and the integration stayed disabled. OpenCodex now completes that transition by keeping the managed root `openai_base_url` override beside the `[model_providers.opencodex]` table. Codex merges the override onto its built-in `openai` provider, so those conversations keep reaching the proxy without being relabeled and no rollout byte or thread row is touched. Only a routing form that requires the `x-opencodex-api-key` admission header still refuses, because Codex's built-in provider cannot carry that header; its message names the two settings that resolve it — route Codex through the loopback listener so the override can be retained, or set `syncResumeHistory` to `false` to accept that those conversations resume against Codex's own OpenAI endpoint. diff --git a/docs-site/src/content/docs/guides/web-dashboard.md b/docs-site/src/content/docs/guides/web-dashboard.md index 88ba70ff136..a985dd41982 100644 --- a/docs-site/src/content/docs/guides/web-dashboard.md +++ b/docs-site/src/content/docs/guides/web-dashboard.md @@ -121,8 +121,8 @@ host and port over a LAN IP or an alias. ## Classic dashboard -The dashboard was redesigned: its sidebar now groups pages into **Everyday**, **Set up** and -**Fine-tuning**, and it opens on a Home page. The previous design stays available as the +The current dashboard opens on **Home**. Its sidebar groups pages into **Everyday** and +**Fine-tuning**. **Route** opens client integrations and has a separate setup tab. The previous design stays available as the **classic dashboard** at `/classic/` on the same proxy, for example `http://127.0.0.1:10100/classic/`. - To switch, select the clock icon (**Classic dashboard**) beside the theme switch at the foot of @@ -299,10 +299,11 @@ historical records beyond the loaded ring. The language picker includes **Português** (Brazilian Portuguese, `pt-BR`). Portuguese browser languages select it automatically unless a supported language preference is already saved. +**Español** uses neutral Spanish. Spanish browser locales such as `es-BO`, `es-MX` and `es-ES` select it automatically unless a supported `ocx-lang` preference is already saved. The document language is `es`, and quota dates use Spanish regional formatting. + ### Linking to a section -There is a single layout, so there is no layout switch to configure. Dashboard sections are -addressable instead: `#dashboard` opens Overview, and `#dashboard/providers` and +Dashboard sections have direct links: `#dashboard` opens Overview, and `#dashboard/providers` and `#dashboard/models` open the other two. Reload, bookmark, and Back all keep the section you were on. **Logs** works the same way with `#logs` and `#logs/debug`. An older `#providers/workspace` bookmark now lands on `#providers`. diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index a2567b88b82..1bd71b3bf76 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -860,18 +860,18 @@ ocx catalog pull https://proxy.example.com/v1/catalog \ The value is sent as a Bearer token but is never accepted as an argv value. Redirects are refused, so authorization cannot cross origins. Catalog and cache writes use the shared Codex catalog lock and atomic writer. A failed fetch, validation, lock acquisition, catalog write, or cache rebuild -preserves the last-known-good files. Identical catalog bytes are a no-op that preserves mtimes and -never touches processes. `--restart-codex`, `--restart-app-server-only`, and the deprecated -`--restart-desktop-app` alias mean the same thing here as they do on `ocx sync` and -`ocx sync-cache`, and they apply only after a real write. +preserves the last-known-good files. `--restart-codex`, `--restart-app-server-only`, and the +deprecated `--restart-desktop-app` alias select the same processes as on `ocx sync` and +`ocx sync-cache`. For a catalog pull, they apply only when the catalog itself is written. The URL must name `/v1/catalog` at the host root. A reverse proxy that serves the endpoint under a path prefix is not supported by this command. The command downloads the full catalog and compares bytes locally instead of issuing an `ETag` / -`If-None-Match` conditional request. Identical bytes are treated as a complete no-op, so a -Codex home whose catalog is correct but whose `models_cache.json` is missing or stale is not -repaired by this command; use `ocx sync-cache` for that. +`If-None-Match` conditional request. Identical catalog bytes leave the catalog file untouched. +The command still repairs a missing or stale `models_cache.json`; in that case, the result can +report `status: "unchanged"` with `cacheSynced: true`. If both files already match, their +modification times are unchanged. `--json` emits one stable envelope on stdout. `schemaVersion`, `ok`, `status`, `catalogWritten`, `cacheSynced`, and `codexRestarted` are always present. `codexRestarted` still means app-servers diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index 880b0c531e6..7aae88e2ed4 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -1830,18 +1830,21 @@ See the [reasoning-effort diagnostic limits](/guides/providers/#reasoning-effort ## Routed agent messages With the [`openai-responses` adapter](/reference/adapters/#openai-responses), Codex -`agent_message` items containing nonempty arrays of supported plaintext parts become user messages when `authMode` is not `"forward"` -(for example, `"key"`). Providers using `authMode: "forward"` retain these items unchanged. +`agent_message` items containing nonempty arrays of supported parts (`input_text`, `input_image` +or `input_file`) become user messages when `authMode` is not `"forward"` (for example, `"key"`). +Providers using `authMode: "forward"` retain these items unchanged. `agent_message` is private to the ChatGPT Codex backend, and the routed destinations reported so far answer the whole request with `422 unknown item type "agent_message"`; Codex replays sub-agent history on every subsequent turn, so the thread keeps failing until the item is converted. Author and recipient remain explicit text metadata, and the content parts are preserved. -For HTTPS `api.x.ai` and `cli-chat-proxy.grok.com` on the standard port, non-forward +For HTTPS `api.x.ai`, `us.api.x.ai` and `cli-chat-proxy.grok.com` on the standard port, non-forward Responses dispatch also accepts a nonblank string child result and turns it into one `input_text` part. The original string, including leading/trailing whitespace and newlines, is preserved. Other destinations keep string-valued agent messages unchanged. Empty or -whitespace-only strings remain unchanged, as do incomplete and mixed encrypted/unknown shapes. +whitespace-only strings remain unchanged, as do empty content arrays and arrays that mix in +encrypted or unknown parts. A nonempty array whose parts all use a supported type is converted +as sent, even when a part lacks its expected field. Encrypted and unknown content is not normalized; native encrypted tasks still require the separate opt-in [task recovery](/reference/configuration/agents/#encrypted-v2-task-recovery). diff --git a/gui/classic/index.html b/gui/classic/index.html index c827eaa6329..72b7d0c49d3 100644 --- a/gui/classic/index.html +++ b/gui/classic/index.html @@ -20,6 +20,7 @@ // Mirrors detectInitial() + LOCALES in src/i18n/shared.ts. var langMap = { en: "en", de: "de", fr: "fr", ko: "ko", zh: "zh-CN", "zh-TW": "zh-TW", ru: "ru", ja: "ja", tr: "tr", vi: "vi" }; langMap.pt = "pt-BR"; + langMap.es = "es"; var stored = null; try { stored = localStorage.getItem("ocx-lang"); @@ -31,6 +32,8 @@ var nav = (navigator.language || "en").toLowerCase(); if (nav.indexOf("zh") === 0) { locale = /tw|hk|mo|hant/.test(nav) ? "zh-TW" : "zh"; + } else if (/^es(?:-|$)/.test(nav)) { + locale = "es"; } else { locale = ["de", "fr", "ko", "ru", "ja", "tr", "vi", "pt"].filter(function (c) { return nav.indexOf(c) === 0; })[0] || "en"; } diff --git a/gui/index.html b/gui/index.html index 85e8946ee19..adb188a06c2 100644 --- a/gui/index.html +++ b/gui/index.html @@ -20,6 +20,7 @@ // Mirrors detectInitial() + LOCALES in src/i18n/shared.ts. var langMap = { en: "en", de: "de", fr: "fr", ko: "ko", zh: "zh-CN", "zh-TW": "zh-TW", ru: "ru", ja: "ja", tr: "tr", vi: "vi" }; langMap.pt = "pt-BR"; + langMap.es = "es"; var stored = null; try { stored = localStorage.getItem("ocx-lang"); @@ -31,6 +32,8 @@ var nav = (navigator.language || "en").toLowerCase(); if (nav.indexOf("zh") === 0) { locale = /tw|hk|mo|hant/.test(nav) ? "zh-TW" : "zh"; + } else if (/^es(?:-|$)/.test(nav)) { + locale = "es"; } else { locale = ["de", "fr", "ko", "ru", "ja", "tr", "vi", "pt"].filter(function (c) { return nav.indexOf(c) === 0; })[0] || "en"; } diff --git a/gui/scripts/sync-locale-keys.mjs b/gui/scripts/sync-locale-keys.mjs index cacb1fc4810..e37dbb1b325 100644 --- a/gui/scripts/sync-locale-keys.mjs +++ b/gui/scripts/sync-locale-keys.mjs @@ -1,17 +1,20 @@ /** - * Copy missing keys from en.ts into de/fr/ko/zh/zh-TW/ru/ja/tr (English fallback for new keys). + * Copy missing English keys into the base locale catalogs (to be translated before shipping). */ -import { readFileSync, writeFileSync } from "node:fs"; -import { fileURLToPath } from "node:url"; +import { readFileSync, readdirSync, writeFileSync } from "node:fs"; +import { fileURLToPath, pathToFileURL } from "node:url"; import { dirname, join } from "node:path"; import { en } from "../src/i18n/en.ts"; -const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const directory = join(dirname(fileURLToPath(import.meta.url)), "..", "src", "i18n"); -for (const loc of ["de", "fr", "ko", "zh", "zh-TW", "ru", "ja", "tr"]) { - const path = join(root, "src", "i18n", `${loc}.ts`); - let text = readFileSync(path, "utf8"); - const missing = Object.entries(en).filter(([key]) => !text.includes(`"${key}":`)); +for (const file of readdirSync(directory).filter(file => /^(?!en\.ts$)[a-z]{2}(?:-[A-Z]{2})?\.ts$/.test(file)).sort()) { + const loc = file.slice(0, -3); + const path = join(directory, file); + // A spread from a shared copy table counts as a translation. Inspect the base + // catalog itself so runtime overlays cannot hide keys missing from the file. + const catalog = (await import(pathToFileURL(path).href))[loc === "zh-TW" ? "zhTW" : loc]; + const missing = Object.entries(en).filter(([key]) => !Object.hasOwn(catalog, key)); if (missing.length === 0) { console.log(`${loc}: up to date`); continue; @@ -20,14 +23,12 @@ for (const loc of ["de", "fr", "ko", "zh", "zh-TW", "ru", "ja", "tr"]) { .map(([key, value]) => ` "${key}": ${JSON.stringify(value)},`) .join("\n"); - if (text.includes("} as const;")) { - text = text.replace(/\n\} as const;/, `\n${block}\n} as const;`); - } else if (/\n\};\s*\n/.test(text) || /\n\};\s*$/.test(text)) { - text = text.replace(/\n\};\s*(?=\n|$)/, `\n${block}\n};\n`); - } else { + const text = readFileSync(path, "utf8"); + const close = /\r?\n\}(?: as const| satisfies Record)?;[ \t]*$/m; + if (!close.test(text)) { throw new Error(`${path}: missing closing brace for locale object`); } - - writeFileSync(path, text); + const newline = text.includes("\r\n") ? "\r\n" : "\n"; + writeFileSync(path, text.replace(close, closing => newline + block.replaceAll("\n", newline) + closing)); console.log(`${loc}: added ${missing.length} keys`); } diff --git a/gui/src/components/QuotaBars.tsx b/gui/src/components/QuotaBars.tsx index 02d65055898..6a19019df41 100644 --- a/gui/src/components/QuotaBars.tsx +++ b/gui/src/components/QuotaBars.tsx @@ -199,6 +199,8 @@ function bcp47(locale: Locale): string { return "de-DE"; case "fr": return "fr-FR"; + case "es": + return "es-ES"; case "ko": return "ko-KR"; case "zh": diff --git a/gui/src/components/provider-workspace/ProviderCapacityQuota.tsx b/gui/src/components/provider-workspace/ProviderCapacityQuota.tsx index 1138e8a4df5..a0a675266a7 100644 --- a/gui/src/components/provider-workspace/ProviderCapacityQuota.tsx +++ b/gui/src/components/provider-workspace/ProviderCapacityQuota.tsx @@ -21,6 +21,7 @@ function bcp47(locale: Locale): string { case "en": return "en-GB"; case "de": return "de-DE"; case "fr": return "fr-FR"; + case "es": return "es-ES"; case "ko": return "ko-KR"; case "zh": return "zh-CN"; case "zh-TW": return "zh-TW"; diff --git a/gui/src/i18n/account-probe-copy.ts b/gui/src/i18n/account-probe-copy.ts index cfd11e0fcd0..c83b36bbe43 100644 --- a/gui/src/i18n/account-probe-copy.ts +++ b/gui/src/i18n/account-probe-copy.ts @@ -1,62 +1,62 @@ -type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; -const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; -type Row = readonly [string, string, string, string, string, string, string, string, string, string, string]; +type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt" | "es"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt", "es"]; +type Row = readonly [string, string, string, string, string, string, string, string, string, string, string, string]; /** Per-account probe and manual model discovery copy, one row per key in `locales` order. */ const rows = { - "acctProbe.test": ["Test", "테스트", "Testen", "Tester", "测试", "測試", "Проверить", "テスト", "Test et", "Kiểm tra", "Testar"], - "acctProbe.testing": ["Testing…", "테스트 중…", "Wird getestet…", "Test en cours…", "测试中…", "測試中…", "Проверка…", "テスト中…", "Test ediliyor…", "Đang kiểm tra…", "Testando…"], - "acctProbe.testAll": ["Test all", "모두 테스트", "Alle testen", "Tout tester", "全部测试", "全部測試", "Проверить все", "すべてテスト", "Tümünü test et", "Kiểm tra tất cả", "Testar todas"], - "acctProbe.hint": ["Read-only: sends one quota request with this account's stored token. Expired tokens are reported, never refreshed.", "읽기 전용: 이 계정에 저장된 토큰으로 할당량 요청을 한 번 보냅니다. 만료된 토큰은 갱신하지 않고 그대로 보고합니다.", "Nur lesend: sendet eine Kontingentanfrage mit dem gespeicherten Token dieses Kontos. Abgelaufene Tokens werden gemeldet, nie erneuert.", "Lecture seule : envoie une requête de quota avec le jeton enregistré de ce compte. Un jeton expiré est signalé, jamais renouvelé.", "只读:用该账号已存的 token 发一次额度查询。token 已过期时只报告,不刷新。", "唯讀:用該帳號已存的 Token 送出一次額度查詢。Token 已過期時只回報,不刷新。", "Только чтение: один запрос квоты с сохранённым токеном аккаунта. Истёкший токен только отмечается, не обновляется.", "読み取り専用:このアカウントの保存済みトークンでクォータ要求を 1 回送ります。期限切れトークンは報告のみで更新しません。", "Salt okunur: bu hesabın kayıtlı belirteciyle bir kota isteği gönderir. Süresi dolmuş belirteç yenilenmez, yalnızca bildirilir.", "Chỉ đọc: gửi một yêu cầu hạn mức bằng token đã lưu của tài khoản. Token hết hạn chỉ được báo, không làm mới.", "Somente leitura: envia uma consulta de cota com o token salvo desta conta. Tokens expirados são informados, nunca renovados."], - "acctProbe.failed": ["Test request failed", "테스트 요청 실패", "Testanfrage fehlgeschlagen", "La requête de test a échoué", "测试请求失败", "測試請求失敗", "Запрос проверки не выполнен", "テスト要求に失敗しました", "Test isteği başarısız", "Yêu cầu kiểm tra thất bại", "Falha na solicitação de teste"], - "acctProbe.status.ok": ["Usable", "사용 가능", "Nutzbar", "Utilisable", "可用", "可用", "Работает", "利用可能", "Kullanılabilir", "Dùng được", "Utilizável"], - "acctProbe.status.paused": ["Paused (not tested)", "일시 중지됨(테스트 안 함)", "Pausiert (nicht getestet)", "En pause (non testé)", "已暂停(未测试)", "已暫停(未測試)", "Приостановлен (не проверялся)", "一時停止中(未テスト)", "Duraklatıldı (test edilmedi)", "Đã tạm dừng (không kiểm tra)", "Pausada (não testada)"], - "acctProbe.status.token_expired": ["Token expired (not refreshed)", "토큰 만료(갱신 안 함)", "Token abgelaufen (nicht erneuert)", "Jeton expiré (non renouvelé)", "token 已过期(未刷新)", "Token 已過期(未刷新)", "Токен истёк (не обновлён)", "トークン期限切れ(未更新)", "Belirteç süresi doldu (yenilenmedi)", "Token hết hạn (chưa làm mới)", "Token expirado (não renovado)"], - "acctProbe.status.suspended": ["Suspended", "정지됨", "Gesperrt", "Suspendu", "已暂停", "已暫停", "Приостановлен", "停止中", "Askıya alındı", "Bị đình chỉ", "Suspensa"], - "acctProbe.status.verification_required": ["Verification required", "인증 필요", "Verifizierung erforderlich", "Vérification requise", "要求验证", "需要驗證", "Требуется подтверждение", "確認が必要", "Doğrulama gerekli", "Cần xác minh", "Verificação necessária"], - "acctProbe.status.rate_limited": ["Rate limited", "요청 제한", "Ratenlimit", "Limite de débit", "限流", "限流", "Ограничение частоты", "レート制限", "Hız sınırı", "Bị giới hạn tốc độ", "Limite de taxa"], - "acctProbe.status.permission_denied": ["Permission denied (403)", "권한 거부(403)", "Zugriff verweigert (403)", "Accès refusé (403)", "权限拒绝(403)", "權限遭拒(403)", "Доступ запрещён (403)", "権限拒否(403)", "İzin reddedildi (403)", "Bị từ chối quyền (403)", "Permissão negada (403)"], - "acctProbe.status.error": ["Other error", "기타 오류", "Anderer Fehler", "Autre erreur", "其他错误", "其他錯誤", "Другая ошибка", "その他のエラー", "Diğer hata", "Lỗi khác", "Outro erro"], - "modelDiscover.now": ["Discover now", "지금 검색", "Jetzt abrufen", "Découvrir maintenant", "立即发现", "立即探索", "Найти сейчас", "今すぐ検出", "Şimdi keşfet", "Khám phá ngay", "Descobrir agora"], - "modelDiscover.running": ["Discovering…", "검색 중…", "Wird abgerufen…", "Découverte…", "发现中…", "探索中…", "Поиск…", "検出中…", "Keşfediliyor…", "Đang khám phá…", "Descobrindo…"], - "modelDiscover.recent": ["Recently added models", "최근 추가된 모델", "Kürzlich hinzugekommene Modelle", "Modèles ajoutés récemment", "最近新增的模型", "最近新增的模型", "Недавно добавленные модели", "最近追加されたモデル", "Son eklenen modeller", "Mô hình mới thêm gần đây", "Modelos adicionados recentemente"], - "modelDiscover.none": ["No new models recorded yet.", "아직 기록된 새 모델이 없습니다.", "Noch keine neuen Modelle erfasst.", "Aucun nouveau modèle enregistré pour l’instant.", "还没有记录到新模型。", "尚未記錄到新模型。", "Новые модели пока не обнаружены.", "新しいモデルはまだ記録されていません。", "Henüz yeni model kaydedilmedi.", "Chưa ghi nhận mô hình mới nào.", "Nenhum modelo novo registrado ainda."], - "modelDiscover.result": ["{count} live models, {added} new", "실시간 모델 {count}개, 새 모델 {added}개", "{count} Live-Modelle, {added} neu", "{count} modèles en direct, {added} nouveaux", "共 {count} 个在线模型,新增 {added} 个", "共 {count} 個線上模型,新增 {added} 個", "Моделей: {count}, новых: {added}", "ライブモデル {count} 件、新規 {added} 件", "{count} canlı model, {added} yeni", "{count} mô hình trực tiếp, {added} mới", "{count} modelos ativos, {added} novos"], - "modelDiscover.failed": ["Discovery failed", "검색 실패", "Abruf fehlgeschlagen", "Échec de la découverte", "发现失败", "探索失敗", "Поиск не удался", "検出に失敗しました", "Keşif başarısız", "Khám phá thất bại", "Falha na descoberta"], - "modelDiscover.inProgress": ["Model discovery is already in progress. Try again shortly.", "이미 모델을 검색하고 있습니다. 잠시 후 다시 시도하세요.", "Modelle werden bereits abgerufen. Versuche es in Kürze erneut.", "La découverte de modèles est déjà en cours. Réessayez dans un instant.", "正在发现模型,请稍后重试。", "正在探索模型,請稍後重試。", "Поиск моделей уже идёт. Повторите попытку чуть позже.", "モデルを検出中です。しばらくしてからもう一度お試しください。", "Model keşfi zaten devam ediyor. Biraz sonra tekrar deneyin.", "Đang khám phá mô hình. Hãy thử lại sau giây lát.", "A descoberta de modelos já está em andamento. Tente novamente em instantes."], - "modelDiscover.static": ["Live discovery is off for this provider.", "이 공급자는 실시간 검색이 꺼져 있습니다.", "Live-Abruf ist für diesen Anbieter aus.", "La découverte en direct est désactivée pour ce fournisseur.", "该供应商未开启在线发现。", "此供應商未開啟線上探索。", "Для этого провайдера поиск моделей отключён.", "このプロバイダーはライブ検出がオフです。", "Bu sağlayıcı için canlı keşif kapalı.", "Nhà cung cấp này đang tắt khám phá trực tiếp.", "A descoberta ao vivo está desativada para este provedor."], - "modelDiscover.autoDisabled": ["hidden by new-model policy", "새 모델 정책으로 숨김", "durch Neu-Modell-Richtlinie ausgeblendet", "masqué par la règle des nouveaux modèles", "按新模型策略已隐藏", "依新模型政策已隱藏", "скрыта политикой новых моделей", "新モデルポリシーで非表示", "yeni model politikasıyla gizlendi", "bị ẩn theo chính sách mô hình mới", "oculto pela política de novos modelos"], - "modelDiscover.new": ["NEW", "NEW", "NEU", "NOUVEAU", "新", "新", "НОВАЯ", "NEW", "YENİ", "MỚI", "NOVO"], - "acctTable.title": ["Account quotas", "계정 할당량", "Kontingente je Konto", "Quotas par compte", "账号额度", "帳號額度", "Квоты аккаунтов", "アカウント別クォータ", "Hesap kotaları", "Hạn mức theo tài khoản", "Cotas por conta"], - "acctTable.actions": ["Actions", "작업", "Aktionen", "Commandes", "操作", "操作", "Действия", "操作", "İşlemler", "Thao tác", "Ações"], - "acctTable.account": ["Account", "계정", "Konto", "Compte", "账号", "帳號", "Аккаунт", "アカウント", "Hesap", "Tài khoản", "Conta"], - "acctTable.plan": ["Plan", "플랜", "Tarif", "Forfait", "套餐", "方案", "План", "プラン", "Plan", "Gói", "Plano"], - "acctTable.status": ["Status", "상태", "Status", "État", "状态", "狀態", "Статус", "状態", "Durum", "Trạng thái", "Status"], - "acctTable.unknownPlan": ["Unknown plan", "알 수 없는 플랜", "Tarif unbekannt", "Forfait inconnu", "未知套餐", "未知方案", "План неизвестен", "プラン不明", "Plan bilinmiyor", "Không rõ gói", "Plano desconhecido"], - "acctTable.planSource": ["Upstream tier: {tier}", "업스트림 등급: {tier}", "Upstream-Stufe: {tier}", "Niveau amont : {tier}", "上游套餐字段:{tier}", "上游方案欄位:{tier}", "Тариф от провайдера: {tier}", "上流の階層: {tier}", "Üst kaynak katmanı: {tier}", "Hạng từ nhà cung cấp: {tier}", "Nível do provedor: {tier}"], - "acctTable.pool.gemini": ["Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini"], - "acctTable.pool.claudeGpt": ["Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT"], - "acctTable.pool.argon": ["Argon", "Argon", "Argon", "Argon", "Argon", "Argon", "Argon", "Argon", "Argon", "Argon", "Argon"], - "acctTable.pool.subscription": ["Subscription", "구독", "Abo", "Abonnement", "订阅额度", "訂閱額度", "Подписка", "サブスク", "Abonelik", "Gói đăng ký", "Assinatura"], - "acctTable.scarce": ["scarce", "희소", "knapp", "rare", "稀缺", "稀缺", "дефицит", "希少", "kıt", "khan hiếm", "escassa"], - "acctTable.fiveHour": ["5h", "5시간", "5 Std.", "5 h", "5 小时", "5 小時", "5 ч", "5時間", "5 sa", "5 giờ", "5 h"], - "acctTable.weekly": ["Week", "주간", "Woche", "Semaine", "每周", "每週", "Неделя", "週", "Hafta", "Tuần", "Semana"], - "acctTable.resetsIn": ["resets in {time}", "{time} 후 초기화", "Reset in {time}", "réinit. dans {time}", "{time} 后重置", "{time} 後重置", "сброс через {time}", "{time} 後リセット", "{time} sonra sıfırlanır", "đặt lại sau {time}", "reinicia em {time}"], - "acctTable.next": ["next", "다음", "als Nächstes", "suivant", "优先", "優先", "следующий", "次", "sıradaki", "kế tiếp", "próxima"], - "acctTable.nextHint": ["Resets soonest among usable accounts, so reset-first spends it first", "사용 가능한 계정 중 가장 먼저 초기화되어 reset-first가 먼저 사용합니다", "Wird unter nutzbaren Konten zuerst zurückgesetzt, daher nutzt reset-first es zuerst", "Se réinitialise en premier parmi les comptes utilisables : reset-first l’utilise d’abord", "在可用账号里最先重置,「最快重置优先」会先用它", "在可用帳號中最先重置,「最快重置優先」會先用它", "Сбрасывается раньше других доступных аккаунтов, поэтому reset-first расходует его первым", "使用可能なアカウントで最も早くリセットされるため、reset-first が先に使います", "Kullanılabilir hesaplar arasında ilk sıfırlanan; reset-first önce bunu kullanır", "Đặt lại sớm nhất trong các tài khoản dùng được, nên reset-first dùng trước", "Reinicia antes entre as contas utilizáveis, então reset-first a usa primeiro"], - "acctTable.noReading": ["No quota reading yet", "아직 할당량을 읽지 못함", "Noch kein Kontingent gelesen", "Aucun quota lu pour l’instant", "还没读到额度", "尚未讀到額度", "Квота ещё не прочитана", "クォータ未取得", "Henüz kota okunmadı", "Chưa đọc được hạn mức", "Cota ainda não lida"], - "acctTable.flag.ok": ["Healthy", "정상", "In Ordnung", "Sain", "正常", "正常", "Работает", "正常", "Sağlıklı", "Bình thường", "Saudável"], - "acctTable.flag.banned": ["Banned upstream", "업스트림 차단됨", "Upstream gesperrt", "Bloqué en amont", "已封禁", "已封禁", "Заблокирован", "上流で停止", "Upstream yasakladı", "Bị chặn phía upstream", "Bloqueada no upstream"], - "acctTable.flag.verify": ["Verification needed", "인증 필요", "Verifizierung nötig", "Vérification requise", "需验证", "需驗證", "Нужна проверка", "確認が必要", "Doğrulama gerekli", "Cần xác minh", "Verificação necessária"], - "acctTable.bannedRow": ["Upstream refused this account; automatic refresh is stopped", "업스트림이 이 계정을 거부해 자동 새로 고침을 멈췄습니다", "Upstream hat dieses Konto abgelehnt; automatische Aktualisierung gestoppt", "Le fournisseur a refusé ce compte ; actualisation automatique arrêtée", "账号已被上游封禁,已停止自动刷新", "帳號已被上游封禁,已停止自動重新整理", "Провайдер отклонил аккаунт; автообновление остановлено", "上流がこのアカウントを拒否したため自動更新を停止しました", "Upstream bu hesabı reddetti; otomatik yenileme durduruldu", "Upstream đã từ chối tài khoản này; đã dừng tự làm mới", "O upstream recusou esta conta; atualização automática parada"], - "acctTable.bannedReason": ["View reason", "사유 보기", "Grund anzeigen", "Voir le motif", "查看原因", "查看原因", "Причина", "理由を見る", "Nedeni gör", "Xem lý do", "Ver motivo"], - "acctTable.flag.paused": ["Paused", "일시 중지", "Pausiert", "En pause", "已暂停", "已暫停", "Приостановлен", "一時停止", "Duraklatıldı", "Đã tạm dừng", "Pausada"], - "acctTable.flag.reauth": ["Sign-in needed", "재로그인 필요", "Anmeldung nötig", "Connexion requise", "需重新登录", "需重新登入", "Нужен вход", "再ログインが必要", "Oturum açılmalı", "Cần đăng nhập lại", "Login necessário"], - "acctTable.flag.rateLimited": ["Rate limited", "요청 제한", "Ratenlimit", "Débit limité", "限流中", "限流中", "Ограничение частоты", "レート制限中", "Hız sınırında", "Bị giới hạn tốc độ", "Limite de taxa"], - "acctTable.flag.quotaLimited": ["Quota cooldown", "할당량 대기", "Kontingent-Pause", "Pause de quota", "额度冷却中", "額度冷卻中", "Квота на паузе", "クォータ待機中", "Kota beklemesi", "Đang chờ hạn mức", "Pausa de cota"], - "acctTable.flag.warning": ["Warning", "경고", "Warnung", "Alerte", "有警告", "有警告", "Предупреждение", "警告", "Uyarı", "Cảnh báo", "Aviso"], - "acctTable.flag.slow": ["Slow", "느림", "Langsam", "Lent", "响应慢", "回應慢", "Медленно", "遅い", "Yavaş", "Chậm", "Lenta"], - "acctTable.flag.stale": ["Quota not read", "할당량 미확인", "Kontingent nicht gelesen", "Quota non lu", "额度没读到", "額度沒讀到", "Квота не прочитана", "クォータ未取得", "Kota okunamadı", "Chưa đọc được hạn mức", "Cota não lida"], + "acctProbe.test": ["Test", "테스트", "Testen", "Tester", "测试", "測試", "Проверить", "テスト", "Test et", "Kiểm tra", "Testar", "Probar"], + "acctProbe.testing": ["Testing…", "테스트 중…", "Wird getestet…", "Test en cours…", "测试中…", "測試中…", "Проверка…", "テスト中…", "Test ediliyor…", "Đang kiểm tra…", "Testando…", "Probando…"], + "acctProbe.testAll": ["Test all", "모두 테스트", "Alle testen", "Tout tester", "全部测试", "全部測試", "Проверить все", "すべてテスト", "Tümünü test et", "Kiểm tra tất cả", "Testar todas", "Probar todas"], + "acctProbe.hint": ["Read-only: sends one quota request with this account's stored token. Expired tokens are reported, never refreshed.", "읽기 전용: 이 계정에 저장된 토큰으로 할당량 요청을 한 번 보냅니다. 만료된 토큰은 갱신하지 않고 그대로 보고합니다.", "Nur lesend: sendet eine Kontingentanfrage mit dem gespeicherten Token dieses Kontos. Abgelaufene Tokens werden gemeldet, nie erneuert.", "Lecture seule : envoie une requête de quota avec le jeton enregistré de ce compte. Un jeton expiré est signalé, jamais renouvelé.", "只读:用该账号已存的 token 发一次额度查询。token 已过期时只报告,不刷新。", "唯讀:用該帳號已存的 Token 送出一次額度查詢。Token 已過期時只回報,不刷新。", "Только чтение: один запрос квоты с сохранённым токеном аккаунта. Истёкший токен только отмечается, не обновляется.", "読み取り専用:このアカウントの保存済みトークンでクォータ要求を 1 回送ります。期限切れトークンは報告のみで更新しません。", "Salt okunur: bu hesabın kayıtlı belirteciyle bir kota isteği gönderir. Süresi dolmuş belirteç yenilenmez, yalnızca bildirilir.", "Chỉ đọc: gửi một yêu cầu hạn mức bằng token đã lưu của tài khoản. Token hết hạn chỉ được báo, không làm mới.", "Somente leitura: envia uma consulta de cota com o token salvo desta conta. Tokens expirados são informados, nunca renovados.", "Solo lectura: envía una solicitud de cuota con el token guardado de esta cuenta. Los tokens vencidos se informan y nunca se renuevan."], + "acctProbe.failed": ["Test request failed", "테스트 요청 실패", "Testanfrage fehlgeschlagen", "La requête de test a échoué", "测试请求失败", "測試請求失敗", "Запрос проверки не выполнен", "テスト要求に失敗しました", "Test isteği başarısız", "Yêu cầu kiểm tra thất bại", "Falha na solicitação de teste", "La solicitud de prueba falló"], + "acctProbe.status.ok": ["Usable", "사용 가능", "Nutzbar", "Utilisable", "可用", "可用", "Работает", "利用可能", "Kullanılabilir", "Dùng được", "Utilizável", "Utilizable"], + "acctProbe.status.paused": ["Paused (not tested)", "일시 중지됨(테스트 안 함)", "Pausiert (nicht getestet)", "En pause (non testé)", "已暂停(未测试)", "已暫停(未測試)", "Приостановлен (не проверялся)", "一時停止中(未テスト)", "Duraklatıldı (test edilmedi)", "Đã tạm dừng (không kiểm tra)", "Pausada (não testada)", "En pausa (no probada)"], + "acctProbe.status.token_expired": ["Token expired (not refreshed)", "토큰 만료(갱신 안 함)", "Token abgelaufen (nicht erneuert)", "Jeton expiré (non renouvelé)", "token 已过期(未刷新)", "Token 已過期(未刷新)", "Токен истёк (не обновлён)", "トークン期限切れ(未更新)", "Belirteç süresi doldu (yenilenmedi)", "Token hết hạn (chưa làm mới)", "Token expirado (não renovado)", "Token vencido (no renovado)"], + "acctProbe.status.suspended": ["Suspended", "정지됨", "Gesperrt", "Suspendu", "已暂停", "已暫停", "Приостановлен", "停止中", "Askıya alındı", "Bị đình chỉ", "Suspensa", "Suspendida"], + "acctProbe.status.verification_required": ["Verification required", "인증 필요", "Verifizierung erforderlich", "Vérification requise", "要求验证", "需要驗證", "Требуется подтверждение", "確認が必要", "Doğrulama gerekli", "Cần xác minh", "Verificação necessária", "Requiere verificación"], + "acctProbe.status.rate_limited": ["Rate limited", "요청 제한", "Ratenlimit", "Limite de débit", "限流", "限流", "Ограничение частоты", "レート制限", "Hız sınırı", "Bị giới hạn tốc độ", "Limite de taxa", "Límite de tasa alcanzado"], + "acctProbe.status.permission_denied": ["Permission denied (403)", "권한 거부(403)", "Zugriff verweigert (403)", "Accès refusé (403)", "权限拒绝(403)", "權限遭拒(403)", "Доступ запрещён (403)", "権限拒否(403)", "İzin reddedildi (403)", "Bị từ chối quyền (403)", "Permissão negada (403)", "Permiso denegado (403)"], + "acctProbe.status.error": ["Other error", "기타 오류", "Anderer Fehler", "Autre erreur", "其他错误", "其他錯誤", "Другая ошибка", "その他のエラー", "Diğer hata", "Lỗi khác", "Outro erro", "Otro error"], + "modelDiscover.now": ["Discover now", "지금 검색", "Jetzt abrufen", "Découvrir maintenant", "立即发现", "立即探索", "Найти сейчас", "今すぐ検出", "Şimdi keşfet", "Khám phá ngay", "Descobrir agora", "Descubrir ahora"], + "modelDiscover.running": ["Discovering…", "검색 중…", "Wird abgerufen…", "Découverte…", "发现中…", "探索中…", "Поиск…", "検出中…", "Keşfediliyor…", "Đang khám phá…", "Descobrindo…", "Descubriendo…"], + "modelDiscover.recent": ["Recently added models", "최근 추가된 모델", "Kürzlich hinzugekommene Modelle", "Modèles ajoutés récemment", "最近新增的模型", "最近新增的模型", "Недавно добавленные модели", "最近追加されたモデル", "Son eklenen modeller", "Mô hình mới thêm gần đây", "Modelos adicionados recentemente", "Modelos añadidos recientemente"], + "modelDiscover.none": ["No new models recorded yet.", "아직 기록된 새 모델이 없습니다.", "Noch keine neuen Modelle erfasst.", "Aucun nouveau modèle enregistré pour l’instant.", "还没有记录到新模型。", "尚未記錄到新模型。", "Новые модели пока не обнаружены.", "新しいモデルはまだ記録されていません。", "Henüz yeni model kaydedilmedi.", "Chưa ghi nhận mô hình mới nào.", "Nenhum modelo novo registrado ainda.", "Todavía no se registraron modelos nuevos."], + "modelDiscover.result": ["{count} live models, {added} new", "실시간 모델 {count}개, 새 모델 {added}개", "{count} Live-Modelle, {added} neu", "{count} modèles en direct, {added} nouveaux", "共 {count} 个在线模型,新增 {added} 个", "共 {count} 個線上模型,新增 {added} 個", "Моделей: {count}, новых: {added}", "ライブモデル {count} 件、新規 {added} 件", "{count} canlı model, {added} yeni", "{count} mô hình trực tiếp, {added} mới", "{count} modelos ativos, {added} novos", "{count} modelos en vivo, {added} nuevos"], + "modelDiscover.failed": ["Discovery failed", "검색 실패", "Abruf fehlgeschlagen", "Échec de la découverte", "发现失败", "探索失敗", "Поиск не удался", "検出に失敗しました", "Keşif başarısız", "Khám phá thất bại", "Falha na descoberta", "El descubrimiento falló"], + "modelDiscover.inProgress": ["Model discovery is already in progress. Try again shortly.", "이미 모델을 검색하고 있습니다. 잠시 후 다시 시도하세요.", "Modelle werden bereits abgerufen. Versuche es in Kürze erneut.", "La découverte de modèles est déjà en cours. Réessayez dans un instant.", "正在发现模型,请稍后重试。", "正在探索模型,請稍後重試。", "Поиск моделей уже идёт. Повторите попытку чуть позже.", "モデルを検出中です。しばらくしてからもう一度お試しください。", "Model keşfi zaten devam ediyor. Biraz sonra tekrar deneyin.", "Đang khám phá mô hình. Hãy thử lại sau giây lát.", "A descoberta de modelos já está em andamento. Tente novamente em instantes.", "El descubrimiento de modelos ya está en curso. Vuelve a intentarlo en un momento."], + "modelDiscover.static": ["Live discovery is off for this provider.", "이 공급자는 실시간 검색이 꺼져 있습니다.", "Live-Abruf ist für diesen Anbieter aus.", "La découverte en direct est désactivée pour ce fournisseur.", "该供应商未开启在线发现。", "此供應商未開啟線上探索。", "Для этого провайдера поиск моделей отключён.", "このプロバイダーはライブ検出がオフです。", "Bu sağlayıcı için canlı keşif kapalı.", "Nhà cung cấp này đang tắt khám phá trực tiếp.", "A descoberta ao vivo está desativada para este provedor.", "El descubrimiento en vivo está desactivado para este proveedor."], + "modelDiscover.autoDisabled": ["hidden by new-model policy", "새 모델 정책으로 숨김", "durch Neu-Modell-Richtlinie ausgeblendet", "masqué par la règle des nouveaux modèles", "按新模型策略已隐藏", "依新模型政策已隱藏", "скрыта политикой новых моделей", "新モデルポリシーで非表示", "yeni model politikasıyla gizlendi", "bị ẩn theo chính sách mô hình mới", "oculto pela política de novos modelos", "oculto por la política de modelos nuevos"], + "modelDiscover.new": ["NEW", "NEW", "NEU", "NOUVEAU", "新", "新", "НОВАЯ", "NEW", "YENİ", "MỚI", "NOVO", "NUEVO"], + "acctTable.title": ["Account quotas", "계정 할당량", "Kontingente je Konto", "Quotas par compte", "账号额度", "帳號額度", "Квоты аккаунтов", "アカウント別クォータ", "Hesap kotaları", "Hạn mức theo tài khoản", "Cotas por conta", "Cuotas de cuentas"], + "acctTable.actions": ["Actions", "작업", "Aktionen", "Commandes", "操作", "操作", "Действия", "操作", "İşlemler", "Thao tác", "Ações", "Acciones"], + "acctTable.account": ["Account", "계정", "Konto", "Compte", "账号", "帳號", "Аккаунт", "アカウント", "Hesap", "Tài khoản", "Conta", "Cuenta"], + "acctTable.plan": ["Plan", "플랜", "Tarif", "Forfait", "套餐", "方案", "План", "プラン", "Plan", "Gói", "Plano", "Plan"], + "acctTable.status": ["Status", "상태", "Status", "État", "状态", "狀態", "Статус", "状態", "Durum", "Trạng thái", "Status", "Estado"], + "acctTable.unknownPlan": ["Unknown plan", "알 수 없는 플랜", "Tarif unbekannt", "Forfait inconnu", "未知套餐", "未知方案", "План неизвестен", "プラン不明", "Plan bilinmiyor", "Không rõ gói", "Plano desconhecido", "Plan desconocido"], + "acctTable.planSource": ["Upstream tier: {tier}", "업스트림 등급: {tier}", "Upstream-Stufe: {tier}", "Niveau amont : {tier}", "上游套餐字段:{tier}", "上游方案欄位:{tier}", "Тариф от провайдера: {tier}", "上流の階層: {tier}", "Üst kaynak katmanı: {tier}", "Hạng từ nhà cung cấp: {tier}", "Nível do provedor: {tier}", "Nivel upstream: {tier}"], + "acctTable.pool.gemini": ["Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini", "Gemini"], + "acctTable.pool.claudeGpt": ["Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude & GPT", "Claude y GPT"], + "acctTable.pool.argon": ["Argon", "Argon", "Argon", "Argon", "Argon", "Argon", "Argon", "Argon", "Argon", "Argon", "Argon", "Argon"], + "acctTable.pool.subscription": ["Subscription", "구독", "Abo", "Abonnement", "订阅额度", "訂閱額度", "Подписка", "サブスク", "Abonelik", "Gói đăng ký", "Assinatura", "Suscripción"], + "acctTable.scarce": ["scarce", "희소", "knapp", "rare", "稀缺", "稀缺", "дефицит", "希少", "kıt", "khan hiếm", "escassa", "escasa"], + "acctTable.fiveHour": ["5h", "5시간", "5 Std.", "5 h", "5 小时", "5 小時", "5 ч", "5時間", "5 sa", "5 giờ", "5 h", "5 h"], + "acctTable.weekly": ["Week", "주간", "Woche", "Semaine", "每周", "每週", "Неделя", "週", "Hafta", "Tuần", "Semana", "Semana"], + "acctTable.resetsIn": ["resets in {time}", "{time} 후 초기화", "Reset in {time}", "réinit. dans {time}", "{time} 后重置", "{time} 後重置", "сброс через {time}", "{time} 後リセット", "{time} sonra sıfırlanır", "đặt lại sau {time}", "reinicia em {time}", "se restablece en {time}"], + "acctTable.next": ["next", "다음", "als Nächstes", "suivant", "优先", "優先", "следующий", "次", "sıradaki", "kế tiếp", "próxima", "siguiente"], + "acctTable.nextHint": ["Resets soonest among usable accounts, so reset-first spends it first", "사용 가능한 계정 중 가장 먼저 초기화되어 reset-first가 먼저 사용합니다", "Wird unter nutzbaren Konten zuerst zurückgesetzt, daher nutzt reset-first es zuerst", "Se réinitialise en premier parmi les comptes utilisables : reset-first l’utilise d’abord", "在可用账号里最先重置,「最快重置优先」会先用它", "在可用帳號中最先重置,「最快重置優先」會先用它", "Сбрасывается раньше других доступных аккаунтов, поэтому reset-first расходует его первым", "使用可能なアカウントで最も早くリセットされるため、reset-first が先に使います", "Kullanılabilir hesaplar arasında ilk sıfırlanan; reset-first önce bunu kullanır", "Đặt lại sớm nhất trong các tài khoản dùng được, nên reset-first dùng trước", "Reinicia antes entre as contas utilizáveis, então reset-first a usa primeiro", "Es la que se restablece antes entre las cuentas utilizables, así que la estrategia de restablecimiento primero la gasta primero"], + "acctTable.noReading": ["No quota reading yet", "아직 할당량을 읽지 못함", "Noch kein Kontingent gelesen", "Aucun quota lu pour l’instant", "还没读到额度", "尚未讀到額度", "Квота ещё не прочитана", "クォータ未取得", "Henüz kota okunmadı", "Chưa đọc được hạn mức", "Cota ainda não lida", "Todavía no hay lectura de cuota"], + "acctTable.flag.ok": ["Healthy", "정상", "In Ordnung", "Sain", "正常", "正常", "Работает", "正常", "Sağlıklı", "Bình thường", "Saudável", "Correcta"], + "acctTable.flag.banned": ["Banned upstream", "업스트림 차단됨", "Upstream gesperrt", "Bloqué en amont", "已封禁", "已封禁", "Заблокирован", "上流で停止", "Upstream yasakladı", "Bị chặn phía upstream", "Bloqueada no upstream", "Bloqueada upstream"], + "acctTable.flag.verify": ["Verification needed", "인증 필요", "Verifizierung nötig", "Vérification requise", "需验证", "需驗證", "Нужна проверка", "確認が必要", "Doğrulama gerekli", "Cần xác minh", "Verificação necessária", "Requiere verificación"], + "acctTable.bannedRow": ["Upstream refused this account; automatic refresh is stopped", "업스트림이 이 계정을 거부해 자동 새로 고침을 멈췄습니다", "Upstream hat dieses Konto abgelehnt; automatische Aktualisierung gestoppt", "Le fournisseur a refusé ce compte ; actualisation automatique arrêtée", "账号已被上游封禁,已停止自动刷新", "帳號已被上游封禁,已停止自動重新整理", "Провайдер отклонил аккаунт; автообновление остановлено", "上流がこのアカウントを拒否したため自動更新を停止しました", "Upstream bu hesabı reddetti; otomatik yenileme durduruldu", "Upstream đã từ chối tài khoản này; đã dừng tự làm mới", "O upstream recusou esta conta; atualização automática parada", "El upstream rechazó esta cuenta; la actualización automática está detenida"], + "acctTable.bannedReason": ["View reason", "사유 보기", "Grund anzeigen", "Voir le motif", "查看原因", "查看原因", "Причина", "理由を見る", "Nedeni gör", "Xem lý do", "Ver motivo", "Ver motivo"], + "acctTable.flag.paused": ["Paused", "일시 중지", "Pausiert", "En pause", "已暂停", "已暫停", "Приостановлен", "一時停止", "Duraklatıldı", "Đã tạm dừng", "Pausada", "En pausa"], + "acctTable.flag.reauth": ["Sign-in needed", "재로그인 필요", "Anmeldung nötig", "Connexion requise", "需重新登录", "需重新登入", "Нужен вход", "再ログインが必要", "Oturum açılmalı", "Cần đăng nhập lại", "Login necessário", "Requiere iniciar sesión"], + "acctTable.flag.rateLimited": ["Rate limited", "요청 제한", "Ratenlimit", "Débit limité", "限流中", "限流中", "Ограничение частоты", "レート制限中", "Hız sınırında", "Bị giới hạn tốc độ", "Limite de taxa", "Límite de tasa alcanzado"], + "acctTable.flag.quotaLimited": ["Quota cooldown", "할당량 대기", "Kontingent-Pause", "Pause de quota", "额度冷却中", "額度冷卻中", "Квота на паузе", "クォータ待機中", "Kota beklemesi", "Đang chờ hạn mức", "Pausa de cota", "Enfriamiento de cuota"], + "acctTable.flag.warning": ["Warning", "경고", "Warnung", "Alerte", "有警告", "有警告", "Предупреждение", "警告", "Uyarı", "Cảnh báo", "Aviso", "Advertencia"], + "acctTable.flag.slow": ["Slow", "느림", "Langsam", "Lent", "响应慢", "回應慢", "Медленно", "遅い", "Yavaş", "Chậm", "Lenta", "Lenta"], + "acctTable.flag.stale": ["Quota not read", "할당량 미확인", "Kontingent nicht gelesen", "Quota non lu", "额度没读到", "額度沒讀到", "Квота не прочитана", "クォータ未取得", "Kota okunamadı", "Chưa đọc được hạn mức", "Cota não lida", "Cuota sin leer"], } as const satisfies Record; export type AccountProbeCopyKey = keyof typeof rows; diff --git a/gui/src/i18n/catalogs.ts b/gui/src/i18n/catalogs.ts index d64033f412d..926bda0d235 100644 --- a/gui/src/i18n/catalogs.ts +++ b/gui/src/i18n/catalogs.ts @@ -9,6 +9,7 @@ import { ja } from "./ja"; import { tr } from "./tr"; import { vi } from "./vi"; import { pt } from "./pt"; +import { es } from "./es"; import { LAB_CATALOG_OVERRIDES, type LabLocale } from "./lab-translations"; /** React-free locale catalog registry for formatters and other shared helpers. */ @@ -35,6 +36,7 @@ export const DICTS: Record> = { tr: withLabTranslations("tr", tr), vi: withLabTranslations("vi", vi), pt: withLabTranslations("pt", pt), + es: withLabTranslations("es", es), }; /** Native language names shown by the language picker, kept inside i18n rather than UI metadata. */ diff --git a/gui/src/i18n/codex-cli-update-copy.ts b/gui/src/i18n/codex-cli-update-copy.ts index 00754988fae..efb4b4ae729 100644 --- a/gui/src/i18n/codex-cli-update-copy.ts +++ b/gui/src/i18n/codex-cli-update-copy.ts @@ -3,67 +3,67 @@ * `locales`, kept apart from the per-locale files like shell-v2-copy.ts so the surface lands as * one reviewable table. Reason codes the table does not name are shown raw, in . */ -type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; -const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; -type Row = readonly [string, string, string, string, string, string, string, string, string, string, string]; +type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt" | "es"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt", "es"]; +type Row = readonly [string, string, string, string, string, string, string, string, string, string, string, string]; const rows = { - tab: ["Codex CLI","Codex CLI","Codex CLI","Codex CLI","Codex CLI","Codex CLI","Codex CLI","Codex CLI","Codex CLI","Codex CLI","Codex CLI"], - title: ["Codex CLI update","Codex CLI 업데이트","Codex-CLI-Update","Mise à jour de Codex CLI","Codex CLI 更新","Codex CLI 更新","Обновление Codex CLI","Codex CLI の更新","Codex CLI güncellemesi","Cập nhật Codex CLI","Atualização do Codex CLI"], - description: ["Check and update the Codex CLI installation OpenCodex uses. This is separate from OpenCodex updates and never touches the Codex desktop app.","OpenCodex가 사용하는 Codex CLI 설치를 확인하고 업데이트해요. OpenCodex 업데이트와는 별개이고 Codex 데스크톱 앱은 건드리지 않아요.","Prüft und aktualisiert die Codex-CLI-Installation, die OpenCodex verwendet. Das ist getrennt von OpenCodex-Updates und berührt die Codex-Desktop-App nie.","Vérifie et met à jour l’installation de Codex CLI utilisée par OpenCodex. C’est distinct des mises à jour d’OpenCodex et ne touche jamais l’application de bureau Codex.","检查并更新 OpenCodex 使用的 Codex CLI 安装。这与 OpenCodex 更新分开,也不会触及 Codex 桌面应用。","檢查並更新 OpenCodex 使用的 Codex CLI 安裝。這與 OpenCodex 更新分開,也不會觸及 Codex 桌面應用程式。","Проверяет и обновляет установку Codex CLI, которую использует OpenCodex. Это не связано с обновлениями OpenCodex и не затрагивает настольное приложение Codex.","OpenCodex が使う Codex CLI のインストールを確認して更新します。OpenCodex の更新とは別で、Codex デスクトップアプリには触れません。","OpenCodex'in kullandığı Codex CLI kurulumunu denetler ve günceller. Bu, OpenCodex güncellemelerinden ayrıdır ve Codex masaüstü uygulamasına asla dokunmaz.","Kiểm tra và cập nhật bản cài đặt Codex CLI mà OpenCodex dùng. Việc này tách biệt với cập nhật OpenCodex và không bao giờ đụng tới ứng dụng Codex trên máy tính.","Verifica e atualiza a instalação do Codex CLI que o OpenCodex usa. Isso é separado das atualizações do OpenCodex e nunca mexe no aplicativo Codex para desktop."], - connectedUnavailable: ["Codex CLI updates run on the computer that serves this dashboard's proxy. Open the dashboard on that computer to check or update its Codex CLI.","Codex CLI 업데이트는 이 프록시를 실행하는 컴퓨터에서 진행돼요. 그 컴퓨터에서 대시보드를 열어 Codex CLI를 확인하거나 업데이트하세요.","Codex-CLI-Updates laufen auf dem Computer, der den Proxy dieses Dashboards betreibt. Öffne das Dashboard auf diesem Computer, um seine Codex CLI zu prüfen oder zu aktualisieren.","Les mises à jour de Codex CLI s’exécutent sur l’ordinateur qui fait tourner le proxy de ce tableau de bord. Ouvrez le tableau de bord sur cet ordinateur pour vérifier ou mettre à jour son Codex CLI.","Codex CLI 更新在运行此代理的电脑上进行。请在那台电脑上打开仪表板来检查或更新它的 Codex CLI。","Codex CLI 更新在執行此代理的電腦上進行。請在那台電腦上開啟儀表板來檢查或更新它的 Codex CLI。","Обновления Codex CLI выполняются на компьютере, где работает прокси этой панели. Откройте панель на том компьютере, чтобы проверить или обновить его Codex CLI.","Codex CLI の更新は、このダッシュボードのプロキシを動かしているコンピューターで行います。そのコンピューターでダッシュボードを開いて確認・更新してください。","Codex CLI güncellemeleri bu panelin proxy'sini çalıştıran bilgisayarda yapılır. Codex CLI'yi denetlemek veya güncellemek için paneli o bilgisayarda açın.","Cập nhật Codex CLI chạy trên máy đang chạy proxy của bảng điều khiển này. Hãy mở bảng điều khiển trên máy đó để kiểm tra hoặc cập nhật Codex CLI.","As atualizações do Codex CLI rodam no computador que executa o proxy deste painel. Abra o painel nesse computador para verificar ou atualizar o Codex CLI dele."], - check: ["Check for update","업데이트 확인","Nach Update suchen","Rechercher une mise à jour","检查更新","檢查更新","Проверить обновление","更新を確認","Güncellemeyi denetle","Kiểm tra cập nhật","Verificar atualização"], - checking: ["Checking…","확인하는 중…","Wird geprüft…","Vérification…","正在检查…","正在檢查…","Проверка…","確認中…","Denetleniyor…","Đang kiểm tra…","Verificando…"], - checkHint: ["Checking is read-only: it inspects the installation and the npm registry and changes nothing.","확인은 읽기만 해요. 설치와 npm 레지스트리를 살펴볼 뿐 아무것도 바꾸지 않아요.","Die Prüfung liest nur: Sie untersucht die Installation und die npm-Registry und ändert nichts.","La vérification est en lecture seule : elle inspecte l’installation et le registre npm sans rien modifier.","检查是只读的:只查看安装和 npm 注册表,不做任何更改。","檢查是唯讀的:只查看安裝和 npm 登錄檔,不做任何變更。","Проверка только читает: она осматривает установку и реестр npm и ничего не меняет.","確認は読み取りのみです。インストールと npm レジストリを調べるだけで、何も変更しません。","Denetleme salt okunurdur: kurulumu ve npm kayıt defterini inceler, hiçbir şeyi değiştirmez.","Kiểm tra chỉ đọc: chỉ xem bản cài đặt và npm registry, không thay đổi gì.","A verificação é somente leitura: ela inspeciona a instalação e o registro npm e não altera nada."], - fieldProvenance: ["Installed by","설치 방식","Installiert über","Installé par","安装方式","安裝方式","Установлено через","インストール方法","Kuran","Cài đặt bởi","Instalado por"], - fieldManaged: ["Managed by OpenCodex","OpenCodex 관리","Von OpenCodex verwaltet","Géré par OpenCodex","由 OpenCodex 管理","由 OpenCodex 管理","Управляется OpenCodex","OpenCodex の管理対象","OpenCodex yönetiyor","Do OpenCodex quản lý","Gerenciado pelo OpenCodex"], - fieldInstalled: ["Installed version","설치된 버전","Installierte Version","Version installée","已安装版本","已安裝版本","Установленная версия","インストール済みバージョン","Kurulu sürüm","Phiên bản đã cài","Versão instalada"], - fieldTarget: ["Available version","받을 수 있는 버전","Verfügbare Version","Version disponible","可用版本","可用版本","Доступная версия","利用可能なバージョン","Mevcut sürüm","Phiên bản có sẵn","Versão disponível"], - fieldSession: ["Codex sessions","Codex 세션","Codex-Sitzungen","Sessions Codex","Codex 会话","Codex 工作階段","Сеансы Codex","Codex セッション","Codex oturumları","Phiên Codex","Sessões do Codex"], - fieldLocation: ["Location","위치","Ort","Emplacement","位置","位置","Расположение","場所","Konum","Vị trí","Local"], - fieldCommand: ["Install command","설치 명령","Installationsbefehl","Commande d’installation","安装命令","安裝指令","Команда установки","インストールコマンド","Kurulum komutu","Lệnh cài đặt","Comando de instalação"], - yes: ["Yes","예","Ja","Oui","是","是","Да","はい","Evet","Có","Sim"], - no: ["No","아니요","Nein","Non","否","否","Нет","いいえ","Hayır","Không","Não"], - unknown: ["Unknown","알 수 없음","Unbekannt","Inconnu","未知","未知","Неизвестно","不明","Bilinmiyor","Không rõ","Desconhecido"], - provNpmGlobal: ["npm (global)","npm (전역)","npm (global)","npm (global)","npm(全局)","npm(全域)","npm (глобально)","npm(グローバル)","npm (genel)","npm (toàn cục)","npm (global)"], - provAppBundle: ["Codex desktop app (bundled)","Codex 데스크톱 앱 (내장)","Codex-Desktop-App (gebündelt)","Application de bureau Codex (intégrée)","Codex 桌面应用(内置)","Codex 桌面應用程式(內建)","Настольное приложение Codex (встроенное)","Codex デスクトップアプリ(同梱)","Codex masaüstü uygulaması (paketli)","Ứng dụng Codex trên máy tính (đi kèm)","Aplicativo Codex para desktop (embutido)"], - provVersionManager: ["A version manager","버전 관리자","Ein Versionsmanager","Un gestionnaire de versions","版本管理器","版本管理器","Менеджер версий","バージョンマネージャー","Bir sürüm yöneticisi","Trình quản lý phiên bản","Um gerenciador de versões"], - provStandaloneUnverified: ["Standalone installer (unverified)","독립 설치 프로그램 (확인 안 됨)","Eigenständiger Installer (nicht verifiziert)","Installateur autonome (non vérifié)","独立安装程序(未验证)","獨立安裝程式(未驗證)","Отдельный установщик (не проверен)","単体インストーラー(未検証)","Bağımsız yükleyici (doğrulanmadı)","Trình cài đặt độc lập (chưa xác minh)","Instalador independente (não verificado)"], - sessionNone: ["None running","실행 중인 세션 없음","Keine aktiv","Aucune en cours","没有运行中的会话","沒有執行中的工作階段","Нет запущенных","実行中なし","Çalışan yok","Không có phiên nào đang chạy","Nenhuma em execução"], - sessionActive: ["{count} running","{count}개 실행 중","{count} aktiv","{count} en cours","{count} 个运行中","{count} 個執行中","Запущено: {count}","{count} 件実行中","{count} çalışıyor","{count} đang chạy","{count} em execução"], - sessionUnknown: ["Could not be checked","확인하지 못했어요","Konnte nicht geprüft werden","Impossible à vérifier","无法检查","無法檢查","Не удалось проверить","確認できませんでした","Denetlenemedi","Không kiểm tra được","Não foi possível verificar"], - sessionNotEvaluated: ["Not checked","확인하지 않음","Nicht geprüft","Non vérifié","未检查","未檢查","Не проверялось","未確認","Denetlenmedi","Chưa kiểm tra","Não verificado"], - ready: ["An update is ready to apply.","적용할 수 있는 업데이트가 있어요.","Ein Update kann angewendet werden.","Une mise à jour est prête à être appliquée.","有可应用的更新。","有可套用的更新。","Обновление готово к установке.","適用できる更新があります。","Uygulanmaya hazır bir güncelleme var.","Có bản cập nhật sẵn sàng để áp dụng.","Há uma atualização pronta para aplicar."], - refusalWindowsInspectionDeferred: ["This Windows installation can't be inspected for updates yet.","이 Windows 설치는 아직 업데이트를 확인할 수 없어요.","Diese Windows-Installation kann noch nicht auf Updates geprüft werden.","Cette installation Windows ne peut pas encore être inspectée pour les mises à jour.","暂时无法检查此 Windows 安装的更新。","暫時無法檢查此 Windows 安裝的更新。","Эту установку Windows пока нельзя проверить на обновления.","この Windows のインストールはまだ更新を確認できません。","Bu Windows kurulumu henüz güncelleme için incelenemiyor.","Chưa thể kiểm tra cập nhật cho bản cài đặt Windows này.","Esta instalação do Windows ainda não pode ser verificada para atualizações."], - refusalWindowsApplyDisabled: ["Updating this Windows installation from OpenCodex is not supported yet.","이 Windows 설치는 아직 OpenCodex에서 업데이트할 수 없어요.","Diese Windows-Installation kann noch nicht aus OpenCodex aktualisiert werden.","La mise à jour de cette installation Windows depuis OpenCodex n’est pas encore prise en charge.","暂不支持从 OpenCodex 更新此 Windows 安装。","暫不支援從 OpenCodex 更新此 Windows 安裝。","Обновление этой установки Windows из OpenCodex пока не поддерживается.","この Windows のインストールは、まだ OpenCodex から更新できません。","Bu Windows kurulumunu OpenCodex'ten güncellemek henüz desteklenmiyor.","Chưa hỗ trợ cập nhật bản cài đặt Windows này từ OpenCodex.","Atualizar esta instalação do Windows pelo OpenCodex ainda não é suportado."], - refusalNotManaged: ["OpenCodex does not manage this installation. Update it with the tool that installed it.","OpenCodex가 관리하는 설치가 아니에요. 설치한 도구로 업데이트하세요.","OpenCodex verwaltet diese Installation nicht. Aktualisiere sie mit dem Werkzeug, das sie installiert hat.","OpenCodex ne gère pas cette installation. Mettez-la à jour avec l’outil qui l’a installée.","OpenCodex 不管理此安装。请用安装它的工具来更新。","OpenCodex 不管理此安裝。請用安裝它的工具來更新。","OpenCodex не управляет этой установкой. Обновите её тем инструментом, которым она установлена.","このインストールは OpenCodex の管理対象ではありません。インストールしたツールで更新してください。","OpenCodex bu kurulumu yönetmiyor. Onu kuran araçla güncelleyin.","OpenCodex không quản lý bản cài đặt này. Hãy cập nhật bằng công cụ đã cài nó.","O OpenCodex não gerencia esta instalação. Atualize-a com a ferramenta que a instalou."], - refusalInstalledVersionUnverified: ["The installed version could not be verified.","설치된 버전을 확인하지 못했어요.","Die installierte Version konnte nicht verifiziert werden.","La version installée n’a pas pu être vérifiée.","无法验证已安装的版本。","無法驗證已安裝的版本。","Не удалось подтвердить установленную версию.","インストール済みのバージョンを確認できませんでした。","Kurulu sürüm doğrulanamadı.","Không xác minh được phiên bản đã cài.","Não foi possível verificar a versão instalada."], - refusalInstallContentUnverified: ["The installed files could not be verified, so no update is offered.","설치된 파일을 확인하지 못해 업데이트를 제안하지 않아요.","Die installierten Dateien konnten nicht verifiziert werden, daher wird kein Update angeboten.","Les fichiers installés n’ont pas pu être vérifiés, aucune mise à jour n’est donc proposée.","无法验证已安装的文件,因此不提供更新。","無法驗證已安裝的檔案,因此不提供更新。","Не удалось проверить установленные файлы, поэтому обновление не предлагается.","インストール済みのファイルを確認できないため、更新は提示しません。","Kurulu dosyalar doğrulanamadı, bu yüzden güncelleme sunulmuyor.","Không xác minh được các tệp đã cài nên không đề xuất cập nhật.","Os arquivos instalados não puderam ser verificados, então nenhuma atualização é oferecida."], - refusalTargetUnresolved: ["The latest version could not be resolved from the npm registry.","npm 레지스트리에서 최신 버전을 확인하지 못했어요.","Die neueste Version konnte nicht aus der npm-Registry ermittelt werden.","La dernière version n’a pas pu être déterminée depuis le registre npm.","无法从 npm 注册表确定最新版本。","無法從 npm 登錄檔確定最新版本。","Не удалось определить последнюю версию в реестре npm.","npm レジストリから最新バージョンを特定できませんでした。","En son sürüm npm kayıt defterinden belirlenemedi.","Không xác định được phiên bản mới nhất từ npm registry.","Não foi possível obter a versão mais recente do registro npm."], - refusalAlreadyCurrent: ["The Codex CLI is already up to date.","Codex CLI가 이미 최신이에요.","Die Codex CLI ist bereits aktuell.","Codex CLI est déjà à jour.","Codex CLI 已是最新版本。","Codex CLI 已是最新版本。","Codex CLI уже обновлён.","Codex CLI はすでに最新です。","Codex CLI zaten güncel.","Codex CLI đã là bản mới nhất.","O Codex CLI já está atualizado."], - refusalTargetNotNewer: ["The registry version is not newer than the installed one.","레지스트리 버전이 설치된 버전보다 새롭지 않아요.","Die Registry-Version ist nicht neuer als die installierte.","La version du registre n’est pas plus récente que celle installée.","注册表中的版本不比已安装的新。","登錄檔中的版本不比已安裝的新。","Версия в реестре не новее установленной.","レジストリのバージョンはインストール済みより新しくありません。","Kayıt defterindeki sürüm kurulu olandan yeni değil.","Phiên bản trên registry không mới hơn bản đã cài.","A versão do registro não é mais nova que a instalada."], - refusalBlockedActiveSession: ["A Codex session is using this installation. Close it and check again.","Codex 세션이 이 설치를 사용하고 있어요. 세션을 닫고 다시 확인하세요.","Eine Codex-Sitzung verwendet diese Installation. Schließe sie und prüfe erneut.","Une session Codex utilise cette installation. Fermez-la puis vérifiez à nouveau.","有 Codex 会话正在使用此安装。请关闭后再检查。","有 Codex 工作階段正在使用此安裝。請關閉後再檢查。","Эту установку использует сеанс Codex. Закройте его и проверьте снова.","Codex セッションがこのインストールを使用中です。閉じてからもう一度確認してください。","Bir Codex oturumu bu kurulumu kullanıyor. Kapatıp yeniden denetleyin.","Một phiên Codex đang dùng bản cài đặt này. Hãy đóng nó rồi kiểm tra lại.","Uma sessão do Codex está usando esta instalação. Feche-a e verifique novamente."], - refusalBlockedProcessStateUnknown: ["Running Codex processes could not be checked, so the update waits.","실행 중인 Codex 프로세스를 확인하지 못해 업데이트를 미뤄요.","Laufende Codex-Prozesse konnten nicht geprüft werden, daher wartet das Update.","Les processus Codex en cours n’ont pas pu être vérifiés, la mise à jour attend donc.","无法检查正在运行的 Codex 进程,因此暂缓更新。","無法檢查執行中的 Codex 程序,因此暫緩更新。","Не удалось проверить запущенные процессы Codex, поэтому обновление откладывается.","実行中の Codex プロセスを確認できないため、更新は保留します。","Çalışan Codex süreçleri denetlenemedi, bu yüzden güncelleme bekliyor.","Không kiểm tra được các tiến trình Codex đang chạy nên việc cập nhật tạm hoãn.","Não foi possível verificar os processos do Codex em execução, então a atualização aguarda."], - confirm: ["I understand this changes only this Codex CLI installation. OpenCodex and the desktop app are not updated or restarted.","이 작업은 이 Codex CLI 설치만 바꾼다는 것을 이해했어요. OpenCodex와 데스크톱 앱은 업데이트하거나 다시 시작하지 않아요.","Mir ist klar, dass nur diese Codex-CLI-Installation geändert wird. OpenCodex und die Desktop-App werden weder aktualisiert noch neu gestartet.","Je comprends que seule cette installation de Codex CLI est modifiée. OpenCodex et l’application de bureau ne sont ni mis à jour ni redémarrés.","我了解这只会更改这个 Codex CLI 安装。OpenCodex 和桌面应用不会被更新或重启。","我了解這只會變更這個 Codex CLI 安裝。OpenCodex 和桌面應用程式不會被更新或重新啟動。","Я понимаю, что меняется только эта установка Codex CLI. OpenCodex и настольное приложение не обновляются и не перезапускаются.","この操作で変わるのはこの Codex CLI のインストールだけだと理解しました。OpenCodex とデスクトップアプリは更新も再起動もされません。","Bunun yalnızca bu Codex CLI kurulumunu değiştirdiğini anlıyorum. OpenCodex ve masaüstü uygulaması güncellenmez ya da yeniden başlatılmaz.","Tôi hiểu việc này chỉ thay đổi bản cài đặt Codex CLI này. OpenCodex và ứng dụng máy tính không được cập nhật hay khởi động lại.","Entendo que isto altera apenas esta instalação do Codex CLI. O OpenCodex e o aplicativo para desktop não são atualizados nem reiniciados."], - apply: ["Update Codex CLI","Codex CLI 업데이트","Codex CLI aktualisieren","Mettre à jour Codex CLI","更新 Codex CLI","更新 Codex CLI","Обновить Codex CLI","Codex CLI を更新","Codex CLI'yi güncelle","Cập nhật Codex CLI","Atualizar Codex CLI"], - applying: ["Updating…","업데이트하는 중…","Wird aktualisiert…","Mise à jour…","正在更新…","正在更新…","Обновление…","更新中…","Güncelleniyor…","Đang cập nhật…","Atualizando…"], - jobQueued: ["Waiting to start…","시작을 기다리는 중…","Wartet auf Start…","En attente de démarrage…","等待开始…","等待開始…","Ожидание запуска…","開始を待っています…","Başlaması bekleniyor…","Đang chờ bắt đầu…","Aguardando início…"], - jobRunning: ["Installing…","설치하는 중…","Wird installiert…","Installation…","正在安装…","正在安裝…","Установка…","インストール中…","Kuruluyor…","Đang cài đặt…","Instalando…"], - jobApplied: ["Updated. The installed version was read back and matches.","업데이트했어요. 설치된 버전을 다시 읽어 확인했어요.","Aktualisiert. Die installierte Version wurde zurückgelesen und stimmt.","Mis à jour. La version installée a été relue et correspond.","已更新。已回读安装的版本并确认一致。","已更新。已回讀安裝的版本並確認一致。","Обновлено. Установленная версия перечитана и совпадает.","更新しました。インストール済みバージョンを読み直して一致を確認しました。","Güncellendi. Kurulu sürüm yeniden okundu ve eşleşiyor.","Đã cập nhật. Phiên bản đã cài được đọc lại và khớp.","Atualizado. A versão instalada foi relida e confere."], - jobNotApplied: ["Not updated. The installation was left as it was.","업데이트하지 않았어요. 설치는 그대로예요.","Nicht aktualisiert. Die Installation blieb unverändert.","Non mis à jour. L’installation est restée telle quelle.","未更新。安装保持原样。","未更新。安裝保持原樣。","Не обновлено. Установка осталась прежней.","更新していません。インストールはそのままです。","Güncellenmedi. Kurulum olduğu gibi bırakıldı.","Chưa cập nhật. Bản cài đặt được giữ nguyên.","Não atualizado. A instalação ficou como estava."], - jobRefused: ["Refused before anything was installed.","설치하기 전에 거부됐어요.","Abgelehnt, bevor etwas installiert wurde.","Refusé avant toute installation.","在安装任何内容之前被拒绝。","在安裝任何內容之前被拒絕。","Отклонено до какой-либо установки.","何かをインストールする前に拒否されました。","Herhangi bir şey kurulmadan reddedildi.","Bị từ chối trước khi cài bất cứ thứ gì.","Recusado antes de qualquer instalação."], - jobAmbiguous: ["The result is unclear. Check the installation yourself; OpenCodex will not retry or roll back.","결과가 분명하지 않아요. 설치를 직접 확인하세요. OpenCodex는 다시 시도하거나 되돌리지 않아요.","Das Ergebnis ist unklar. Prüfe die Installation selbst; OpenCodex wiederholt nichts und rollt nichts zurück.","Le résultat est incertain. Vérifiez l’installation vous-même ; OpenCodex ne réessaie pas et n’annule rien.","结果不明确。请自行检查安装;OpenCodex 不会重试或回滚。","結果不明確。請自行檢查安裝;OpenCodex 不會重試或復原。","Результат неясен. Проверьте установку сами; OpenCodex не повторяет и не откатывает.","結果がはっきりしません。インストールをご自身で確認してください。OpenCodex は再試行もロールバックもしません。","Sonuç belirsiz. Kurulumu kendiniz denetleyin; OpenCodex yeniden denemez veya geri almaz.","Kết quả không rõ ràng. Hãy tự kiểm tra bản cài đặt; OpenCodex sẽ không thử lại hay hoàn tác.","O resultado é incerto. Verifique a instalação você mesmo; o OpenCodex não tentará de novo nem desfará."], - reasonOwnerStateUnknown: ["OpenCodex lost track of this job (for example after a restart), so its result is unknown.", "OpenCodex가 이 작업을 추적하지 못했어요(예: 다시 시작된 경우). 그래서 결과를 알 수 없어요.", "OpenCodex hat den Auftrag aus den Augen verloren (etwa nach einem Neustart), daher ist das Ergebnis unbekannt.", "OpenCodex a perdu le suivi de cette tâche (par exemple après un redémarrage), son résultat est donc inconnu.", "OpenCodex 失去了对此任务的跟踪(例如重启后),因此结果未知。", "OpenCodex 失去了對此工作的追蹤(例如重新啟動後),因此結果未知。", "OpenCodex потерял отслеживание этого задания (например, после перезапуска), поэтому результат неизвестен.", "OpenCodex がこのジョブを追跡できなくなりました(再起動後など)。そのため結果は不明です。", "OpenCodex bu işin izini kaybetti (örneğin yeniden başlatmadan sonra), bu yüzden sonuç bilinmiyor.", "OpenCodex đã mất dấu tác vụ này (ví dụ sau khi khởi động lại) nên không rõ kết quả.", "O OpenCodex perdeu o acompanhamento desta tarefa (por exemplo, após reiniciar), então o resultado é desconhecido."], - reasonLabel: ["Reason code","사유 코드","Grundcode","Code de raison","原因代码","原因代碼","Код причины","理由コード","Neden kodu","Mã lý do","Código do motivo"], - errPlanUnavailable: ["The update check failed. Try again.","업데이트 확인에 실패했어요. 다시 시도하세요.","Die Update-Prüfung ist fehlgeschlagen. Versuche es erneut.","La vérification a échoué. Réessayez.","检查更新失败。请重试。","檢查更新失敗。請重試。","Проверка обновления не удалась. Повторите попытку.","更新の確認に失敗しました。もう一度お試しください。","Güncelleme denetimi başarısız oldu. Yeniden deneyin.","Kiểm tra cập nhật thất bại. Hãy thử lại.","A verificação falhou. Tente novamente."], - errLocalOnly: ["Applying needs a paired browser on this computer. Pair it below (it runs the ocx gui pair command), or update from a terminal:","적용하려면 이 컴퓨터에서 페어링된 브라우저가 필요해요. 아래에서 페어링하거나(ocx gui pair 명령을 실행해요) 터미널에서 업데이트하세요:","Zum Anwenden braucht es einen gekoppelten Browser auf diesem Computer. Kopple ihn unten (dabei läuft der Befehl ocx gui pair) oder aktualisiere im Terminal:","L’application exige un navigateur appairé sur cet ordinateur. Appairez-le ci-dessous (avec la commande ocx gui pair) ou mettez à jour depuis un terminal :","应用需要在这台电脑上已配对的浏览器。请在下方配对(会使用 ocx gui pair 命令),或在终端中更新:","套用需要在這台電腦上已配對的瀏覽器。請在下方配對(會使用 ocx gui pair 指令),或在終端機中更新:","Для установки нужен сопряжённый браузер на этом компьютере. Выполните сопряжение ниже (через команду ocx gui pair) или обновите из терминала:","適用するには、このコンピューターでペアリング済みのブラウザーが必要です。下でペアリングする(ocx gui pair コマンドを使います)か、ターミナルから更新してください:","Uygulamak için bu bilgisayarda eşleştirilmiş bir tarayıcı gerekir. Aşağıdan eşleştirin (ocx gui pair komutunu kullanır) veya terminalden güncelleyin:","Để áp dụng cần một trình duyệt đã ghép đôi trên máy này. Hãy ghép đôi bên dưới (dùng lệnh ocx gui pair) hoặc cập nhật từ terminal:","Aplicar exige um navegador pareado neste computador. Pareie-o abaixo (usa o comando ocx gui pair) ou atualize pelo terminal:"], - errIdempotencyConflict: ["This update request no longer matches. Check again before updating.","이 업데이트 요청이 더 이상 맞지 않아요. 업데이트 전에 다시 확인하세요.","Diese Update-Anfrage passt nicht mehr. Prüfe erneut, bevor du aktualisierst.","Cette demande de mise à jour ne correspond plus. Vérifiez à nouveau avant de mettre à jour.","此更新请求已不再匹配。更新前请重新检查。","此更新請求已不再相符。更新前請重新檢查。","Этот запрос на обновление больше не подходит. Проверьте снова перед обновлением.","この更新リクエストはもう一致しません。更新する前にもう一度確認してください。","Bu güncelleme isteği artık eşleşmiyor. Güncellemeden önce yeniden denetleyin.","Yêu cầu cập nhật này không còn khớp. Hãy kiểm tra lại trước khi cập nhật.","Esta solicitação de atualização não confere mais. Verifique novamente antes de atualizar."], - errStore: ["The update job store on this computer can't be used, so the update can't start.","이 컴퓨터의 업데이트 작업 저장소를 쓸 수 없어 업데이트를 시작할 수 없어요.","Der Update-Auftragsspeicher auf diesem Computer ist nicht nutzbar, daher kann das Update nicht starten.","Le stockage des tâches de mise à jour de cet ordinateur est inutilisable ; la mise à jour ne peut pas démarrer.","此电脑上的更新任务存储无法使用,因此无法开始更新。","此電腦上的更新工作儲存無法使用,因此無法開始更新。","Хранилище заданий обновления на этом компьютере недоступно, поэтому обновление не может начаться.","このコンピューターの更新ジョブ保存先が使えないため、更新を開始できません。","Bu bilgisayardaki güncelleme işi deposu kullanılamıyor, bu yüzden güncelleme başlayamıyor.","Không dùng được kho tác vụ cập nhật trên máy này nên không thể bắt đầu cập nhật.","O armazenamento de tarefas de atualização deste computador não pode ser usado, então a atualização não pode começar."], - errRetry: ["The update could not start right now. Try again.","지금은 업데이트를 시작하지 못했어요. 다시 시도하세요.","Das Update konnte gerade nicht starten. Versuche es erneut.","La mise à jour n’a pas pu démarrer pour le moment. Réessayez.","现在无法开始更新。请重试。","現在無法開始更新。請重試。","Сейчас не удалось начать обновление. Повторите попытку.","今は更新を開始できませんでした。もう一度お試しください。","Güncelleme şu anda başlatılamadı. Yeniden deneyin.","Hiện chưa thể bắt đầu cập nhật. Hãy thử lại.","Não foi possível iniciar a atualização agora. Tente novamente."], - errApplyFailed: ["The update could not start. The reason code is below.", "업데이트를 시작하지 못했어요. 아래 사유 코드를 확인하세요.", "Das Update konnte nicht starten. Der Grundcode steht unten.", "La mise à jour n’a pas pu démarrer. Le code de raison figure ci-dessous.", "无法开始更新。原因代码见下方。", "無法開始更新。原因代碼見下方。", "Не удалось начать обновление. Код причины указан ниже.", "更新を開始できませんでした。理由コードは下にあります。", "Güncelleme başlatılamadı. Neden kodu aşağıda.", "Không thể bắt đầu cập nhật. Mã lý do ở bên dưới.", "Não foi possível iniciar a atualização. O código do motivo está abaixo."], - retry: ["Try again","다시 시도","Erneut versuchen","Réessayer","重试","重試","Повторить","再試行","Yeniden dene","Thử lại","Tentar novamente"], - errJobNotFound: ["The job record is gone, so its result is unknown. Check the installation yourself.","작업 기록이 사라져 결과를 알 수 없어요. 설치를 직접 확인하세요.","Der Auftragseintrag fehlt, daher ist das Ergebnis unbekannt. Prüfe die Installation selbst.","L’enregistrement de la tâche a disparu, son résultat est inconnu. Vérifiez l’installation vous-même.","任务记录已不存在,结果未知。请自行检查安装。","工作紀錄已不存在,結果未知。請自行檢查安裝。","Запись задания пропала, результат неизвестен. Проверьте установку сами.","ジョブの記録がなくなったため、結果は不明です。インストールをご自身で確認してください。","İş kaydı yok, bu yüzden sonuç bilinmiyor. Kurulumu kendiniz denetleyin.","Bản ghi tác vụ đã mất nên không rõ kết quả. Hãy tự kiểm tra bản cài đặt.","O registro da tarefa sumiu, então o resultado é desconhecido. Verifique a instalação você mesmo."], - errJobUnreadable: ["The job status can't be read right now. Read it from a terminal:","지금은 작업 상태를 읽을 수 없어요. 터미널에서 확인하세요:","Der Auftragsstatus kann gerade nicht gelesen werden. Lies ihn im Terminal:","Le statut de la tâche est illisible pour le moment. Lisez-le depuis un terminal :","现在无法读取任务状态。请在终端中查看:","現在無法讀取工作狀態。請在終端機中查看:","Сейчас не удаётся прочитать статус задания. Посмотрите его в терминале:","今はジョブの状態を読み取れません。ターミナルで確認してください:","İş durumu şu anda okunamıyor. Terminalden okuyun:","Hiện không đọc được trạng thái tác vụ. Hãy xem từ terminal:","O status da tarefa não pode ser lido agora. Leia-o pelo terminal:"], + tab: ["Codex CLI","Codex CLI","Codex CLI","Codex CLI","Codex CLI","Codex CLI","Codex CLI","Codex CLI","Codex CLI","Codex CLI","Codex CLI", "Codex CLI"], + title: ["Codex CLI update","Codex CLI 업데이트","Codex-CLI-Update","Mise à jour de Codex CLI","Codex CLI 更新","Codex CLI 更新","Обновление Codex CLI","Codex CLI の更新","Codex CLI güncellemesi","Cập nhật Codex CLI","Atualização do Codex CLI", "Actualización de Codex CLI"], + description: ["Check and update the Codex CLI installation OpenCodex uses. This is separate from OpenCodex updates and never touches the Codex desktop app.","OpenCodex가 사용하는 Codex CLI 설치를 확인하고 업데이트해요. OpenCodex 업데이트와는 별개이고 Codex 데스크톱 앱은 건드리지 않아요.","Prüft und aktualisiert die Codex-CLI-Installation, die OpenCodex verwendet. Das ist getrennt von OpenCodex-Updates und berührt die Codex-Desktop-App nie.","Vérifie et met à jour l’installation de Codex CLI utilisée par OpenCodex. C’est distinct des mises à jour d’OpenCodex et ne touche jamais l’application de bureau Codex.","检查并更新 OpenCodex 使用的 Codex CLI 安装。这与 OpenCodex 更新分开,也不会触及 Codex 桌面应用。","檢查並更新 OpenCodex 使用的 Codex CLI 安裝。這與 OpenCodex 更新分開,也不會觸及 Codex 桌面應用程式。","Проверяет и обновляет установку Codex CLI, которую использует OpenCodex. Это не связано с обновлениями OpenCodex и не затрагивает настольное приложение Codex.","OpenCodex が使う Codex CLI のインストールを確認して更新します。OpenCodex の更新とは別で、Codex デスクトップアプリには触れません。","OpenCodex'in kullandığı Codex CLI kurulumunu denetler ve günceller. Bu, OpenCodex güncellemelerinden ayrıdır ve Codex masaüstü uygulamasına asla dokunmaz.","Kiểm tra và cập nhật bản cài đặt Codex CLI mà OpenCodex dùng. Việc này tách biệt với cập nhật OpenCodex và không bao giờ đụng tới ứng dụng Codex trên máy tính.","Verifica e atualiza a instalação do Codex CLI que o OpenCodex usa. Isso é separado das atualizações do OpenCodex e nunca mexe no aplicativo Codex para desktop.", "Comprueba y actualiza la instalación de Codex CLI que usa OpenCodex. Es independiente de las actualizaciones de OpenCodex y no modifica la aplicación de escritorio de Codex."], + connectedUnavailable: ["Codex CLI updates run on the computer that serves this dashboard's proxy. Open the dashboard on that computer to check or update its Codex CLI.","Codex CLI 업데이트는 이 프록시를 실행하는 컴퓨터에서 진행돼요. 그 컴퓨터에서 대시보드를 열어 Codex CLI를 확인하거나 업데이트하세요.","Codex-CLI-Updates laufen auf dem Computer, der den Proxy dieses Dashboards betreibt. Öffne das Dashboard auf diesem Computer, um seine Codex CLI zu prüfen oder zu aktualisieren.","Les mises à jour de Codex CLI s’exécutent sur l’ordinateur qui fait tourner le proxy de ce tableau de bord. Ouvrez le tableau de bord sur cet ordinateur pour vérifier ou mettre à jour son Codex CLI.","Codex CLI 更新在运行此代理的电脑上进行。请在那台电脑上打开仪表板来检查或更新它的 Codex CLI。","Codex CLI 更新在執行此代理的電腦上進行。請在那台電腦上開啟儀表板來檢查或更新它的 Codex CLI。","Обновления Codex CLI выполняются на компьютере, где работает прокси этой панели. Откройте панель на том компьютере, чтобы проверить или обновить его Codex CLI.","Codex CLI の更新は、このダッシュボードのプロキシを動かしているコンピューターで行います。そのコンピューターでダッシュボードを開いて確認・更新してください。","Codex CLI güncellemeleri bu panelin proxy'sini çalıştıran bilgisayarda yapılır. Codex CLI'yi denetlemek veya güncellemek için paneli o bilgisayarda açın.","Cập nhật Codex CLI chạy trên máy đang chạy proxy của bảng điều khiển này. Hãy mở bảng điều khiển trên máy đó để kiểm tra hoặc cập nhật Codex CLI.","As atualizações do Codex CLI rodam no computador que executa o proxy deste painel. Abra o painel nesse computador para verificar ou atualizar o Codex CLI dele.", "Codex CLI se actualiza en el equipo que ejecuta el proxy de este panel. Abre el panel en ese equipo para comprobar o actualizar su Codex CLI."], + check: ["Check for update","업데이트 확인","Nach Update suchen","Rechercher une mise à jour","检查更新","檢查更新","Проверить обновление","更新を確認","Güncellemeyi denetle","Kiểm tra cập nhật","Verificar atualização", "Buscar actualización"], + checking: ["Checking…","확인하는 중…","Wird geprüft…","Vérification…","正在检查…","正在檢查…","Проверка…","確認中…","Denetleniyor…","Đang kiểm tra…","Verificando…", "Comprobación…"], + checkHint: ["Checking is read-only: it inspects the installation and the npm registry and changes nothing.","확인은 읽기만 해요. 설치와 npm 레지스트리를 살펴볼 뿐 아무것도 바꾸지 않아요.","Die Prüfung liest nur: Sie untersucht die Installation und die npm-Registry und ändert nichts.","La vérification est en lecture seule : elle inspecte l’installation et le registre npm sans rien modifier.","检查是只读的:只查看安装和 npm 注册表,不做任何更改。","檢查是唯讀的:只查看安裝和 npm 登錄檔,不做任何變更。","Проверка только читает: она осматривает установку и реестр npm и ничего не меняет.","確認は読み取りのみです。インストールと npm レジストリを調べるだけで、何も変更しません。","Denetleme salt okunurdur: kurulumu ve npm kayıt defterini inceler, hiçbir şeyi değiştirmez.","Kiểm tra chỉ đọc: chỉ xem bản cài đặt và npm registry, không thay đổi gì.","A verificação é somente leitura: ela inspeciona a instalação e o registro npm e não altera nada.", "La comprobación solo consulta la instalación y el registro de npm. No realiza cambios."], + fieldProvenance: ["Installed by","설치 방식","Installiert über","Installé par","安装方式","安裝方式","Установлено через","インストール方法","Kuran","Cài đặt bởi","Instalado por", "Instalado por"], + fieldManaged: ["Managed by OpenCodex","OpenCodex 관리","Von OpenCodex verwaltet","Géré par OpenCodex","由 OpenCodex 管理","由 OpenCodex 管理","Управляется OpenCodex","OpenCodex の管理対象","OpenCodex yönetiyor","Do OpenCodex quản lý","Gerenciado pelo OpenCodex", "Gestionado por OpenCodex"], + fieldInstalled: ["Installed version","설치된 버전","Installierte Version","Version installée","已安装版本","已安裝版本","Установленная версия","インストール済みバージョン","Kurulu sürüm","Phiên bản đã cài","Versão instalada", "Versión instalada"], + fieldTarget: ["Available version","받을 수 있는 버전","Verfügbare Version","Version disponible","可用版本","可用版本","Доступная версия","利用可能なバージョン","Mevcut sürüm","Phiên bản có sẵn","Versão disponível", "Versión disponible"], + fieldSession: ["Codex sessions","Codex 세션","Codex-Sitzungen","Sessions Codex","Codex 会话","Codex 工作階段","Сеансы Codex","Codex セッション","Codex oturumları","Phiên Codex","Sessões do Codex", "Sesiones de Codex"], + fieldLocation: ["Location","위치","Ort","Emplacement","位置","位置","Расположение","場所","Konum","Vị trí","Local", "Ubicación"], + fieldCommand: ["Install command","설치 명령","Installationsbefehl","Commande d’installation","安装命令","安裝指令","Команда установки","インストールコマンド","Kurulum komutu","Lệnh cài đặt","Comando de instalação", "Comando de instalación"], + yes: ["Yes","예","Ja","Oui","是","是","Да","はい","Evet","Có","Sim", "Sí"], + no: ["No","아니요","Nein","Non","否","否","Нет","いいえ","Hayır","Không","Não", "No"], + unknown: ["Unknown","알 수 없음","Unbekannt","Inconnu","未知","未知","Неизвестно","不明","Bilinmiyor","Không rõ","Desconhecido", "Desconocido"], + provNpmGlobal: ["npm (global)","npm (전역)","npm (global)","npm (global)","npm(全局)","npm(全域)","npm (глобально)","npm(グローバル)","npm (genel)","npm (toàn cục)","npm (global)", "npm (global)"], + provAppBundle: ["Codex desktop app (bundled)","Codex 데스크톱 앱 (내장)","Codex-Desktop-App (gebündelt)","Application de bureau Codex (intégrée)","Codex 桌面应用(内置)","Codex 桌面應用程式(內建)","Настольное приложение Codex (встроенное)","Codex デスクトップアプリ(同梱)","Codex masaüstü uygulaması (paketli)","Ứng dụng Codex trên máy tính (đi kèm)","Aplicativo Codex para desktop (embutido)", "Aplicación de escritorio de Codex (incluido)"], + provVersionManager: ["A version manager","버전 관리자","Ein Versionsmanager","Un gestionnaire de versions","版本管理器","版本管理器","Менеджер версий","バージョンマネージャー","Bir sürüm yöneticisi","Trình quản lý phiên bản","Um gerenciador de versões", "Gestor de versiones"], + provStandaloneUnverified: ["Standalone installer (unverified)","독립 설치 프로그램 (확인 안 됨)","Eigenständiger Installer (nicht verifiziert)","Installateur autonome (non vérifié)","独立安装程序(未验证)","獨立安裝程式(未驗證)","Отдельный установщик (не проверен)","単体インストーラー(未検証)","Bağımsız yükleyici (doğrulanmadı)","Trình cài đặt độc lập (chưa xác minh)","Instalador independente (não verificado)", "Instalador independiente (sin verificar)"], + sessionNone: ["None running","실행 중인 세션 없음","Keine aktiv","Aucune en cours","没有运行中的会话","沒有執行中的工作階段","Нет запущенных","実行中なし","Çalışan yok","Không có phiên nào đang chạy","Nenhuma em execução", "Ninguna en ejecución"], + sessionActive: ["{count} running","{count}개 실행 중","{count} aktiv","{count} en cours","{count} 个运行中","{count} 個執行中","Запущено: {count}","{count} 件実行中","{count} çalışıyor","{count} đang chạy","{count} em execução", "En ejecución: {count}"], + sessionUnknown: ["Could not be checked","확인하지 못했어요","Konnte nicht geprüft werden","Impossible à vérifier","无法检查","無法檢查","Не удалось проверить","確認できませんでした","Denetlenemedi","Không kiểm tra được","Não foi possível verificar", "No se pudo comprobar"], + sessionNotEvaluated: ["Not checked","확인하지 않음","Nicht geprüft","Non vérifié","未检查","未檢查","Не проверялось","未確認","Denetlenmedi","Chưa kiểm tra","Não verificado", "No comprobado"], + ready: ["An update is ready to apply.","적용할 수 있는 업데이트가 있어요.","Ein Update kann angewendet werden.","Une mise à jour est prête à être appliquée.","有可应用的更新。","有可套用的更新。","Обновление готово к установке.","適用できる更新があります。","Uygulanmaya hazır bir güncelleme var.","Có bản cập nhật sẵn sàng để áp dụng.","Há uma atualização pronta para aplicar.", "Hay una actualización lista para aplicar."], + refusalWindowsInspectionDeferred: ["This Windows installation can't be inspected for updates yet.","이 Windows 설치는 아직 업데이트를 확인할 수 없어요.","Diese Windows-Installation kann noch nicht auf Updates geprüft werden.","Cette installation Windows ne peut pas encore être inspectée pour les mises à jour.","暂时无法检查此 Windows 安装的更新。","暫時無法檢查此 Windows 安裝的更新。","Эту установку Windows пока нельзя проверить на обновления.","この Windows のインストールはまだ更新を確認できません。","Bu Windows kurulumu henüz güncelleme için incelenemiyor.","Chưa thể kiểm tra cập nhật cho bản cài đặt Windows này.","Esta instalação do Windows ainda não pode ser verificada para atualizações.", "Aún no se pueden buscar actualizaciones para esta instalación de Windows."], + refusalWindowsApplyDisabled: ["Updating this Windows installation from OpenCodex is not supported yet.","이 Windows 설치는 아직 OpenCodex에서 업데이트할 수 없어요.","Diese Windows-Installation kann noch nicht aus OpenCodex aktualisiert werden.","La mise à jour de cette installation Windows depuis OpenCodex n’est pas encore prise en charge.","暂不支持从 OpenCodex 更新此 Windows 安装。","暫不支援從 OpenCodex 更新此 Windows 安裝。","Обновление этой установки Windows из OpenCodex пока не поддерживается.","この Windows のインストールは、まだ OpenCodex から更新できません。","Bu Windows kurulumunu OpenCodex'ten güncellemek henüz desteklenmiyor.","Chưa hỗ trợ cập nhật bản cài đặt Windows này từ OpenCodex.","Atualizar esta instalação do Windows pelo OpenCodex ainda não é suportado.", "Aún no se puede actualizar esta instalación de Windows desde OpenCodex."], + refusalNotManaged: ["OpenCodex does not manage this installation. Update it with the tool that installed it.","OpenCodex가 관리하는 설치가 아니에요. 설치한 도구로 업데이트하세요.","OpenCodex verwaltet diese Installation nicht. Aktualisiere sie mit dem Werkzeug, das sie installiert hat.","OpenCodex ne gère pas cette installation. Mettez-la à jour avec l’outil qui l’a installée.","OpenCodex 不管理此安装。请用安装它的工具来更新。","OpenCodex 不管理此安裝。請用安裝它的工具來更新。","OpenCodex не управляет этой установкой. Обновите её тем инструментом, которым она установлена.","このインストールは OpenCodex の管理対象ではありません。インストールしたツールで更新してください。","OpenCodex bu kurulumu yönetmiyor. Onu kuran araçla güncelleyin.","OpenCodex không quản lý bản cài đặt này. Hãy cập nhật bằng công cụ đã cài nó.","O OpenCodex não gerencia esta instalação. Atualize-a com a ferramenta que a instalou.", "OpenCodex no gestiona esta instalación. Actualízala con la herramienta que la instaló."], + refusalInstalledVersionUnverified: ["The installed version could not be verified.","설치된 버전을 확인하지 못했어요.","Die installierte Version konnte nicht verifiziert werden.","La version installée n’a pas pu être vérifiée.","无法验证已安装的版本。","無法驗證已安裝的版本。","Не удалось подтвердить установленную версию.","インストール済みのバージョンを確認できませんでした。","Kurulu sürüm doğrulanamadı.","Không xác minh được phiên bản đã cài.","Não foi possível verificar a versão instalada.", "No se pudo verificar la versión instalada."], + refusalInstallContentUnverified: ["The installed files could not be verified, so no update is offered.","설치된 파일을 확인하지 못해 업데이트를 제안하지 않아요.","Die installierten Dateien konnten nicht verifiziert werden, daher wird kein Update angeboten.","Les fichiers installés n’ont pas pu être vérifiés, aucune mise à jour n’est donc proposée.","无法验证已安装的文件,因此不提供更新。","無法驗證已安裝的檔案,因此不提供更新。","Не удалось проверить установленные файлы, поэтому обновление не предлагается.","インストール済みのファイルを確認できないため、更新は提示しません。","Kurulu dosyalar doğrulanamadı, bu yüzden güncelleme sunulmuyor.","Không xác minh được các tệp đã cài nên không đề xuất cập nhật.","Os arquivos instalados não puderam ser verificados, então nenhuma atualização é oferecida.", "No se pudieron verificar los archivos instalados, por lo que no se ofrece una actualización."], + refusalTargetUnresolved: ["The latest version could not be resolved from the npm registry.","npm 레지스트리에서 최신 버전을 확인하지 못했어요.","Die neueste Version konnte nicht aus der npm-Registry ermittelt werden.","La dernière version n’a pas pu être déterminée depuis le registre npm.","无法从 npm 注册表确定最新版本。","無法從 npm 登錄檔確定最新版本。","Не удалось определить последнюю версию в реестре npm.","npm レジストリから最新バージョンを特定できませんでした。","En son sürüm npm kayıt defterinden belirlenemedi.","Không xác định được phiên bản mới nhất từ npm registry.","Não foi possível obter a versão mais recente do registro npm.", "No se pudo determinar la última versión en el registro de npm."], + refusalAlreadyCurrent: ["The Codex CLI is already up to date.","Codex CLI가 이미 최신이에요.","Die Codex CLI ist bereits aktuell.","Codex CLI est déjà à jour.","Codex CLI 已是最新版本。","Codex CLI 已是最新版本。","Codex CLI уже обновлён.","Codex CLI はすでに最新です。","Codex CLI zaten güncel.","Codex CLI đã là bản mới nhất.","O Codex CLI já está atualizado.", "Codex CLI ya está actualizado."], + refusalTargetNotNewer: ["The registry version is not newer than the installed one.","레지스트리 버전이 설치된 버전보다 새롭지 않아요.","Die Registry-Version ist nicht neuer als die installierte.","La version du registre n’est pas plus récente que celle installée.","注册表中的版本不比已安装的新。","登錄檔中的版本不比已安裝的新。","Версия в реестре не новее установленной.","レジストリのバージョンはインストール済みより新しくありません。","Kayıt defterindeki sürüm kurulu olandan yeni değil.","Phiên bản trên registry không mới hơn bản đã cài.","A versão do registro não é mais nova que a instalada.", "La versión del registro no es más reciente que la instalada."], + refusalBlockedActiveSession: ["A Codex session is using this installation. Close it and check again.","Codex 세션이 이 설치를 사용하고 있어요. 세션을 닫고 다시 확인하세요.","Eine Codex-Sitzung verwendet diese Installation. Schließe sie und prüfe erneut.","Une session Codex utilise cette installation. Fermez-la puis vérifiez à nouveau.","有 Codex 会话正在使用此安装。请关闭后再检查。","有 Codex 工作階段正在使用此安裝。請關閉後再檢查。","Эту установку использует сеанс Codex. Закройте его и проверьте снова.","Codex セッションがこのインストールを使用中です。閉じてからもう一度確認してください。","Bir Codex oturumu bu kurulumu kullanıyor. Kapatıp yeniden denetleyin.","Một phiên Codex đang dùng bản cài đặt này. Hãy đóng nó rồi kiểm tra lại.","Uma sessão do Codex está usando esta instalação. Feche-a e verifique novamente.", "Una sesión de Codex usa esta instalación. Ciérrala y vuelve a comprobar."], + refusalBlockedProcessStateUnknown: ["Running Codex processes could not be checked, so the update waits.","실행 중인 Codex 프로세스를 확인하지 못해 업데이트를 미뤄요.","Laufende Codex-Prozesse konnten nicht geprüft werden, daher wartet das Update.","Les processus Codex en cours n’ont pas pu être vérifiés, la mise à jour attend donc.","无法检查正在运行的 Codex 进程,因此暂缓更新。","無法檢查執行中的 Codex 程序,因此暫緩更新。","Не удалось проверить запущенные процессы Codex, поэтому обновление откладывается.","実行中の Codex プロセスを確認できないため、更新は保留します。","Çalışan Codex süreçleri denetlenemedi, bu yüzden güncelleme bekliyor.","Không kiểm tra được các tiến trình Codex đang chạy nên việc cập nhật tạm hoãn.","Não foi possível verificar os processos do Codex em execução, então a atualização aguarda.", "No se pudieron comprobar los procesos de Codex en ejecución. La actualización queda en espera."], + confirm: ["I understand this changes only this Codex CLI installation. OpenCodex and the desktop app are not updated or restarted.","이 작업은 이 Codex CLI 설치만 바꾼다는 것을 이해했어요. OpenCodex와 데스크톱 앱은 업데이트하거나 다시 시작하지 않아요.","Mir ist klar, dass nur diese Codex-CLI-Installation geändert wird. OpenCodex und die Desktop-App werden weder aktualisiert noch neu gestartet.","Je comprends que seule cette installation de Codex CLI est modifiée. OpenCodex et l’application de bureau ne sont ni mis à jour ni redémarrés.","我了解这只会更改这个 Codex CLI 安装。OpenCodex 和桌面应用不会被更新或重启。","我了解這只會變更這個 Codex CLI 安裝。OpenCodex 和桌面應用程式不會被更新或重新啟動。","Я понимаю, что меняется только эта установка Codex CLI. OpenCodex и настольное приложение не обновляются и не перезапускаются.","この操作で変わるのはこの Codex CLI のインストールだけだと理解しました。OpenCodex とデスクトップアプリは更新も再起動もされません。","Bunun yalnızca bu Codex CLI kurulumunu değiştirdiğini anlıyorum. OpenCodex ve masaüstü uygulaması güncellenmez ya da yeniden başlatılmaz.","Tôi hiểu việc này chỉ thay đổi bản cài đặt Codex CLI này. OpenCodex và ứng dụng máy tính không được cập nhật hay khởi động lại.","Entendo que isto altera apenas esta instalação do Codex CLI. O OpenCodex e o aplicativo para desktop não são atualizados nem reiniciados.", "Entiendo que esto solo modifica esta instalación de Codex CLI. OpenCodex y la aplicación de escritorio no se actualizan ni se reinician."], + apply: ["Update Codex CLI","Codex CLI 업데이트","Codex CLI aktualisieren","Mettre à jour Codex CLI","更新 Codex CLI","更新 Codex CLI","Обновить Codex CLI","Codex CLI を更新","Codex CLI'yi güncelle","Cập nhật Codex CLI","Atualizar Codex CLI", "Actualizar Codex CLI"], + applying: ["Updating…","업데이트하는 중…","Wird aktualisiert…","Mise à jour…","正在更新…","正在更新…","Обновление…","更新中…","Güncelleniyor…","Đang cập nhật…","Atualizando…", "Actualizando…"], + jobQueued: ["Waiting to start…","시작을 기다리는 중…","Wartet auf Start…","En attente de démarrage…","等待开始…","等待開始…","Ожидание запуска…","開始を待っています…","Başlaması bekleniyor…","Đang chờ bắt đầu…","Aguardando início…", "Esperando para empezar…"], + jobRunning: ["Installing…","설치하는 중…","Wird installiert…","Installation…","正在安装…","正在安裝…","Установка…","インストール中…","Kuruluyor…","Đang cài đặt…","Instalando…", "Instalando…"], + jobApplied: ["Updated. The installed version was read back and matches.","업데이트했어요. 설치된 버전을 다시 읽어 확인했어요.","Aktualisiert. Die installierte Version wurde zurückgelesen und stimmt.","Mis à jour. La version installée a été relue et correspond.","已更新。已回读安装的版本并确认一致。","已更新。已回讀安裝的版本並確認一致。","Обновлено. Установленная версия перечитана и совпадает.","更新しました。インストール済みバージョンを読み直して一致を確認しました。","Güncellendi. Kurulu sürüm yeniden okundu ve eşleşiyor.","Đã cập nhật. Phiên bản đã cài được đọc lại và khớp.","Atualizado. A versão instalada foi relida e confere.", "Actualizado. Se comprobó que la versión instalada coincide."], + jobNotApplied: ["Not updated. The installation was left as it was.","업데이트하지 않았어요. 설치는 그대로예요.","Nicht aktualisiert. Die Installation blieb unverändert.","Non mis à jour. L’installation est restée telle quelle.","未更新。安装保持原样。","未更新。安裝保持原樣。","Не обновлено. Установка осталась прежней.","更新していません。インストールはそのままです。","Güncellenmedi. Kurulum olduğu gibi bırakıldı.","Chưa cập nhật. Bản cài đặt được giữ nguyên.","Não atualizado. A instalação ficou como estava.", "No se actualizó. La instalación quedó como estaba."], + jobRefused: ["Refused before anything was installed.","설치하기 전에 거부됐어요.","Abgelehnt, bevor etwas installiert wurde.","Refusé avant toute installation.","在安装任何内容之前被拒绝。","在安裝任何內容之前被拒絕。","Отклонено до какой-либо установки.","何かをインストールする前に拒否されました。","Herhangi bir şey kurulmadan reddedildi.","Bị từ chối trước khi cài bất cứ thứ gì.","Recusado antes de qualquer instalação.", "Se rechazó antes de instalar nada."], + jobAmbiguous: ["The result is unclear. Check the installation yourself; OpenCodex will not retry or roll back.","결과가 분명하지 않아요. 설치를 직접 확인하세요. OpenCodex는 다시 시도하거나 되돌리지 않아요.","Das Ergebnis ist unklar. Prüfe die Installation selbst; OpenCodex wiederholt nichts und rollt nichts zurück.","Le résultat est incertain. Vérifiez l’installation vous-même ; OpenCodex ne réessaie pas et n’annule rien.","结果不明确。请自行检查安装;OpenCodex 不会重试或回滚。","結果不明確。請自行檢查安裝;OpenCodex 不會重試或復原。","Результат неясен. Проверьте установку сами; OpenCodex не повторяет и не откатывает.","結果がはっきりしません。インストールをご自身で確認してください。OpenCodex は再試行もロールバックもしません。","Sonuç belirsiz. Kurulumu kendiniz denetleyin; OpenCodex yeniden denemez veya geri almaz.","Kết quả không rõ ràng. Hãy tự kiểm tra bản cài đặt; OpenCodex sẽ không thử lại hay hoàn tác.","O resultado é incerto. Verifique a instalação você mesmo; o OpenCodex não tentará de novo nem desfará.", "El resultado no está claro. Comprueba la instalación manualmente. OpenCodex no reintentará ni revertirá el cambio."], + reasonOwnerStateUnknown: ["OpenCodex lost track of this job (for example after a restart), so its result is unknown.", "OpenCodex가 이 작업을 추적하지 못했어요(예: 다시 시작된 경우). 그래서 결과를 알 수 없어요.", "OpenCodex hat den Auftrag aus den Augen verloren (etwa nach einem Neustart), daher ist das Ergebnis unbekannt.", "OpenCodex a perdu le suivi de cette tâche (par exemple après un redémarrage), son résultat est donc inconnu.", "OpenCodex 失去了对此任务的跟踪(例如重启后),因此结果未知。", "OpenCodex 失去了對此工作的追蹤(例如重新啟動後),因此結果未知。", "OpenCodex потерял отслеживание этого задания (например, после перезапуска), поэтому результат неизвестен.", "OpenCodex がこのジョブを追跡できなくなりました(再起動後など)。そのため結果は不明です。", "OpenCodex bu işin izini kaybetti (örneğin yeniden başlatmadan sonra), bu yüzden sonuç bilinmiyor.", "OpenCodex đã mất dấu tác vụ này (ví dụ sau khi khởi động lại) nên không rõ kết quả.", "O OpenCodex perdeu o acompanhamento desta tarefa (por exemplo, após reiniciar), então o resultado é desconhecido.", "OpenCodex perdió el seguimiento de esta tarea (por ejemplo, tras un reinicio). Se desconoce el resultado."], + reasonLabel: ["Reason code","사유 코드","Grundcode","Code de raison","原因代码","原因代碼","Код причины","理由コード","Neden kodu","Mã lý do","Código do motivo", "Código del motivo"], + errPlanUnavailable: ["The update check failed. Try again.","업데이트 확인에 실패했어요. 다시 시도하세요.","Die Update-Prüfung ist fehlgeschlagen. Versuche es erneut.","La vérification a échoué. Réessayez.","检查更新失败。请重试。","檢查更新失敗。請重試。","Проверка обновления не удалась. Повторите попытку.","更新の確認に失敗しました。もう一度お試しください。","Güncelleme denetimi başarısız oldu. Yeniden deneyin.","Kiểm tra cập nhật thất bại. Hãy thử lại.","A verificação falhou. Tente novamente.", "Falló la comprobación de actualizaciones. Vuelve a intentarlo."], + errLocalOnly: ["Applying needs a paired browser on this computer. Pair it below (it runs the ocx gui pair command), or update from a terminal:","적용하려면 이 컴퓨터에서 페어링된 브라우저가 필요해요. 아래에서 페어링하거나(ocx gui pair 명령을 실행해요) 터미널에서 업데이트하세요:","Zum Anwenden braucht es einen gekoppelten Browser auf diesem Computer. Kopple ihn unten (dabei läuft der Befehl ocx gui pair) oder aktualisiere im Terminal:","L’application exige un navigateur appairé sur cet ordinateur. Appairez-le ci-dessous (avec la commande ocx gui pair) ou mettez à jour depuis un terminal :","应用需要在这台电脑上已配对的浏览器。请在下方配对(会使用 ocx gui pair 命令),或在终端中更新:","套用需要在這台電腦上已配對的瀏覽器。請在下方配對(會使用 ocx gui pair 指令),或在終端機中更新:","Для установки нужен сопряжённый браузер на этом компьютере. Выполните сопряжение ниже (через команду ocx gui pair) или обновите из терминала:","適用するには、このコンピューターでペアリング済みのブラウザーが必要です。下でペアリングする(ocx gui pair コマンドを使います)か、ターミナルから更新してください:","Uygulamak için bu bilgisayarda eşleştirilmiş bir tarayıcı gerekir. Aşağıdan eşleştirin (ocx gui pair komutunu kullanır) veya terminalden güncelleyin:","Để áp dụng cần một trình duyệt đã ghép đôi trên máy này. Hãy ghép đôi bên dưới (dùng lệnh ocx gui pair) hoặc cập nhật từ terminal:","Aplicar exige um navegador pareado neste computador. Pareie-o abaixo (usa o comando ocx gui pair) ou atualize pelo terminal:", "Para aplicar la actualización necesitas un navegador emparejado en este equipo. Emparéjalo abajo (se ejecuta ocx gui pair) o actualiza desde una terminal:"], + errIdempotencyConflict: ["This update request no longer matches. Check again before updating.","이 업데이트 요청이 더 이상 맞지 않아요. 업데이트 전에 다시 확인하세요.","Diese Update-Anfrage passt nicht mehr. Prüfe erneut, bevor du aktualisierst.","Cette demande de mise à jour ne correspond plus. Vérifiez à nouveau avant de mettre à jour.","此更新请求已不再匹配。更新前请重新检查。","此更新請求已不再相符。更新前請重新檢查。","Этот запрос на обновление больше не подходит. Проверьте снова перед обновлением.","この更新リクエストはもう一致しません。更新する前にもう一度確認してください。","Bu güncelleme isteği artık eşleşmiyor. Güncellemeden önce yeniden denetleyin.","Yêu cầu cập nhật này không còn khớp. Hãy kiểm tra lại trước khi cập nhật.","Esta solicitação de atualização não confere mais. Verifique novamente antes de atualizar.", "Esta solicitud de actualización ya no coincide. Vuelve a comprobar antes de actualizar."], + errStore: ["The update job store on this computer can't be used, so the update can't start.","이 컴퓨터의 업데이트 작업 저장소를 쓸 수 없어 업데이트를 시작할 수 없어요.","Der Update-Auftragsspeicher auf diesem Computer ist nicht nutzbar, daher kann das Update nicht starten.","Le stockage des tâches de mise à jour de cet ordinateur est inutilisable ; la mise à jour ne peut pas démarrer.","此电脑上的更新任务存储无法使用,因此无法开始更新。","此電腦上的更新工作儲存無法使用,因此無法開始更新。","Хранилище заданий обновления на этом компьютере недоступно, поэтому обновление не может начаться.","このコンピューターの更新ジョブ保存先が使えないため、更新を開始できません。","Bu bilgisayardaki güncelleme işi deposu kullanılamıyor, bu yüzden güncelleme başlayamıyor.","Không dùng được kho tác vụ cập nhật trên máy này nên không thể bắt đầu cập nhật.","O armazenamento de tarefas de atualização deste computador não pode ser usado, então a atualização não pode começar.", "No se puede usar el registro de tareas de actualización en este equipo, por lo que no se puede iniciar la actualización."], + errRetry: ["The update could not start right now. Try again.","지금은 업데이트를 시작하지 못했어요. 다시 시도하세요.","Das Update konnte gerade nicht starten. Versuche es erneut.","La mise à jour n’a pas pu démarrer pour le moment. Réessayez.","现在无法开始更新。请重试。","現在無法開始更新。請重試。","Сейчас не удалось начать обновление. Повторите попытку.","今は更新を開始できませんでした。もう一度お試しください。","Güncelleme şu anda başlatılamadı. Yeniden deneyin.","Hiện chưa thể bắt đầu cập nhật. Hãy thử lại.","Não foi possível iniciar a atualização agora. Tente novamente.", "No se pudo iniciar la actualización en este momento. Vuelve a intentarlo."], + errApplyFailed: ["The update could not start. The reason code is below.", "업데이트를 시작하지 못했어요. 아래 사유 코드를 확인하세요.", "Das Update konnte nicht starten. Der Grundcode steht unten.", "La mise à jour n’a pas pu démarrer. Le code de raison figure ci-dessous.", "无法开始更新。原因代码见下方。", "無法開始更新。原因代碼見下方。", "Не удалось начать обновление. Код причины указан ниже.", "更新を開始できませんでした。理由コードは下にあります。", "Güncelleme başlatılamadı. Neden kodu aşağıda.", "Không thể bắt đầu cập nhật. Mã lý do ở bên dưới.", "Não foi possível iniciar a atualização. O código do motivo está abaixo.", "No se pudo iniciar la actualización. El código del motivo aparece abajo."], + retry: ["Try again","다시 시도","Erneut versuchen","Réessayer","重试","重試","Повторить","再試行","Yeniden dene","Thử lại","Tentar novamente", "Inténtalo de nuevo"], + errJobNotFound: ["The job record is gone, so its result is unknown. Check the installation yourself.","작업 기록이 사라져 결과를 알 수 없어요. 설치를 직접 확인하세요.","Der Auftragseintrag fehlt, daher ist das Ergebnis unbekannt. Prüfe die Installation selbst.","L’enregistrement de la tâche a disparu, son résultat est inconnu. Vérifiez l’installation vous-même.","任务记录已不存在,结果未知。请自行检查安装。","工作紀錄已不存在,結果未知。請自行檢查安裝。","Запись задания пропала, результат неизвестен. Проверьте установку сами.","ジョブの記録がなくなったため、結果は不明です。インストールをご自身で確認してください。","İş kaydı yok, bu yüzden sonuç bilinmiyor. Kurulumu kendiniz denetleyin.","Bản ghi tác vụ đã mất nên không rõ kết quả. Hãy tự kiểm tra bản cài đặt.","O registro da tarefa sumiu, então o resultado é desconhecido. Verifique a instalação você mesmo.", "Ya no se encuentra el registro de la tarea, por lo que se desconoce el resultado. Comprueba la instalación manualmente."], + errJobUnreadable: ["The job status can't be read right now. Read it from a terminal:","지금은 작업 상태를 읽을 수 없어요. 터미널에서 확인하세요:","Der Auftragsstatus kann gerade nicht gelesen werden. Lies ihn im Terminal:","Le statut de la tâche est illisible pour le moment. Lisez-le depuis un terminal :","现在无法读取任务状态。请在终端中查看:","現在無法讀取工作狀態。請在終端機中查看:","Сейчас не удаётся прочитать статус задания. Посмотрите его в терминале:","今はジョブの状態を読み取れません。ターミナルで確認してください:","İş durumu şu anda okunamıyor. Terminalden okuyun:","Hiện không đọc được trạng thái tác vụ. Hãy xem từ terminal:","O status da tarefa não pode ser lido agora. Leia-o pelo terminal:", "No se puede leer el estado de la tarea en este momento. Consúltalo desde una terminal:"], } satisfies Record; export type CodexCliUpdateCopyKey = `codexCliUpdate.${keyof typeof rows}`; diff --git a/gui/src/i18n/connections-copy.ts b/gui/src/i18n/connections-copy.ts index eed3965d872..baac84648ee 100644 --- a/gui/src/i18n/connections-copy.ts +++ b/gui/src/i18n/connections-copy.ts @@ -3,54 +3,54 @@ * One row per key, columns in the order of `locales`, kept apart from the per-locale files like * gateway-clients-copy.ts. Paths and setting keys are shown as sent. */ -type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; -const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; -type Row = readonly [string, string, string, string, string, string, string, string, string, string, string]; +type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt" | "es"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt", "es"]; +type Row = readonly [string, string, string, string, string, string, string, string, string, string, string, string]; const rows = { - "title": ["Client connections","클라이언트 연결","Client-Verbindungen","Connexions des clients","客户端连接","用戶端連線","Подключения клиентов","クライアント接続","İstemci bağlantıları","Kết nối máy khách","Conexões dos clientes"], - "intro": ["Where each client goes now, who owns its settings, and what switching it back would change. Read-only: nothing here writes.","각 클라이언트가 지금 어디로 가는지, 설정을 누가 소유하는지, 되돌리면 무엇이 바뀌는지 보여 줘요. 읽기 전용이라 여기서는 아무것도 쓰지 않아요.","Wohin jeder Client gerade geht, wem seine Einstellungen gehören und was ein Zurückschalten ändern würde. Nur lesend: hier wird nichts geschrieben.","Où va chaque client maintenant, à qui appartiennent ses réglages et ce que le retour en arrière changerait. Lecture seule : rien n’est écrit ici.","每个客户端现在去往哪里、谁拥有它的设置、切回会改变什么。只读:这里不会写入任何内容。","每個用戶端現在前往哪裡、誰擁有它的設定、切回會改變什麼。唯讀:這裡不會寫入任何內容。","Куда сейчас идёт каждый клиент, кому принадлежат его настройки и что изменит возврат. Только чтение: здесь ничего не записывается.","各クライアントが今どこへ向かっているか、設定の所有者、元に戻すと何が変わるかを表示します。読み取り専用で、ここでは何も書き込みません。","Her istemcinin şu an nereye gittiği, ayarlarının kime ait olduğu ve geri almanın neyi değiştireceği. Salt okunur: burada hiçbir şey yazılmaz.","Mỗi máy khách hiện đi đâu, ai sở hữu cài đặt của nó và chuyển về sẽ thay đổi gì. Chỉ đọc: không ghi gì ở đây.","Para onde cada cliente vai agora, quem é dono das configurações e o que voltar atrás mudaria. Somente leitura: nada é gravado aqui."], - "loading": ["Reading connection status…","연결 상태를 읽는 중…","Verbindungsstatus wird gelesen…","Lecture de l’état des connexions…","正在读取连接状态…","正在讀取連線狀態…","Чтение состояния подключений…","接続状態を読み込み中…","Bağlantı durumu okunuyor…","Đang đọc trạng thái kết nối…","Lendo o status das conexões…"], - "loadFail": ["Could not read the connection status.","연결 상태를 읽지 못했어요.","Der Verbindungsstatus konnte nicht gelesen werden.","Impossible de lire l’état des connexions.","无法读取连接状态。","無法讀取連線狀態。","Не удалось прочитать состояние подключений.","接続状態を読み取れませんでした。","Bağlantı durumu okunamadı.","Không đọc được trạng thái kết nối.","Não foi possível ler o status das conexões."], - "refresh": ["Refresh","새로고침","Aktualisieren","Actualiser","刷新","重新整理","Обновить","更新","Yenile","Làm mới","Atualizar"], - "homeDefault": ["Default home","기본 home","Standard-Home","Dossier par défaut","默认主目录","預設主目錄","Домашний каталог по умолчанию","既定のホーム","Varsayılan ana dizin","Thư mục mặc định","Pasta padrão"], - "homeExtra": ["Registered home {n}","등록한 home {n}","Registriertes Home {n}","Dossier enregistré {n}","已登记的主目录 {n}","已登記的主目錄 {n}","Зарегистрированный каталог {n}","登録したホーム {n}","Kayıtlı ana dizin {n}","Thư mục đã đăng ký {n}","Pasta registrada {n}"], - "desired": ["Wanted","원하는 상태","Gewünscht","Souhaité","期望","期望","Нужно","希望","İstenen","Mong muốn","Desejado"], - "observed": ["Now","현재","Aktuell","Actuel","当前","目前","Сейчас","現在","Şu an","Hiện tại","Agora"], - "owner": ["Owner","소유자","Eigentümer","Propriétaire","所有者","擁有者","Владелец","所有者","Sahip","Chủ sở hữu","Dono"], - "state.proxy": ["Through OpenCodex","OpenCodex 경유","Über OpenCodex","Via OpenCodex","经由 OpenCodex","經由 OpenCodex","Через OpenCodex","OpenCodex 経由","OpenCodex üzerinden","Qua OpenCodex","Via OpenCodex"], - "state.native": ["Native","기본 경로","Nativ","Natif","原生","原生","Напрямую","ネイティブ","Yerel","Gốc","Nativo"], - "state.remote-home": ["Through the Remote Link Home","Remote Link Home 경유","Über das Remote-Link-Home","Via le Remote Link Home","经由 Remote Link Home","經由 Remote Link Home","Через Remote Link Home","Remote Link Home 経由","Remote Link Home üzerinden","Qua Remote Link Home","Via o Remote Link Home"], - "state.unset": ["Not managed by OpenCodex","OpenCodex가 관리하지 않음","Nicht von OpenCodex verwaltet","Non géré par OpenCodex","不由 OpenCodex 管理","不由 OpenCodex 管理","Не управляется OpenCodex","OpenCodex の管理外","OpenCodex tarafından yönetilmiyor","OpenCodex không quản lý","Não gerenciado pelo OpenCodex"], - "state.foreign": ["Another proxy or provider","다른 프록시 또는 공급자","Anderer Proxy oder Anbieter","Autre proxy ou fournisseur","其他代理或提供商","其他代理或供應商","Другой прокси или провайдер","別のプロキシまたはプロバイダー","Başka bir proxy veya sağlayıcı","Proxy hoặc nhà cung cấp khác","Outro proxy ou provedor"], - "state.missing": ["Not set up","설정 없음","Nicht eingerichtet","Non configuré","未设置","未設定","Не настроено","未設定","Kurulmamış","Chưa thiết lập","Não configurado"], - "state.unknown": ["Unknown","알 수 없음","Unbekannt","Inconnu","未知","未知","Неизвестно","不明","Bilinmiyor","Không rõ","Desconhecido"], - "owner.opencodex": ["Managed by OpenCodex","OpenCodex가 관리","Von OpenCodex verwaltet","Géré par OpenCodex","由 OpenCodex 管理","由 OpenCodex 管理","Управляется OpenCodex","OpenCodex が管理","OpenCodex tarafından yönetiliyor","Do OpenCodex quản lý","Gerenciado pelo OpenCodex"], - "owner.external": ["Someone else","다른 소유자","Jemand anderes","Quelqu’un d’autre","其他所有者","其他擁有者","Кто-то другой","他の所有者","Başka biri","Bên khác","Outra parte"], - "owner.hub": ["Hub mode","Hub 모드","Hub-Modus","Mode hub","Hub 模式","Hub 模式","Режим хаба","Hub モード","Hub modu","Chế độ Hub","Modo hub"], - "owner.none": ["Nobody","없음","Niemand","Personne","无","無","Никто","なし","Yok","Không có","Ninguém"], - "owner.unknown": ["Unknown","알 수 없음","Unbekannt","Inconnu","未知","未知","Неизвестно","不明","Bilinmiyor","Không rõ","Desconhecido"], - "ownerPath": ["Owned by {path}","소유 파일: {path}","Gehört zu {path}","Appartient à {path}","所属文件:{path}","所屬檔案:{path}","Принадлежит {path}","所有ファイル: {path}","Sahibi: {path}","Thuộc về {path}","Pertence a {path}"], - "reason.external_owner": ["Another program, OpenCodex home or service owns these files, so OpenCodex leaves them alone.","다른 프로그램, OpenCodex home 또는 서비스가 이 파일을 소유하고 있어서 OpenCodex가 건드리지 않아요.","Ein anderes Programm, OpenCodex-Home oder ein Dienst besitzt diese Dateien, daher lässt OpenCodex sie unverändert.","Un autre programme, dossier OpenCodex ou service possède ces fichiers ; OpenCodex n’y touche donc pas.","这些文件属于其他程序、OpenCodex 主目录或服务,因此 OpenCodex 不会改动它们。","這些檔案屬於其他程式、OpenCodex 主目錄或服務,因此 OpenCodex 不會變動它們。","Этими файлами владеет другая программа, каталог OpenCodex или служба, поэтому OpenCodex их не трогает.","別のプログラム、OpenCodex ホーム、またはサービスがこれらのファイルを所有しているため、OpenCodex は変更しません。","Bu dosyalar başka bir programa, OpenCodex ana dizinine veya hizmete ait; bu yüzden OpenCodex onlara dokunmaz.","Một chương trình, thư mục OpenCodex hoặc dịch vụ khác sở hữu các tệp này, nên OpenCodex không động vào.","Outro programa, pasta do OpenCodex ou serviço é dono destes arquivos, então o OpenCodex não mexe neles."], - "reason.account_mode": ["Claude Desktop is pinned to one account mode but runs the other.","Claude Desktop이 한 계정 모드로 고정되어 있지만 다른 모드로 실행 중이에요.","Claude Desktop ist auf einen Kontomodus festgelegt, läuft aber im anderen.","Claude Desktop est fixé sur un mode de compte mais fonctionne dans l’autre.","Claude Desktop 固定为一种账户模式,却在以另一种模式运行。","Claude Desktop 固定為一種帳戶模式,卻以另一種模式執行。","Claude Desktop закреплён за одним режимом учётной записи, но работает в другом.","Claude Desktop は一方のアカウントモードに固定されていますが、もう一方で動いています。","Claude Desktop bir hesap moduna sabitlenmiş ama diğerinde çalışıyor.","Claude Desktop được ghim vào một chế độ tài khoản nhưng đang chạy chế độ kia.","O Claude Desktop está fixado em um modo de conta, mas roda no outro."], - "reason.hub_gated": ["This machine is a hub, so it does not rewrite its own clients unless the loopback listener is enabled.","이 기기는 hub라서 loopback listener를 켜지 않으면 자기 클라이언트 설정을 다시 쓰지 않아요.","Dieser Rechner ist ein Hub und schreibt seine eigenen Clients nur mit aktiviertem Loopback-Listener um.","Cette machine est un hub : elle ne réécrit ses propres clients que si l’écoute loopback est activée.","这台机器是 hub,除非启用 loopback 监听,否则不会改写自己的客户端。","這台機器是 hub,除非啟用 loopback 監聽,否則不會改寫自己的用戶端。","Эта машина — хаб и не перезаписывает свои клиенты, пока не включён loopback-слушатель.","このマシンは hub なので、loopback リスナーを有効にしない限り自身のクライアントを書き換えません。","Bu makine bir hub; loopback dinleyicisi açık olmadıkça kendi istemcilerini yeniden yazmaz.","Máy này là hub nên không ghi lại máy khách của chính nó trừ khi bật loopback listener.","Esta máquina é um hub e não reescreve os próprios clientes, a menos que o listener de loopback esteja ativado."], - "reason.intercept_disabled": ["First-party is on, but the interception proxy is disabled here.","first-party가 켜져 있지만 이 기기에서는 가로채기 프록시가 꺼져 있어요.","First-Party ist an, aber der Abfang-Proxy ist hier deaktiviert.","Le mode first-party est actif, mais le proxy d’interception est désactivé ici.","first-party 已开启,但这里的拦截代理已禁用。","first-party 已開啟,但這裡的攔截代理已停用。","Режим first-party включён, но перехватывающий прокси здесь отключён.","first-party はオンですが、ここではインターセプトプロキシが無効です。","First-party açık ama burada yakalama proxy'si devre dışı.","First-party đang bật nhưng proxy chặn đã bị tắt ở đây.","O first-party está ligado, mas o proxy de interceptação está desativado aqui."], - "reason.file_edited": ["The file no longer matches the switch: it was edited, rewritten by the app, or left over from an earlier change.","파일이 스위치와 맞지 않아요. 직접 수정됐거나, 앱이 다시 썼거나, 이전 변경에서 남은 거예요.","Die Datei passt nicht mehr zum Schalter: bearbeitet, von der App neu geschrieben oder von einer früheren Änderung übrig.","Le fichier ne correspond plus à l’interrupteur : modifié, réécrit par l’application ou resté d’un changement précédent.","文件已与开关不一致:被编辑过、被应用改写,或是之前更改的残留。","檔案已與開關不一致:被編輯過、被應用程式改寫,或是先前變更的殘留。","Файл больше не соответствует переключателю: его изменили, перезаписало приложение или он остался от прошлого изменения.","ファイルがスイッチと一致しません。編集されたか、アプリが書き換えたか、以前の変更の残りです。","Dosya artık anahtarla eşleşmiyor: düzenlenmiş, uygulama tarafından yeniden yazılmış ya da önceki bir değişiklikten kalmış.","Tệp không còn khớp với công tắc: đã bị sửa, bị ứng dụng ghi lại hoặc còn sót từ thay đổi trước.","O arquivo não corresponde mais ao interruptor: foi editado, reescrito pelo app ou sobrou de uma mudança anterior."], - "reason.pending_restart": ["The settings are written, but the listener they point at is stopped or on another port. Start OpenCodex or run ocx ensure.","설정은 써 있지만 가리키는 listener가 멈췄거나 다른 포트에 있어요. OpenCodex를 시작하거나 ocx ensure를 실행하세요.","Die Einstellungen sind geschrieben, aber der Listener ist gestoppt oder auf einem anderen Port. Starten Sie OpenCodex oder führen Sie ocx ensure aus.","Les réglages sont écrits, mais l’écouteur visé est arrêté ou sur un autre port. Démarrez OpenCodex ou lancez ocx ensure.","设置已写入,但指向的监听器已停止或在其他端口。请启动 OpenCodex 或运行 ocx ensure。","設定已寫入,但指向的監聽器已停止或在其他連接埠。請啟動 OpenCodex 或執行 ocx ensure。","Настройки записаны, но указанный слушатель остановлен или на другом порту. Запустите OpenCodex или выполните ocx ensure.","設定は書き込まれていますが、指す先のリスナーが停止しているか別のポートです。OpenCodex を起動するか ocx ensure を実行してください。","Ayarlar yazıldı ama gösterdikleri dinleyici durmuş ya da başka bir portta. OpenCodex'i başlatın veya ocx ensure çalıştırın.","Cài đặt đã được ghi nhưng listener mà nó trỏ tới đã dừng hoặc ở cổng khác. Hãy khởi động OpenCodex hoặc chạy ocx ensure.","As configurações estão gravadas, mas o listener indicado está parado ou em outra porta. Inicie o OpenCodex ou rode ocx ensure."], - "restoreTitle": ["Switching it back would change","되돌리면 바뀌는 항목","Zurückschalten würde ändern","Le retour en arrière changerait","切回将会改变","切回將會改變","Возврат изменит","元に戻すと変わる項目","Geri almak şunları değiştirir","Chuyển về sẽ thay đổi","Voltar atrás mudaria"], - "restoreNone": ["No settings keys would change.","바뀌는 설정 키가 없어요.","Keine Einstellungsschlüssel würden sich ändern.","Aucune clé de réglage ne changerait.","没有设置键会改变。","沒有設定鍵會改變。","Ни один ключ настроек не изменится.","変わる設定キーはありません。","Hiçbir ayar anahtarı değişmez.","Không có khóa cài đặt nào thay đổi.","Nenhuma chave de configuração mudaria."], - "change.add": ["added","추가","hinzugefügt","ajoutée","新增","新增","добавится","追加","eklenir","thêm","adicionada"], - "change.update": ["changed","변경","geändert","modifiée","更改","變更","изменится","変更","değişir","thay đổi","alterada"], - "change.remove": ["removed","삭제","entfernt","supprimée","移除","移除","удалится","削除","kaldırılır","xóa","removida"], - "outcome.refused": ["Switching back would be refused first: {reason}","되돌리기가 먼저 거절돼요: {reason}","Das Zurückschalten würde zuerst abgelehnt: {reason}","Le retour en arrière serait d’abord refusé : {reason}","切回会先被拒绝:{reason}","切回會先被拒絕:{reason}","Возврат будет сначала отклонён: {reason}","元に戻す操作は先に拒否されます: {reason}","Geri alma önce reddedilir: {reason}","Chuyển về sẽ bị từ chối trước: {reason}","Voltar atrás seria recusado primeiro: {reason}"], - "homesTitle": ["Claude homes","Claude home 목록","Claude-Homes","Dossiers Claude","Claude 主目录","Claude 主目錄","Каталоги Claude","Claude ホーム","Claude ana dizinleri","Thư mục Claude","Pastas do Claude"], - "homesHint": ["The switch acts on the default home. Add more under claudeCode.extraConfigDirs to see them here.","스위치는 기본 home에만 적용돼요. claudeCode.extraConfigDirs에 추가하면 여기에 함께 보여요.","Der Schalter wirkt auf das Standard-Home. Weitere unter claudeCode.extraConfigDirs eintragen, um sie hier zu sehen.","L’interrupteur agit sur le dossier par défaut. Ajoutez-en d’autres dans claudeCode.extraConfigDirs pour les voir ici.","开关只作用于默认主目录。把其他目录加到 claudeCode.extraConfigDirs 即可在此看到。","開關只作用於預設主目錄。把其他目錄加到 claudeCode.extraConfigDirs 即可在此看到。","Переключатель действует на каталог по умолчанию. Добавьте другие в claudeCode.extraConfigDirs, чтобы видеть их здесь.","スイッチは既定のホームに作用します。claudeCode.extraConfigDirs に追加するとここに表示されます。","Anahtar varsayılan ana dizine uygulanır. Diğerlerini burada görmek için claudeCode.extraConfigDirs'e ekleyin.","Công tắc tác động lên thư mục mặc định. Thêm thư mục khác vào claudeCode.extraConfigDirs để xem ở đây.","O interruptor age na pasta padrão. Adicione outras em claudeCode.extraConfigDirs para vê-las aqui."], - "preview.title": ["Turn on first-party for Claude Code?","Claude Code first-party를 켤까요?","First-Party für Claude Code einschalten?","Activer le mode first-party pour Claude Code ?","为 Claude Code 开启 first-party?","為 Claude Code 開啟 first-party?","Включить first-party для Claude Code?","Claude Code の first-party をオンにしますか?","Claude Code için first-party açılsın mı?","Bật first-party cho Claude Code?","Ligar o first-party para o Claude Code?"], - "preview.intro": ["These keys in {path} would change. Values are not shown.","{path}에서 아래 키가 바뀌어요. 값은 보여 주지 않아요.","Diese Schlüssel in {path} würden sich ändern. Werte werden nicht angezeigt.","Ces clés de {path} changeraient. Les valeurs ne sont pas affichées.","{path} 中的以下键会改变。不显示值。","{path} 中的以下鍵會改變。不顯示值。","Эти ключи в {path} изменятся. Значения не показываются.","{path} の次のキーが変わります。値は表示しません。","{path} içindeki şu anahtarlar değişir. Değerler gösterilmez.","Các khóa sau trong {path} sẽ thay đổi. Không hiển thị giá trị.","Estas chaves em {path} mudariam. Os valores não são mostrados."], - "preview.checks": ["The switch can still refuse while it starts the intercept or prepares its certificate and token.","가로채기를 시작하거나 인증서와 토큰을 준비하는 중에 스위치가 거절될 수도 있어요.","Der Schalter kann noch ablehnen, während er den Abfang startet oder Zertifikat und Token vorbereitet.","L’interrupteur peut encore refuser en démarrant l’interception ou en préparant son certificat et son jeton.","在启动拦截或准备证书和令牌时,开关仍可能拒绝。","在啟動攔截或準備憑證和權杖時,開關仍可能拒絕。","Переключатель ещё может отказать при запуске перехвата или подготовке сертификата и токена.","インターセプトの開始や証明書・トークンの準備中に、スイッチが拒否することもあります。","Anahtar, yakalamayı başlatırken veya sertifika ve belirtecini hazırlarken yine de reddedebilir.","Công tắc vẫn có thể từ chối khi khởi động chặn hoặc chuẩn bị chứng chỉ và token.","O interruptor ainda pode recusar ao iniciar a interceptação ou preparar o certificado e o token."], - "preview.confirm": ["Turn on","켜기","Einschalten","Activer","开启","開啟","Включить","オンにする","Aç","Bật","Ligar"], - "preview.cancel": ["Cancel","취소","Abbrechen","Annuler","取消","取消","Отмена","キャンセル","İptal","Hủy","Cancelar"], - "preview.loadFail": ["Could not preview the change, so nothing was changed.","변경 내용을 미리 보지 못해서 아무것도 바꾸지 않았어요.","Die Änderung konnte nicht vorab angezeigt werden; nichts wurde geändert.","Impossible de prévisualiser le changement ; rien n’a été modifié.","无法预览更改,因此没有做任何改动。","無法預覽變更,因此沒有做任何變動。","Не удалось показать изменение заранее, поэтому ничего не изменено.","変更をプレビューできなかったため、何も変更していません。","Değişiklik önizlenemedi, bu yüzden hiçbir şey değiştirilmedi.","Không xem trước được thay đổi nên chưa thay đổi gì.","Não foi possível pré-visualizar a mudança, então nada foi alterado."], + "title": ["Client connections","클라이언트 연결","Client-Verbindungen","Connexions des clients","客户端连接","用戶端連線","Подключения клиентов","クライアント接続","İstemci bağlantıları","Kết nối máy khách","Conexões dos clientes", "Conexiones de clientes"], + "intro": ["Where each client goes now, who owns its settings, and what switching it back would change. Read-only: nothing here writes.","각 클라이언트가 지금 어디로 가는지, 설정을 누가 소유하는지, 되돌리면 무엇이 바뀌는지 보여 줘요. 읽기 전용이라 여기서는 아무것도 쓰지 않아요.","Wohin jeder Client gerade geht, wem seine Einstellungen gehören und was ein Zurückschalten ändern würde. Nur lesend: hier wird nichts geschrieben.","Où va chaque client maintenant, à qui appartiennent ses réglages et ce que le retour en arrière changerait. Lecture seule : rien n’est écrit ici.","每个客户端现在去往哪里、谁拥有它的设置、切回会改变什么。只读:这里不会写入任何内容。","每個用戶端現在前往哪裡、誰擁有它的設定、切回會改變什麼。唯讀:這裡不會寫入任何內容。","Куда сейчас идёт каждый клиент, кому принадлежат его настройки и что изменит возврат. Только чтение: здесь ничего не записывается.","各クライアントが今どこへ向かっているか、設定の所有者、元に戻すと何が変わるかを表示します。読み取り専用で、ここでは何も書き込みません。","Her istemcinin şu an nereye gittiği, ayarlarının kime ait olduğu ve geri almanın neyi değiştireceği. Salt okunur: burada hiçbir şey yazılmaz.","Mỗi máy khách hiện đi đâu, ai sở hữu cài đặt của nó và chuyển về sẽ thay đổi gì. Chỉ đọc: không ghi gì ở đây.","Para onde cada cliente vai agora, quem é dono das configurações e o que voltar atrás mudaria. Somente leitura: nada é gravado aqui.", "A dónde va ahora cada cliente, quién controla su configuración y qué cambiaría al restaurarlo. Solo lectura: aquí no se escribe nada."], + "loading": ["Reading connection status…","연결 상태를 읽는 중…","Verbindungsstatus wird gelesen…","Lecture de l’état des connexions…","正在读取连接状态…","正在讀取連線狀態…","Чтение состояния подключений…","接続状態を読み込み中…","Bağlantı durumu okunuyor…","Đang đọc trạng thái kết nối…","Lendo o status das conexões…", "Leyendo el estado de las conexiones…"], + "loadFail": ["Could not read the connection status.","연결 상태를 읽지 못했어요.","Der Verbindungsstatus konnte nicht gelesen werden.","Impossible de lire l’état des connexions.","无法读取连接状态。","無法讀取連線狀態。","Не удалось прочитать состояние подключений.","接続状態を読み取れませんでした。","Bağlantı durumu okunamadı.","Không đọc được trạng thái kết nối.","Não foi possível ler o status das conexões.", "No se pudo leer el estado de las conexiones."], + "refresh": ["Refresh","새로고침","Aktualisieren","Actualiser","刷新","重新整理","Обновить","更新","Yenile","Làm mới","Atualizar", "Actualizar"], + "homeDefault": ["Default home","기본 home","Standard-Home","Dossier par défaut","默认主目录","預設主目錄","Домашний каталог по умолчанию","既定のホーム","Varsayılan ana dizin","Thư mục mặc định","Pasta padrão", "Directorio predeterminado"], + "homeExtra": ["Registered home {n}","등록한 home {n}","Registriertes Home {n}","Dossier enregistré {n}","已登记的主目录 {n}","已登記的主目錄 {n}","Зарегистрированный каталог {n}","登録したホーム {n}","Kayıtlı ana dizin {n}","Thư mục đã đăng ký {n}","Pasta registrada {n}", "Directorio registrado {n}"], + "desired": ["Wanted","원하는 상태","Gewünscht","Souhaité","期望","期望","Нужно","希望","İstenen","Mong muốn","Desejado", "Deseado"], + "observed": ["Now","현재","Aktuell","Actuel","当前","目前","Сейчас","現在","Şu an","Hiện tại","Agora", "Actual"], + "owner": ["Owner","소유자","Eigentümer","Propriétaire","所有者","擁有者","Владелец","所有者","Sahip","Chủ sở hữu","Dono", "Propietario"], + "state.proxy": ["Through OpenCodex","OpenCodex 경유","Über OpenCodex","Via OpenCodex","经由 OpenCodex","經由 OpenCodex","Через OpenCodex","OpenCodex 経由","OpenCodex üzerinden","Qua OpenCodex","Via OpenCodex", "A través de OpenCodex"], + "state.native": ["Native","기본 경로","Nativ","Natif","原生","原生","Напрямую","ネイティブ","Yerel","Gốc","Nativo", "Nativo"], + "state.remote-home": ["Through the Remote Link Home","Remote Link Home 경유","Über das Remote-Link-Home","Via le Remote Link Home","经由 Remote Link Home","經由 Remote Link Home","Через Remote Link Home","Remote Link Home 経由","Remote Link Home üzerinden","Qua Remote Link Home","Via o Remote Link Home", "A través de Remote Link Home"], + "state.unset": ["Not managed by OpenCodex","OpenCodex가 관리하지 않음","Nicht von OpenCodex verwaltet","Non géré par OpenCodex","不由 OpenCodex 管理","不由 OpenCodex 管理","Не управляется OpenCodex","OpenCodex の管理外","OpenCodex tarafından yönetilmiyor","OpenCodex không quản lý","Não gerenciado pelo OpenCodex", "No administrado por OpenCodex"], + "state.foreign": ["Another proxy or provider","다른 프록시 또는 공급자","Anderer Proxy oder Anbieter","Autre proxy ou fournisseur","其他代理或提供商","其他代理或供應商","Другой прокси или провайдер","別のプロキシまたはプロバイダー","Başka bir proxy veya sağlayıcı","Proxy hoặc nhà cung cấp khác","Outro proxy ou provedor", "Otro proxy o proveedor"], + "state.missing": ["Not set up","설정 없음","Nicht eingerichtet","Non configuré","未设置","未設定","Не настроено","未設定","Kurulmamış","Chưa thiết lập","Não configurado", "Sin configurar"], + "state.unknown": ["Unknown","알 수 없음","Unbekannt","Inconnu","未知","未知","Неизвестно","不明","Bilinmiyor","Không rõ","Desconhecido", "Desconocido"], + "owner.opencodex": ["Managed by OpenCodex","OpenCodex가 관리","Von OpenCodex verwaltet","Géré par OpenCodex","由 OpenCodex 管理","由 OpenCodex 管理","Управляется OpenCodex","OpenCodex が管理","OpenCodex tarafından yönetiliyor","Do OpenCodex quản lý","Gerenciado pelo OpenCodex", "Administrado por OpenCodex"], + "owner.external": ["Someone else","다른 소유자","Jemand anderes","Quelqu’un d’autre","其他所有者","其他擁有者","Кто-то другой","他の所有者","Başka biri","Bên khác","Outra parte", "Otro propietario"], + "owner.hub": ["Hub mode","Hub 모드","Hub-Modus","Mode hub","Hub 模式","Hub 模式","Режим хаба","Hub モード","Hub modu","Chế độ Hub","Modo hub", "Modo Hub"], + "owner.none": ["Nobody","없음","Niemand","Personne","无","無","Никто","なし","Yok","Không có","Ninguém", "Nadie"], + "owner.unknown": ["Unknown","알 수 없음","Unbekannt","Inconnu","未知","未知","Неизвестно","不明","Bilinmiyor","Không rõ","Desconhecido", "Desconocido"], + "ownerPath": ["Owned by {path}","소유 파일: {path}","Gehört zu {path}","Appartient à {path}","所属文件:{path}","所屬檔案:{path}","Принадлежит {path}","所有ファイル: {path}","Sahibi: {path}","Thuộc về {path}","Pertence a {path}", "Propiedad de {path}"], + "reason.external_owner": ["Another program, OpenCodex home or service owns these files, so OpenCodex leaves them alone.","다른 프로그램, OpenCodex home 또는 서비스가 이 파일을 소유하고 있어서 OpenCodex가 건드리지 않아요.","Ein anderes Programm, OpenCodex-Home oder ein Dienst besitzt diese Dateien, daher lässt OpenCodex sie unverändert.","Un autre programme, dossier OpenCodex ou service possède ces fichiers ; OpenCodex n’y touche donc pas.","这些文件属于其他程序、OpenCodex 主目录或服务,因此 OpenCodex 不会改动它们。","這些檔案屬於其他程式、OpenCodex 主目錄或服務,因此 OpenCodex 不會變動它們。","Этими файлами владеет другая программа, каталог OpenCodex или служба, поэтому OpenCodex их не трогает.","別のプログラム、OpenCodex ホーム、またはサービスがこれらのファイルを所有しているため、OpenCodex は変更しません。","Bu dosyalar başka bir programa, OpenCodex ana dizinine veya hizmete ait; bu yüzden OpenCodex onlara dokunmaz.","Một chương trình, thư mục OpenCodex hoặc dịch vụ khác sở hữu các tệp này, nên OpenCodex không động vào.","Outro programa, pasta do OpenCodex ou serviço é dono destes arquivos, então o OpenCodex não mexe neles.", "Otro programa, directorio de OpenCodex o servicio controla estos archivos, así que OpenCodex no los toca."], + "reason.account_mode": ["Claude Desktop is pinned to one account mode but runs the other.","Claude Desktop이 한 계정 모드로 고정되어 있지만 다른 모드로 실행 중이에요.","Claude Desktop ist auf einen Kontomodus festgelegt, läuft aber im anderen.","Claude Desktop est fixé sur un mode de compte mais fonctionne dans l’autre.","Claude Desktop 固定为一种账户模式,却在以另一种模式运行。","Claude Desktop 固定為一種帳戶模式,卻以另一種模式執行。","Claude Desktop закреплён за одним режимом учётной записи, но работает в другом.","Claude Desktop は一方のアカウントモードに固定されていますが、もう一方で動いています。","Claude Desktop bir hesap moduna sabitlenmiş ama diğerinde çalışıyor.","Claude Desktop được ghim vào một chế độ tài khoản nhưng đang chạy chế độ kia.","O Claude Desktop está fixado em um modo de conta, mas roda no outro.", "Claude Desktop está fijado en un modo de cuenta, pero se ejecuta en el otro."], + "reason.hub_gated": ["This machine is a hub, so it does not rewrite its own clients unless the loopback listener is enabled.","이 기기는 hub라서 loopback listener를 켜지 않으면 자기 클라이언트 설정을 다시 쓰지 않아요.","Dieser Rechner ist ein Hub und schreibt seine eigenen Clients nur mit aktiviertem Loopback-Listener um.","Cette machine est un hub : elle ne réécrit ses propres clients que si l’écoute loopback est activée.","这台机器是 hub,除非启用 loopback 监听,否则不会改写自己的客户端。","這台機器是 hub,除非啟用 loopback 監聽,否則不會改寫自己的用戶端。","Эта машина — хаб и не перезаписывает свои клиенты, пока не включён loopback-слушатель.","このマシンは hub なので、loopback リスナーを有効にしない限り自身のクライアントを書き換えません。","Bu makine bir hub; loopback dinleyicisi açık olmadıkça kendi istemcilerini yeniden yazmaz.","Máy này là hub nên không ghi lại máy khách của chính nó trừ khi bật loopback listener.","Esta máquina é um hub e não reescreve os próprios clientes, a menos que o listener de loopback esteja ativado.", "Este equipo es un hub, así que no reescribe sus propios clientes salvo que el listener de loopback esté activado."], + "reason.intercept_disabled": ["First-party is on, but the interception proxy is disabled here.","first-party가 켜져 있지만 이 기기에서는 가로채기 프록시가 꺼져 있어요.","First-Party ist an, aber der Abfang-Proxy ist hier deaktiviert.","Le mode first-party est actif, mais le proxy d’interception est désactivé ici.","first-party 已开启,但这里的拦截代理已禁用。","first-party 已開啟,但這裡的攔截代理已停用。","Режим first-party включён, но перехватывающий прокси здесь отключён.","first-party はオンですが、ここではインターセプトプロキシが無効です。","First-party açık ama burada yakalama proxy'si devre dışı.","First-party đang bật nhưng proxy chặn đã bị tắt ở đây.","O first-party está ligado, mas o proxy de interceptação está desativado aqui.", "El modo first-party está activado, pero el proxy de interceptación está desactivado aquí."], + "reason.file_edited": ["The file no longer matches the switch: it was edited, rewritten by the app, or left over from an earlier change.","파일이 스위치와 맞지 않아요. 직접 수정됐거나, 앱이 다시 썼거나, 이전 변경에서 남은 거예요.","Die Datei passt nicht mehr zum Schalter: bearbeitet, von der App neu geschrieben oder von einer früheren Änderung übrig.","Le fichier ne correspond plus à l’interrupteur : modifié, réécrit par l’application ou resté d’un changement précédent.","文件已与开关不一致:被编辑过、被应用改写,或是之前更改的残留。","檔案已與開關不一致:被編輯過、被應用程式改寫,或是先前變更的殘留。","Файл больше не соответствует переключателю: его изменили, перезаписало приложение или он остался от прошлого изменения.","ファイルがスイッチと一致しません。編集されたか、アプリが書き換えたか、以前の変更の残りです。","Dosya artık anahtarla eşleşmiyor: düzenlenmiş, uygulama tarafından yeniden yazılmış ya da önceki bir değişiklikten kalmış.","Tệp không còn khớp với công tắc: đã bị sửa, bị ứng dụng ghi lại hoặc còn sót từ thay đổi trước.","O arquivo não corresponde mais ao interruptor: foi editado, reescrito pelo app ou sobrou de uma mudança anterior.", "El archivo ya no coincide con el interruptor: se editó, la aplicación lo reescribió o quedó de un cambio anterior."], + "reason.pending_restart": ["The settings are written, but the listener they point at is stopped or on another port. Start OpenCodex or run ocx ensure.","설정은 써 있지만 가리키는 listener가 멈췄거나 다른 포트에 있어요. OpenCodex를 시작하거나 ocx ensure를 실행하세요.","Die Einstellungen sind geschrieben, aber der Listener ist gestoppt oder auf einem anderen Port. Starten Sie OpenCodex oder führen Sie ocx ensure aus.","Les réglages sont écrits, mais l’écouteur visé est arrêté ou sur un autre port. Démarrez OpenCodex ou lancez ocx ensure.","设置已写入,但指向的监听器已停止或在其他端口。请启动 OpenCodex 或运行 ocx ensure。","設定已寫入,但指向的監聽器已停止或在其他連接埠。請啟動 OpenCodex 或執行 ocx ensure。","Настройки записаны, но указанный слушатель остановлен или на другом порту. Запустите OpenCodex или выполните ocx ensure.","設定は書き込まれていますが、指す先のリスナーが停止しているか別のポートです。OpenCodex を起動するか ocx ensure を実行してください。","Ayarlar yazıldı ama gösterdikleri dinleyici durmuş ya da başka bir portta. OpenCodex'i başlatın veya ocx ensure çalıştırın.","Cài đặt đã được ghi nhưng listener mà nó trỏ tới đã dừng hoặc ở cổng khác. Hãy khởi động OpenCodex hoặc chạy ocx ensure.","As configurações estão gravadas, mas o listener indicado está parado ou em outra porta. Inicie o OpenCodex ou rode ocx ensure.", "La configuración está escrita, pero el listener al que apunta está detenido o en otro puerto. Inicia OpenCodex o ejecuta ocx ensure."], + "restoreTitle": ["Switching it back would change","되돌리면 바뀌는 항목","Zurückschalten würde ändern","Le retour en arrière changerait","切回将会改变","切回將會改變","Возврат изменит","元に戻すと変わる項目","Geri almak şunları değiştirir","Chuyển về sẽ thay đổi","Voltar atrás mudaria", "Al restaurarlo cambiaría"], + "restoreNone": ["No settings keys would change.","바뀌는 설정 키가 없어요.","Keine Einstellungsschlüssel würden sich ändern.","Aucune clé de réglage ne changerait.","没有设置键会改变。","沒有設定鍵會改變。","Ни один ключ настроек не изменится.","変わる設定キーはありません。","Hiçbir ayar anahtarı değişmez.","Không có khóa cài đặt nào thay đổi.","Nenhuma chave de configuração mudaria.", "No cambiaría ninguna clave de configuración."], + "change.add": ["added","추가","hinzugefügt","ajoutée","新增","新增","добавится","追加","eklenir","thêm","adicionada", "añadida"], + "change.update": ["changed","변경","geändert","modifiée","更改","變更","изменится","変更","değişir","thay đổi","alterada", "modificada"], + "change.remove": ["removed","삭제","entfernt","supprimée","移除","移除","удалится","削除","kaldırılır","xóa","removida", "eliminada"], + "outcome.refused": ["Switching back would be refused first: {reason}","되돌리기가 먼저 거절돼요: {reason}","Das Zurückschalten würde zuerst abgelehnt: {reason}","Le retour en arrière serait d’abord refusé : {reason}","切回会先被拒绝:{reason}","切回會先被拒絕:{reason}","Возврат будет сначала отклонён: {reason}","元に戻す操作は先に拒否されます: {reason}","Geri alma önce reddedilir: {reason}","Chuyển về sẽ bị từ chối trước: {reason}","Voltar atrás seria recusado primeiro: {reason}", "La restauración se rechazaría primero: {reason}"], + "homesTitle": ["Claude homes","Claude home 목록","Claude-Homes","Dossiers Claude","Claude 主目录","Claude 主目錄","Каталоги Claude","Claude ホーム","Claude ana dizinleri","Thư mục Claude","Pastas do Claude", "Directorios de Claude"], + "homesHint": ["The switch acts on the default home. Add more under claudeCode.extraConfigDirs to see them here.","스위치는 기본 home에만 적용돼요. claudeCode.extraConfigDirs에 추가하면 여기에 함께 보여요.","Der Schalter wirkt auf das Standard-Home. Weitere unter claudeCode.extraConfigDirs eintragen, um sie hier zu sehen.","L’interrupteur agit sur le dossier par défaut. Ajoutez-en d’autres dans claudeCode.extraConfigDirs pour les voir ici.","开关只作用于默认主目录。把其他目录加到 claudeCode.extraConfigDirs 即可在此看到。","開關只作用於預設主目錄。把其他目錄加到 claudeCode.extraConfigDirs 即可在此看到。","Переключатель действует на каталог по умолчанию. Добавьте другие в claudeCode.extraConfigDirs, чтобы видеть их здесь.","スイッチは既定のホームに作用します。claudeCode.extraConfigDirs に追加するとここに表示されます。","Anahtar varsayılan ana dizine uygulanır. Diğerlerini burada görmek için claudeCode.extraConfigDirs'e ekleyin.","Công tắc tác động lên thư mục mặc định. Thêm thư mục khác vào claudeCode.extraConfigDirs để xem ở đây.","O interruptor age na pasta padrão. Adicione outras em claudeCode.extraConfigDirs para vê-las aqui.", "El interruptor actúa sobre el directorio predeterminado. Añade más en claudeCode.extraConfigDirs para verlos aquí."], + "preview.title": ["Turn on first-party for Claude Code?","Claude Code first-party를 켤까요?","First-Party für Claude Code einschalten?","Activer le mode first-party pour Claude Code ?","为 Claude Code 开启 first-party?","為 Claude Code 開啟 first-party?","Включить first-party для Claude Code?","Claude Code の first-party をオンにしますか?","Claude Code için first-party açılsın mı?","Bật first-party cho Claude Code?","Ligar o first-party para o Claude Code?", "¿Activar el modo first-party para Claude Code?"], + "preview.intro": ["These keys in {path} would change. Values are not shown.","{path}에서 아래 키가 바뀌어요. 값은 보여 주지 않아요.","Diese Schlüssel in {path} würden sich ändern. Werte werden nicht angezeigt.","Ces clés de {path} changeraient. Les valeurs ne sont pas affichées.","{path} 中的以下键会改变。不显示值。","{path} 中的以下鍵會改變。不顯示值。","Эти ключи в {path} изменятся. Значения не показываются.","{path} の次のキーが変わります。値は表示しません。","{path} içindeki şu anahtarlar değişir. Değerler gösterilmez.","Các khóa sau trong {path} sẽ thay đổi. Không hiển thị giá trị.","Estas chaves em {path} mudariam. Os valores não são mostrados.", "Cambiarían estas claves en {path}. Los valores no se muestran."], + "preview.checks": ["The switch can still refuse while it starts the intercept or prepares its certificate and token.","가로채기를 시작하거나 인증서와 토큰을 준비하는 중에 스위치가 거절될 수도 있어요.","Der Schalter kann noch ablehnen, während er den Abfang startet oder Zertifikat und Token vorbereitet.","L’interrupteur peut encore refuser en démarrant l’interception ou en préparant son certificat et son jeton.","在启动拦截或准备证书和令牌时,开关仍可能拒绝。","在啟動攔截或準備憑證和權杖時,開關仍可能拒絕。","Переключатель ещё может отказать при запуске перехвата или подготовке сертификата и токена.","インターセプトの開始や証明書・トークンの準備中に、スイッチが拒否することもあります。","Anahtar, yakalamayı başlatırken veya sertifika ve belirtecini hazırlarken yine de reddedebilir.","Công tắc vẫn có thể từ chối khi khởi động chặn hoặc chuẩn bị chứng chỉ và token.","O interruptor ainda pode recusar ao iniciar a interceptação ou preparar o certificado e o token.", "El interruptor todavía puede rechazar el cambio mientras inicia la interceptación o prepara su certificado y su token."], + "preview.confirm": ["Turn on","켜기","Einschalten","Activer","开启","開啟","Включить","オンにする","Aç","Bật","Ligar", "Activar"], + "preview.cancel": ["Cancel","취소","Abbrechen","Annuler","取消","取消","Отмена","キャンセル","İptal","Hủy","Cancelar", "Cancelar"], + "preview.loadFail": ["Could not preview the change, so nothing was changed.","변경 내용을 미리 보지 못해서 아무것도 바꾸지 않았어요.","Die Änderung konnte nicht vorab angezeigt werden; nichts wurde geändert.","Impossible de prévisualiser le changement ; rien n’a été modifié.","无法预览更改,因此没有做任何改动。","無法預覽變更,因此沒有做任何變動。","Не удалось показать изменение заранее, поэтому ничего не изменено.","変更をプレビューできなかったため、何も変更していません。","Değişiklik önizlenemedi, bu yüzden hiçbir şey değiştirilmedi.","Không xem trước được thay đổi nên chưa thay đổi gì.","Não foi possível pré-visualizar a mudança, então nada foi alterado.", "No se pudo previsualizar el cambio, así que no se modificó nada."], } satisfies Record; export type ConnectionsCopyKey = `connections.${keyof typeof rows}`; diff --git a/gui/src/i18n/desktop-compatibility-copy.ts b/gui/src/i18n/desktop-compatibility-copy.ts index 6276898f2e5..3348818a315 100644 --- a/gui/src/i18n/desktop-compatibility-copy.ts +++ b/gui/src/i18n/desktop-compatibility-copy.ts @@ -1,19 +1,19 @@ -type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; -const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; -type Row = readonly [string, string, string, string, string, string, string, string, string, string, string]; +type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt" | "es"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt", "es"]; +type Row = readonly [string, string, string, string, string, string, string, string, string, string, string, string]; const rows = { - authorizationUnavailable: ["Desktop authorization is unavailable here. On the proxy computer, configure the standalone proxy hostname as the literal loopback address 127.0.0.1 or ::1 if it is localhost or a non-loopback address such as 0.0.0.0. Restart the proxy, then open the matching address and configured port directly over HTTP. Forwarding, a different role or port, and the current session can also prevent authorization.", "여기서는 Desktop 승인을 사용할 수 없습니다. 프록시 컴퓨터에서 독립 실행 프록시의 hostname이 localhost나 0.0.0.0 같은 비루프백 주소라면 127.0.0.1 또는 ::1로 설정하세요. 프록시를 재시작한 뒤 해당 주소와 설정된 포트로 HTTP에 직접 접속하세요. 포워딩, 다른 역할이나 포트, 현재 세션도 승인을 막을 수 있습니다.", "Die Desktop-Autorisierung ist hier nicht verfügbar. Setzen Sie auf dem Proxy-Rechner den Hostnamen des eigenständigen Proxys auf die wörtliche Loopback-Adresse 127.0.0.1 oder ::1, falls er localhost oder eine Nicht-Loopback-Adresse wie 0.0.0.0 ist. Starten Sie den Proxy neu und öffnen Sie die passende Adresse und den konfigurierten Port direkt über HTTP. Weiterleitung, eine andere Rolle oder ein anderer Port sowie die aktuelle Sitzung können die Autorisierung ebenfalls verhindern.", "L’autorisation Desktop est indisponible ici. Sur le proxy autonome, si hostname vaut localhost ou une adresse non loopback comme 0.0.0.0, configurez-le sur 127.0.0.1 ou ::1. Redémarrez le proxy puis ouvrez directement en HTTP l’adresse correspondante et le port configuré. Le transfert, un autre rôle ou port et la session actuelle peuvent aussi empêcher l’autorisation.", "此处无法授权 Desktop。如果独立代理的 hostname 是 localhost 或 0.0.0.0 等非回环地址,请在代理电脑上将其设为字面回环地址 127.0.0.1 或 ::1。重启代理,再通过 HTTP 直接打开对应地址和配置的端口。转发、其他角色或端口以及当前会话也可能阻止授权。", "此處無法授權 Desktop。如果獨立代理的 hostname 是 localhost 或 0.0.0.0 等非迴圈位址,請在代理電腦上設為字面迴圈位址 127.0.0.1 或 ::1。重新啟動代理,再透過 HTTP 直接開啟對應位址和設定的連接埠。轉送、其他角色或連接埠以及目前的工作階段也可能阻止授權。", "Авторизация Desktop здесь недоступна. На компьютере прокси задайте hostname автономного прокси как буквальный адрес loopback 127.0.0.1 или ::1, если сейчас указан localhost или адрес вне loopback, например 0.0.0.0. Перезапустите прокси и откройте соответствующий адрес и настроенный порт напрямую по HTTP. Пересылка, другая роль или порт и текущий сеанс также могут помешать авторизации.", "ここでは Desktop を認証できません。スタンドアロンプロキシの hostname が localhost または 0.0.0.0 などの非ループバックアドレスなら、プロキシのコンピューターで 127.0.0.1 または ::1 に設定してください。プロキシを再起動し、対応するアドレスと設定済みポートを HTTP で直接開いてください。転送、異なる役割やポート、現在のセッションも認証を妨げる場合があります。", "Desktop yetkilendirmesi burada kullanılamıyor. Bağımsız proxy hostname değeri localhost veya 0.0.0.0 gibi döngü dışı bir adresse proxy bilgisayarında 127.0.0.1 ya da ::1 olarak ayarlayın. Proxy’yi yeniden başlatın ve eşleşen adresi ve yapılandırılmış portu doğrudan HTTP ile açın. Yönlendirme, farklı rol veya port ve geçerli oturum da yetkilendirmeyi engelleyebilir.", "Không thể cấp quyền Desktop tại đây. Trên máy proxy, nếu hostname của proxy độc lập là localhost hoặc địa chỉ không phải loopback như 0.0.0.0, hãy đặt thành 127.0.0.1 hoặc ::1. Khởi động lại proxy rồi mở trực tiếp địa chỉ tương ứng và cổng đã cấu hình qua HTTP. Chuyển tiếp, vai trò hoặc cổng khác và phiên hiện tại cũng có thể ngăn cấp quyền.", "A autorização Desktop está indisponível aqui. No computador do proxy, se o hostname do proxy independente for localhost ou um endereço que não seja loopback, como 0.0.0.0, configure-o como 127.0.0.1 ou ::1. Reinicie o proxy e abra diretamente por HTTP o endereço correspondente e a porta configurada. Encaminhamento, outra função ou porta e a sessão atual também podem impedir a autorização."], - rememberedSession: ["This remembered session cannot authorize Desktop. On the proxy computer, open the same address and port in a private browser window, then return to this page and request a new code there.", "기억된 세션에서는 Desktop을 승인할 수 없습니다. 프록시 컴퓨터의 비공개 브라우저 창에서 같은 주소와 포트를 열고 이 페이지로 돌아와 새 코드를 발급받으세요.", "Diese gespeicherte Sitzung kann Desktop nicht autorisieren. Öffnen Sie dieselbe Adresse und denselben Port auf dem Proxy-Rechner in einem privaten Browserfenster und fordern Sie dort auf dieser Seite einen neuen Code an.", "Cette session mémorisée ne peut pas autoriser Desktop. Sur le proxy, ouvrez la même adresse et le même port dans une fenêtre privée, puis revenez à cette page et demandez un nouveau code.", "记住的会话无法授权 Desktop。在代理电脑的无痕浏览窗口中打开相同地址和端口,回到此页面并申请新代码。", "記住的工作階段無法授權 Desktop。在代理電腦的私人瀏覽視窗開啟相同位址和連接埠,回到此頁面並申請新代碼。", "Сохранённый сеанс не может авторизовать Desktop. На компьютере прокси откройте тот же адрес и порт в приватном окне браузера, вернитесь на эту страницу и запросите новый код.", "記憶されたセッションでは Desktop を認証できません。プロキシのコンピューターのプライベートブラウザーで同じアドレスとポートを開き、このページに戻って新しいコードを取得してください。", "Hatırlanan oturum Desktop yetkilendirmesi yapamaz. Proxy bilgisayarında aynı adresi ve portu özel tarayıcı penceresinde açın, bu sayfaya dönüp yeni kod isteyin.", "Phiên đã ghi nhớ không thể cấp quyền Desktop. Trên máy proxy, mở cùng địa chỉ và cổng trong cửa sổ duyệt web riêng tư, quay lại trang này và yêu cầu mã mới.", "A sessão lembrada não pode autorizar o Desktop. No computador do proxy, abra o mesmo endereço e porta em uma janela privada, volte a esta página e solicite um novo código."], - authorizeHint: ["Authorize Desktop actions for up to five minutes. Run this command on the proxy computer and paste its one-use code. If ocx is missing, install the CLI first; a private-home permission refusal must be resolved before a code can be issued. Reauthorization never repeats an earlier action.", "Desktop 작업을 최대 5분간 승인합니다. 프록시 컴퓨터에서 명령을 실행하고 일회용 코드를 붙여 넣으세요. ocx가 없으면 CLI를 먼저 설치하고, 개인 홈 권한 거부는 코드 발급 전에 해결하세요. 재인증해도 이전 작업은 다시 실행되지 않습니다.", "Desktop-Aktionen für höchstens fünf Minuten freigeben. Befehl auf dem Proxy-Rechner ausführen und Einmalcode einfügen. Fehlende CLI zuerst installieren; private Zugriffsrechte müssen stimmen. Frühere Aktionen werden nicht wiederholt.", "Autorisez les actions Desktop pour cinq minutes au maximum. Exécutez la commande sur le proxy et collez le code unique. Installez d’abord la CLI absente et corrigez les permissions du dossier privé. Aucune action précédente n’est rejouée.", "授权 Desktop 操作最多五分钟。在代理电脑运行命令并粘贴一次性代码。若缺少 ocx,请先安装 CLI;须先解决私有主目录权限问题。重新授权不会重放之前的操作。", "授權 Desktop 操作最多五分鐘。在代理電腦執行命令並貼上一次性代碼。若缺少 ocx,請先安裝 CLI;須先解決私人家目錄權限問題。重新授權不會重播先前的操作。", "Разрешите действия Desktop максимум на пять минут. Выполните команду на компьютере прокси и вставьте одноразовый код. Сначала установите CLI и исправьте права приватного каталога. Предыдущие действия не повторяются.", "Desktop 操作を最大5分間許可します。プロキシのコンピューターで実行し、ワンタイムコードを貼り付けてください。CLI がなければ先にインストールし、私有ホームの権限拒否を解消してください。以前の操作は再実行されません。", "Desktop işlemlerini en fazla beş dakika yetkilendirin. Komutu proxy bilgisayarında çalıştırıp tek kullanımlık kodu yapıştırın. Önce CLI’yi kurun ve özel dizin izinlerini düzeltin. Önceki işlem tekrarlanmaz.", "Cho phép thao tác Desktop tối đa năm phút. Chạy lệnh trên máy proxy và dán mã một lần. Cài CLI trước và xử lý quyền thư mục riêng nếu bị từ chối. Thao tác trước không được chạy lại.", "Autorize ações Desktop por até cinco minutos. Execute o comando no computador do proxy e cole o código único. Instale a CLI e corrija as permissões da pasta privada primeiro. Ações anteriores não são repetidas."], - authorizationCode: ["One-use Desktop code", "Desktop 일회용 코드", "Desktop-Einmalcode", "Code Desktop unique", "Desktop 一次性代码", "Desktop 一次性代碼", "Одноразовый код Desktop", "Desktop ワンタイムコード", "Tek kullanımlık Desktop kodu", "Mã Desktop một lần", "Código Desktop de uso único"], - authorize: ["Authorize Desktop", "Desktop 승인", "Desktop freigeben", "Autoriser Desktop", "授权 Desktop", "授權 Desktop", "Разрешить Desktop", "Desktop を許可", "Desktop yetkilendir", "Cho phép Desktop", "Autorizar Desktop"], - authorized: ["Desktop actions are temporarily authorized for this session.", "이 세션의 Desktop 작업이 임시 승인되었습니다.", "Desktop-Aktionen sind für diese Sitzung vorübergehend freigegeben.", "Les actions Desktop sont temporairement autorisées pour cette session.", "此会话已临时获准执行 Desktop 操作。", "此工作階段已暫時獲准執行 Desktop 操作。", "Действия Desktop временно разрешены для этого сеанса.", "このセッションの Desktop 操作は一時的に許可されています。", "Bu oturum için Desktop işlemleri geçici olarak yetkilendirildi.", "Thao tác Desktop được cho phép tạm thời trong phiên này.", "As ações Desktop estão temporariamente autorizadas nesta sessão."], - observation: ["Identity-checked usage responses: JSON {json}, SSE {sse}; active bound streams: {streams}. Counts do not identify the sending process or prove composer recovery.", "신원이 확인된 사용량 응답: JSON {json}, SSE {sse}; 연결된 검증 스트림: {streams}. 이 수치로 발신 프로세스나 입력창 복구를 확인할 수는 없습니다.", "Nutzungsantworten mit geprüfter Identität: JSON {json}, SSE {sse}; aktive zugeordnete Streams: {streams}. Die Zahlen belegen weder den sendenden Prozess noch die Wiederherstellung der Eingabe.", "Réponses d’usage à identité vérifiée : JSON {json}, SSE {sse} ; flux associés actifs : {streams}. Ces nombres ne prouvent ni le processus émetteur ni le rétablissement de la saisie.", "身份已验证的用量响应:JSON {json},SSE {sse};活动绑定流:{streams}。这些计数无法证明发送进程或输入框已恢复。", "身分已驗證的用量回應:JSON {json},SSE {sse};作用中的綁定串流:{streams}。這些計數無法證明傳送程序或輸入框已恢復。", "Ответы об использовании с проверенной идентичностью: JSON {json}, SSE {sse}; активные связанные потоки: {streams}. Счётчики не подтверждают процесс-отправитель или восстановление ввода.", "本人確認済みの使用量応答: JSON {json}、SSE {sse}。接続中の確認済みストリーム: {streams}。この数値だけでは送信プロセスや入力欄の復旧を確認できません。", "Kimliği doğrulanmış kullanım yanıtları: JSON {json}, SSE {sse}; etkin bağlı akışlar: {streams}. Sayılar gönderen süreci veya giriş alanının düzeldiğini kanıtlamaz.", "Phản hồi mức dùng đã xác minh danh tính: JSON {json}, SSE {sse}; luồng liên kết đang hoạt động: {streams}. Các số này không xác nhận tiến trình gửi hay ô nhập đã phục hồi.", "Respostas de uso com identidade verificada: JSON {json}, SSE {sse}; fluxos vinculados ativos: {streams}. As contagens não identificam o processo que enviou nem comprovam a recuperação do campo de texto."], - cacheRefreshHint: ["Stopping correction does not immediately reset the Codex display. Codex must receive fresh usage data; this panel cannot confirm that refresh.", "교정을 중단해도 Codex 화면이 즉시 원복되지는 않습니다. Codex가 새 사용량 데이터를 받아야 하며, 이 패널에서는 해당 갱신을 확인할 수 없습니다.", "Das Stoppen der Korrektur setzt die Codex-Anzeige nicht sofort zurück. Codex muss neue Nutzungsdaten empfangen; dieses Panel kann die Aktualisierung nicht bestätigen.", "L’arrêt de la correction ne rétablit pas immédiatement l’affichage de Codex. Codex doit recevoir de nouvelles données d’usage ; ce panneau ne peut pas confirmer cette actualisation.", "停止修正不会立即恢复 Codex 界面。Codex 必须收到新的用量数据;此面板无法确认是否已刷新。", "停止修正不會立即還原 Codex 畫面。Codex 必須收到新的用量資料;此面板無法確認是否已更新。", "Остановка коррекции не восстанавливает отображение Codex мгновенно. Codex должен получить свежие данные об использовании; эта панель не может подтвердить обновление.", "補正を停止しても Codex の表示はすぐには戻りません。Codex が新しい使用量データを受信する必要があり、このパネルでは更新を確認できません。", "Düzeltmeyi durdurmak Codex görünümünü hemen eski haline getirmez. Codex yeni kullanım verilerini almalıdır; bu panel yenilemeyi doğrulayamaz.", "Dừng hiệu chỉnh không khôi phục ngay giao diện Codex. Codex phải nhận dữ liệu sử dụng mới; bảng này không thể xác nhận việc làm mới.", "Interromper a correção não redefine imediatamente a exibição do Codex. O Codex precisa receber dados de uso atualizados; este painel não consegue confirmar essa atualização."], - routingChanged: ["Native Codex routing no longer matches this OpenCodex process. Correction is off; review the integration before restarting observation.", "Codex 기본 연결이 이 OpenCodex 프로세스와 일치하지 않습니다. 교정이 꺼졌습니다. 연동 설정을 확인한 뒤 관찰을 다시 시작하세요.", "Die native Codex-Verbindung passt nicht mehr zu diesem OpenCodex-Prozess. Korrektur ist aus; Integration vor einem Neustart prüfen.", "La connexion native Codex ne correspond plus à ce processus OpenCodex. La correction est désactivée ; vérifiez l’intégration avant de relancer l’observation.", "原生 Codex 路由与此 OpenCodex 进程不再匹配。修正已关闭;重新观察前请检查集成。", "原生 Codex 路由與此 OpenCodex 程序不再相符。修正已關閉;重新觀察前請檢查整合。", "Маршрут Codex больше не соответствует этому процессу OpenCodex. Коррекция выключена; проверьте интеграцию перед перезапуском наблюдения.", "Codex の接続先がこの OpenCodex プロセスと一致しません。補正はオフです。連携設定を確認してから観察を再開してください。", "Codex yönlendirmesi artık bu OpenCodex süreciyle eşleşmiyor. Düzeltme kapalı; gözlemi yeniden başlatmadan önce entegrasyonu kontrol edin.", "Định tuyến Codex không còn khớp tiến trình OpenCodex này. Hiệu chỉnh đã tắt; kiểm tra tích hợp trước khi quan sát lại.", "O roteamento nativo do Codex não corresponde mais a este processo do OpenCodex. A correção está desativada; revise a integração antes de retomar a observação."], - autoStart: ["Resume observation when OpenCodex starts", "OpenCodex 시작 시 관찰 자동 재개", "Beobachtung beim Start von OpenCodex fortsetzen", "Reprendre l’observation au démarrage d’OpenCodex", "OpenCodex 启动时恢复观察", "OpenCodex 啟動時恢復觀察", "Возобновлять наблюдение при запуске OpenCodex", "OpenCodex 起動時に観察を再開", "OpenCodex başladığında gözlemi sürdür", "Tiếp tục quan sát khi OpenCodex khởi động", "Retomar a observação quando o OpenCodex iniciar"], - autoStartHint: ["Applies at the next proxy start and requires an existing trusted certificate. Does not open Codex, register trust or start a correction trial. Turning this off does not stop a running service.", "다음 프록시 시작부터 적용되며 이미 신뢰된 인증서가 필요합니다. Codex 실행·신뢰 등록·복구 시험을 자동 수행하지 않습니다. 끄더라도 실행 중인 서비스는 중지하지 않습니다.", "Gilt ab dem nächsten Proxystart und erfordert ein bereits vertrauenswürdiges Zertifikat. Öffnet Codex nicht, registriert kein Vertrauen und startet keinen Korrekturtest. Ausschalten stoppt keinen laufenden Dienst.", "S’applique au prochain démarrage du proxy et nécessite un certificat déjà approuvé. N’ouvre pas Codex, n’enregistre pas de confiance et ne lance pas d’essai. La désactivation n’arrête pas un service actif.", "从下次代理启动起生效,需要已受信任的证书。不会打开 Codex、注册信任或启动修正试验。关闭此选项不会停止正在运行的服务。", "從下次代理啟動起生效,需要已受信任的憑證。不會開啟 Codex、註冊信任或啟動修正試驗。關閉此選項不會停止執行中的服務。", "Действует со следующего запуска прокси и требует доверенного сертификата. Не открывает Codex, не добавляет доверие и не запускает тест. Отключение не останавливает работающую службу.", "次回のプロキシ起動時から適用され、信頼済み証明書が必要です。Codex の起動・信頼登録・補正テストは自動実行しません。オフにしても実行中のサービスは停止しません。", "Sonraki proxy başlangıcında uygulanır; önceden güvenilen sertifika gerekir. Codex’i açmaz, güven kaydetmez veya deneme başlatmaz. Kapatmak çalışan hizmeti durdurmaz.", "Áp dụng từ lần khởi động proxy tiếp theo và cần chứng chỉ đã tin cậy. Không mở Codex, đăng ký tin cậy hay chạy thử hiệu chỉnh. Tắt tùy chọn không dừng dịch vụ đang chạy.", "Aplica-se na próxima inicialização do proxy e requer um certificado já confiável. Não abre o Codex, registra confiança nem inicia um teste de correção. Desativar esta opção não interrompe um serviço em execução."], - connectionUnavailable: ["The saved local connection could not be opened. Its address was not changed automatically.", "저장된 로컬 연결을 열지 못했습니다. 연결 주소를 자동으로 변경하지 않았습니다.", "Die gespeicherte lokale Verbindung konnte nicht geöffnet werden. Ihre Adresse wurde nicht automatisch geändert.", "La connexion locale enregistrée n’a pas pu être ouverte. Son adresse n’a pas été modifiée automatiquement.", "无法打开保存的本地连接。未自动更改其地址。", "無法開啟儲存的本機連線。並未自動變更其位址。", "Не удалось открыть сохранённое локальное соединение. Его адрес автоматически не менялся.", "保存されたローカル接続を開けませんでした。接続先を自動変更していません。", "Kaydedilen yerel bağlantı açılamadı. Adresi otomatik değiştirilmedi.", "Không mở được kết nối cục bộ đã lưu. Địa chỉ không được tự động thay đổi.", "Não foi possível abrir a conexão local salva. O endereço não foi alterado automaticamente."], + authorizationUnavailable: ["Desktop authorization is unavailable here. On the proxy computer, configure the standalone proxy hostname as the literal loopback address 127.0.0.1 or ::1 if it is localhost or a non-loopback address such as 0.0.0.0. Restart the proxy, then open the matching address and configured port directly over HTTP. Forwarding, a different role or port, and the current session can also prevent authorization.", "여기서는 Desktop 승인을 사용할 수 없습니다. 프록시 컴퓨터에서 독립 실행 프록시의 hostname이 localhost나 0.0.0.0 같은 비루프백 주소라면 127.0.0.1 또는 ::1로 설정하세요. 프록시를 재시작한 뒤 해당 주소와 설정된 포트로 HTTP에 직접 접속하세요. 포워딩, 다른 역할이나 포트, 현재 세션도 승인을 막을 수 있습니다.", "Die Desktop-Autorisierung ist hier nicht verfügbar. Setzen Sie auf dem Proxy-Rechner den Hostnamen des eigenständigen Proxys auf die wörtliche Loopback-Adresse 127.0.0.1 oder ::1, falls er localhost oder eine Nicht-Loopback-Adresse wie 0.0.0.0 ist. Starten Sie den Proxy neu und öffnen Sie die passende Adresse und den konfigurierten Port direkt über HTTP. Weiterleitung, eine andere Rolle oder ein anderer Port sowie die aktuelle Sitzung können die Autorisierung ebenfalls verhindern.", "L’autorisation Desktop est indisponible ici. Sur le proxy autonome, si hostname vaut localhost ou une adresse non loopback comme 0.0.0.0, configurez-le sur 127.0.0.1 ou ::1. Redémarrez le proxy puis ouvrez directement en HTTP l’adresse correspondante et le port configuré. Le transfert, un autre rôle ou port et la session actuelle peuvent aussi empêcher l’autorisation.", "此处无法授权 Desktop。如果独立代理的 hostname 是 localhost 或 0.0.0.0 等非回环地址,请在代理电脑上将其设为字面回环地址 127.0.0.1 或 ::1。重启代理,再通过 HTTP 直接打开对应地址和配置的端口。转发、其他角色或端口以及当前会话也可能阻止授权。", "此處無法授權 Desktop。如果獨立代理的 hostname 是 localhost 或 0.0.0.0 等非迴圈位址,請在代理電腦上設為字面迴圈位址 127.0.0.1 或 ::1。重新啟動代理,再透過 HTTP 直接開啟對應位址和設定的連接埠。轉送、其他角色或連接埠以及目前的工作階段也可能阻止授權。", "Авторизация Desktop здесь недоступна. На компьютере прокси задайте hostname автономного прокси как буквальный адрес loopback 127.0.0.1 или ::1, если сейчас указан localhost или адрес вне loopback, например 0.0.0.0. Перезапустите прокси и откройте соответствующий адрес и настроенный порт напрямую по HTTP. Пересылка, другая роль или порт и текущий сеанс также могут помешать авторизации.", "ここでは Desktop を認証できません。スタンドアロンプロキシの hostname が localhost または 0.0.0.0 などの非ループバックアドレスなら、プロキシのコンピューターで 127.0.0.1 または ::1 に設定してください。プロキシを再起動し、対応するアドレスと設定済みポートを HTTP で直接開いてください。転送、異なる役割やポート、現在のセッションも認証を妨げる場合があります。", "Desktop yetkilendirmesi burada kullanılamıyor. Bağımsız proxy hostname değeri localhost veya 0.0.0.0 gibi döngü dışı bir adresse proxy bilgisayarında 127.0.0.1 ya da ::1 olarak ayarlayın. Proxy’yi yeniden başlatın ve eşleşen adresi ve yapılandırılmış portu doğrudan HTTP ile açın. Yönlendirme, farklı rol veya port ve geçerli oturum da yetkilendirmeyi engelleyebilir.", "Không thể cấp quyền Desktop tại đây. Trên máy proxy, nếu hostname của proxy độc lập là localhost hoặc địa chỉ không phải loopback như 0.0.0.0, hãy đặt thành 127.0.0.1 hoặc ::1. Khởi động lại proxy rồi mở trực tiếp địa chỉ tương ứng và cổng đã cấu hình qua HTTP. Chuyển tiếp, vai trò hoặc cổng khác và phiên hiện tại cũng có thể ngăn cấp quyền.", "A autorização Desktop está indisponível aqui. No computador do proxy, se o hostname do proxy independente for localhost ou um endereço que não seja loopback, como 0.0.0.0, configure-o como 127.0.0.1 ou ::1. Reinicie o proxy e abra diretamente por HTTP o endereço correspondente e a porta configurada. Encaminhamento, outra função ou porta e a sessão atual também podem impedir a autorização.", "Aquí no se puede autorizar Desktop. En el equipo del proxy, configura su nombre de host como la dirección literal de loopback 127.0.0.1 o ::1 si ahora es localhost o una dirección que no sea de loopback, como 0.0.0.0. Reinicia el proxy y abre directamente por HTTP esa misma dirección y el puerto configurado. El reenvío, un rol o puerto distinto y la sesión actual también pueden impedir la autorización."], + rememberedSession: ["This remembered session cannot authorize Desktop. On the proxy computer, open the same address and port in a private browser window, then return to this page and request a new code there.", "기억된 세션에서는 Desktop을 승인할 수 없습니다. 프록시 컴퓨터의 비공개 브라우저 창에서 같은 주소와 포트를 열고 이 페이지로 돌아와 새 코드를 발급받으세요.", "Diese gespeicherte Sitzung kann Desktop nicht autorisieren. Öffnen Sie dieselbe Adresse und denselben Port auf dem Proxy-Rechner in einem privaten Browserfenster und fordern Sie dort auf dieser Seite einen neuen Code an.", "Cette session mémorisée ne peut pas autoriser Desktop. Sur le proxy, ouvrez la même adresse et le même port dans une fenêtre privée, puis revenez à cette page et demandez un nouveau code.", "记住的会话无法授权 Desktop。在代理电脑的无痕浏览窗口中打开相同地址和端口,回到此页面并申请新代码。", "記住的工作階段無法授權 Desktop。在代理電腦的私人瀏覽視窗開啟相同位址和連接埠,回到此頁面並申請新代碼。", "Сохранённый сеанс не может авторизовать Desktop. На компьютере прокси откройте тот же адрес и порт в приватном окне браузера, вернитесь на эту страницу и запросите новый код.", "記憶されたセッションでは Desktop を認証できません。プロキシのコンピューターのプライベートブラウザーで同じアドレスとポートを開き、このページに戻って新しいコードを取得してください。", "Hatırlanan oturum Desktop yetkilendirmesi yapamaz. Proxy bilgisayarında aynı adresi ve portu özel tarayıcı penceresinde açın, bu sayfaya dönüp yeni kod isteyin.", "Phiên đã ghi nhớ không thể cấp quyền Desktop. Trên máy proxy, mở cùng địa chỉ và cổng trong cửa sổ duyệt web riêng tư, quay lại trang này và yêu cầu mã mới.", "A sessão lembrada não pode autorizar o Desktop. No computador do proxy, abra o mesmo endereço e porta em uma janela privada, volte a esta página e solicite um novo código.", "Esta sesión recordada no puede autorizar Desktop. En el equipo del proxy, abre la misma dirección y puerto en una ventana privada y solicita allí un código nuevo."], + authorizeHint: ["Authorize Desktop actions for up to five minutes. Run this command on the proxy computer and paste its one-use code. If ocx is missing, install the CLI first; a private-home permission refusal must be resolved before a code can be issued. Reauthorization never repeats an earlier action.", "Desktop 작업을 최대 5분간 승인합니다. 프록시 컴퓨터에서 명령을 실행하고 일회용 코드를 붙여 넣으세요. ocx가 없으면 CLI를 먼저 설치하고, 개인 홈 권한 거부는 코드 발급 전에 해결하세요. 재인증해도 이전 작업은 다시 실행되지 않습니다.", "Desktop-Aktionen für höchstens fünf Minuten freigeben. Befehl auf dem Proxy-Rechner ausführen und Einmalcode einfügen. Fehlende CLI zuerst installieren; private Zugriffsrechte müssen stimmen. Frühere Aktionen werden nicht wiederholt.", "Autorisez les actions Desktop pour cinq minutes au maximum. Exécutez la commande sur le proxy et collez le code unique. Installez d’abord la CLI absente et corrigez les permissions du dossier privé. Aucune action précédente n’est rejouée.", "授权 Desktop 操作最多五分钟。在代理电脑运行命令并粘贴一次性代码。若缺少 ocx,请先安装 CLI;须先解决私有主目录权限问题。重新授权不会重放之前的操作。", "授權 Desktop 操作最多五分鐘。在代理電腦執行命令並貼上一次性代碼。若缺少 ocx,請先安裝 CLI;須先解決私人家目錄權限問題。重新授權不會重播先前的操作。", "Разрешите действия Desktop максимум на пять минут. Выполните команду на компьютере прокси и вставьте одноразовый код. Сначала установите CLI и исправьте права приватного каталога. Предыдущие действия не повторяются.", "Desktop 操作を最大5分間許可します。プロキシのコンピューターで実行し、ワンタイムコードを貼り付けてください。CLI がなければ先にインストールし、私有ホームの権限拒否を解消してください。以前の操作は再実行されません。", "Desktop işlemlerini en fazla beş dakika yetkilendirin. Komutu proxy bilgisayarında çalıştırıp tek kullanımlık kodu yapıştırın. Önce CLI’yi kurun ve özel dizin izinlerini düzeltin. Önceki işlem tekrarlanmaz.", "Cho phép thao tác Desktop tối đa năm phút. Chạy lệnh trên máy proxy và dán mã một lần. Cài CLI trước và xử lý quyền thư mục riêng nếu bị từ chối. Thao tác trước không được chạy lại.", "Autorize ações Desktop por até cinco minutos. Execute o comando no computador do proxy e cole o código único. Instale a CLI e corrija as permissões da pasta privada primeiro. Ações anteriores não são repetidas.", "Autoriza las acciones de Desktop por un máximo de cinco minutos. Ejecuta este comando en el equipo del proxy y pega el código de un solo uso. Si falta ocx, instala la CLI primero. Si se denegó el acceso por los permisos del directorio privado de OpenCodex, corrígelos antes de emitir el código. Volver a autorizar no repite una acción anterior."], + authorizationCode: ["One-use Desktop code", "Desktop 일회용 코드", "Desktop-Einmalcode", "Code Desktop unique", "Desktop 一次性代码", "Desktop 一次性代碼", "Одноразовый код Desktop", "Desktop ワンタイムコード", "Tek kullanımlık Desktop kodu", "Mã Desktop một lần", "Código Desktop de uso único", "Código de Desktop de un solo uso"], + authorize: ["Authorize Desktop", "Desktop 승인", "Desktop freigeben", "Autoriser Desktop", "授权 Desktop", "授權 Desktop", "Разрешить Desktop", "Desktop を許可", "Desktop yetkilendir", "Cho phép Desktop", "Autorizar Desktop", "Autorizar Desktop"], + authorized: ["Desktop actions are temporarily authorized for this session.", "이 세션의 Desktop 작업이 임시 승인되었습니다.", "Desktop-Aktionen sind für diese Sitzung vorübergehend freigegeben.", "Les actions Desktop sont temporairement autorisées pour cette session.", "此会话已临时获准执行 Desktop 操作。", "此工作階段已暫時獲准執行 Desktop 操作。", "Действия Desktop временно разрешены для этого сеанса.", "このセッションの Desktop 操作は一時的に許可されています。", "Bu oturum için Desktop işlemleri geçici olarak yetkilendirildi.", "Thao tác Desktop được cho phép tạm thời trong phiên này.", "As ações Desktop estão temporariamente autorizadas nesta sessão.", "Las acciones de Desktop están autorizadas temporalmente en esta sesión."], + observation: ["Identity-checked usage responses: JSON {json}, SSE {sse}; active bound streams: {streams}. Counts do not identify the sending process or prove composer recovery.", "신원이 확인된 사용량 응답: JSON {json}, SSE {sse}; 연결된 검증 스트림: {streams}. 이 수치로 발신 프로세스나 입력창 복구를 확인할 수는 없습니다.", "Nutzungsantworten mit geprüfter Identität: JSON {json}, SSE {sse}; aktive zugeordnete Streams: {streams}. Die Zahlen belegen weder den sendenden Prozess noch die Wiederherstellung der Eingabe.", "Réponses d’usage à identité vérifiée : JSON {json}, SSE {sse} ; flux associés actifs : {streams}. Ces nombres ne prouvent ni le processus émetteur ni le rétablissement de la saisie.", "身份已验证的用量响应:JSON {json},SSE {sse};活动绑定流:{streams}。这些计数无法证明发送进程或输入框已恢复。", "身分已驗證的用量回應:JSON {json},SSE {sse};作用中的綁定串流:{streams}。這些計數無法證明傳送程序或輸入框已恢復。", "Ответы об использовании с проверенной идентичностью: JSON {json}, SSE {sse}; активные связанные потоки: {streams}. Счётчики не подтверждают процесс-отправитель или восстановление ввода.", "本人確認済みの使用量応答: JSON {json}、SSE {sse}。接続中の確認済みストリーム: {streams}。この数値だけでは送信プロセスや入力欄の復旧を確認できません。", "Kimliği doğrulanmış kullanım yanıtları: JSON {json}, SSE {sse}; etkin bağlı akışlar: {streams}. Sayılar gönderen süreci veya giriş alanının düzeldiğini kanıtlamaz.", "Phản hồi mức dùng đã xác minh danh tính: JSON {json}, SSE {sse}; luồng liên kết đang hoạt động: {streams}. Các số này không xác nhận tiến trình gửi hay ô nhập đã phục hồi.", "Respostas de uso com identidade verificada: JSON {json}, SSE {sse}; fluxos vinculados ativos: {streams}. As contagens não identificam o processo que enviou nem comprovam a recuperação do campo de texto.", "Respuestas de uso con identidad verificada: JSON {json}, SSE {sse}; flujos activos vinculados: {streams}. Los recuentos no identifican el proceso emisor ni demuestran que el cuadro de entrada se haya recuperado."], + cacheRefreshHint: ["Stopping correction does not immediately reset the Codex display. Codex must receive fresh usage data; this panel cannot confirm that refresh.", "교정을 중단해도 Codex 화면이 즉시 원복되지는 않습니다. Codex가 새 사용량 데이터를 받아야 하며, 이 패널에서는 해당 갱신을 확인할 수 없습니다.", "Das Stoppen der Korrektur setzt die Codex-Anzeige nicht sofort zurück. Codex muss neue Nutzungsdaten empfangen; dieses Panel kann die Aktualisierung nicht bestätigen.", "L’arrêt de la correction ne rétablit pas immédiatement l’affichage de Codex. Codex doit recevoir de nouvelles données d’usage ; ce panneau ne peut pas confirmer cette actualisation.", "停止修正不会立即恢复 Codex 界面。Codex 必须收到新的用量数据;此面板无法确认是否已刷新。", "停止修正不會立即還原 Codex 畫面。Codex 必須收到新的用量資料;此面板無法確認是否已更新。", "Остановка коррекции не восстанавливает отображение Codex мгновенно. Codex должен получить свежие данные об использовании; эта панель не может подтвердить обновление.", "補正を停止しても Codex の表示はすぐには戻りません。Codex が新しい使用量データを受信する必要があり、このパネルでは更新を確認できません。", "Düzeltmeyi durdurmak Codex görünümünü hemen eski haline getirmez. Codex yeni kullanım verilerini almalıdır; bu panel yenilemeyi doğrulayamaz.", "Dừng hiệu chỉnh không khôi phục ngay giao diện Codex. Codex phải nhận dữ liệu sử dụng mới; bảng này không thể xác nhận việc làm mới.", "Interromper a correção não redefine imediatamente a exibição do Codex. O Codex precisa receber dados de uso atualizados; este painel não consegue confirmar essa atualização.", "Detener la corrección no restablece de inmediato lo que muestra Codex. Codex debe recibir datos de uso nuevos; este panel no puede confirmar esa actualización."], + routingChanged: ["Native Codex routing no longer matches this OpenCodex process. Correction is off; review the integration before restarting observation.", "Codex 기본 연결이 이 OpenCodex 프로세스와 일치하지 않습니다. 교정이 꺼졌습니다. 연동 설정을 확인한 뒤 관찰을 다시 시작하세요.", "Die native Codex-Verbindung passt nicht mehr zu diesem OpenCodex-Prozess. Korrektur ist aus; Integration vor einem Neustart prüfen.", "La connexion native Codex ne correspond plus à ce processus OpenCodex. La correction est désactivée ; vérifiez l’intégration avant de relancer l’observation.", "原生 Codex 路由与此 OpenCodex 进程不再匹配。修正已关闭;重新观察前请检查集成。", "原生 Codex 路由與此 OpenCodex 程序不再相符。修正已關閉;重新觀察前請檢查整合。", "Маршрут Codex больше не соответствует этому процессу OpenCodex. Коррекция выключена; проверьте интеграцию перед перезапуском наблюдения.", "Codex の接続先がこの OpenCodex プロセスと一致しません。補正はオフです。連携設定を確認してから観察を再開してください。", "Codex yönlendirmesi artık bu OpenCodex süreciyle eşleşmiyor. Düzeltme kapalı; gözlemi yeniden başlatmadan önce entegrasyonu kontrol edin.", "Định tuyến Codex không còn khớp tiến trình OpenCodex này. Hiệu chỉnh đã tắt; kiểm tra tích hợp trước khi quan sát lại.", "O roteamento nativo do Codex não corresponde mais a este processo do OpenCodex. A correção está desativada; revise a integração antes de retomar a observação.", "El enrutamiento de Codex nativo ya no coincide con este proceso de OpenCodex. La corrección está desactivada; revisa la integración antes de reiniciar la observación."], + autoStart: ["Resume observation when OpenCodex starts", "OpenCodex 시작 시 관찰 자동 재개", "Beobachtung beim Start von OpenCodex fortsetzen", "Reprendre l’observation au démarrage d’OpenCodex", "OpenCodex 启动时恢复观察", "OpenCodex 啟動時恢復觀察", "Возобновлять наблюдение при запуске OpenCodex", "OpenCodex 起動時に観察を再開", "OpenCodex başladığında gözlemi sürdür", "Tiếp tục quan sát khi OpenCodex khởi động", "Retomar a observação quando o OpenCodex iniciar", "Reanudar la observación al iniciar OpenCodex"], + autoStartHint: ["Applies at the next proxy start and requires an existing trusted certificate. Does not open Codex, register trust or start a correction trial. Turning this off does not stop a running service.", "다음 프록시 시작부터 적용되며 이미 신뢰된 인증서가 필요합니다. Codex 실행·신뢰 등록·복구 시험을 자동 수행하지 않습니다. 끄더라도 실행 중인 서비스는 중지하지 않습니다.", "Gilt ab dem nächsten Proxystart und erfordert ein bereits vertrauenswürdiges Zertifikat. Öffnet Codex nicht, registriert kein Vertrauen und startet keinen Korrekturtest. Ausschalten stoppt keinen laufenden Dienst.", "S’applique au prochain démarrage du proxy et nécessite un certificat déjà approuvé. N’ouvre pas Codex, n’enregistre pas de confiance et ne lance pas d’essai. La désactivation n’arrête pas un service actif.", "从下次代理启动起生效,需要已受信任的证书。不会打开 Codex、注册信任或启动修正试验。关闭此选项不会停止正在运行的服务。", "從下次代理啟動起生效,需要已受信任的憑證。不會開啟 Codex、註冊信任或啟動修正試驗。關閉此選項不會停止執行中的服務。", "Действует со следующего запуска прокси и требует доверенного сертификата. Не открывает Codex, не добавляет доверие и не запускает тест. Отключение не останавливает работающую службу.", "次回のプロキシ起動時から適用され、信頼済み証明書が必要です。Codex の起動・信頼登録・補正テストは自動実行しません。オフにしても実行中のサービスは停止しません。", "Sonraki proxy başlangıcında uygulanır; önceden güvenilen sertifika gerekir. Codex’i açmaz, güven kaydetmez veya deneme başlatmaz. Kapatmak çalışan hizmeti durdurmaz.", "Áp dụng từ lần khởi động proxy tiếp theo và cần chứng chỉ đã tin cậy. Không mở Codex, đăng ký tin cậy hay chạy thử hiệu chỉnh. Tắt tùy chọn không dừng dịch vụ đang chạy.", "Aplica-se na próxima inicialização do proxy e requer um certificado já confiável. Não abre o Codex, registra confiança nem inicia um teste de correção. Desativar esta opção não interrompe um serviço em execução.", "Se aplica en el próximo inicio del proxy y requiere un certificado de confianza existente. No abre Codex, no registra confianza ni inicia una prueba de corrección. Desactivar esta opción no detiene un servicio que esté en ejecución."], + connectionUnavailable: ["The saved local connection could not be opened. Its address was not changed automatically.", "저장된 로컬 연결을 열지 못했습니다. 연결 주소를 자동으로 변경하지 않았습니다.", "Die gespeicherte lokale Verbindung konnte nicht geöffnet werden. Ihre Adresse wurde nicht automatisch geändert.", "La connexion locale enregistrée n’a pas pu être ouverte. Son adresse n’a pas été modifiée automatiquement.", "无法打开保存的本地连接。未自动更改其地址。", "無法開啟儲存的本機連線。並未自動變更其位址。", "Не удалось открыть сохранённое локальное соединение. Его адрес автоматически не менялся.", "保存されたローカル接続を開けませんでした。接続先を自動変更していません。", "Kaydedilen yerel bağlantı açılamadı. Adresi otomatik değiştirilmedi.", "Không mở được kết nối cục bộ đã lưu. Địa chỉ không được tự động thay đổi.", "Não foi possível abrir a conexão local salva. O endereço não foi alterado automaticamente.", "No se pudo abrir la conexión local guardada. Su dirección no se cambió automáticamente."], blockedByBuild: [ "Correction is unavailable because the Codex package changed or could not be verified. If verification keeps failing, repair or reinstall Codex from Microsoft Store. A new trial requires successful verification, a fresh exhaustion observation and your consent.", "Codex 패키지가 변경되었거나 검증되지 않아 교정을 사용할 수 없습니다. 검증이 계속 실패하면 Microsoft Store에서 Codex를 복구하거나 다시 설치하세요. 새 시험에는 검증 성공, 새로운 소진 확인, 사용자 동의가 필요합니다.", @@ -26,34 +26,35 @@ const rows = { "Codex paketi değiştiği veya doğrulanamadığı için düzeltme kullanılamıyor. Doğrulama başarısız olmaya devam ederse Codex’i Microsoft Store’dan onarın veya yeniden yükleyin. Yeni bir deneme için doğrulamanın başarılı olması, kullanım hakkının tükendiğinin yeniden gözlemlenmesi ve onayınız gerekir.", "Không thể hiệu chỉnh vì gói Codex thay đổi hoặc không thể xác minh. Nếu tiếp tục không xác minh được, hãy sửa chữa hoặc cài đặt lại Codex từ Microsoft Store. Lần thử mới cần xác minh thành công, quan sát mới cho thấy đã hết hạn mức và sự đồng ý của bạn.", "A correção está indisponível porque o pacote do Codex mudou ou não pôde ser verificado. Se a verificação continuar falhando, repare ou reinstale o Codex pela Microsoft Store. Um novo teste exige verificação bem-sucedida, uma nova observação de esgotamento e seu consentimento.", + "La corrección no está disponible porque el paquete de Codex cambió o no se pudo verificar. Si la verificación sigue fallando, repara o reinstala Codex desde Microsoft Store. Una nueva prueba requiere una verificación correcta, una nueva observación del agotamiento y tu consentimiento.", ], - blockedByProxy: ["The outbound proxy setting is invalid or unsupported. Correct it before starting observation; no direct fallback was used.", "외부 프록시 설정이 잘못되었거나 지원되지 않습니다. 관찰 시작 전에 설정을 확인하세요. 직접 연결로 우회하지 않았습니다.", "Die Proxy-Einstellung ist ungültig oder nicht unterstützt. Vor dem Start korrigieren; keine direkte Ersatzverbindung wurde genutzt.", "Le proxy sortant est invalide ou non pris en charge. Corrigez-le avant l’observation ; aucun repli direct n’a été utilisé.", "出站代理设置无效或不受支持。观察前请修正;未回退到直接连接。", "輸出代理設定無效或不受支援。觀察前請修正;並未改用直接連線。", "Настройка прокси неверна или не поддерживается. Исправьте её до наблюдения; прямое подключение не использовалось.", "送信プロキシ設定が無効または未対応です。観察開始前に修正してください。直接接続への切り替えは行っていません。", "Çıkış proxy ayarı geçersiz veya desteklenmiyor. Gözlemden önce düzeltin; doğrudan bağlantıya geçilmedi.", "Cấu hình proxy đầu ra không hợp lệ hoặc chưa hỗ trợ. Sửa trước khi quan sát; không chuyển sang kết nối trực tiếp.", "A configuração do proxy de saída é inválida ou não é compatível. Corrija-a antes de iniciar a observação; não foi usado acesso direto como alternativa."], - closeApp: ["Save drafts, close Codex, then refresh status before trying again.", "초안을 저장하고 Codex를 닫은 뒤 상태를 새로고침하여 재시도하세요.", "Entwürfe speichern, Codex schließen und vor dem nächsten Versuch den Status aktualisieren.", "Enregistrez les brouillons, fermez Codex, puis actualisez l’état avant de réessayer.", "保存草稿并关闭 Codex,然后刷新状态再重试。", "儲存草稿並關閉 Codex,然後重新整理狀態再重試。", "Сохраните черновики, закройте Codex и обновите состояние перед повтором.", "下書きを保存して Codex を閉じ、状態を更新してから再試行してください。", "Taslakları kaydedip Codex’i kapatın; yeniden denemeden önce durumu yenileyin.", "Lưu bản nháp, đóng Codex rồi làm mới trạng thái trước khi thử lại.", "Salve os rascunhos, feche o Codex e atualize o status antes de tentar novamente."], - connectedUnavailable: ["These local controls are unavailable in OpenCodex managed client mode.", "OpenCodex 관리형 클라이언트 모드에서는 이 로컬 제어를 사용할 수 없습니다.", "Diese lokalen Steuerelemente sind im verwalteten Clientmodus von OpenCodex nicht verfügbar.", "Ces commandes locales ne sont pas disponibles en mode client géré OpenCodex.", "OpenCodex 托管客户端模式不提供这些本地控制。", "OpenCodex 受管理用戶端模式不提供這些本機控制。", "Эти локальные действия недоступны в управляемом клиентском режиме OpenCodex.", "OpenCodex の管理対象クライアントモードでは、このローカル操作を利用できません。", "Bu yerel denetimler OpenCodex yönetilen istemci modunda kullanılamaz.", "Các điều khiển cục bộ này không có trong chế độ máy khách được quản lý của OpenCodex.", "Estes controles locais não estão disponíveis no modo de cliente gerenciado do OpenCodex."], - title: ["Desktop compatibility", "데스크톱 호환", "Desktop-Kompatibilität", "Compatibilité du bureau", "桌面兼容", "桌面相容", "Совместимость приложения", "デスクトップ互換性", "Masaüstü uyumluluğu", "Tương thích ứng dụng", "Compatibilidade com o desktop"], - description: ["Experimental Windows integration. Keeps the Codex login; setup alone does not enable correction.", "실험적인 Windows 연동입니다. Codex 로그인을 유지하며, 준비만으로 교정이 켜지지 않습니다.", "Experimentelle Windows-Integration. Die Codex-Anmeldung bleibt erhalten; die Einrichtung aktiviert keine Korrektur.", "Intégration Windows expérimentale. La connexion Codex est conservée ; la préparation seule n’active pas la correction.", "实验性 Windows 集成。保留 Codex 登录;仅完成准备不会启用修正。", "實驗性 Windows 整合。保留 Codex 登入;僅完成準備不會啟用修正。", "Экспериментальная интеграция Windows. Вход в Codex сохраняется; подготовка не включает коррекцию.", "実験的な Windows 連携です。Codex のログインを保持し、準備だけでは補正を有効にしません。", "Deneysel Windows entegrasyonu. Codex oturumu korunur; hazırlık tek başına düzeltmeyi açmaz.", "Tích hợp Windows thử nghiệm. Giữ đăng nhập Codex; chuẩn bị không tự bật hiệu chỉnh.", "Integração experimental com Windows. Mantém o login do Codex; apenas preparar não ativa a correção."], - refresh: ["Refresh status", "상태 새로고침", "Status aktualisieren", "Actualiser l’état", "刷新状态", "重新整理狀態", "Обновить состояние", "状態を更新", "Durumu yenile", "Làm mới trạng thái", "Atualizar status"], - prepare: ["Prepare certificate", "인증서 준비", "Zertifikat vorbereiten", "Préparer le certificat", "准备证书", "準備憑證", "Подготовить сертификат", "証明書を準備", "Sertifikayı hazırla", "Chuẩn bị chứng chỉ", "Preparar certificado"], - trust: ["Register trust", "신뢰 등록", "Vertrauen registrieren", "Enregistrer la confiance", "注册信任", "註冊信任", "Добавить доверие", "信頼を登録", "Güveni kaydet", "Đăng ký tin cậy", "Registrar confiança"], - remove: ["Remove trust", "신뢰 해제", "Vertrauen entfernen", "Retirer la confiance", "移除信任", "移除信任", "Удалить доверие", "信頼を解除", "Güveni kaldır", "Gỡ tin cậy", "Remover confiança"], - renew: ["Renew certificate", "인증서 갱신", "Zertifikat erneuern", "Renouveler le certificat", "更新证书", "更新憑證", "Обновить сертификат", "証明書を更新", "Sertifikayı yenile", "Gia hạn chứng chỉ", "Renovar certificado"], - start: ["Start observation", "관찰 시작", "Beobachtung starten", "Démarrer l’observation", "开始观察", "開始觀察", "Начать наблюдение", "観察を開始", "Gözlemi başlat", "Bắt đầu quan sát", "Iniciar observação"], - stop: ["Stop service", "서비스 중지", "Dienst stoppen", "Arrêter le service", "停止服务", "停止服務", "Остановить службу", "サービスを停止", "Hizmeti durdur", "Dừng dịch vụ", "Parar serviço"], - launch: ["Open Codex", "Codex 열기", "Codex öffnen", "Ouvrir Codex", "打开 Codex", "開啟 Codex", "Открыть Codex", "Codex を開く", "Codex’i aç", "Mở Codex", "Abrir Codex"], - observe: ["Return to observation", "관찰 모드로 복귀", "Zur Beobachtung zurück", "Revenir à l’observation", "返回观察", "返回觀察", "Вернуться к наблюдению", "観察に戻る", "Gözleme dön", "Trở lại quan sát", "Voltar à observação"], - apply: ["Run 3-minute trial", "3분 복구 시험", "3-Minuten-Test starten", "Essai de 3 minutes", "运行 3 分钟试验", "執行 3 分鐘試驗", "Запустить тест на 3 минуты", "3分間のテスト", "3 dakikalık deneme", "Thử nghiệm 3 phút", "Executar teste de 3 minutos"], - confirm: ["Confirm action", "동작 확인", "Aktion bestätigen", "Confirmer l’action", "确认操作", "確認操作", "Подтвердить действие", "操作を確認", "İşlemi onayla", "Xác nhận thao tác", "Confirmar ação"], - acknowledge: ["I understand the scope of this action.", "이 동작의 적용 범위를 이해했습니다.", "Ich verstehe den Umfang dieser Aktion.", "Je comprends la portée de cette action.", "我了解此操作的范围。", "我了解此操作的範圍。", "Я понимаю область действия.", "この操作の範囲を理解しました。", "Bu işlemin kapsamını anlıyorum.", "Tôi hiểu phạm vi thao tác này.", "Entendo o escopo desta ação."], - risk: ["Trust applies to this Windows user and allows the local relay to handle chatgpt.com traffic. Stop the service and close Codex before renewal or removal. Stopping may interrupt active connections.", "이 Windows 사용자에게 인증서 신뢰가 적용되어 로컬 릴레이가 chatgpt.com 트래픽을 처리합니다. 갱신·해제 전 서비스를 중지하고 Codex를 닫으세요. 중지하면 진행 중인 연결이 끊길 수 있습니다.", "Das Vertrauen gilt für diesen Windows-Benutzer und erlaubt dem lokalen Relay, chatgpt.com-Verkehr zu verarbeiten. Vor Erneuerung oder Entfernung Dienst stoppen und Codex schließen. Ein Stopp kann aktive Verbindungen unterbrechen.", "La confiance s’applique à cet utilisateur Windows et autorise le relais local à traiter le trafic chatgpt.com. Arrêtez le service et fermez Codex avant renouvellement ou suppression. L’arrêt peut interrompre les connexions actives.", "信任适用于此 Windows 用户,允许本地中继处理 chatgpt.com 流量。更新或移除前请停止服务并关闭 Codex。停止可能中断活动连接。", "信任適用於此 Windows 使用者,允許本機中繼處理 chatgpt.com 流量。更新或移除前請停止服務並關閉 Codex。停止可能中斷使用中的連線。", "Доверие действует для этого пользователя Windows и позволяет локальному ретранслятору обрабатывать трафик chatgpt.com. Перед обновлением или удалением остановите службу и закройте Codex. Остановка может прервать соединения.", "信頼はこの Windows ユーザーに適用され、ローカルリレーが chatgpt.com の通信を処理します。更新・解除前にサービスを停止し Codex を閉じてください。停止すると接続が中断される場合があります。", "Güven bu Windows kullanıcısı için geçerlidir ve yerel aktarıcının chatgpt.com trafiğini işlemesine izin verir. Yenilemeden veya kaldırmadan önce hizmeti durdurup Codex’i kapatın. Durdurma etkin bağlantıları kesebilir.", "Tin cậy áp dụng cho người dùng Windows này, cho phép bộ chuyển tiếp cục bộ xử lý lưu lượng chatgpt.com. Dừng dịch vụ và đóng Codex trước khi gia hạn hoặc gỡ. Dừng có thể ngắt kết nối đang dùng.", "A confiança se aplica a este usuário do Windows e permite que o relay local processe o tráfego de chatgpt.com. Pare o serviço e feche o Codex antes de renovar ou remover o certificado. Parar pode interromper conexões ativas."], - trialRisk: ["For up to 3 minutes, two UI flags are adjusted for the whole signed-in account, across models. Usage, credits and server limits remain unchanged. Observed exhaustion is required; a response does not prove the composer recovered.", "최대 3분 동안 모델 구분 없이 로그인 계정 전체의 UI 표시 두 항목을 교정합니다. 사용량·크레딧·서버 한도는 유지됩니다. 실제 소진 관찰이 필요하며, 응답 생성만으로 입력창 복구가 입증되지는 않습니다.", "Bis zu 3 Minuten werden zwei UI-Werte für das gesamte angemeldete Konto modellübergreifend angepasst. Nutzung, Guthaben und Serverlimits bleiben unverändert. Eine beobachtete Erschöpfung ist erforderlich; eine Antwort beweist keine Wiederherstellung der Eingabe.", "Pendant 3 minutes au maximum, deux indicateurs d’interface sont ajustés pour tout le compte connecté, tous modèles confondus. Usage, crédits et limites serveur restent inchangés. Un épuisement observé est requis ; une réponse ne prouve pas le rétablissement de la saisie.", "最多 3 分钟内,调整整个已登录账户的两个界面标志,影响所有模型。用量、余额和服务器限制不变。需要观察到额度耗尽;收到响应不代表输入框已恢复。", "最多 3 分鐘內,調整整個已登入帳戶的兩個介面旗標,影響所有模型。用量、點數和伺服器限制不變。必須觀察到額度耗盡;收到回應不代表輸入框已恢復。", "Не более 3 минут корректируются два флага интерфейса всего аккаунта для всех моделей. Использование, кредиты и лимиты сервера не меняются. Требуется наблюдаемое исчерпание; ответ не доказывает восстановление ввода.", "最大3分間、ログイン中のアカウント全体でモデルを区別せず2つのUIフラグを補正します。使用量・クレジット・サーバー制限は変更しません。上限到達の観察が必要で、応答だけでは入力欄の復旧を証明できません。", "En fazla 3 dakika boyunca tüm modellerde oturum açmış hesabın iki arayüz bayrağı düzeltilir. Kullanım, krediler ve sunucu sınırları değişmez. Kotanın tükendiğinin gözlenmesi gerekir; yanıt, giriş alanının düzeldiğini kanıtlamaz.", "Trong tối đa 3 phút, điều chỉnh hai cờ giao diện của toàn bộ tài khoản đã đăng nhập, cho mọi mô hình. Mức dùng, tín dụng và giới hạn máy chủ không đổi. Cần quan sát thấy hết hạn mức; phản hồi không chứng minh ô nhập đã phục hồi.", "Por até 3 minutos, dois indicadores da interface são ajustados para toda a conta conectada, em todos os modelos. Uso, créditos e limites do servidor permanecem inalterados. É necessário observar o esgotamento; uma resposta não comprova que o campo de texto foi recuperado."], - error: ["Completion could not be confirmed. Refresh status before retrying.", "완료 여부를 확인하지 못했습니다. 재시도 전에 상태를 새로고침하세요.", "Abschluss nicht bestätigt. Vor einem erneuten Versuch Status aktualisieren.", "Fin non confirmée. Actualisez l’état avant de réessayer.", "无法确认是否完成。重试前请刷新状态。", "無法確認是否完成。重試前請重新整理狀態。", "Завершение не подтверждено. Обновите состояние перед повтором.", "完了を確認できませんでした。再試行前に状態を更新してください。", "Tamamlandığı doğrulanamadı. Yeniden denemeden önce durumu yenileyin.", "Chưa xác nhận hoàn tất. Làm mới trạng thái trước khi thử lại.", "Não foi possível confirmar a conclusão. Atualize o status antes de tentar novamente."], - done: ["Action confirmed. Status refreshed.", "동작을 확인하고 상태를 새로고침했습니다.", "Aktion bestätigt. Status aktualisiert.", "Action confirmée. État actualisé.", "操作已确认,状态已刷新。", "操作已確認,狀態已重新整理。", "Действие подтверждено. Состояние обновлено.", "操作を確認し、状態を更新しました。", "İşlem doğrulandı. Durum yenilendi.", "Đã xác nhận thao tác và làm mới trạng thái.", "Ação confirmada. Status atualizado."], - certificate: ["Certificate", "인증서", "Zertifikat", "Certificat", "证书", "憑證", "Сертификат", "証明書", "Sertifika", "Chứng chỉ", "Certificado"], - runtime: ["Service", "서비스", "Dienst", "Service local", "服务", "服務", "Служба", "サービス", "Hizmet", "Dịch vụ", "Serviço"], - expiry: ["Expires", "만료", "Ablauf", "Expiration", "到期", "到期", "Истекает", "有効期限", "Bitiş", "Hết hạn", "Expira"], - renewalDue: ["Certificate renewal is due soon.", "인증서 갱신 시기가 다가옵니다.", "Zertifikat bald erneuern.", "Le certificat doit bientôt être renouvelé.", "证书即将需要更新。", "憑證即將需要更新。", "Скоро потребуется обновить сертификат.", "証明書の更新時期が近づいています。", "Sertifika yakında yenilenmeli.", "Chứng chỉ sắp cần gia hạn.", "O certificado precisa ser renovado em breve."], - unsupported: ["Available on supported Windows installations only.", "지원되는 Windows 설치에서만 사용할 수 있습니다.", "Nur für unterstützte Windows-Installationen.", "Disponible uniquement sur les installations Windows prises en charge.", "仅适用于受支持的 Windows 安装。", "僅適用於受支援的 Windows 安裝。", "Доступно только для поддерживаемых установок Windows.", "対応する Windows 環境でのみ利用できます。", "Yalnızca desteklenen Windows kurulumlarında kullanılabilir.", "Chỉ dùng được trên bản cài Windows được hỗ trợ.", "Disponível apenas em instalações Windows compatíveis."], - localOnly: ["Changes require this computer’s local dashboard. Save drafts and close Codex before launching it here.", "변경은 이 컴퓨터의 로컬 대시보드에서 가능합니다. 여기서 앱을 실행하기 전에 초안을 저장하고 Codex를 닫으세요.", "Änderungen erfordern das lokale Dashboard dieses Computers. Vor dem Start Entwürfe speichern und Codex schließen.", "Les modifications nécessitent le tableau de bord local de cet ordinateur. Enregistrez les brouillons et fermez Codex avant de le lancer ici.", "更改需要此计算机的本地仪表板。在此启动前,请保存草稿并关闭 Codex。", "變更需要此電腦的本機儀表板。在此啟動前,請儲存草稿並關閉 Codex。", "Изменения требуют локальной панели этого компьютера. Сохраните черновики и закройте Codex перед запуском здесь.", "変更にはこのPCのローカルダッシュボードが必要です。ここから起動する前に下書きを保存し Codex を閉じてください。", "Değişiklikler bu bilgisayarın yerel panosunu gerektirir. Buradan açmadan önce taslakları kaydedip Codex’i kapatın.", "Thay đổi cần bảng điều khiển cục bộ của máy này. Lưu bản nháp và đóng Codex trước khi mở tại đây.", "As alterações exigem o painel local deste computador. Salve os rascunhos e feche o Codex antes de abri-lo aqui."], + blockedByProxy: ["The outbound proxy setting is invalid or unsupported. Correct it before starting observation; no direct fallback was used.", "외부 프록시 설정이 잘못되었거나 지원되지 않습니다. 관찰 시작 전에 설정을 확인하세요. 직접 연결로 우회하지 않았습니다.", "Die Proxy-Einstellung ist ungültig oder nicht unterstützt. Vor dem Start korrigieren; keine direkte Ersatzverbindung wurde genutzt.", "Le proxy sortant est invalide ou non pris en charge. Corrigez-le avant l’observation ; aucun repli direct n’a été utilisé.", "出站代理设置无效或不受支持。观察前请修正;未回退到直接连接。", "輸出代理設定無效或不受支援。觀察前請修正;並未改用直接連線。", "Настройка прокси неверна или не поддерживается. Исправьте её до наблюдения; прямое подключение не использовалось.", "送信プロキシ設定が無効または未対応です。観察開始前に修正してください。直接接続への切り替えは行っていません。", "Çıkış proxy ayarı geçersiz veya desteklenmiyor. Gözlemden önce düzeltin; doğrudan bağlantıya geçilmedi.", "Cấu hình proxy đầu ra không hợp lệ hoặc chưa hỗ trợ. Sửa trước khi quan sát; không chuyển sang kết nối trực tiếp.", "A configuração do proxy de saída é inválida ou não é compatível. Corrija-a antes de iniciar a observação; não foi usado acesso direto como alternativa.", "La configuración del proxy de salida no es válida o no se admite. Corrígela antes de iniciar la observación; no se recurrió a una conexión directa."], + closeApp: ["Save drafts, close Codex, then refresh status before trying again.", "초안을 저장하고 Codex를 닫은 뒤 상태를 새로고침하여 재시도하세요.", "Entwürfe speichern, Codex schließen und vor dem nächsten Versuch den Status aktualisieren.", "Enregistrez les brouillons, fermez Codex, puis actualisez l’état avant de réessayer.", "保存草稿并关闭 Codex,然后刷新状态再重试。", "儲存草稿並關閉 Codex,然後重新整理狀態再重試。", "Сохраните черновики, закройте Codex и обновите состояние перед повтором.", "下書きを保存して Codex を閉じ、状態を更新してから再試行してください。", "Taslakları kaydedip Codex’i kapatın; yeniden denemeden önce durumu yenileyin.", "Lưu bản nháp, đóng Codex rồi làm mới trạng thái trước khi thử lại.", "Salve os rascunhos, feche o Codex e atualize o status antes de tentar novamente.", "Guarda los borradores, cierra Codex y actualiza el estado antes de volver a intentarlo."], + connectedUnavailable: ["These local controls are unavailable in OpenCodex managed client mode.", "OpenCodex 관리형 클라이언트 모드에서는 이 로컬 제어를 사용할 수 없습니다.", "Diese lokalen Steuerelemente sind im verwalteten Clientmodus von OpenCodex nicht verfügbar.", "Ces commandes locales ne sont pas disponibles en mode client géré OpenCodex.", "OpenCodex 托管客户端模式不提供这些本地控制。", "OpenCodex 受管理用戶端模式不提供這些本機控制。", "Эти локальные действия недоступны в управляемом клиентском режиме OpenCodex.", "OpenCodex の管理対象クライアントモードでは、このローカル操作を利用できません。", "Bu yerel denetimler OpenCodex yönetilen istemci modunda kullanılamaz.", "Các điều khiển cục bộ này không có trong chế độ máy khách được quản lý của OpenCodex.", "Estes controles locais não estão disponíveis no modo de cliente gerenciado do OpenCodex.", "Estos controles locales no están disponibles en el modo de cliente administrado de OpenCodex."], + title: ["Desktop compatibility", "데스크톱 호환", "Desktop-Kompatibilität", "Compatibilité du bureau", "桌面兼容", "桌面相容", "Совместимость приложения", "デスクトップ互換性", "Masaüstü uyumluluğu", "Tương thích ứng dụng", "Compatibilidade com o desktop", "Compatibilidad con Desktop"], + description: ["Experimental Windows integration. Keeps the Codex login; setup alone does not enable correction.", "실험적인 Windows 연동입니다. Codex 로그인을 유지하며, 준비만으로 교정이 켜지지 않습니다.", "Experimentelle Windows-Integration. Die Codex-Anmeldung bleibt erhalten; die Einrichtung aktiviert keine Korrektur.", "Intégration Windows expérimentale. La connexion Codex est conservée ; la préparation seule n’active pas la correction.", "实验性 Windows 集成。保留 Codex 登录;仅完成准备不会启用修正。", "實驗性 Windows 整合。保留 Codex 登入;僅完成準備不會啟用修正。", "Экспериментальная интеграция Windows. Вход в Codex сохраняется; подготовка не включает коррекцию.", "実験的な Windows 連携です。Codex のログインを保持し、準備だけでは補正を有効にしません。", "Deneysel Windows entegrasyonu. Codex oturumu korunur; hazırlık tek başına düzeltmeyi açmaz.", "Tích hợp Windows thử nghiệm. Giữ đăng nhập Codex; chuẩn bị không tự bật hiệu chỉnh.", "Integração experimental com Windows. Mantém o login do Codex; apenas preparar não ativa a correção.", "Integración experimental para Windows. Conserva el inicio de sesión de Codex; la configuración por sí sola no activa la corrección."], + refresh: ["Refresh status", "상태 새로고침", "Status aktualisieren", "Actualiser l’état", "刷新状态", "重新整理狀態", "Обновить состояние", "状態を更新", "Durumu yenile", "Làm mới trạng thái", "Atualizar status", "Actualizar estado"], + prepare: ["Prepare certificate", "인증서 준비", "Zertifikat vorbereiten", "Préparer le certificat", "准备证书", "準備憑證", "Подготовить сертификат", "証明書を準備", "Sertifikayı hazırla", "Chuẩn bị chứng chỉ", "Preparar certificado", "Preparar certificado"], + trust: ["Register trust", "신뢰 등록", "Vertrauen registrieren", "Enregistrer la confiance", "注册信任", "註冊信任", "Добавить доверие", "信頼を登録", "Güveni kaydet", "Đăng ký tin cậy", "Registrar confiança", "Registrar confianza"], + remove: ["Remove trust", "신뢰 해제", "Vertrauen entfernen", "Retirer la confiance", "移除信任", "移除信任", "Удалить доверие", "信頼を解除", "Güveni kaldır", "Gỡ tin cậy", "Remover confiança", "Quitar confianza"], + renew: ["Renew certificate", "인증서 갱신", "Zertifikat erneuern", "Renouveler le certificat", "更新证书", "更新憑證", "Обновить сертификат", "証明書を更新", "Sertifikayı yenile", "Gia hạn chứng chỉ", "Renovar certificado", "Renovar certificado"], + start: ["Start observation", "관찰 시작", "Beobachtung starten", "Démarrer l’observation", "开始观察", "開始觀察", "Начать наблюдение", "観察を開始", "Gözlemi başlat", "Bắt đầu quan sát", "Iniciar observação", "Iniciar observación"], + stop: ["Stop service", "서비스 중지", "Dienst stoppen", "Arrêter le service", "停止服务", "停止服務", "Остановить службу", "サービスを停止", "Hizmeti durdur", "Dừng dịch vụ", "Parar serviço", "Detener servicio"], + launch: ["Open Codex", "Codex 열기", "Codex öffnen", "Ouvrir Codex", "打开 Codex", "開啟 Codex", "Открыть Codex", "Codex を開く", "Codex’i aç", "Mở Codex", "Abrir Codex", "Abrir Codex"], + observe: ["Return to observation", "관찰 모드로 복귀", "Zur Beobachtung zurück", "Revenir à l’observation", "返回观察", "返回觀察", "Вернуться к наблюдению", "観察に戻る", "Gözleme dön", "Trở lại quan sát", "Voltar à observação", "Volver a la observación"], + apply: ["Run 3-minute trial", "3분 복구 시험", "3-Minuten-Test starten", "Essai de 3 minutes", "运行 3 分钟试验", "執行 3 分鐘試驗", "Запустить тест на 3 минуты", "3分間のテスト", "3 dakikalık deneme", "Thử nghiệm 3 phút", "Executar teste de 3 minutos", "Ejecutar prueba de 3 minutos"], + confirm: ["Confirm action", "동작 확인", "Aktion bestätigen", "Confirmer l’action", "确认操作", "確認操作", "Подтвердить действие", "操作を確認", "İşlemi onayla", "Xác nhận thao tác", "Confirmar ação", "Confirmar acción"], + acknowledge: ["I understand the scope of this action.", "이 동작의 적용 범위를 이해했습니다.", "Ich verstehe den Umfang dieser Aktion.", "Je comprends la portée de cette action.", "我了解此操作的范围。", "我了解此操作的範圍。", "Я понимаю область действия.", "この操作の範囲を理解しました。", "Bu işlemin kapsamını anlıyorum.", "Tôi hiểu phạm vi thao tác này.", "Entendo o escopo desta ação.", "Comprendo el alcance de esta acción."], + risk: ["Trust applies to this Windows user and allows the local relay to handle chatgpt.com traffic. Stop the service and close Codex before renewal or removal. Stopping may interrupt active connections.", "이 Windows 사용자에게 인증서 신뢰가 적용되어 로컬 릴레이가 chatgpt.com 트래픽을 처리합니다. 갱신·해제 전 서비스를 중지하고 Codex를 닫으세요. 중지하면 진행 중인 연결이 끊길 수 있습니다.", "Das Vertrauen gilt für diesen Windows-Benutzer und erlaubt dem lokalen Relay, chatgpt.com-Verkehr zu verarbeiten. Vor Erneuerung oder Entfernung Dienst stoppen und Codex schließen. Ein Stopp kann aktive Verbindungen unterbrechen.", "La confiance s’applique à cet utilisateur Windows et autorise le relais local à traiter le trafic chatgpt.com. Arrêtez le service et fermez Codex avant renouvellement ou suppression. L’arrêt peut interrompre les connexions actives.", "信任适用于此 Windows 用户,允许本地中继处理 chatgpt.com 流量。更新或移除前请停止服务并关闭 Codex。停止可能中断活动连接。", "信任適用於此 Windows 使用者,允許本機中繼處理 chatgpt.com 流量。更新或移除前請停止服務並關閉 Codex。停止可能中斷使用中的連線。", "Доверие действует для этого пользователя Windows и позволяет локальному ретранслятору обрабатывать трафик chatgpt.com. Перед обновлением или удалением остановите службу и закройте Codex. Остановка может прервать соединения.", "信頼はこの Windows ユーザーに適用され、ローカルリレーが chatgpt.com の通信を処理します。更新・解除前にサービスを停止し Codex を閉じてください。停止すると接続が中断される場合があります。", "Güven bu Windows kullanıcısı için geçerlidir ve yerel aktarıcının chatgpt.com trafiğini işlemesine izin verir. Yenilemeden veya kaldırmadan önce hizmeti durdurup Codex’i kapatın. Durdurma etkin bağlantıları kesebilir.", "Tin cậy áp dụng cho người dùng Windows này, cho phép bộ chuyển tiếp cục bộ xử lý lưu lượng chatgpt.com. Dừng dịch vụ và đóng Codex trước khi gia hạn hoặc gỡ. Dừng có thể ngắt kết nối đang dùng.", "A confiança se aplica a este usuário do Windows e permite que o relay local processe o tráfego de chatgpt.com. Pare o serviço e feche o Codex antes de renovar ou remover o certificado. Parar pode interromper conexões ativas.", "La confianza se aplica a este usuario de Windows y permite que el intermediario local gestione el tráfico de chatgpt.com. Detén el servicio y cierra Codex antes de renovar el certificado o quitar la confianza. Detenerlo puede interrumpir conexiones activas."], + trialRisk: ["For up to 3 minutes, two UI flags are adjusted for the whole signed-in account, across models. Usage, credits and server limits remain unchanged. Observed exhaustion is required; a response does not prove the composer recovered.", "최대 3분 동안 모델 구분 없이 로그인 계정 전체의 UI 표시 두 항목을 교정합니다. 사용량·크레딧·서버 한도는 유지됩니다. 실제 소진 관찰이 필요하며, 응답 생성만으로 입력창 복구가 입증되지는 않습니다.", "Bis zu 3 Minuten werden zwei UI-Werte für das gesamte angemeldete Konto modellübergreifend angepasst. Nutzung, Guthaben und Serverlimits bleiben unverändert. Eine beobachtete Erschöpfung ist erforderlich; eine Antwort beweist keine Wiederherstellung der Eingabe.", "Pendant 3 minutes au maximum, deux indicateurs d’interface sont ajustés pour tout le compte connecté, tous modèles confondus. Usage, crédits et limites serveur restent inchangés. Un épuisement observé est requis ; une réponse ne prouve pas le rétablissement de la saisie.", "最多 3 分钟内,调整整个已登录账户的两个界面标志,影响所有模型。用量、余额和服务器限制不变。需要观察到额度耗尽;收到响应不代表输入框已恢复。", "最多 3 分鐘內,調整整個已登入帳戶的兩個介面旗標,影響所有模型。用量、點數和伺服器限制不變。必須觀察到額度耗盡;收到回應不代表輸入框已恢復。", "Не более 3 минут корректируются два флага интерфейса всего аккаунта для всех моделей. Использование, кредиты и лимиты сервера не меняются. Требуется наблюдаемое исчерпание; ответ не доказывает восстановление ввода.", "最大3分間、ログイン中のアカウント全体でモデルを区別せず2つのUIフラグを補正します。使用量・クレジット・サーバー制限は変更しません。上限到達の観察が必要で、応答だけでは入力欄の復旧を証明できません。", "En fazla 3 dakika boyunca tüm modellerde oturum açmış hesabın iki arayüz bayrağı düzeltilir. Kullanım, krediler ve sunucu sınırları değişmez. Kotanın tükendiğinin gözlenmesi gerekir; yanıt, giriş alanının düzeldiğini kanıtlamaz.", "Trong tối đa 3 phút, điều chỉnh hai cờ giao diện của toàn bộ tài khoản đã đăng nhập, cho mọi mô hình. Mức dùng, tín dụng và giới hạn máy chủ không đổi. Cần quan sát thấy hết hạn mức; phản hồi không chứng minh ô nhập đã phục hồi.", "Por até 3 minutos, dois indicadores da interface são ajustados para toda a conta conectada, em todos os modelos. Uso, créditos e limites do servidor permanecem inalterados. É necessário observar o esgotamento; uma resposta não comprova que o campo de texto foi recuperado.", "Durante un máximo de 3 minutos se ajustan dos indicadores de la interfaz para toda la cuenta con sesión iniciada, en todos los modelos. El uso, los créditos y los límites del servidor no cambian. Es necesario haber observado el agotamiento de cuota; recibir una respuesta no demuestra que el cuadro de entrada se haya recuperado."], + error: ["Completion could not be confirmed. Refresh status before retrying.", "완료 여부를 확인하지 못했습니다. 재시도 전에 상태를 새로고침하세요.", "Abschluss nicht bestätigt. Vor einem erneuten Versuch Status aktualisieren.", "Fin non confirmée. Actualisez l’état avant de réessayer.", "无法确认是否完成。重试前请刷新状态。", "無法確認是否完成。重試前請重新整理狀態。", "Завершение не подтверждено. Обновите состояние перед повтором.", "完了を確認できませんでした。再試行前に状態を更新してください。", "Tamamlandığı doğrulanamadı. Yeniden denemeden önce durumu yenileyin.", "Chưa xác nhận hoàn tất. Làm mới trạng thái trước khi thử lại.", "Não foi possível confirmar a conclusão. Atualize o status antes de tentar novamente.", "No se pudo confirmar que la acción haya finalizado. Actualiza el estado antes de reintentar."], + done: ["Action confirmed. Status refreshed.", "동작을 확인하고 상태를 새로고침했습니다.", "Aktion bestätigt. Status aktualisiert.", "Action confirmée. État actualisé.", "操作已确认,状态已刷新。", "操作已確認,狀態已重新整理。", "Действие подтверждено. Состояние обновлено.", "操作を確認し、状態を更新しました。", "İşlem doğrulandı. Durum yenilendi.", "Đã xác nhận thao tác và làm mới trạng thái.", "Ação confirmada. Status atualizado.", "Acción confirmada. Estado actualizado."], + certificate: ["Certificate", "인증서", "Zertifikat", "Certificat", "证书", "憑證", "Сертификат", "証明書", "Sertifika", "Chứng chỉ", "Certificado", "Certificado"], + runtime: ["Service", "서비스", "Dienst", "Service local", "服务", "服務", "Служба", "サービス", "Hizmet", "Dịch vụ", "Serviço", "Servicio"], + expiry: ["Expires", "만료", "Ablauf", "Expiration", "到期", "到期", "Истекает", "有効期限", "Bitiş", "Hết hạn", "Expira", "Caduca"], + renewalDue: ["Certificate renewal is due soon.", "인증서 갱신 시기가 다가옵니다.", "Zertifikat bald erneuern.", "Le certificat doit bientôt être renouvelé.", "证书即将需要更新。", "憑證即將需要更新。", "Скоро потребуется обновить сертификат.", "証明書の更新時期が近づいています。", "Sertifika yakında yenilenmeli.", "Chứng chỉ sắp cần gia hạn.", "O certificado precisa ser renovado em breve.", "Pronto será necesario renovar el certificado."], + unsupported: ["Available on supported Windows installations only.", "지원되는 Windows 설치에서만 사용할 수 있습니다.", "Nur für unterstützte Windows-Installationen.", "Disponible uniquement sur les installations Windows prises en charge.", "仅适用于受支持的 Windows 安装。", "僅適用於受支援的 Windows 安裝。", "Доступно только для поддерживаемых установок Windows.", "対応する Windows 環境でのみ利用できます。", "Yalnızca desteklenen Windows kurulumlarında kullanılabilir.", "Chỉ dùng được trên bản cài Windows được hỗ trợ.", "Disponível apenas em instalações Windows compatíveis.", "Disponible únicamente en instalaciones de Windows compatibles."], + localOnly: ["Changes require this computer’s local dashboard. Save drafts and close Codex before launching it here.", "변경은 이 컴퓨터의 로컬 대시보드에서 가능합니다. 여기서 앱을 실행하기 전에 초안을 저장하고 Codex를 닫으세요.", "Änderungen erfordern das lokale Dashboard dieses Computers. Vor dem Start Entwürfe speichern und Codex schließen.", "Les modifications nécessitent le tableau de bord local de cet ordinateur. Enregistrez les brouillons et fermez Codex avant de le lancer ici.", "更改需要此计算机的本地仪表板。在此启动前,请保存草稿并关闭 Codex。", "變更需要此電腦的本機儀表板。在此啟動前,請儲存草稿並關閉 Codex。", "Изменения требуют локальной панели этого компьютера. Сохраните черновики и закройте Codex перед запуском здесь.", "変更にはこのPCのローカルダッシュボードが必要です。ここから起動する前に下書きを保存し Codex を閉じてください。", "Değişiklikler bu bilgisayarın yerel panosunu gerektirir. Buradan açmadan önce taslakları kaydedip Codex’i kapatın.", "Thay đổi cần bảng điều khiển cục bộ của máy này. Lưu bản nháp và đóng Codex trước khi mở tại đây.", "As alterações exigem o painel local deste computador. Salve os rascunhos e feche o Codex antes de abri-lo aqui.", "Los cambios requieren el panel local de este equipo. Guarda los borradores y cierra Codex antes de abrirlo desde aquí."], reconnectHint: [ "After a normal launch or update, close Codex and use Open Codex here to restore the managed connection.", "일반 실행이나 업데이트 후에는 Codex를 닫고 여기에서 Codex 열기를 눌러 관리 연결을 복구하세요.", @@ -66,11 +67,12 @@ const rows = { "Normal başlatma veya güncellemeden sonra Codex’i kapatın ve yönetilen bağlantıyı yeniden kurmak için burada Codex’i aç’ı seçin.", "Sau khi khởi chạy thông thường hoặc cập nhật, hãy đóng Codex rồi chọn Mở Codex tại đây để khôi phục kết nối được quản lý.", "Após uma abertura normal ou atualização, feche o Codex e selecione Abrir Codex aqui para restaurar a conexão gerenciada.", + "Después de iniciar la aplicación normalmente o actualizarla, cierra Codex y usa Abrir Codex aquí para recuperar la conexión administrada.", ], - assessedPackage: ["Assessed baseline version", "평가된 기준 버전", "Bewertete Basisversion", "Version de référence évaluée", "已评估的基线版本", "已評估的基準版本", "Оценённая базовая версия", "評価済みベースラインバージョン", "Değerlendirilen temel sürüm", "Phiên bản cơ sở đã đánh giá", "Versão de base avaliada"], - observedPackage: ["Last observed package version", "마지막으로 관측한 패키지 버전", "Zuletzt erkannte Paketversion", "Dernière version du paquet observée", "上次检测到的包版本", "上次偵測到的套件版本", "Последняя обнаруженная версия пакета", "最後に検出されたパッケージバージョン", "Son algılanan paket sürümü", "Phiên bản gói quan sát lần cuối", "Última versão do pacote observada"], - lastObservedAt: ["Observed at", "관측 시각", "Erkannt am", "Observée le", "检测时间", "偵測時間", "Время проверки", "検出日時", "Algılanma zamanı", "Thời điểm quan sát", "Observada em"], - noObservedPackage: ["Not detected", "감지되지 않음", "Nicht erkannt", "Non détectée", "未检测到", "未偵測到", "Не обнаружена", "未検出", "Algılanmadı", "Không phát hiện", "Não detectada"], + assessedPackage: ["Assessed baseline version", "평가된 기준 버전", "Bewertete Basisversion", "Version de référence évaluée", "已评估的基线版本", "已評估的基準版本", "Оценённая базовая версия", "評価済みベースラインバージョン", "Değerlendirilen temel sürüm", "Phiên bản cơ sở đã đánh giá", "Versão de base avaliada", "Versión base evaluada"], + observedPackage: ["Last observed package version", "마지막으로 관측한 패키지 버전", "Zuletzt erkannte Paketversion", "Dernière version du paquet observée", "上次检测到的包版本", "上次偵測到的套件版本", "Последняя обнаруженная версия пакета", "最後に検出されたパッケージバージョン", "Son algılanan paket sürümü", "Phiên bản gói quan sát lần cuối", "Última versão do pacote observada", "Última versión del paquete observada"], + lastObservedAt: ["Observed at", "관측 시각", "Erkannt am", "Observée le", "检测时间", "偵測時間", "Время проверки", "検出日時", "Algılanma zamanı", "Thời điểm quan sát", "Observada em", "Observado el"], + noObservedPackage: ["Not detected", "감지되지 않음", "Nicht erkannt", "Non détectée", "未检测到", "未偵測到", "Не обнаружена", "未検出", "Algılanmadı", "Không phát hiện", "Não detectada", "No detectado"], } as const satisfies Record; export function desktopCompatibilityCopy(locale: Locale): Record<`desktopCompat.${keyof typeof rows}`, string> { diff --git a/gui/src/i18n/es.ts b/gui/src/i18n/es.ts new file mode 100644 index 00000000000..81d7368c8af --- /dev/null +++ b/gui/src/i18n/es.ts @@ -0,0 +1,4627 @@ +import { desktopCompatibilityCopy } from "./desktop-compatibility-copy"; +import { accountProbeCopy } from "./account-probe-copy"; +import { shellV2Copy } from "./shell-v2-copy"; +import { codexCliUpdateCopy } from "./codex-cli-update-copy"; +import { remoteLinkDiagnosticsCopy } from "./remote-link-diagnostics-copy"; +import { remoteLinkChildCopy } from "./remote-link-child-copy"; +import { gatewayClientsCopy } from "./gateway-clients-copy"; +import { connectionsCopy } from "./connections-copy"; +import { modelsV2Copy } from "./v2-pages/models-copy"; +import { modelsOverallCopy } from "./models-overall-copy"; +import { accountsV2Copy } from "./v2-pages/accounts-copy"; +import { subagentsV2Copy } from "./v2-pages/subagents-copy"; +import { usageV2Copy } from "./v2-pages/usage-copy"; +import { logsV2Copy } from "./v2-pages/logs-copy"; +import { connectV2Copy } from "./v2-pages/connect-copy"; +import { startupV2Copy } from "./v2-pages/startup-copy"; +import { proxyV2Copy } from "./v2-pages/proxy-copy"; +import { telemetryProfileCopy } from "./v2-pages/telemetry-profile-copy"; +import type { TKey } from "./en"; + +// Neutral Spanish. Use the shared copy tables for the same namespaces as English. +export const es = { + "pws.firstResponse.title": "Progreso hasta la primera respuesta", + "pws.firstResponse.stepProvider": "Proveedor", + "pws.firstResponse.stepModels": "Modelos", + "pws.firstResponse.stepClients": "Routing del cliente", + "pws.firstResponse.stepProbe": "Primera respuesta", + "pws.firstResponse.providerSaved": "Configuración del proveedor guardada", + "pws.firstResponse.providerNeedsSetup": "Guardado · Se necesitan credenciales", + "pws.firstResponse.providerNeedsLogin": "Guardado · Debes iniciar sesión en la cuenta", + "pws.firstResponse.providerNeedsAttention": "Guardado · Vuelve a autenticar la cuenta activa", + "pws.firstResponse.providerDisabled": "El proveedor está desactivado", + "pws.firstResponse.modelsLoading": "Comprobando la lista de modelos…", + "pws.firstResponse.modelsFailed": "No se pudo cargar la lista de modelos", + "pws.firstResponse.modelsPending": "La lista inicial sigue pendiente. Los modelos permanecen ocultos hasta que termine la búsqueda.", + "pws.firstResponse.modelsReady": "Modelos habilitados para routing: {count}", + "pws.firstResponse.modelsReadyDiscoveryFailed": "Modelos conservados y habilitados: {count}. Falló la detección en vivo.", + "pws.firstResponse.modelsAllOff": "Todos los modelos están desactivados. Habilítalos en Modelos.", + "pws.firstResponse.modelsConfigured": "Modelos configurados: {count}", + "pws.firstResponse.modelsEmpty": "Aún no se han detectado ni configurado modelos", + "pws.firstResponse.openProviderModels": "Elegir modelos", + "pws.firstResponse.clientStep": "Aplica la configuración de un cliente en Enrutamiento y selecciona {provider}/. Los cambios se aplican a las sesiones nuevas.", + "pws.firstResponse.openConnect": "Abrir Enrutamiento", + "pws.firstResponse.probeUntested": "Aún sin verificar. Ejecuta la prueba de respuesta del modelo que aparece abajo.", + "pws.firstResponse.probeOk": "Respuesta de {model} verificada", + "pws.firstResponse.probeFailed": "La última prueba de respuesta falló para {model}", + "pws.firstResponse.stepDisconnect": "Desconectar y restaurar", + "pws.firstResponse.disconnectNote": "En Enrutamiento, desactivar Claude Code solo quita el bloque del proxy para las sesiones nuevas de Claude. Desactivar Codex interrumpe el enrutamiento por el proxy y restaura el catálogo nativo de Codex y el historial de conversaciones. Las sesiones en curso conservan su entorno hasta que se reinicien. Desactivar o quitar {provider} no restaura la configuración del cliente en Enrutamiento.", + "pws.firstResponse.probeReverify": "La configuración de conexión cambió desde la prueba fallida. Vuelve a probar {model} para verificar la corrección.", + "pws.completion.recovery.auth": "Comprueba o actualiza la clave API o las credenciales de la cuenta del proveedor. Luego vuelve a probar {model}.", + "pws.completion.recovery.rateLimit": "El proveedor limitó esta solicitud (HTTP 429). Espera a que se restablezca el límite de solicitudes o cambia de cuenta o clave API. Luego vuelve a probar {model}.", + "pws.completion.recovery.connection": "La solicitud agotó el tiempo de espera o no pudo llegar al endpoint. Comprueba la URL base y la configuración de red. Luego vuelve a probar {model}.", + "pws.completion.recovery.model": "El proveedor rechazó la solicitud para este modelo. Comprueba el ID del modelo en la pestaña Modelos o elige otro y vuelve a probar.", + "pws.completion.recovery.upstream": "El proveedor devolvió un error o un flujo incompleto. Vuelve a probar {model} o revisa la configuración del proveedor.", + "pws.completion.recovery.aborted": "Se canceló la prueba antes de completarse. Vuelve a probar {model} cuando quieras.", + "pws.completion.recovery.credentialChanged": "La configuración o las credenciales del proveedor cambiaron al iniciar la prueba. Vuelve a probar {model}.", + "pws.completion.recovery.request": "No se pudo iniciar la solicitud de prueba. Espera a que termine la prueba en curso o vuelve a probar {model}.", + "pws.completion.recovery.fixAuth": "Actualizar credenciales", + "pws.completion.recovery.fixSettings": "Comprobar configuración", + "pws.completion.title": "Prueba de respuesta del modelo", + "pws.completion.model": "Modelo que se probará", + "pws.completion.choose": "Elige un modelo", + "pws.completion.run": "Probar modelo", + "pws.completion.confirm": "¿Probar {model} en {provider}? Se enviará una solicitud real de respuesta con un límite de salida de 32 tokens. Consume cuota y puede generar costos.", + "pws.completion.failed": "La prueba del modelo falló", + "pws.completion.ok": "La prueba del modelo se completó correctamente", + "pws.completion.notApplicable": "Prueba no aplicable", + "pws.completion.ttft": "Tiempo hasta el primer token", + "pws.completion.total": "Latencia total", + "pws.completion.reported": "El proveedor de origen indicó {upstream} para {model}", + "pws.completion.unreported": "El proveedor de origen no indicó un modelo para {model}", + "pws.completion.identity": "El proveedor de origen informa los metadatos del modelo; estos no verifican la identidad del modelo real.", + "pws.completion.match": "Coincide", + "pws.completion.mismatch": "No coincide", + "pws.completion.unknown": "Desconocido", + "pws.completion.missing_metadata": "La respuesta del proveedor de origen no contiene metadatos del modelo.", + "pws.completion.conflicting_metadata": "La respuesta del proveedor de origen contiene metadatos del modelo contradictorios.", + "pws.completion.disabled": "Este proveedor está desactivado.", + "pws.completion.forward_auth": "No se admite la autenticación reenviada.", + "pws.completion.oauth_auth": "No se admite la autenticación OAuth.", + "pws.completion.unsupported_adapter": "Este adaptador no es compatible.", + "pws.completion.unsupported_transport": "Esta configuración de transporte no es compatible.", + "pws.completion.tls_profile": "Se configura un perfil TLS personalizado.", + "pws.completion.upstream_http_version": "Hay una versión de HTTP configurada para el proveedor de origen.", + "pws.completion.request_pacing": "El control del ritmo de solicitudes está activado.", + "pws.completion.custom_executor_egress": "No se puede conservar un ejecutor fetch personalizado junto con un proxy del proveedor.", + "pws.completion.runAll": "Probar todos los modelos", + "pws.completion.allConfirm": "¿Probar todos los modelos de {provider} ({count} en total)? Se envían solicitudes reales de respuesta de una en una (hasta {count}), con un límite de salida de 32 tokens cada una. Es posible que se omitan algunos modelos antes del envío. Esta prueba consume cuota y puede generar cargos.", + "pws.completion.stop": "Detener", + "pws.completion.progress": "Probando {done} de {total}…", + "pws.completion.stopped": "Prueba detenida: {done} de {total} completadas", + "pws.completion.summary": "Correctos: {passed}; fallidos: {failed}; sin probar: {skipped}", + "pws.completion.passed": "Correcto", + "pws.completion.failedShort": "Falló", + "pws.completion.notTested": "Sin probar", + "pws.completion.disableFailed": "Desactivar modelos que fallaron ({count})", + "pws.completion.disableConfirm": "¿Desactivar los modelos cuya prueba falló en {provider} ({count})? Desaparecerán del catálogo y del selector, pero podrás llamarlos por su ID exacto hasta que vuelvas a habilitarlos en Modelos.", + "pws.completion.disabledDone": "Modelos desactivados: {count}. Puedes volver a habilitarlos en Modelos.", + "pws.completion.disableError": "No se pudieron desactivar los modelos que fallaron", + + "reasoningRetention.advanced": "Configuración avanzada", + "reasoningRetention.title": "Conservación del razonamiento", + "reasoningRetention.enable": "Activar la conservación del razonamiento", + "reasoningRetention.description": "Desactivada de forma predeterminada. Al activarla para la compactación enrutada v1/v2 con un resumen legible, el razonamiento que cabe en el menor de estos límites —el porcentaje de la ventana de contexto y el límite de tokens— vuelve como contexto histórico junto con el resumen. Si supera ese límite, se archiva localmente y se sustituye por una nota con la ruta. Valores al activarla: 20 % y 100.000 tokens. No se descifra el razonamiento privado del proveedor; la salida opaca de compactación permanece intacta.", + "reasoningRetention.storageHint": "Activarla puede conservar razonamiento en texto sin cifrar en el historial y los archivos locales. Los archivos completados no tienen límite de tamaño total ni caducidad; elimina manualmente los que ya no necesites.", + "reasoningRetention.percent": "Ventana de contexto (%)", + "reasoningRetention.tokens": "Límite de tokens", + "reasoningRetention.reset": "Restablecer y desactivar", + "reasoningRetention.invalid": "Introduce un porcentaje mayor que 0 y menor o igual que 100, y una cantidad entera positiva de tokens.", + "reasoningRetention.loadFailed": "No se pudo cargar la configuración de conservación del razonamiento.", + "reasoningRetention.saveFailed": "No se pudo guardar la configuración de conservación del razonamiento.", + "reasoningRetention.saved": "Se guardó la configuración de conservación del razonamiento.", + "nativeReasoningRetention.title": "Conservación del razonamiento nativo de OpenAI", + "nativeReasoningRetention.description": "Solo para solicitudes nativas al backend oficial de ChatGPT, incluidos los cambios reales de destino en Combos y cuentas agrupadas. Permite volver a enviar razonamiento cifrado anterior; su reutilización depende del backend. Ambas opciones están desactivadas de forma predeterminada.", + "nativeReasoningRetention.modelSwitch": "Conservar el razonamiento cifrado al cambiar de modelo", + "nativeReasoningRetention.accountSwitch": "Conservar el razonamiento cifrado al cambiar de cuenta (experimental)", + "nativeReasoningRetention.accountHint": "Conservar el texto cifrado no comparte identificadores de respuestas guardadas ni archivos entre cuentas. Una solicitud correcta no demuestra que se haya reutilizado el razonamiento. El tratamiento de la compactación nativa no cambia.", + "nativeReasoningRetention.reset": "Restaurar valores predeterminados", + "nativeReasoningRetention.loadFailed": "No se pudo cargar la configuración de razonamiento nativo.", + "nativeReasoningRetention.saveFailed": "No se pudo guardar la configuración de razonamiento nativo.", + "nativeReasoningRetention.saved": "Se guardó la configuración de razonamiento nativo.", + "workflowBudget.title": "Límites del flujo de trabajo para subagentes", + "workflowBudget.description": "Límites por tarea. Cada tarea abarca una conversación y los subagentes que inicia, con un recuento en una ventana móvil de {minutes} minutos. Se rechaza localmente con un 429 cualquier solicitud que supere un límite, antes de contactar al proveedor. Los cambios se aplican a partir de la siguiente solicitud y se mantiene el uso ya contabilizado.", + "workflowBudget.maxConcurrentChildren": "Turnos en paralelo", + "workflowBudget.maxConcurrentChildrenHint": "Turnos que una tarea puede ejecutar al mismo tiempo. Se reserva un turno para tu conversación, por lo que los subagentes disponen de uno menos.", + "workflowBudget.maxPhysicalSends": "Solicitudes a modelos por ventana", + "workflowBudget.maxPhysicalSendsHint": "Solicitudes a proveedores, incluidos reintentos, que puede enviar una tarea dentro de la ventana.", + "workflowBudget.maxDistinctChildren": "Subagentes distintos por ventana", + "workflowBudget.maxDistinctChildrenHint": "Conversaciones de subagentes distintas que una tarea puede iniciar dentro de la ventana.", + "workflowBudget.range": "Predeterminado: {default}. Intervalo permitido: {min}–{max}.", + "workflowBudget.invalid": "Ingresa un número entero entre {min} y {max}.", + "workflowBudget.increase": "Aumentar {label}", + "workflowBudget.decrease": "Disminuir {label}", + "workflowBudget.reset": "Restaurar valores predeterminados", + "workflowBudget.loadFailed": "No se pudieron cargar los límites del flujo de trabajo.", + "workflowBudget.saveFailed": "No se pudieron guardar los límites del flujo de trabajo.", + "workflowBudget.saved": "Límites del flujo de trabajo guardados.", + ...desktopCompatibilityCopy("es"), + ...accountProbeCopy("es"), + ...shellV2Copy("es"), + ...codexCliUpdateCopy("es"), + ...remoteLinkDiagnosticsCopy("es"), + ...remoteLinkChildCopy("es"), + ...gatewayClientsCopy("es"), + ...connectionsCopy("es"), + ...modelsV2Copy("es"), + ...modelsOverallCopy("es"), + ...accountsV2Copy("es"), + ...subagentsV2Copy("es"), + ...usageV2Copy("es"), + ...logsV2Copy("es"), + ...connectV2Copy("es"), + ...startupV2Copy("es"), + ...proxyV2Copy("es"), + ...telemetryProfileCopy("es"), + "claude.tierDefaults.unset": "Desactivado (mantener la configuración Claude existente)", + "claude.tierDefaults.recovery": "La aplicación se detuvo y la restauración automática falló. Revisa la copia de seguridad de abajo antes de reintentar.", + "claude.tierDefaults.title": "Valores predeterminados de nivel CLI", + "claude.tierDefaults.preview": "Previsualizar la configuración de Claude", + "claude.tierDefaults.apply": "Aplicar a la configuración de Claude", + "claude.tierDefaults.applied": "La configuración de Claude coincide con los valores predeterminados guardados.", + "claude.tierDefaults.failed": "No se pudieron aplicar los valores predeterminados. Vuelve a previsualizar y revisa la configuración de Claude.", + "sidecar.pool": "Pool", + "sidecar.poolCurrent": "Pool de la solicitud actual", + "sidecar.poolA": "Anthropic", + "sidecar.poolB": "Anthropic · Pool 2", + "sidecar.poolMixed": "Esta selección explícita puede utilizar un grupo diferente de la solicitud principal.", + "provider.name.anthropic2": "Anthropic · Pool 2", + "nav.claude": "Claude", + "claude.pageSub": "Enrutamiento y configuración de OpenCodex para Claude Code.", + + "pws.anthropicAccountThresholdHint": "Sustituye el valor predeterminado del grupo de Claude. 0 desactiva el cambio por uso solo para esta cuenta; siguen aplicándose las pausas y la recuperación ante límites de solicitudes.", + "kiroLogin.title": "Iniciar sesión en Kiro", + "kiroLogin.chooseMethod": "Elige un método de inicio de sesión", + "kiroLogin.cli": "Kiro CLI", + "kiroLogin.iam": "AWS IAM Identity Center", + "kiroLogin.iamDescription": "Usa el portal de acceso a AWS y la región de IAM Identity Center de tu organización.", + "kiroLogin.startUrl": "URL del portal de acceso a AWS", + "kiroLogin.region": "Región de IAM Identity Center", + "kiroLogin.invalidIam": "Ingresa una URL HTTPS del portal de acceso a AWS que termine en /start y una región de AWS válida.", + "kiroLogin.back": "Atrás", + "kiroLogin.continue": "Continuar a AWS", + "kiroLogin.selectProfile": "Elige un perfil de Kiro", + "kiroLogin.profile": "Perfil de Kiro", + "kiroLogin.saveAccount": "Guardar cuenta", + "kiroLogin.selecting": "Guardando la cuenta de Kiro…", + "kiroLogin.profileFailed": "No se pudo guardar este perfil. Vuelve a intentarlo.", + "kiroLogin.builderId": "Builder ID", + "kiroLogin.google": "Google", + "kiroLogin.github": "GitHub", + "kiroLogin.addDescription": "Añade una cuenta de Kiro mediante un código de dispositivo o importa una sesión de Kiro CLI.", + "kiroLogin.loginDescription": "Inicia sesión mediante un código de dispositivo o importa tu sesión de Kiro CLI.", + "kiroLogin.starting": "Inicio de sesión del dispositivo…", + "kiroLogin.pending": "Introduce este código en la página de verificación y espera aquí.", + "kiroLogin.done": "Se agregó la cuenta Kiro.", + "kiroLogin.expired": "El inicio de sesión del dispositivo expiró. Vuelve a intentarlo.", + "kiroLogin.ended": "El inicio de sesión terminó. Revisa la lista de cuentas.", + "kiroLogin.failed": "El inicio de sesión Kiro falló.", + "kiroLogin.startFailed": "No se pudo iniciar sesión en Kiro. Vuelve a intentarlo.", + "kiroLogin.tryAgain": "Inténtalo de nuevo", + "kiroLogin.copyCode": "Copiar código", + "kiroLogin.copied": "Código copiado", + "kiroLogin.copyUnavailable": "Copiar no disponible", + "kiroLogin.openVerification": "Abrir la página de verificación", + "kiroLogin.unexpectedHost": "Host de verificación inesperado. Comprueba la dirección antes de copiarla.", + "kiroLogin.duplicate": "Este perfil Kiro ya está en la lista de cuentas.", + "kiroLogin.manualReview": "Puede ser necesaria una revisión manual de esta cuenta.", + "kiroSelection.suspended": "Sin selección automática: cuenta suspendida", + "kiroSelection.quotaExhausted": "Sin selección automática: cuota agotada", + "kiroSelection.cooldown": "Sin selección automática: en espera de recuperación", + "kiroSelection.generic": "Sin selección automática", + "tray.updated": "Actualizado {time} · cada 60s", + "tray.today": "Hoy", + "tray.input": "Entrada", + "tray.output": "Salida", + "tray.cost": "Costo · est.", + "tray.cached": "{percent} en caché", + + "usage.incomplete": "Algunos registros de uso no se pueden incluir. Los recuentos, las fechas y los rankings solo reflejan registros legibles.", + "models.pickerOrder.usageIncomplete": "No se puede guardar el orden más utilizado porque el historial de uso está incompleto. Elige otro orden o repara el historial primero.", + "api.attribution.noRecordedUse": "Ningún uso en registros legibles", + "audio.dictation": "Dictado", + "audio.liveVoice": "Voz en vivo", + "audio.configured": "Configurado, no verificado", + "audio.notConfigured": "No configurado", + "audio.unknown": "Metadatos de audio no disponibles", + "audio.key": "Clave de datos OpenCodex", + "audio.file": "Archivo de audio (25 MB máximo)", + "audio.transcribe": "Transcribir", + "audio.transcribing": "Transcripción...", + "audio.transcript": "Transcripción", + "audio.emptyTranscript": "No se detectó habla", + "audio.examples": "Ejemplos de API", + "audio.streaming": "Dictado de streaming", + "audio.connect": "Comprobar la conexión", + "audio.disconnect": "Desconectar", + "audio.events": "Eventos de sesión", + "audio.state.idle": "No comprobado", + "audio.state.connecting": "Conectando...", + "audio.state.connected": "Sesión lista", + "audio.state.disconnected": "Desconectado", + "audio.state.failed": "Conexión fallida", + "audio.error.auth": "Llave rechazada. Comprueba su clave de datos OpenCodex.", + "audio.error.unavailable": "Proveedor de origen no disponible. Comprueba la cuenta del proveedor.", + "audio.error.rateLimit": "Límite de velocidad alcanzado. Inténtalo de nuevo más tarde.", + "audio.error.invalid": "Solicitud rechazada. Comprueba el archivo y el proveedor.", + "audio.error.size": "Elige un archivo de audio no vacío de hasta 25 MB.", + "audio.error.network": "Falló la conexión. Comprueba la dirección proxy.", + "audio.error.timeout": "La petición se agotó. Vuelve a intentarlo.", + "audio.error.protocol": "Respuesta de audio inesperada. Comprobar la compatibilidad del proveedor.", + "models.pickerOrder.label": "Orden del selector", + "models.pickerOrder.default": "Predeterminado", + "models.pickerOrder.alphabetical": "A–Z por modelo", + "models.pickerOrder.provider": "Grupo por proveedor", + "models.pickerOrder.mostUsed": "Más usados (instantánea)", + "models.pickerOrder.custom": "Orden personalizado", + "models.pickerOrder.apply": "Aplicar orden", + "models.pickerOrder.applying": "Aplicación…", + "models.pickerOrder.saved": "Se guardó el orden del selector. Vuelve a abrir los clientes que todavía muestran el catálogo anterior.", + "models.pickerOrder.pending": "Se guardó el orden; la actualización del catálogo está pendiente.", + "models.pickerOrder.usageFailed": "No se pudo cargar el uso del modelo.", + "models.pickerOrder.loadFailed": "No se pudo cargar la configuración del selector.", + "models.pickerOrder.retry": "Reintentar", + "models.pickerOrder.hint": "Guarda el orden de los modelos enrutados para el descubrimiento de Codex y Claude. Las secciones de destacados y nativos mantienen su posición; Más usados refleja una instantánea. Las opciones nativas anunciadas pueden cambiar.", + "models.fastRows.title": "Mostrar filas de modelo rápido", + "models.fastRows.desc": "Añade selectores «Modelo rápido» compatibles a los selectores de modelos de clientes externos. No cambia las opciones de esfuerzo de razonamiento del modelo base. Al guardar se actualizan las integraciones conectadas cuando es posible; de lo contrario, actualiza la integración o el catálogo del cliente.", + "models.fastRows.refreshHint": "Guardado. La actualización del catálogo está pendiente.", + "models.fastRows.enabled": "Filas de modelo rápidas habilitadas.", + "models.fastRows.disabled": "Filas de modelo rápido deshabilitadas.", + "models.fastRows.loadFailed": "No se pudo cargar la configuración de filas rápidas.", + "models.fastRows.updateFailed": "No se pudo actualizar la configuración de filas rápidas.", + "codexAuth.quotaAutoRefreshAllHint": "Controla las ventanas semanales y de 5 horas compatibles para todas las cuentas actuales juntas. En el modo Pool, se envía una pequeña solicitud después de cada restablecimiento y utiliza la cuota.", + "codexAuth.quotaAutoRefreshMixed": "Algunas ventanas están habilitadas.", + "codexAuth.quotaAutoRefreshEmpty": "No se admiten ventanas de cuota. Actualizar las cuotas de la cuenta para comprobar de nuevo.", + "codexAuth.quotaAutoRefreshLoadFailed": "No se pudo cargar la configuración de activación. Reintentar comprobar su estado.", + "codexAuth.quotaAutoRefreshPartial": "Algunos configuración no se pueden guardar. Intenta terminar el mismo cambio.", + "nav.dashboard": "Panel", + "uptime.day": "d", + "uptime.hour": "h", + "uptime.minute": "m", + "uptime.second": "s", + "nav.startup": "Arranque", + "nav.providers": "Proveedores", + "nav.models": "Modelos", + "nav.combos": "Combos", + "nav.subagents": "Subagentes", + "nav.advisor": "Asesor", + "advisor.description": "Un modelo experto independiente que revisa la tarea del agente ejecutor y devuelve recomendaciones. OpenCodex administra la consulta: el agente puede llamar a la herramienta sintética de Advisor y la política de comprobación previa también intenta una consulta automática por tarea, sin requerir su colaboración. El intento se activa cuando hay evidencia inicial de orientación: una llamada a herramientas del asistente o un resultado de herramienta posterior al último mensaje del usuario. Se evita repetir el intento por tarea en clientes con una identidad estable de conversación. Sin esa identidad, puede repetirse en cada nueva solicitud compatible.", + "advisor.enabled": "Asesor habilitado", + "advisor.model": "Modelo experto", + "advisor.modelClear": "Quitar modelo", + "advisor.modelUnavailable": "El modelo actual no es seleccionable; se conserva su identificador guardado.", + "advisor.modelHint": "Elige un modelo que pueda devolver consejos de texto. Los identificadores de catálogo se guardan exactamente como se indica.", + "advisor.modelsLoadFailed": "No se pudo cargar modelos. Se conserva su selección actual.", + "advisor.modelsEmpty": "No hay modelos seleccionables. Habilita un proveedor y un modelo, luego vuelve a intentarlo.", + "advisor.effort": "Razonamiento", + "advisor.policy": "Política", + "advisor.questionOnly": "Enviar solo la pregunta del agente ejecutor", + "advisor.questionOnlyNote": "Solo se envía la pregunta del agente ejecutor (hasta 2000 caracteres, con un aviso si se recorta), junto con una instrucción fija para el asesor. No se adjuntan el historial, los resultados de las herramientas ni el contexto de la tarea. El agente ejecutor debe incluir la información imprescindible. Las consultas automáticas se pausan y los límites de consulta se mantienen.", + "advisor.policy.manual": "Manual — solo cuando el trabajador pregunta", + "advisor.policy.preflight": "Prevuelo — intento de consulta automática una vez que existe evidencia de orientación", + "advisor.policy.adaptive": "Orientación adaptativa — y consultas de reparación fallida", + "advisor.taskLimit": "Consultas por tarea", + "advisor.adaptiveNote": "Las consultas automáticas requieren una identidad de conversación estable. El asesoramiento inicial sigue a la evidencia de orientación (una llamada a herramientas o resultado). El asesoramiento de reparación fallida requiere una validación fallida, una edición completa del archivo y luego un nuevo fallo del mismo comando en el mismo directorio; los fallos repetidos por sí solos no califican. Las llamadas manuales también consumen el presupuesto de la tarea; las reservas caducan después de 24 horas y sobreviven a los reinicios del proxy.", + "advisor.activity.title": "Actividad reciente del asesor", + "advisor.activity.note": "Hasta 100 registros de este proceso, retenidos durante 24 horas. No se almacena ningún texto de tarea o consejo. Razonamiento muestra el esfuerzo asignado por el adaptador → solicitado; no reportado no confirma soporte. Los tokens muestran la entrada / salida reportada. La adopción de consejos y el costo exacto no se infieren.", + "advisor.activity.empty": "Aún no se han registrado consultas.", + "advisor.activity.failed": "No se pudo cargar la actividad del asesor.", + "advisor.activity.started": "Inicio", + "advisor.activity.trigger": "Razón / estado", + "advisor.activity.tokens": "Entrada / salida tokens", + "advisor.activity.duration": "Duración", + "advisor.activity.trigger.manual": "Solicitud de trabajador", + "advisor.activity.trigger.preflight": "Consulta inicial", + "advisor.activity.trigger.repair_failure": "La reparación falló de nuevo", + "advisor.activity.status.running": "Correr", + "advisor.activity.status.ok": "Consejos devueltos", + "advisor.activity.status.failed": "Falló", + "advisor.activity.status.cancelled": "Cancelado", + "advisor.activity.status.blocked": "Bloqueado", + "advisor.timeout": "Tiempo de espera (ms)", + "advisor.save": "Guardar la configuración del asesor", + "advisor.saved": "Configuración del asesor guardada.", + "advisor.loadFailed": "No se pudo cargar la configuración del asesor. ¿Está funcionando el proxy?", + "advisor.warning.noModel": "Habilitado, pero ningún modelo experto está configurado aún — el Asesor no puede ejecutarse hasta que se configura un modelo.", + "advisor.notices": "Notificaciones de costos y de intercambio de datos", + "advisor.costNote": "Las consultas son llamadas modelo adicionales reales. Cada uno aparece en uso bajo el modelo de asesor, no el modelo de trabajador.", + "advisor.privacyNote": "Aviso sobre el envío a otro proveedor: las consultas envían la conversación de la tarea y los resultados de herramientas al proveedor configurado de Advisor, que puede ser distinto del proveedor del agente ejecutor. No se eliminan los secretos que ya estén en el contenido. No habilites Advisor para tareas cuyo contenido no compartirías con ese proveedor. Activarlo no registra por sí solo este consentimiento.", + "advisor.disclosure": "Una consulta puede enviar la tarea más reciente del usuario; el texto analizado de mensajes de usuario, asistente y desarrollador; las llamadas a herramientas con sus argumentos y resultados; el catálogo de herramientas y la identidad del agente ejecutor; el modelo de Advisor configurado y una pregunta opcional de enfoque. OpenCodex no añade claves API de proveedores, encabezados de autorización, tokens OAuth, secretos del backend, variables del entorno del proceso ni cadenas de pensamiento ocultas. No se eliminan los secretos que ya estén en el contenido de la tarea: una clave pegada, un secreto en un archivo o un token mostrado por una herramienta pueden enviarse. El proveedor de Advisor puede ser distinto del proveedor del agente ejecutor.", + "advisor.consent.label": "Entiendo que las consultas de Advisor pueden enviar la conversación, las llamadas a herramientas y sus resultados al proveedor configurado de Advisor, que puede ser distinto del proveedor del agente ejecutor. No se eliminan los secretos que ya estén en el contenido.", + "advisor.consent.required": "El asesor no se puede ejecutar hasta que se registre el consentimiento de intercambio de contexto. Ningún contenido de tarea se envía sin él.", + "nav.logs": "Registros y depuración", + "nav.usage": "Uso", + "common.github": "GitHub", + "sidebar.star": "Dar una estrella en GitHub", + "sidebar.starred": "Repositorio con estrella en GitHub", + "sidebar.starUnauthenticated": "Abrir GitHub para dar una estrella (sin sesión en gh CLI)", + "sidebar.starFailed": "No se pudo estrellar a través de gh. Abrir GitHub.", + "onboarding.star.title": "¿Te gusta OpenCodex?", + "onboarding.star.body": "OpenCodex es libre y de código abierto. Una estrella en GitHub ayuda a otros desarrolladores a encontrarlo y mantiene el proyecto en marcha.", + "onboarding.star.cta": "Dar una estrella en GitHub", + "onboarding.star.ghHint": "Añade una estrella al repositorio con tu sesión de GitHub CLI (gh). No se añade ninguna hasta que hagas clic.", + "onboarding.star.browserHint": "Abre el repositorio en github.com desde tu navegador.", + "onboarding.star.openPage": "Abrir la página GitHub en su lugar", + "onboarding.star.later": "Tal vez más tarde", + "onboarding.star.failed": "No se pudo añadir la estrella con GitHub CLI (gh). Puedes hacerlo desde la página de GitHub.", + "onboarding.star.starring": "Enviando estrella…", + "onboarding.star.thanks": "¡Gracias por la estrella!", + "onboarding.star.thanksBody": "Tu apoyo ayuda al proyecto. El enlace de GitHub en la barra lateral te permite volver al repositorio cuando quieras.", + "onboarding.star.done": "Hecho", + "sidebar.updateAvailable": "Actualización disponible: {version}", + "sidebar.checkUpdate": "Buscar actualizaciones", + "sidebar.desktopUpdate": "Abrir actualizaciones de escritorio", + "sidebar.terminalCommand": "Comando de terminal", + "common.save": "Guardar", + "common.saving": "Guardando…", + "common.cancel": "Cancelar", + "common.discard": "Descartar cambios", + "common.delete": "Eliminar", + "common.close": "Cerrar", + "common.ok": "OK", + "common.remove": "Quitar", + "common.loading": "Cargando…", + "common.retry": "Reintentar", + "prov.affinityResetPending": "Se guardó el cambio de cuenta, pero no terminó la actualización del routing de conversaciones. Vuelve a intentarlo para completar el cambio.", + "prov.affinityResetComplete": "Se actualizó el routing de conversaciones.", + "prov.affinityResetRetryUnavailable": "No se puede reintentar con esta cuenta. Actualiza la lista y, si hace falta, reactiva la cuenta o vuelve a iniciar sesión.", + "common.undo": "Deshacer", + "auth.adminTokenTitle": "Token de administración de OpenCodex (OPENCODEX_ADMIN_AUTH_TOKEN)", + "auth.adminAccountLabel": "Cuenta", + "auth.adminTokenFieldLabel": "Token de administración", + "auth.adminTokenRejected": "Ese administrador token fue rechazado. Revísalo y vuelve a intentarlo.", + "auth.adminTokenUnavailable": "El administrador token no pudo ser verificado. Vuelve a intentarlo.", + "auth.adminTokenHelp": "Este es el token de administración de OpenCodex, no una clave API de un proveedor. El proxy lo escribe en ~/.opencodex/admin-api-token (o $OPENCODEX_HOME/admin-api-token) al iniciarse por primera vez. OPENCODEX_ADMIN_AUTH_TOKEN tiene prioridad sobre ese archivo.", + "auth.rememberDevice": "Recordar este dispositivo", + "auth.rememberDeviceHint": "Conserva una sesión revocable del panel mediante una cookie HttpOnly durante 30 días. No almacena el token de administrador. Requiere acceso directo al panel por HTTPS con el mismo origen que la API, o acceso local por loopback.", + "auth.rememberUnsupported": "OpenCodex no puede recordar este dispositivo en esta dirección. Se necesita acceso directo al panel por HTTPS o acceso local por loopback. Si usas un proxy inverso, inicia sesión sin activar esta opción.", + "connection.forgetDevice": "Olvidar este dispositivo", + "connection.forgetDeviceFailed": "No se pudo olvidar este dispositivo. Se conservó la sesión.", + "auth.adminTokenDocsLink": "Cómo encontrarlo", + "app.logoAria": "Logo opencodex", + "app.claudeOn": "Claude activado", + "app.claudeOff": "Claude desactivado", + "theme.label": "Tema", + "theme.light": "Claro", + "theme.dark": "Oscuro", + "theme.system": "Sistema", + "zoom.label": "Zoom", + "zoom.out": "Ampliar", + "zoom.in": "Ampliar", + "zoom.reset": "Reiniciar el zoom al 100%", + "lang.label": "Idioma", + "lang.nativeName": "Español", + "provider.name.commandCodeAuth": "Command Code - Auth", + "provider.name.commandCodeApi": "Command Code - API", + "provider.name.orcaRouterApi": "OrcaRouter - API", + "provider.name.orcaRouterAuth": "OrcaRouter - Auth", + "provider.name.volcengine": "Volcengine Ark", + "provider.name.volcengineCodingPlan": "Volcengine Ark Coding Plan", + "provider.name.volcengineAgentPlan": "Volcengine Ark Agent Plan", + "errorBoundary.title": "No se pudo cargar la página", + "errorBoundary.message": "Se produjo un error al mostrar esta sección. Recárgala para volver a intentarlo.", + "errorBoundary.details": "Error", + "errorBoundary.reload": "Recargar", + + "routing.title": "Inteligencia de enrutamiento (beta)", + "routing.subtitle": "Perfiles de políticas, evaluación de ejecución en seco y análisis de enrutamiento respaldado por fuentes.", + "routing.loadFailed": "No se pudo cargar los datos de enrutamiento", + "routing.empty": "No hay perfiles de enrutamiento configurados. Añadir `routingProfiles` a config.json.", + "routing.revision": "rev", + "routing.detail": "Perfil", + "routing.createProfile": "Crear perfil", + "routing.dryRunError": "Error de ejecución en seco (HTTP {status})", + "routing.removeConfirm": "Eliminar perfil {id}?", + "routing.unknownEvidence.allow": "permitir", + "routing.unknownEvidence.penalize": "penalizar", + "routing.unknownEvidence.exclude": "excluir", + "routing.removeCandidate": "Eliminar candidato {provider}/{model}", + "routing.candidates": "Candidatos", + "routing.require": "Requerimientos difíciles", + "routing.optimize": "Pesos de optimización", + "routing.limits": "Límites", + "routing.unknownEvidence": "Política de evidencia desconocida", + "routing.compatibility.title": "Política de compatibilidad", + "routing.compatibility.enabled": "Requiere evidencia Compatibility Lab", + "routing.compatibility.requiredSuites": "Suites requeridas", + "routing.compatibility.loadingCatalog": "Cargando catálogo de laboratorio…", + "routing.compatibility.catalogUnavailable": "— ingrese los identificadores de la suite manualmente en config.json.", + "routing.compatibility.layer.protocol_conformance": "Conformidad del protocolo", + "routing.compatibility.layer.live_route_compatibility": "Compatibilidad de ruta en vivo", + "routing.compatibility.minStatus": "Estado de compatibilidad mínimo", + "routing.none": "ninguno", + "routing.unavailable": "–", + "routing.dryRun": "Evaluación en seco", + "routing.dryRunContext": "Ventana de contexto de solicitud (tokens)", + "routing.dryRunTools": "La solicitud requiere herramientas", + "routing.dryRunImage": "Solicitud requiere entrada de imagen", + "routing.dryRunStructured": "La solicitud requiere un resultado estructurado", + "routing.dryRunRun": "Evaluar candidatos", + "routing.candidate": "Candidato", + "routing.eligible": "Elegible", + "routing.exclusions": "Exclusiones", + "routing.costCap": "Límite de coste", + "routing.capOutcome.satisfied": "dentro de los límites", + "routing.capOutcome.exceeded": "Sobre el límite", + "routing.capOutcome.unknown-allowed": "desconocido (permitido)", + "routing.capOutcome.unknown-excluded": "desconocido (excluido)", + "routing.exclusion.capability-unsatisfied": "Capacidad no cumplida", + "routing.exclusion.unknown-capability": "Capacidad desconocida", + "routing.exclusion.cost-limit": "sobre el límite de costo", + "routing.exclusion.cost-limit-unknown": "costo desconocido bajo la límite", + "routing.exclusion.cooldown": "Tiempo de reutilización", + "routing.exclusion.unknown-health": "Salud Desconocida", + "routing.exclusion.unknown-quota": "Cuota desconocida", + "routing.exclusion.unknown-price": "precio desconocido", + "routing.exclusion.other": "exclusión: {code}", + "routing.score": "Puntuación", + "routing.selected": "seleccionado", + "routing.yes": "sí", + "routing.no": "no", + "routing.analytics": "Análisis de enrutamiento", + "routing.analyticsTotal": "Solicitudes", + "routing.analyticsSuccessRate": "Correcto", + "routing.analyticsFallbackRate": "Alternativa", + "routing.analyticsP50": "p50", + "routing.analyticsP95": "p95", + "routing.analyticsP99": "p99", + "routing.analyticsCooldown": "Fallos durante la espera de recuperación", + "routing.analyticsConfidence": "Confianza", + "routing.analyticsTruncated": "historial truncado", + "routing.analyticsRequests": "Solicitudes", + "routing.analyticsEmpty": "Sin análisis aún — enviar algunas solicitudes primero.", + + "startup.title": "Seguridad de inicio", + "startup.subtitle": "Comprueba que Codex pueda llegar a opencodex después de un reinicio, antes de que el enrutamiento proxy local se convierta en un bucle de reconexión.", + "startup.refresh": "Actualizar", + "startup.backToDashboard": "Volver a la página principal", + "startup.loading": "Comprobación de la protección de inicio…", + "startup.error": "No se puede leer la protección de inicio.", + "startup.staleData": "La última comprobación de inicio falló. Los siguientes valores son obsoletos y no deben ser tratados como prueba de protección.", + "startup.status.native": "Enrutamiento nativo", + "startup.status.protected": "Reiniciar protegido", + "startup.status.atRisk": "Medidas necesarias", + "startup.summary.native": "Codex no depende del proxy local", + "startup.summary.protected": "opencodex estará disponible después de reiniciar", + "startup.summary.atRisk": "Codex puede perder el acceso al modelo después de reiniciar", + "startup.riskDetail": "Codex está anclado al proxy local, pero ningún servicio persistente o elemento de arranque saludable lo iniciará de nuevo.", + "startup.riskDetailCustomLocal": "Codex apunta a una puerta de enlace local personalizada. opencodex no puede administrar o verificar el ciclo de vida de reinicio de esa puerta de enlace.", + "startup.riskDetailWindowsShim": "El shim de inicio protege los scripts de CLI compatibles, pero Codex Desktop y los inicios directos de codex.exe pueden omitirlo en Windows.", + "startup.safeDetail": "El enrutamiento actual y el mecanismo de inicio son coherentes. No debería ser necesario ejecutar ocx start manualmente después de reiniciar.", + "startup.routing": "Codex enrutamiento", + "startup.routing.proxy": "Proxy local", + "startup.routing.native": "Nativo OpenAI", + "startup.routing.customLocal": "Puerta de enlace local personalizada", + "startup.routing.customRemote": "Puerta de enlace remota personalizada", + "startup.routing.unknown": "Enrutamiento desconocido o no válido", + "startup.restartProtection": "Reiniciar la protección", + "startup.preference": "Inicio bajo demanda", + "startup.enabled": "Activado", + "startup.disabled": "Desactivado", + "startup.protection.desktop": "Aplicación de escritorio", + "startup.desktopHint": "Comienza en el inicio de sesión; la aplicación de escritorio supervisa su proxy incluido. La propiedad y los procesos en vivo se verifican.", + "startup.desktopRecovery": "OpenCodex administra este proxy. Vuelve a abrir la aplicación de escritorio y comprueba Iniciar al iniciar sesión (Start at Login). Si ya está activado, verifica que el sistema permita abrir OpenCodex al iniciar sesión (macOS: Configuración del Sistema → General → Ítems de inicio y extensiones). El servicio en segundo plano permanece desactivado mientras la aplicación administra el proxy; el shim de inicio todavía puede instalarse.", + "startup.desktopSupervisedRecovery": "OpenCodex Desktop ejecuta este proxy, pero no se pudo verificar Iniciar al iniciar sesión (Start at Login). Actívalo en el menú de OpenCodex. Si ya está activado, verifica que el sistema permita abrir OpenCodex al iniciar sesión (macOS: Configuración del Sistema → General → Ítems de inicio y extensiones). El servicio en segundo plano permanece desactivado mientras la aplicación ejecuta el proxy; para usarlo, cierra OpenCodex y ejecuta el comando en una terminal. El shim de inicio todavía puede instalarse.", + "startup.desktopReopenRecovery": "Reabrir OpenCodex y comprobar Inicio de sesión.", + "startup.protection.service": "Servicio en segundo plano", + "startup.protection.shim": "Cojín de lanzamiento", + "startup.protection.none": "No instalado", + "startup.details": "Detalles de protección", + "startup.service": "Servicio en segundo plano", + "startup.serviceHint": "Comienza en el inicio de sesión y reinicia el proxy después de un bloqueo.", + "startup.installed": "Instalado", + "startup.notInstalled": "No instalado", + "startup.unsupported": "No compatible", + "startup.shim": "Shim de inicio de Codex", + "startup.shimHint": "Ejecuta ocx ensure cuando se inicia un script de lanzamiento de Codex compatible.", + "startup.healthy": "Saludable", + "startup.cliOnly": "Solo CLI", + "startup.stale": "Desactualizado", + "startup.viable": "Listo", + "startup.unhealthy": "Instalado pero poco saludable", + "startup.desktopLoginUnverified": "Ejecución de · Iniciar sesión no verificado", + "startup.loginUnverifiedTitle": "Inicio al iniciar sesión sin verificar", + "startup.unverified": "Sin verificar", + "startup.loginUnverifiedAction": "Comprueba la opción de inicio al iniciar sesión en el menú de OpenCodex. En Linux sin bandeja, revisa ~/.config/autostart/OpenCodex.desktop.", + "startup.loginDisabled": "En ejecución · Inicio al iniciar sesión desactivado", + "startup.desktopRunning": "OpenCodex Desktop ejecuta este proxy.", + "startup.conflict": "Conflicto de servicio", + "startup.installedDisabled": "Instalado pero desactivado", + "startup.shimActivationPending": "Activación · instalada no confirmada", + "startup.shimActivationHint": "Añadir . ~/.opencodex/codex-shell-env.sh después de otra configuración PATH en su archivo de inicio de shell, luego abra un nuevo terminal. El panel de control no siempre puede ver la PATH de su shell.", + "startup.install": "Instalar", + "startup.installing": "Instalando…", + "startup.repair": "Reparar", + "startup.repairing": "Reparando…", + "startup.serviceInstalled": "Servicio en segundo plano instalado correctamente.", + "startup.serviceRepaired": "El servicio en segundo plano se reparó con éxito.", + "startup.shimInstalled": "El shim de inicio de Codex se instaló correctamente.", + "startup.shimRepaired": "El shim de inicio de Codex se reparó correctamente.", + "startup.installFailed": "Fallo de instalación:", + "startup.tray.title": "Bandeja del sistema Windows", + "startup.tray.hint": "Instale un icono de bandeja de inicio de sesión para los controles de inicio, parada, reinicio, panel y estado del proxy con un solo clic.", + "startup.tray.login": "Inicio de sesión en Windows", + "startup.tray.notProtection": "La bandeja es un controlador, no una protección de reinicio. Todavía se requiere un servicio de fondo viable para la recuperación de proxy desatendida.", + "startup.tray.running": "Correr", + "startup.tray.stopped": "Instalado, oculto", + "startup.tray.stale": "Reparaciones requeridas", + "startup.tray.notInstalled": "No instalado", + "startup.tray.loading": "Comprobación…", + "startup.tray.unavailable": "Estado no disponible", + "startup.tray.install": "Instalar y mostrar la bandeja", + "startup.tray.start": "Mostrar icono de bandeja", + "startup.tray.stop": "Icono de bandeja de salida", + "startup.tray.uninstall": "Eliminar bandeja de inicio de sesión", + "startup.tray.error": "Falló la acción de la bandeja de Windows. Consulta ocx tray status para ver los detalles.", + "startup.recovery": "Opciones de reparación", + "startup.recoveryHint": "Usa los instaladores de un solo clic anteriores o copie un comando para la reparación manual. El servicio en segundo plano se recomienda para los ejecutables Codex Desktop y Windows.", + "startup.command.service": "Recomendado: servicio de fondo persistente", + "startup.command.shim": "Alternativa: shim de inicio de la CLI", + "startup.command.native": "Fail-safe: restaurar el enrutamiento nativo Codex", + "startup.copy": "Copiar", + "startup.copied": "Copiado", + "startup.recommended": "Reparación recomendada: {cmd}", + "startup.navRisk": "La protección de inicio requiere atención", + "startup.codexRuntime.clampHidden": "Algunas opciones de esfuerzo de razonamiento estaban ocultas porque OpenCodex usaba Codex {version}.", + "startup.codexRuntime.clampHiddenWithEfforts": "Algunas opciones de esfuerzo de razonamiento estaban ocultas porque OpenCodex usaba Codex {version} (eliminado: {efforts}).", + "startup.codexRuntime.olderBinary": "OpenCodex está utilizando un binario Codex más antiguo ({version}). Una instalación más nueva está disponible.", + + "dash.subtitle": "Estado en tiempo real del proxy local opencodex, sus proveedores y los modelos enrutados a Codex.", + "dash.workspace.overview": "Descripción general", + "dash.workspace.sections": "Secciones", + "dash.status": "Estado", + "dash.online": "En línea", + "dash.offline": "Fuera de línea", + "dash.version": "Versión", + "dash.uptime": "Tiempo de actividad", + "dash.providers": "Proveedores", + "dash.tokens30d": "Tokens (30d)", + "dash.coverage": "Cobertura {pct}", + "dash.mem.title": "Observabilidad de la memoria", + "dash.mem.hint": "Diagnósticos de tiempo de ejecución de solo lectura. La memoria observada es max (RSS, externa, ArrayBuffers) por lo que el ajuste del conjunto de trabajo Windows no oculta la retención comprometida.", + "dash.mem.rss": "Conjunto de residentes (RSS)", + "dash.mem.jsHeap": "Heap JS en uso", + "dash.mem.jsHeapArena": "arena {total}", + "dash.mem.pressure": "Umbral de advertencia", + "dash.mem.pressureOf": "{pct}% del umbral", + "dash.mem.pressureUnknown": "No se ha notificado ningún umbral", + "dash.mem.jscHeap": "Heap JSC", + "dash.mem.external": "Externo", + "dash.mem.arrayBuffers": "ArrayBuffers", + "dash.mem.observed": "Observado", + "dash.mem.runtime": "Contadores de tiempo de ejecución", + "dash.mem.growth": "Desviación observada / hora", + "dash.mem.perHour": "/h", + "dash.mem.store": "Almacén de continuaciones", + "dash.mem.storeHint": "Caché de previous_response_id del proxy. Si los bytes totales aumentan junto con el heap, el indicio apunta a la conservación de conversaciones y no al asignador de memoria del entorno de ejecución.", + "dash.mem.storeEntries": "Entradas", + "dash.mem.storeTotal": "Total", + "dash.mem.storeLargest": "El más grande", + "dash.mem.storeOldest": "Los más antiguos", + "dash.mem.threshold": "Umbral de advertencia", + "dash.mem.lastWarn": "Ultima advertencia", + "dash.mem.never": "Nunca", + "dash.mem.details": "Detalles", + "dash.mem.unavailable": "Diagnósticos de memoria no disponibles (antiguo proxy).", + "dash.mem.inFlight": "Solicitudes en curso", + "dash.mem.restart": "Drenar y reiniciar", + "dash.mem.restartConfirm": "Espera a que terminen {count} solicitudes en curso y reinicia (hasta {seconds} s; al agotarse el tiempo se interrumpen las restantes).", + "dash.mem.draining": "Drenaje {count} solicitud(es)… reiniciarse cuando se complete", + "dash.mem.reconnecting": "Reinicio de proxy… esperando para volver a conectarse", + "dash.mem.restartFailed": "Drenar y reiniciar falló. Comprueba que el proxy se está ejecutando.", + "dash.mem.restartNoSupervisor": "No se detectó protección de reinicio. El proxy puede permanecer detenido si no vuelves a iniciarlo.", + "dash.activeProviders": "Proveedores activos", + "dash.noProviders": "No hay proveedores configurados. Ejecuta {cmd}.", + "dash.col.name": "Nombre", + "dash.col.adapter": "Adaptador", + "dash.col.baseUrl": "URL base", + "dash.col.model": "Modelo", + "dash.modelsNoResults": "Ningún modelo coincide con tu búsqueda.", + "dash.availableModels": "Modelos disponibles", + "dash.noModels": "No se encontraron modelos. Compruebe las claves API del proveedor.", + "dash.cannotConnect": "No se puede conectar a proxy. ¿Está funcionando?", + "dash.runStart": "Ejecuta {cmd} para iniciar el proxy.", + "dash.stop": "Detener el proxy", + "dash.stopConfirm": "¿Detener el proxy y restaurar Codex nativo?", + "dash.stopFailed": "No se pudo detener el proxy (HTTP {status}).", + "dash.stopStillRunning": "El proxy sigue respondiendo, por lo que no se detuvo.", + "dash.stopUnknown": "El proxy no confirmó la parada. Comprueba si sigue funcionando antes de volver a intentarlo.", + "dash.maSwitchFailed": "No se pudo cambiar de modo (HTTP {status}).", + "dash.maNetworkError": "Error de red — ¿Está funcionando el proxy?", + "dash.stopping": "Parada…", + "dash.actions": "Proxy", + "dash.codexRestart": "Recargar modelos Codex", + "dash.codexRestarting": "Parada…", + "dash.codexRestartConfirm": "¿Detener los servidores de aplicaciones Codex para que vuelvan a cargar la lista de modelos? Cualquier giro Codex en progreso se interrumpe, y Codex no se reinicia en su propio — reabrirlo después.", + "dash.codexRestartDone": "Se detuvieron {count} servidores app-server de Codex. Vuelve a abrir Codex para cargar la lista actual de modelos.", + "dash.codexRestartNothing": "No se está ejecutando ningún servidor de aplicaciones Codex. El siguiente lanzamiento lee la lista de modelos actual.", + "dash.codexRestartUnknown": "No se pudo enumerar los procesos, por lo que no se detuvo nada.", + "dash.codexRestartPartial": "La(s) aplicación/servidor(es) {count} no salió(n). Deténgalos manualmente si la lista de modelos permanece obsoleta.", + "dash.codexRestartFailed": "No se pudo recargar los modelos Codex (HTTP {status}).", + "dash.codexRestartUnreachable": "No se pudo llegar al proxy.", + "dash.codexRestartMalformed": "El proxy devolvió una respuesta inesperada.", + "dash.codexRestartTimeout": "El proxy no respondió a tiempo. Es posible que todavía esté deteniendo los servidores de aplicaciones.", + "models.staleBanner": "Codex muestra una lista de modelos más antigua que este catálogo. Reinicia Codex para volver a cargarlo.", + "dash.codexAutoStart": "Iniciar opencodex con Codex", + "dash.codexAutoStartHint": "Permite que un shim de inicio instalado ejecute ocx ensure. Esta opción no instala protección de reinicio; consulta Seguridad de inicio para ver el estado efectivo.", + "dash.searchModel": "Buscar modelo de sidecar", + "dash.searchModelHint": "Modelo utilizado para web_search en modelos no enrutados OpenAI. Requiere inicio de sesión ChatGPT.", + "dash.searchReasoning": "Esfuerzo de razonamiento", + "dash.visionModel": "Modelo de sidecar de visión", + "dash.visionModelHint": "Modelo utilizado para describir imágenes para modelos enrutados solo de texto. Requiere iniciar sesión en ChatGPT.", + "dash.webSearchSidecar": "Búsqueda en la web", + "dash.webSearchSidecarHint": "Elige el backend y el modelo utilizado para la búsqueda web en los modelos enrutados.", + "dash.webSearchOff": "Desactivado", + "dash.webSearchCodexSync": "Guardado. La configuración de Codex no se reescribió; pulsa Sincronizar modelos para aplicar el cambio.", + "dash.webSearchStream": "Transmitir respuestas en vivo", + "dash.webSearchStreamHint": "Muestra en vivo el texto y el razonamiento del modelo principal hasta que decide llamar una herramienta. El resto del turno se almacena para interceptar la búsqueda. Parte del texto anterior a una búsqueda puede repetirse.", + "dash.visionSidecar": "Sidecar de visión", + "dash.visionSidecarHint": "Elige el backend y el modelo utilizados para describir las imágenes de los modelos enrutados solo de texto.", + "dash.visionOff": "Desactivado", + "dash.visionAdvanced": "Configuración avanzada", + "dash.visionMaxDescriptions": "Descripciones máximas por turno", + "dash.visionMaxDescriptionsInvalid": "Introduce un número entero positivo.", + "dash.visionTimeout": "Tiempo de espera", + "dash.visionTimeoutInvalid": "Introduce un número entero entre {min} y {max} milisegundos.", + "dash.visionAdvancedPopover": "Configuración de visión avanzada", + "compactionRouting.title": "Enrutamiento de compactación", + "compactionRouting.description": "Elige un modelo para las solicitudes de compactación de Codex y qué eventos activan esta ruta. Los mensajes posteriores conservan la configuración de la conversación.", + "compactionRouting.model": "Modelo de compactación", + "compactionRouting.effort": "Esfuerzo de razonamiento", + "compactionRouting.triggers": "Se aplica a", + "compactionRouting.triggersManual": "Solo /compact manual", + "compactionRouting.triggersBoth": "Manual y automático", + "compactionRouting.triggersAuto": "Solo automático", + "compactionRouting.sources": "Fuentes", + "compactionRouting.sourcesAll": "Todos los modelos de conversación", + "compactionRouting.sourcesSelected": "Solo fuentes seleccionadas", + "compactionRouting.sourcesProviders": "Proveedores enteros", + "compactionRouting.sourcesModels": "Modelos individuales", + "compactionRouting.sourcesSaved": "Selectores guardados no en el catálogo actual", + "compactionRouting.sourcesNone": "Selecciona al menos una fuente, o cambie de nuevo a todos los modelos de conversación.", + "compactionRouting.sourcesHint": "Aplica esta ruta solo si el modelo de origen coincide con un modelo seleccionado o con el patrón proveedor/*. Las demás solicitudes conservan su propio modelo.", + "compactionRouting.sourcesGridTitle": "Reenrutar las solicitudes de compactación cuyo modelo de origen coincida con:", + "compactionRouting.currentModel": "Usar el modelo de conversación", + "compactionRouting.currentEffort": "Mantener el esfuerzo de solicitud", + "compactionRouting.effortHint": "El esfuerzo se aplica si el destino de compactación lo admite. El modelo debe aceptar la conversación completa.", + "compactionRouting.dataNotice": "Una solicitud de compactación cubierta envía toda la conversación al proveedor del modelo seleccionado para su resumen, incluso cuando la conversación se ejecuta en otro proveedor.", + "compactionRouting.autoNotice": "La compactación automática se ejecuta por sí sola, por lo que se puede enviar una larga conversación a ese proveedor sin que usted lo solicite.", + "compactionRouting.providerWarning": "Con esta configuración, cada solicitud de compactación cubierta envía el contenido completo de la conversación a {provider} para su resumen.", + "compactionRouting.comboWarning": "Con esta configuración, cada solicitud de compactación cubierta envía el contenido completo de la conversación al combo {combo} para su resumen. El combo selecciona uno de sus objetivos ({providers}) por su estrategia de enrutamiento, pero después de un fallo reintentable puede volver a intentar la misma solicitud de conversación completa en otro objetivo, para que uno o más proveedores de destino puedan recibir la conversación.", + "compactionRouting.comboProvidersUnknown": "sus proveedores de destino configurados", + "compactionRouting.providerWarningScoped": "Con esta configuración, solo las solicitudes de compactación cuyo modelo de origen coincida con {sources} envían el contenido completo de la conversación a {provider} para su resumen; otras solicitudes siguen utilizando su propio modelo.", + "compactionRouting.comboWarningScoped": "Con esta configuración, solo las solicitudes de compactación cuyo modelo de origen coincida con {sources} envían el contenido completo de la conversación a combo {combo} para su resumen; otras solicitudes siguen usando su propio modelo. El combo elige uno de sus objetivos ({providers}) por su estrategia de enrutamiento, pero después de un fallo reintentable puede volver a intentar la misma solicitud de conversación completa en otro objetivo, para que uno o más proveedores de destino puedan recibir la conversación.", + "compactionRouting.loadFailed": "No se pudo cargar la configuración de compactación.", + "compactionRouting.saved": "Se guardó la configuración de compactación.", + "compactionRouting.saveFailed": "No se pudo guardar. Tus cambios se conservan; vuelve a intentarlo.", + "memoryModels.title": "Enrutamiento de memoria", + "memoryModels.description": "Codex crea memorias después de cada sesión terminada. Elige un modelo para cada fase o conserva su ruta existente.", + "memoryModels.infoLabel": "¿Qué son el extracto y la consolidación?", + "memoryModels.info": "Codex convierte las sesiones terminadas en memoria en dos pasos. Extract lee una sesión terminada y anota lo que sucedió: una nota por sesión, por lo que hace muchas llamadas pequeñas. La consolidación toma esas notas y las escribe en los archivos de memoria que Codex lee al comienzo de sus próximas sesiones. Se ejecuta raramente, pero edita archivos. Cada paso pide su propio modelo, por lo que se enumeran por separado aquí.", + "memoryModels.extract": "Extracción", + "memoryModels.extractHint": "Resume cada sesión terminada en una nota de memoria. Se ejecuta una vez por sesión.", + "memoryModels.consolidation": "Consolidación", + "memoryModels.consolidationHint": "Combina las notas de memoria en los archivos que Codex lee después. Se ejecuta con poca frecuencia y edita archivos.", + "memoryModels.model": "Modelo", + "memoryModels.effort": "Esfuerzo de razonamiento", + "memoryModels.off": "Desactivado", + "memoryModels.defaultEffort": "Codex por defecto", + "memoryModels.dataNotice": "El modelo elegido recibe los datos de su fase: la sesión terminada para Extracción y las notas de memoria para Consolidación.", + "memoryModels.accountNotice": "Solo una fase se enruta aquí; la otra mantiene su ruta existente. Shadow Call Intercept también puede enviar las llamadas de memoria de esa fase a su modelo configurado.", + "memoryModels.loadFailed": "No se pudo cargar la configuración de la memoria.", + "memoryModels.saved": "Se guardó la configuración de memoria.", + "memoryModels.saveFailed": "No se pudo guardar. Tus cambios se conservan; vuelve a intentarlo.", + "dash.shadowCallIntercept": "Interceptación de llamadas auxiliares", + "shadowCall.memoryLabel": "Memoria: Terra", + "shadowCall.sourceCoveredShort": "Cubierto por {prefix}", + "shadowCall.sourceRequired": "Debe permanecer activado", + "dash.shadowCallInterceptHint": "Intercepta las llamadas auxiliares de Codex App en segundo plano para títulos, mensajes de commit y coordinación de habilidades. Elige los modelos de origen a continuación. La consolidación de memoria suele ejecutarse en Terra y sigue el routing de memoria si está configurado.", + "dash.shadowCallWarning": "⚠ Al activarlo, las solicitudes de cada origen seleccionado ({models}) se redirigen al modelo elegido. Terra se activa por separado. El routing de memoria tiene prioridad para la consolidación.", + "dash.shadowCallOriginal": "Original", + "dash.shadowCallModel": "Modelo de reemplazo", + "dash.shadowCallTooltip": "Codex App realiza llamadas en segundo plano para generar títulos de conversaciones y mensajes de commit, y coordinar habilidades. El modelo auxiliar ha variado entre versiones del cliente, por lo que OpenCodex puede interceptar varios orígenes. Elige los que quieras redirigir. Terra consolida la memoria y está desactivado inicialmente porque Codex también lo usa para tareas ordinarias. Si hay un modelo de consolidación configurado en el routing de memoria, esa ruta tiene prioridad. Al menos un origen debe quedar activo. Usa el interruptor principal para dejar de interceptar llamadas en segundo plano.", + "shadowCall.sources": "Orígenes interceptados", + "shadowCall.sourceHelper": "Auxiliar", + "shadowCall.sourceMemory": "Memoria", + "shadowCall.sourceLegacy": "Anterior", + "shadowCall.sourceCustom": "Personalizado", + "shadowCall.sourceHint": "Solo se interceptan los orígenes habilitados. Al menos uno debe quedar activo. Usa el interruptor principal para dejar de interceptar llamadas en segundo plano. El routing de memoria tiene prioridad para la consolidación si está configurado.", + "shadowCall.sourceCovered": "El prefijo personalizado {prefix} cubre este origen. Elimínalo o restringe su alcance en config.json para cambiar este origen por separado.", + "shadowCall.sourceLastRequired": "Al menos un origen debe quedar activo. Usa el interruptor principal para dejar de interceptar llamadas en segundo plano.", + "models.shadowCallIntercept": "Interceptación de llamadas auxiliares", + "models.shadowCallInterceptHint": "Intercepta las llamadas auxiliares de Codex App en segundo plano para títulos, mensajes de commit y coordinación de habilidades. Elige los modelos de origen a continuación. La consolidación de memoria suele ejecutarse en Terra y sigue el routing de memoria si está configurado.", + "models.shadowCallSaveFailed": "No se pudo guardar la configuración de llamadas en segundo plano.", + "models.shadowCallTargetInvalid": "El destino de reemplazo coincide con un origen activo. Elige otro modelo.", + "models.shadowCallSourceInvalid": "La selección de orígenes no es válida. Elige al menos uno sin espacios ni prefijo de proveedor.", + "models.autoReviewOverride": "Anulación de revisión automática", + "models.autoReviewOverrideHint": "Elige el modelo que Codex utiliza para la revisión automática (el revisor de aprobación). Aplicado a cada fila de catálogo en sincronización; un autoReviewModel con alcance de proveedor todavía tiene prioridad en sus propias filas.", + "models.autoReviewPending": "Pendiente", + "dash.sidecarBackend": "Backend", + "dash.sidecarModel": "Modelo", + "dash.backendAuto": "Automático", + "dash.backendOpenAI": "OpenAI", + "dash.backendAnthropic": "Anthropic", + "dash.sidecarSaved": "Se guardó la configuración del sidecar. Se aplicará en la siguiente solicitud.", + "dash.sidecarSaveFailed": "No se pudo guardar la configuración del sidecar.", + "dash.injectionLabel": "Delegación de subagentes", + "dash.injectionHint": "Elige el modelo Codex debe mano sub-agente de trabajo. Los dos switches a continuación deciden dónde se usa esa selección.", + "dash.injectionManage": "Abrir configuración", + "dash.syncCodexSubagentDefaults": "También guardar como predeterminado Codex", + "dash.syncCodexSubagentDefaultsHint": "Al activarlo, la selección anterior se escribe en la configuración de Codex para que las tareas nuevas también usen ese modelo. Al desactivarlo, solo se recuerda aquí. Se aplica en la siguiente sincronización o reinicio y conserva los ajustes [agents] escritos manualmente.", + "dash.multiAgentGuidance": "Dile a Codex cómo dividir el trabajo", + "dash.multiAgentGuidanceHint": "Envía una nota corta diciéndole a Codex cómo trabajar manualmente con subagentes. En v2 nombra los modelos que puede usar y cuáles preferir; en v1 solo se aplica en el esfuerzo de razonamiento máximo o ultra. Fuera, no se agrega ninguna nota.", + "dash.injectionNone": "Ninguno", + "dash.injectionEffortLabel": "Esfuerzo de razonamiento", + "dash.injectionEffortNone": "Modelo predeterminado", + "dash.effortCapLabel": "Límite de esfuerzo ultra V2", + "dash.subagentEffortCapLabel": "Límite de esfuerzo del subagente V2", + "dash.effortCapHelp": "Limita el esfuerzo de razonamiento de los turnos V2 en modo ultra. Las solicitudes entrantes con esfuerzo máximo se reducen al nivel elegido. El límite de subagentes solo afecta a los subagentes creados. Los límites reducen el esfuerzo, nunca lo aumentan. Si un modelo no admite el nivel elegido, se usa el nivel compatible más cercano que no lo supere.", + "dash.effortCapNone": "Sin límite", + "dash.maintenance": "Mantenimiento", + "dash.maintenanceHint": "Actualizar el catálogo de modelos de Codex o instalar una versión más reciente de opencodex.", + "dash.syncModels": "Sincronizar modelos", + "dash.syncModelsHint": "Reescribe el catálogo de modelos de Codex de los proveedores que hayas conectado.", + "dash.syncRun": "Sincronizar ahora", + "dash.syncing": "Sincronización…", + "dash.syncOk": "Sincronización completa. Modelo(s) de {count} anexado.", + "dash.syncStaleHint": "Si Codex sigue mostrando una lista anterior, reinicia su servidor app-server persistente ({cmd}).", + "dash.syncFailed": "Fallo de sincronización: {error}", + "dash.projectConfigTitle": "La configuración del proyecto Codex evita OpenCodex", + "dash.projectConfigHint": "Estos configuración repo-local anulan el proxy OpenCodex (e.g. ruta a OpenCode Ir directamente). Elimínelos para que se aplique el enrutamiento ~/.codex/config.toml en ese proyecto.", + "dash.checkUpdate": "Comprobar la actualización", + "dash.updateTitle": "Actualizar opencodex", + "dash.updateDesc": "Comprueba npm para el canal seleccionado y, a continuación, elija si desea reiniciar el proxy después de la instalación.", + "dash.updateChannel": "Canal", + "dash.updateChecking": "Comprobación de actualizaciones…", + "dash.updateInstalled": "Instalado", + "dash.updateLatest": "Más reciente", + "dash.updateAvailable": "Actualización disponible", + "dash.updateCurrent": "Hasta la fecha", + "dash.updateCommand": "Comando", + "dash.updateSource": "Esta es una fuente de pago. Actualízalo desde el terminal con el comando mostrado.", + "dash.updateManaged": "Las actualizaciones son automáticas. El actualizador programado del host actualiza este directorio de versión; aquí no hace falta hacer nada.", + "dash.updateUnavailable": "No se pudo leer la última versión de npm. Inténtalo de nuevo más tarde.", + "dash.updateRetry": "Reintentar", + "dash.updateRecheck": "Volver a comprobar", + "dash.updateCannotAuto": "La actualización con un solo clic no está disponible ({reason}).", + "dash.updateReason.source_checkout": "Código fuente", + "dash.updateReason.managed_release": "directorio de versión administrado", + "dash.updateReason.latest_unavailable": "Registro npm inaccesible", + "dash.updateReason.already_latest": "Ya en el último", + "dash.updateReason.externally_managed": "administrado externamente por mise; ejecute el comando mostrado", + "dash.updateReason.external_ownership_invalid": "Los metadatos de propiedad de mise son ilegibles o inconsistentes", + "dash.updateReason.unknown": "Actualización no disponible", + "dash.updateRestart": "Reiniciar después de la actualización", + "dash.updateRestartHint": "Recomendado. El GUI actual sigue ejecutando el código antiguo hasta que se reinicia el proxy.", + "dash.runUpdate": "Actualizar", + "dash.updateReconnecting": "Esperando el proxy… reiniciado", + "dash.updateStatus.running": "Actualización de opencodex.", + "dash.updateStatus.restarting": "Actualización instalada. Reiniciando proxy.", + "dash.updateStatus.succeeded": "Actualización terminada.", + "dash.updateVersionTransition": "{currentVersion} -> {latestVersion}.", + + "dash.updateStatus.failed": "Falló la actualización.", + + "prov.subtitle": "Configura los proveedores que opencodex conecta con Codex. Inicia sesión con una cuenta, añade un proveedor o edita la configuración directamente.", + "prov.add": "Añadir proveedor", + "prov.editJson": "Editar JSON", + "prov.accountLogin": "Inicio de sesión de cuenta", + "prov.noOauth": "No hay proveedores de OAuth disponibles.", + "prov.loggedIn": "Conectado", + "prov.notLoggedIn": "No ha iniciado sesión", + "prov.logout": "Cierre de sesión", + "prov.login": "Inicio de sesión", + "prov.loginWith": "Iniciar sesión con {provider}", + "prov.waitingBrowser": "Esperando a browser…", + "prov.didntOpen": "¿No se abrió? Haz clic aquí", + "prov.copyLink": "Copiar enlace", + "prov.dontOpenBrowser": "No abra un navegador en la máquina proxy", + "prov.dontOpenBrowserHint": "Es útil para un perfil de navegador diferente, o cuando el panel de control no está en la máquina del proxy.", + "prov.linkCopied": "Copiado", + "prov.linkCopyUnavailable": "Clipboard no disponible", + "prov.deviceCode": "Código del dispositivo", + "prov.copyCode": "Copiar código", + "prov.copyCodeAndOpen": "Copiar código & abrir", + "prov.openSignInPage": "Abrir la página de inicio de sesión", + "prov.browserLaunchFailed": "El navegador no se abre automáticamente. Abra la página de inicio de sesión a continuación o copie el enlace.", + "prov.codeCopied": "Código copiado", + "prov.editAlias": "Editar alias", + "prov.aliasPrompt": "Mostrar nombre (dejar vacío para borrar)", + "prov.aliasSaved": "Alias salvados", + "prov.aliasSaveFailed": "No se pudo guardar el alias", + "prov.aliasInvalid": "Usa como máximo 80 caracteres, sin caracteres de control.", + "prov.accountId": "ID", + "prov.pasteRedirect": "Pegar redirección URL o código", + "prov.pasteRedirectHint": "Si el navegador muestra un error localhost, copie la URL completa de su barra de direcciones y péguela aquí (o pegue el código de autorización).", + "prov.pasteSubmit": "Enviar", + "prov.pasteSubmitting": "Envío…", + "prov.pasteOk": "Código enviado — finalización de inicio de sesión…", + "prov.pasteFail": "No se pudo enviar el código: {error}", + "prov.port": "Puerto", + "prov.default": "Predeterminado", + "prov.loadingConfig": "Cargando…", + "prov.targetChanged": "Cambió el servidor al que está conectado el panel. Vuelve a abrir el formulario en el servidor actual.", + "prov.loginExpired": "Este intento de inicio de sesión ya terminó. Vuelve a pulsar «Inicio de sesión» y pega el código del nuevo intento.", + "prov.legacyTargetPreflight": "Este proxy comprueba el servidor de destino antes de guardar, pero no puede verificarlo de forma atómica. Actualízalo para vincular cada guardado a su destino.", + "prov.saved": "Guardado. Reinicia el proxy para aplicar el cambio.", + "prov.loadConfigFail": "No se pudo cargar la configuración", + "prov.invalidJson": "Inválido JSON", + "prov.saveFailed": "Guardar falló", + "prov.loginFailStart": "{provider} inicio de sesión no pudo iniciarse", + "prov.loginError": "Error de inicio de sesión {provider}: {error}", + "prov.loginRequestFail": "Solicitud de inicio de sesión {provider} fallida", + "prov.loginCancelled": "{provider} inicio de sesión cancelado", + "prov.loginTimeout": "Se agotó el plazo para iniciar sesión en {provider}: el navegador se cerró o no terminó el proceso. Vuelve a intentarlo.", + "prov.loginOk": "Inicia sesión en {provider}. Ejecuta {cmd} (o aplica en vivo) para listar sus modelos.", + "prov.loginSameAccount": "Se inició sesión con la misma cuenta de {provider}. Cambia de cuenta en el navegador y vuelve a pulsar Añadir cuenta.", + "oauthTos.highTitle": "{provider}: riesgo de suscripción OAuth", + "oauthTos.elevatedTitle": "{provider}: puente no oficial OAuth", + "oauthTos.anthropicBody": "Esto conecta una suscripción Claude a través del proxy de terceros de OpenCodex. Anthropic no ha respaldado esta conexión ni la agrupación automatizada de cuentas; el acceso depende de sus términos y aplicación actuales.", + "oauthTos.highBody": "OpenCodex conecta {provider} a través de una ruta OAuth de terceros. El uso no soportado puede conducir a límites de acceso o suspensión.", + "oauthTos.elevatedBody": "OpenCodex conecta {provider} a través de una ruta no oficial OAuth. Use el cliente oficial cuando sea posible; el tráfico inusual o automatizado puede ser tratado como abuso y el acceso puede ser limitado o suspendido.", + "oauthTos.acknowledge": "Entiendo el riesgo y quiero continuar con OAuth de todos modos.", + "oauthTos.continue": "Continuar con OAuth", + "oauthTos.anthropicTitle": "Claude conexión de suscripción", + "oauthTos.anthropicConditions": "Usa una cuenta que te pertenezca o que tengas autorización para usar. Usar el cliente original de Claude Code con una persona que supervise la sesión es distinto de enviar tokens de una suscripción a través de otros clientes. OpenCodex también admite esos otros clientes, por lo que establecer esta conexión no garantiza que todos los usos estén permitidos. Las integraciones compatibles con Agent SDK se tratan por separado.", + "oauthTos.anthropicSaferPath": "Para otros clientes o automatización desatendida, configura una clave API de Anthropic.", + "oauthTos.anthropicAcknowledge": "Entiendo que esta es una conexión de suscripción de terceros y verificaré los términos aplicables.", + "oauthTos.anthropicContinue": "Continuar con la suscripción a Claude", + "oauthTos.antigravityTitle": "Google puede desactivar permanentemente el acceso a Gemini y Antigravity en esta cuenta de Google", + "oauthTos.antigravityBody": "{provider} usa un inicio de sesión de Google destinado a la propia aplicación Antigravity de Google. OpenCodex es un proxy de terceros, y usuarios de herramientas de terceros han informado de que se desactivó el acceso a Gemini y Antigravity en sus cuentas de Google con este error: “This service has been disabled in this account for violation of Terms of Service.”", + "oauthTos.antigravityConditions": "El bloqueo afecta a la cuenta de Google, no solo a OpenCodex: el acceso a Gemini Code Assist y Antigravity puede dejar de funcionar en todas partes, incluso en las herramientas de Google.\nPara recuperar el acceso hay que recurrir al proceso de apelación de Google, y el resultado no está garantizado.\nUsa solo una cuenta de Google separada cuya pérdida puedas asumir. Nunca uses tu cuenta principal, personal, de estudios o de trabajo.\nCada cuenta que añadas, vuelvas a autenticar o importes aquí corre el mismo riesgo.", + "oauthTos.antigravitySaferPath": "Opción más segura: usa una clave API de Gemini (Google AI Studio o Vertex AI). Las claves API son la forma admitida por Google de usar Gemini desde otras herramientas.", + "oauthTos.antigravityAcknowledge": "Entiendo que Google puede desactivar de forma permanente el acceso a Gemini y Antigravity en esta cuenta y que estoy usando una cuenta cuya pérdida puedo asumir.", + "oauthTos.antigravityContinue": "Aceptar el riesgo y continuar", + "subagentSurface.selectionTitle": "¿Cambiar la superficie del subagente a {mode}?", + "subagentSurface.selectionBody": "En {mode}, los modelos de ChatGPT que usan la interfaz v2 —Sol y Terra en base, y todos los modelos en v2— entregan su tarea a un modelo enrutado como Grok o Claude cifrada para el backend de ChatGPT. El modelo enrutado no puede leerla. Esa delegación falla con unreadable_encrypted_agent_task hasta que se corrija en origen. v1 permite delegar entre proveedores de forma fiable.", + "subagentSurface.advisoryTitle": "v1 es ahora la interfaz predeterminada de subagentes", + "subagentSurface.advisoryBody": "Esta instalación usa {mode}. En la interfaz v2, un modelo de ChatGPT entrega al modelo enrutado una tarea cifrada que este no puede leer, por lo que falla la delegación entre proveedores. Recomendamos v1 hasta que se corrija en origen. Tu configuración actual no cambia hasta que elijas.", + "subagentSurface.continue": "Continuar", + "subagentSurface.switchToV1": "Cambiar a v1", + "subagentSurface.learnMore": "Por qué falla esto", + "prov.logoutOk": "Salido de {provider}.", + "prov.logoutConfirmShared": "¿Cerrar sesión de la cuenta activa de {provider}? Es el inicio de sesión compartido de {provider}, así que la fila {provider} Chat también cierra sesión. Si hay otra cuenta de {provider} guardada, pasa a ser la activa en ambas filas: ninguna fila la usa mientras está en pausa y, si necesita volver a iniciar sesión, inicia sesión en ella de nuevo.", + "prov.logoutOkShared": "Se cerró la sesión de la cuenta activa de {provider} en las filas Chat y Responses.", + "prov.logoutFail": "No se pudo cerrar la sesión de {provider}. El estado de su cuenta no ha cambiado.", + "prov.logoutBusy": "Hay un cambio de cuenta en curso. Espera a que termine e intenta cerrar sesión de nuevo.", + "prov.accountRemoveUnverified": "No se pudo verificar si se eliminó {email}. Actualiza la lista de cuentas antes de reintentar.", + "prov.removed": "Eliminado \"{name}\".", + "prov.removedDefault": "Eliminado \"{name}\". El proveedor predeterminado es ahora \"{defaultProvider}\".", + "prov.removedShadowTarget": "Eliminado \"{name}\". Shadow Call Intercept todavía apunta a \"{model}\", por lo que las llamadas de ayuda fallarán hasta que elija otro objetivo.", + "prov.removeFail": "No se pudo eliminar \"{name}\".", + "prov.removeLastProvider": "No puede eliminar este proveedor cuando ningún otro proveedor habilitado puede convertirse en el predeterminado.", + "prov.removeHasDependentCombos": "Elimine o actualice primero estos combos dependientes: {combos}.", + "prov.setDefault": "Establecer como predeterminado", + "prov.setDefaultSuccess": "\"{name}\" es ahora el proveedor predeterminado.", + "prov.setDefaultFail": "No se pudo establecer \"{name}\" como el proveedor predeterminado.", + "prov.defaultDisabled": "Habilite este proveedor antes de convertirlo en el predeterminado.", + "prov.updateFail": "No se pudo actualizar este proveedor.", + "prov.networkError": "Error de red. Comprueba que el proxy se está ejecutando y vuelva a intentarlo.", + "prov.added": "Se ha añadido \"{name}\". En vivo ahora — ejecutar {cmd} (o reiniciar) para listar sus modelos en el selector de Codex.", + "prov.modelsNoticeTitle": "Elegir modelos", + "prov.modelsNoticeChecking": "Verificando la lista de modelos. Los switches de modelo no desactivan el proveedor.", + "prov.modelsNoticePending": "La lista de modelos iniciales aún no está confirmada. Los modelos permanecen ocultos hasta que el descubrimiento termina.", + "prov.modelsNoticeOff": "Todos los switches del modelo se giraron OFF en el registro. Habilite los modelos que desee en la página Modelos.", + "prov.modelsNoticeReady": "Elige qué modelos aparecen en la página Modelos. Los switches de modelo no desactivan el proveedor.", + "prov.modelsNoticeFailed": "El proveedor se guardó, pero la lista de modelos no se pudo actualizar. Vuelve a intentarlo.", + "prov.modelsNoticeCount": "{count} modelos", + "prov.modelsNoticeOpen": "Modelos abiertos", + "models.initialSelectionPending": "Descubrimiento inicial pendiente", + "prov.removeConfirm": "¿Quitar proveedor \"{name}\"? Sus modelos desaparecen del selector de Codex.", + "prov.hasApiKey": "clave api configurada", + "prov.hasHeaders": "cabeceras personalizadas configuradas", + "prov.accounts": "Cuentas ({n})", + "prov.accountsAria": "Cambiar cuentas {name}", + "prov.accountActive": "Activo", + "prov.accountReauth": "Volver a iniciar sesión", + "prov.reauthenticate": "Re-autenticar", + "prov.reauthAccountMissing": "La cuenta seleccionada no se encontró después de iniciar sesión", + "prov.reauthIdentityMismatch": "La cuenta iniciada no coincide con la cuenta seleccionada", + "prov.accountAdd": "Añadir cuenta", + "prov.accountNoLabel": "cuenta {id}", + "prov.accountSwitchTitle": "Usa esta cuenta", + "prov.accountSwitched": "Cambiado a {email}.", + "prov.accountSwitchFail": "No se pudo cambiar de cuenta", + "prov.accountRemoved": "Eliminado {email}.", + "prov.accountRemoveFail": "No se pudo eliminar {email}. La cuenta no ha cambiado.", + "prov.accountRemoveAria": "Eliminar {email}", + "prov.accountRemoveConfirm": "Eliminar cuenta {email}? Su inicio de sesión se elimina de este proxy.", + "prov.accountRemoveConfirmShared": "¿Quitar la cuenta {email}? Su inicio de sesión se elimina de este proxy. Es una cuenta compartida de {provider}, así que la fila {provider} Chat también la pierde.", + "prov.accountPauseConfirmShared": "¿Pausar la cuenta {email}? Es una cuenta compartida de {provider}, así que la fila {provider} Chat también deja de usarla.", + "pws.sharedAccountsNote": "Estas son tus cuentas compartidas de {provider}. Cambiar, pausar, renombrar o quitar una aquí también se aplica a la fila {provider} Chat.", + "prov.keyAdd": "Agregar clave API", + "prov.keyAdded": "Se ha añadido la clave API a {name}.", + "prov.keyAddFail": "No se pudo agregar la clave API", + "prov.keyPlaceholder": "Pegar clave API", + "prov.keySwitchTitle": "Usa esta clave", + "prov.keySwitched": "Se cambió a la tecla {key}.", + "prov.keySwitchFail": "No se pudo cambiar la tecla", + "prov.keyRemoved": "Clave eliminada {key}.", + "prov.keyRemoveAria": "Quitar clave {key}", + "prov.keyRemoveConfirm": "Eliminar API clave {key}? Se elimina de la configuración de este proxy.", + "prov.activeBadge": "Activo", + "prov.disabledBadge": "Desactivado", + "prov.defaultBadge": "Predeterminado", + "prov.enable": "Activar", + "prov.disable": "Desactivar", + "prov.enabled": "Habilitado \"{name}\". Sus modelos pueden aparecer en Codex de nuevo.", + "prov.disabled": "Se desactivó «{name}». Se conserva su configuración, pero sus modelos quedan ocultos.", + "prov.disabledShadowTarget": "Deshabilitado \"{name}\". Shadow Call Intercept todavía apunta a \"{model}\", por lo que las llamadas de ayudante fallarán hasta que elija otro objetivo o vuelva a habilitar \"{name}\".", + "prov.enableFail": "No se pudo habilitar \"{name}\".", + "prov.disableFail": "No se pudo desactivar \"{name}\".", + "prov.enableAria": "Activar proveedor {name}", + "prov.disableAria": "Deshabilitar proveedor {name}", + "prov.defaultCannotDisable": "El proveedor predeterminado no se puede deshabilitar", + "prov.openaiAccountMode": "Modo de cuenta Codex", + "prov.openaiModePool": "Pool", + "prov.openaiModeDirect": "Direct", + "prov.openaiPoolDesc": "Predeterminado. Alterna entre la cuenta principal y las añadidas según afinidad, cuota, espera de recuperación y respaldo ante fallos.", + "prov.openaiDirectDesc": "Usa solo el inicio de sesión actual / principal Codex. Las cuentas de grupo almacenadas no se leen ni rotan.", + "prov.openaiModeSaved": "El modo de cuenta OpenAI cambió a {mode}.", + "prov.openaiModeSaveFailed": "No se pudo cambiar el modo de cuenta OpenAI.", + "prov.openaiApiDesc": "Utiliza una clave OpenAI API y nunca utiliza credenciales de cuenta Codex.", + "prov.manageCodexAccounts": "Administrar cuentas Codex", + "prov.openaiApiMissing": "API clave requerida", + "prov.openaiApiSetup": "Configurar la tecla API", + + "models.tab.catalog": "Modelos", + "models.tab.combos": "Combos", + "models.tab.compatibility": "Compatibilidad", + "models.tab.routing": "Enrutamiento (beta)", + "models.tabsLabel": "Interfaces de modelos", + "models.subtitle.combos": "Grupos ordenados de modelos que responden como un solo id. Encadena los objetivos con conmutación por error o distribuye la carga con una estrategia de equilibrio.", + "models.subtitle.compatibility": "Matriz de veredicto de compatibilidad de solo lectura a partir de pruebas de proyección de laboratorio.", + "models.subtitle.routing": "Perfiles de políticas, evaluación de ejecución en seco y análisis de enrutamiento respaldado por fuentes.", + "models.subtitle": "Elige qué modelos ve Codex: los GPT nativos por paso directo y los modelos enrutados, agrupados por proveedor. Pulsa un encabezado para contraerlo. Los modelos ocultos no aparecen en el catálogo ni en el selector, pero puedes llamarlos directamente con su identificador exacto.", + "models.delivery.title": "Cómo llegan los cambios a Codex", + "models.delivery.chip.saved": "Guardado aquí", + "models.delivery.chip.savedHub": "Guardado en el hub", + "models.delivery.chip.synced": "{time} sincronizado", + "models.delivery.chip.syncedUnknown": "Sin sincronización registrada", + "models.delivery.chip.loaded": "Codex lo carga en el reinicio", + "models.delivery.saved.title": "Guardado en este proxy", + "models.delivery.saved.body": "Guardar en esta página actualiza el catálogo que este proxy de OpenCodex entrega a Codex y que muestra su selector de modelos. La confirmación de guardado indica que este paso terminó.", + "models.delivery.savedHub.title": "Guardado en el hub", + "models.delivery.savedHub.body": "Esta máquina está conectada a un concentrador OpenCodex compartido, por lo que guardar aquí cambia el catálogo del concentrador. La confirmación después de guardar significa que el concentrador lo tiene; esta máquina todavía tiene que descargarlo.", + "models.delivery.synced.title": "Sincronizado con esta máquina", + "models.delivery.synced.bodyAt": "Esta máquina descargó por última vez el catálogo del concentrador en {time} y lo escribió donde Codex lo lee. Ese tiempo solo te dice cuándo se ejecutó la descarga. Si guardó en el concentrador después de él, esta máquina mantiene la lista anterior hasta la siguiente sincronización.", + "models.delivery.synced.bodyUnknown": "Esta máquina aún no tiene descarga registrada del catálogo de concentradores, por lo que es posible que Codex todavía esté leyendo una lista anterior. La siguiente sincronización lo descarga.", + "models.delivery.loaded.title": "Cargado por Codex", + "models.delivery.loaded.body": "Codex lee el catálogo cuando se inicia, por lo que una ventana Codex que ya estaba abierta mantiene su lista de modelos antiguos. OpenCodex no puede mirar dentro de un Codex en ejecución para ver qué lista utiliza. Cuando puede saber que Codex comenzó antes de su cambio, aparece un aviso de reinicio encima de las pestañas.", + "models.delivery.hint": "Si un modelo que encendió no se muestra en Codex, presione Recargar modelos de Codex en la parte superior derecha de esta página, luego vuelva a abrir Codex.", + "models.nativeGroupLabel": "OpenAI nativo", + "models.nativeHint": "Los modelos Passthrough utilizan la opción de cuenta Pool o Direct seleccionada en Proveedores. Al alternar uno solo se oculta del selector Codex (la entrada del catálogo se mantiene, por lo que volver a habilitarlo lo restaura exactamente). Agregar un modelo aquí registra un selector `openai/` enrutado, no una nueva identificación de paso a través.", + "models.active": "{active}/{total} visible", + "models.workspace.providers": "Proveedores", + "models.workspace.allProviders": "Todos los proveedores", + "models.workspace.mainAria": "Detalles del modelo", + "models.allOn": "Activar todos", + "models.allOff": "Desactivar todos", + "models.presetLabel": "Modelos", + "models.presetMode_preset": "Preestablecido", + "models.presetMode_all": "Todos", + "models.presetMode_custom": "Personalizado", + "models.presetSummary": "{count} de {total} muestra — preajuste del núcleo v{version}", + "models.presetUpdateAvailable": "Preajuste v{version} disponible", + "models.presetAppliedToast": "{provider}: preajuste aplicado — {count} modelos seleccionados", + "models.presetClearedToast": "{provider}: mostrando todos los modelos", + "models.presetEmpty": "{provider}: no hay modelos preestablecidos — selección sin cambios", + "models.presetConfirmReplace": "¿Sustituye su selección por el ajuste preestablecido de modelo {count}?", + "models.cap350k": "Tapa 350k", + "models.capApplied": "— tiene efecto en el siguiente turno Codex.", + "models.capSaveFailed": "No se pudo guardar el límite de contexto", + "models.contextCapped": "Tapa de 350k", + "models.contextCapLabel": "Ventana o límite predeterminado", + "models.v2Label": "Subagente", + "models.shadowCallOriginal": "{models} →", + "models.v2DocsLink": "¿Qué es v1 / v2?", + "models.v2Mode_v1": "v1", + "models.v2Mode_default": "base", + "models.v2Mode_v2": "v2", + "models.v2Mode_v2-plaintext": "V2 · tareas en texto claro", + "models.v2ModeDesc_v1": "Todos los modelos → superficie v1", + "models.v2ModeDesc_default": "Valores predeterminados de flujo ascendente (sol/terra-v2, luna-v1)", + "models.v2ModeDesc_v2": "Todos los modelos → superficie v2", + "models.v2PlaintextOn": "Está configurado el envío de tareas en texto claro (experimental)", + "models.keepNativeOnV1": "Mantener ChatGPT en v1", + "models.keepNativeOnV1Hint": "ChatGPT cifra las tareas secundarias de v2 solo cuando un padre nativo de ChatGPT permanece en v2, por lo que Grok y Claude no pueden leerlas. Encienda esto para mantener Sol/Terra en v1 y evitar ese cifrado. Los padres enrutados mantienen v2.", + "models.v2Help": "Controla el modo multiagente de todos los modelos.\n\nv1: Agente clásico de un solo hilo. Todos los modelos usan la interfaz de colaboración v1.\nbase: Valores predeterminados del proveedor. Sol y Terra usan v2; Luna usa v1; los demás siguen la opción de Codex.\nv2: Agente con varios hilos mediante spawn_agent. Todos los modelos usan la interfaz de colaboración v2.\nV2 · tareas en texto claro: Variante opcional de v2. Todos los modelos conservan la interfaz v2 y se envía en texto claro el contenido de las tareas compatibles.\n\nEn v2, «Mantener ChatGPT en v1» deja a Sol y Terra en la interfaz v1 para que puedan iniciar Grok o Claude. ChatGPT cifra las tareas de subagentes en v2; los modelos enrutados no pueden leerlas. Los agentes principales enrutados se mantienen en v2.\n\nLos cambios de catálogo se aplican a las sesiones nuevas. Mientras esté habilitado, el compilador también se aplica a solicitudes canónicas de ChatGPT compatibles que se envíen después desde sesiones V2 existentes. Al desactivarlo no se borran las copias conservadas. v1 sigue disponible.", + "plaintextV2.title": "¿Habilitar V2 · tareas en texto claro?", + "plaintextV2.body": "Experimental. Los mensajes de tareas de colaboración compatibles usan texto claro en la aplicación y pueden quedar en el historial de Codex, las solicitudes al proveedor elegido y los datos locales de respuestas y diagnóstico. HTTPS y la autenticación permanecen activos. No se descifran textos existentes ni se reescribe el historial guardado.", + "plaintextV2.caveat": "Si no se puede reescribir una solicitud de forma segura, se envía tal cual y la delegación aún puede fallar.", + "plaintextV2.scope": "Los cambios de catálogo se aplican a las sesiones nuevas. Mientras esté habilitado, el compilador también se aplica a solicitudes canónicas de ChatGPT compatibles que se envíen después desde sesiones V2 existentes. Al desactivarlo no se borran las copias conservadas. v1 sigue disponible.", + "plaintextV2.acknowledge": "Entiendo que el texto de las tareas puede conservarse en texto claro.", + "plaintextV2.confirm": "Habilitar tareas en texto claro", + "dash.multiAgent": "Subagente", + "dash.codexDesktopAuthless": "Abrir Codex sin iniciar sesión", + "dash.codexDesktopAuthlessHint": "Desactivado de forma predeterminada. Omite el inicio de sesión independiente de Desktop para las conexiones locales compatibles. El proveedor de origen sigue necesitando credenciales. Reinicia Codex después de cambiar esta opción. Las funciones de Desktop que requieren una cuenta pueden no estar disponibles.", + "dash.codexClientCompaction": "Usa la compactación del lado del cliente", + "dash.codexClientCompactionHint": "Desactivada de forma predeterminada; solo en conexiones de bucle local autenticadas. Las futuras compactaciones guardan resúmenes portátiles en texto sin cifrar mientras siguen activos OpenCodeX y el enrutamiento de proveedores V2; el proveedor configurado puede procesarlos y consumir cuota. El historial no cambia y los hilos existentes siguen pasando por el proxy mediante la opción openai_base_url que administra OpenCodeX. Si configuraste esa línea por tu cuenta, se conserva y esos hilos usan tu destino. El historial ocx1 existente sigue siendo recuperable; recupera un hilo por separado solo antes de reproducirlo en Codex nativo. Reinicia Codex después de cambiar esta opción.", + "dash.codexRemoteHistoryHint": "El enrutamiento de la tabla del proveedor puede ocultar los hilos etiquetados con openai existentes en algunas listas remotas móviles. El historial no se elimina. El cliente remoto debe enumerar todos los proveedores; este conmutador no repara ese filtro de cliente.", + "models.v2Conflict": "[agents] tiene configurado max_concurrent_threads_per_session / max_threads; codex se negará a iniciar. Elimina ese ajuste de config.toml.", + "models.v2Applied": "Modo de subagentes actualizado. El catálogo cambia para sesiones nuevas. Con el texto claro habilitado, también pueden verse afectadas solicitudes posteriores compatibles de sesiones V2 existentes. Reinicia Codex App para actualizar el selector.", + "models.v2ThreadsLabel": "Límite de subagentes", + "models.v2ThreadsDefault": "predeterminado", + "models.v2ThreadsApplied": "El límite de subagentes actualizado — se aplica a nuevas sesiones", + "models.v2ThreadsInvalid": "El límite de subagente debe ser un entero >= 1", + "models.v2ThreadsApply": "Aplicar", + "models.capValue": "Por defecto {value}", + "models.contextSettings": "Ventanas personalizadas", + "models.contextSettingsTitle": "Windows personalizados — {provider}", + "models.contextDefault": "Proveedor predeterminado", + "models.contextModel": "Modelo", + "models.contextModelOverride": "Anulación del modelo", + "models.contextHint": "Escriba la ventana Codex real aquí cuando ya lo sepa. Esto llena una ventana de flujo ascendente que falta y solo baja una más grande informada. Deje en blanco para usar la ventana / límite predeterminada del proveedor, o 128k si esa límite está desactivada.", + "models.contextAutomatic": "Descubrimiento automático", + "models.contextSaved": "Contexto windows actualizado — entra en vigor en el próximo turno Codex.", + "models.contextUnchanged": "No hay cambios en la ventana de contexto para guardar.", + "models.contextSaveFailed": "No se pudo guardar las ventanas de contexto", + "models.contextInvalid": "Las ventanas de contexto deben ser números enteros positivos", + "models.contextCappedValue": "{value} límite", + "models.setAll": "Establecer todo", + "models.setAllHint": "Active la ventana predeterminada de {value} para cada proveedor enrutado. Los relés que omiten context_window / context_length obtienen esto como la ventana Codex real. Usa Ventanas personalizadas en una fila de proveedor para establecer un modelo a mano. Los proveedores nativos no se ven afectados.", + "models.collapseAll": "Colapsar todo", + "models.expandAll": "Expandir todo", + "models.orderHint": "El orden predeterminado sigue los destacados y la prioridad del catálogo; los modelos enrutados empatados se ordenan por proveedor y modelo. Un orden de selección guardado puede reemplazar el orden visible. Los controles de visibilidad filtran las filas que aparecen. Un cliente puede conservar un catálogo antiguo hasta volver a consultarlo.", + "models.settingsPanel.title": "Configuración del modelo", + "models.settingsPanel.off": "apagado", + "models.settingsPanel.attention": "Necesita atención", + "models.custom": "Personalizado…", + "models.customApply": "Aplicar", + "models.customPlaceholder": "Tokens (p. ej., 420000)", + "models.customAdd": "Añadir modelo personalizado", + "models.customAddTitle": "Añadir modelo personalizado — {provider}", + "models.customEditTitle": "Editar modelo personalizado — {provider}", + "models.settingsTitle": "Editar modelo — {model}", + "models.settingsContextInherit": "No anulado — actualmente {value}", + "models.settingsContextUnknown": "Desconocido", + "models.settingsReload": "Recargar", + "models.settingsReloaded": "Se recargó la lista de modelos. Vuelve a abrir {model} para ver los valores guardados.", + "models.settingsNoChange": "La configuración de {model} no cambió", + "models.settingsSaved": "Configuración del modelo guardada para {model}", + "models.settingsSaveFailed": "No pudimos confirmar si se guardó la configuración. Recarga la lista de modelos antes de reintentar.", + "models.settingsRefreshFailed": "Se guardó la configuración, pero no se recargó la lista de modelos y la fila podría mostrar valores anteriores. Recárgala para comprobarlo.", + "models.settingsSavedCodexStale": "Se guardó {model}, pero no se actualizó el catálogo de Codex. Pulsa Sincronizar ahora en el panel para que Codex reciba el cambio.", + "models.settingsRejected": "El servidor rechazó esta configuración, por lo que no se guardó nada. Comprueba los valores y vuelva a intentarlo.", + "models.settingsDefaultEffort": "Nivel predeterminado", + "models.settingsModalitiesInherit": "No anulado — actualmente siguiendo la declaración ascendente: {modalities}", + "models.settingsModalitiesUnknown": "No declarado", + "models.settingsRestore": "Restaurar", + "models.settingsRestoreHint": "Borre cada anulación en este modelo y vuelva a los valores calculados.", + "models.settingsRestoreConfirm": "Restaurar {model} a los valores calculados? Esto despeja su ventana de contexto, la modalidad y el razonamiento anula.", + "models.settingsRestored": "{model} restaurado a los valores calculados", + "models.settingsNothingToRestore": "{model} no tiene anulaciones; ya los valores calculados", + "pws.manageModelVisibility": "Gestionar la visibilidad en modelos", + "pws.modelOwnershipLoading": "Comprobación de las definiciones del modelo…", + "pws.modelOwnershipFailed": "No se pudieron cargar las definiciones del modelo. Vuelve a intentarlo antes de hacer cambios.", + "pws.modelSelectionPending": "Finalizar la selección de modelos en Modelos antes de realizar cambios.", + "pws.modelSaved": "Se guarda la definición de modelo personalizada.", + "pws.modelSavedHidden": "Definición guardada. Este modelo está oculto; gestiona la visibilidad en Modelos.", + "pws.modelSavedRefreshPending": "Se guardó la definición, pero no se pudo actualizar el catálogo de modelos. Reintenta la actualización; no vuelvas a añadir el modelo.", + "pws.modelMutationUnconfirmed": "El cambio no pudo ser confirmado. Actualiza los modelos antes de volver a intentarlo.", + "pws.modelRemovedRefreshPending": "El cambio se guardó, pero el catálogo de modelos no se pudo actualizar. Vuelve a probar la actualización.", + "pws.modelHidden": "Modelo oculto. Restaure la visibilidad en Modelos.", + "pws.modelDefinitionDeleted": "Definición personalizada eliminada. Un modelo subyacente todavía puede aparecer.", + "pws.modelKnown": "Este modelo ya se conoce. Gestionar su visibilidad en Modelos.", + "models.customAdded": "Modelo personalizado añadido", + "models.customUpdated": "Modelo personalizado actualizado", + "models.customDeleted": "Modelo personalizado eliminado", + "models.customSaveFailed": "No se pudo guardar el modelo personalizado", + "models.customSaving": "Guardando…", + "models.customAddBtn": "Añadir", + "models.customEditBtn": "Actualizar", + "models.customEdit": "Editar", + "models.customDelete": "Eliminar", + "models.customDeleteConfirm": "¿Eliminar la definición personalizada de {name}? Un modelo nativo subyacente o descubierto puede aparecer de nuevo.", + "models.hide": "Ocultar", + "models.hideConfirm": "Ocultar {name} del catálogo de modelos? Esto no elimina su definición ni cambia la política de enrutamiento directo.", + "models.customBadge": "Personalizado", + "models.customSummary": "{count} personalizado", + "models.customFieldModelId": "ID del modelo (barra de extremo)", + "models.customFieldModelIdPlaceholder": "p. ej., qwen4-max-preview", + "models.customFieldDisplayName": "Nombre (opcional)", + "models.customFieldDisplayNamePlaceholder": "e.g. Qwen 4 Max Vista previa", + "models.customFieldContext": "Ventana de contexto", + "models.customFieldModalities": "Modalidades de los insumos", + "models.customFieldReasoning": "Esfuerzo de razonamiento", + "models.customFieldReasoningOverride": "Anular el esfuerzo de razonamiento", + "models.reasoningEffort.none": "Ninguno", + "models.reasoningEffort.minimal": "Mínimo", + "models.reasoningEffort.low": "Bajo", + "models.reasoningEffort.medium": "Medio", + "models.reasoningEffort.high": "Alto", + "models.reasoningEffort.xhigh": "Muy alto", + "models.reasoningEffort.max": "Máximo", + "models.reasoningEffort.ultra": "Ultra", + "models.tipProvider": "Proveedor", + "models.tipContext": "Contexto", + "models.tipModalities": "Modalidades", + "models.tipStatus": "Estado", + "models.tipActive": "Activo", + "models.tipDisabled": "Desactivado", + "models.applied": "Guardado. Codex mostrará el cambio cuando vuelva a cargar la lista de modelos.", + "models.integrationRefreshWarning": "Selección de modelo guardada. Algunos catálogos de clientes no se pudieron actualizar. Comprueba las integraciones antes de comenzar una nueva sesión.", + "models.saveFailed": "Guardar falló", + "models.networkError": "Error de red — ¿Está funcionando el proxy?", + "models.loadFail": "¿Ha fallado la carga de los modelos? —", + "models.noRouted": "No hay modelos enrutados", + "models.noRoutedHint": "Primero inicia sesión en un proveedor o añade uno.", + "models.emptyDiscovery": "No se descubrieron modelos. Comprueba el punto final del proveedor o añada un modelo estático/personalizado.", + "models.emptyDiscoveryDisabled": "El descubrimiento de modelos en vivo está desactivado y no se configuran modelos estáticos.", + "models.discoveryFailedBadge": "Descubrimiento fallido", + "models.discoveryFailedHttp": "Falló el descubrimiento del modelo (HTTP {status}).", + "models.discoveryFailedBlocked": "El descubrimiento del modelo fue bloqueado por la política de destino.", + "models.discoveryFailedInvalidResponse": "El descubrimiento del modelo devolvió una respuesta no válida.", + "models.discoveryFailedNetwork": "El descubrimiento del modelo falló debido a un error de red.", + "models.discoveryFailedProvider": "El proveedor informó de un error de descubrimiento del modelo.", + "models.discoveryFailedGeneric": "El descubrimiento del modelo falló.", + "models.openProviderSettings": "Abrir la configuración del proveedor", + "models.inactiveNoCredit": "Sin crédito", + "models.inactiveNoCreditHint": "Todos los proveedores detrás de esta entrada están fuera de crédito en este momento, por lo que una solicitud fallaría. Se mantiene en la lista y vuelve a ser utilizable cuando el crédito se restablece o se recarga.", + "models.discoveryFailedDependency": "El descubrimiento del modelo está encendido para este proveedor. Si bien sigue fallando, desactive \"{control}\" en la configuración del proveedor para usar modelos agregados manualmente o estáticos.", + "models.loading": "Cargando…", + "models.search": "Buscar modelos…", + "models.showMore": "Mostrar {n} más", + "models.freeOnly": "Solo gratis", + "models.noFreeMatch": "Aquí no hay modelos libres. Desactivar libre sólo para ver el resto.", + "models.allowlistLabel": "Solo seleccionados", + "models.allowlistHint": "Solo los modelos verificados se envían al catálogo (vacía . Es útil para proveedores que exponen miles de modelos.", + "models.selectedCount": "{n} seleccionado", + + "sub.forceTitle": "Usar un solo modelo para todos los subagentes", + "sub.forceModel": "Modelo de subagente Claude Code", + "sub.forceChoose": "Elige un modelo expuesto", + "sub.forceHelp": "Se aplica a los agentes integrados y de plugins, incluidos Explore y Plan, y reemplaza los modelos elegidos en cada llamada. Las bifurcaciones y las skills con model: inherit conservan el modelo de la conversación principal. No afecta al modelo principal ni a los sidecars Haiku/small-fast.", + "sub.forceScope": "Desactivado de forma predeterminada. Se aplica desde el próximo inicio enrutado con ocx claude, no al ejecutar claude directamente. Tienen prioridad las variables exportadas por la shell; env en settings.json puede sustituirlas. El estado solo comprueba la CLI y la configuración de usuario del servidor, no otras shells ni configuraciones del proyecto.", + "sub.forceInvalid": "El destino configurado no está disponible. Se omitirá la anulación de inicio; elige un modelo expuesto o desactiva esta opción.", + "sub.forceOld": "Claude Code es más antiguo que 2.1.257: se ignora FORCE; solo se aplica el valor predeterminado de subagente no forzado.", + "sub.forceUnknown": "La versión Claude Code es desconocida. El soporte de fuerza requiere la versión 2.1.257 o posterior.", + "sub.forceOverride": "Anulado por settings.json: su env contiene un modelo de subagente o la configuración FORCE. OpenCodex no lo modifica.", + "sub.forceSettingsUnknown": "No se pudo inspeccionar settings.json. Se desconoce el estado de anulación de la configuración.", + "sub.forceSaved": "Guardado. Tendrá efecto la próxima vez que inicies ocx claude con enrutamiento.", + "sub.subtitle": "Codex de {cmd} anuncia solo los primeros 5 modelos (por prioridad) como anulaciones. Recoger hasta 5 aquí — nativo gpt o enrutado — y opencodex establece su prioridad de catálogo por lo que exactamente estos plomo. Cualquier otro modelo todavía se puede llamar por su nombre exacto; esto solo controla lo que se muestra.", + "sub.featured": "Destacados", + "sub.advanced": "Avanzado", + "sub.orderHintAria": "Cómo se usa este orden", + "sub.orderHint": "Este orden determina los puestos 1 a 5 del selector de modelos de Codex y los modelos candidatos predeterminados para {cmd}. Si se muestran menos de 5 modelos destacados, los espacios restantes siguen la prioridad del catálogo. Si hay 5 destacados visibles, ocupan la lista salvo que el orden personalizado del selector cambie la prioridad.", + "sub.noneSelected": "Ninguno seleccionado — elegir de la lista de abajo.", + "sub.models": "Modelos", + "sub.search": "Modelos de búsqueda (nativo gpt + routed)…", + "sub.settings": "Configuración", + "sub.sections": "Secciones de subagente", + "sub.delegation.model": "Modelo para llamar primero", + "sub.delegation.modelHint": "Es el modelo al que Codex delega trabajo primero. La lista de destacados indica cuáles puede llamar; esta opción elige cuál llama antes que los demás.", + "sub.suggest.button": "Sugerir", + "sub.suggest.label": "Trabajo delegado", + "sub.suggest.placeholder": "¿Qué es lo que Codex suele entregar? e.g. búsquedas de solo lectura en el repositorio o refactores multimódulo", + "sub.suggest.submit": "Tamaño it", + "sub.suggest.running": "Calculando tamaño…", + "sub.suggest.failed": "No se pudo dimensionar el trabajo delegado.", + "sub.suggest.title": "Modelo sugerido", + "sub.suggest.accept": "Usa este", + "sub.noModels": "No hay modelos — iniciar sesión en un proveedor o añadir uno primero.", + "sub.saved": "Se guardaron {n} modelos. Inicia una sesión nueva de Codex o ejecuta {cmd} para verlos como opciones de modelo de spawn_agent.", + "sub.saveFailed": "Guardar falló", + "sub.networkError": "Error de red — ¿Está funcionando el proxy?", + "sub.loadFail": "¿Ha fallado la carga de los modelos? —", + "sub.loading": "Cargando…", + "sub.moveUp": "Mover {m} hacia arriba", + "sub.moveDown": "Mover {m} hacia abajo", + "sub.removeAria": "Eliminar {m}", + "sub.workspace.addToFeatured": "Agregar {m} a la lista de destacados", + "sub.workspace.allModels": "Todos los modelos", + "sub.workspace.featuredFull": "La lista está completa (max 5)", + "sub.workspace.mainAria": "Detalles del modelo de Subagent", + "sub.workspace.notFeatured": "No aparece", + "sub.workspace.priority": "Prioridad", + "sub.ultraMode": "Delegación siempre proactiva", + "sub.ultraModeHint": "Activa la política de delegación multiagente proactiva para todos los modelos y niveles de esfuerzo, sin cambiar el esfuerzo de razonamiento. Escribe features.multi_agent_v2.multi_agent_mode_hint_text en config.toml.", + "sub.ultraModeV2Required": "Requiere el modo multiagente v2: activa multi_agent_v2 y selecciona v2 en el control de modo de subagentes.", + "sub.ultraModeText": "Texto de delegación proactivo", + "sub.ultraModePreset": "Restaurar preajuste", + "sub.ultraModeLoadFail": "No se pudo cargar la configuración de delegación proactiva — ¿Está funcionando el proxy?", + "sub.ultraModeSaveFail": "No se pudo guardar la configuración de delegación proactiva", + "sub.ultraModeSaved": "Se guardó la delegación proactiva. Se aplica a sesiones nuevas de Codex.", + "sub.workspace.removeFromFeatured": "Eliminar {m} de destacados", + "sub.workspace.selectModel": "Selecciona un modelo", + "sub.workspace.selectModelDesc": "Elige un modelo de la lista para ver los detalles y presentarlo para spawn_agent.", + "sub.workspace.selector": "Selector público", + "sub.fallbackLabel": "Cadena de reserva de subagente", + "sub.fallbackHint": "Los modelos ordenados se prueban cuando un modelo de subagente no está disponible o falla.", + "sub.fallbackAdd": "Añadir modelo de reserva…", + "sub.fallbackPoll": "Intervalo de comprobación de disponibilidad", + "sub.fallbackSaved": "Configuración de reserva de subagente guardada.", + "sub.fallbackSaveFailed": "No se pudo guardar la configuración de reserva", + "sub.fallbackUnavailable": "Actualmente no se anuncia; se mantiene en la cadena.", + "sub.fallbackPollInvalid": "Introduce un número entero entre 5000 y 600000 ms.", + "sub.v2Compatibility.title": "Compatibilidad con V2 de padres nativos", + "sub.v2Compatibility.risk": "Si un padre nativo de ChatGPT delega en este modelo enrutado usando V2, su tarea puede cifrarse y fallar antes de la ejecución. Las tareas legibles de los padres enrutados no se ven afectadas.", + "sub.v2Compatibility.recoveryUnknown": "El estado de recuperación/elegibilidad no está expuesto por este servidor. Usa la delegación compatible con V1/plaintext, o habilite la recuperación experimental de V2 solo si es elegible. La recuperación agrega cuota, latencia, dependencia del backend y posible pérdida de fidelidad; no corrige el protocolo ascendente.", + "sub.v2Compatibility.details": "Detalles de compatibilidad", + + "logs.title": "Solicitar registros", + "logs.tabLogs": "Registros", + "logs.tabDebug": "Depurar", + "logs.subtitle": "Las solicitudes recientes se enrutan a través del proxy local opencodex, primero el más reciente.", + "logs.autoRefresh": "Actualizar automáticamente", + "logs.noRequests": "No hay solicitudes todavía.", + "logs.loadError": "No se pudo cargar los registros de solicitud.", + "logs.filter.surface.label": "Superficie", + "logs.filter.model.all": "Todos los modelos", + "logs.filter.provider.label": "Proveedor", + "logs.filter.provider.all": "Todos los proveedores", + "logs.filter.status.label": "Estado", + "logs.filter.status.all": "Todos los estados", + "logs.filter.status.success": "El éxito (2xx)", + "logs.filter.status.errors": "Errores (4xx/5xx)", + "logs.filter.time.label": "Hora", + "logs.filter.time.all": "Todo el tiempo", + "logs.filter.time.15m": "Ultimos 15m", + "logs.filter.time.1h": "Ultimas 1h", + "logs.filter.time.24h": "Ultima 1d", + "logs.filter.speed.label": "Velocidad", + "logs.filter.speed.all": "Todas las velocidades", + "logs.filter.speed.slow": "15 tok/s", + "logs.filter.speed.medium": "15– 50 tok/s", + "logs.filter.speed.fast": "≥ 50 tok/s", + "logs.filter.reset": "Restablecer filtros", + "logs.filter.showingCount": "Mostrando {count} de {total}", + "logs.noMatchingRequests": "No hay solicitudes que coincidan.", + "logs.filter.surface.all": "Todos", + "logs.filter.surface.claude": "Claude", + "logs.filter.surface.codex": "Codex", + "logs.filter.surface.grok": "Grok", + "logs.filter.interceptedHelpersOnly": "Solo ayudantes interceptados", + "logs.badge.interceptedHelper": "I · {model}", + "logs.badge.interceptedHelperTitle": "Solicitud de ayuda interceptada", + "logs.filter.conversation.label": "Conversación", + "logs.filter.conversation.placeholder": "Pegar ID de conversación", + "logs.filter.conversation.clear": "Limpiar", + "logs.filter.model.label": "Modelo", + "logs.filter.model.placeholder": "Filtrar por modelo o proveedor", + "logs.filter.conversation.apply": "Registros de filtro", + "logs.conversation.totals": "{requests} solicita · {tokens} tokens · {cost}", + "logs.conversation.scope": "Los totales solo cubren el anillo Logs cargado actualmente.", + "logs.conversation.excluded": "({unpriced} sin precio, {unmetered} sin medidor excluido de ~$)", + "logs.cost.approximate": "{amount}", + "logs.cost.partial": "Conocido {amount}", + "logs.cost.partialMissing": "Intentos sin estimación de costo ({count})", + "logs.cost.lowerBound": "≥{amount}", + "logs.cost.unavailable": "—", + "logs.detail.conversation": "Conversación", + "logs.badge.claude": "Claude", + "logs.badge.grok": "Grok", + "logs.col.time": "Hora", + "logs.col.request": "Solicitud", + "logs.col.model": "Modelo", + "logs.col.effort": "Esfuerzo", + "logs.col.provider": "Proveedor", + "logs.col.status": "Estado", + "logs.col.tokens": "Tokens", + "logs.col.tokPerSec": "tok/s", + "logs.col.estimatedCost": "~$", + "logs.metric.tokPerSecTitle": "Salida tokens por segundo durante toda la duración de la solicitud", + "logs.metric.estimatedCostTitle": "API precio de lista equivalente, no un cargo real; precio sin igual no está disponible", + "usage.cost.total": "API list-price equivalente (este rango)", + "usage.cost.disclaimer": "No es un recibo de facturación. En su lugar, se puede aplicar el uso de suscripción o créditos de proveedor.", + "usage.cost.unpricedNote": "Solicitudes {count} excluidas (sin precio ni uso)", + "usage.cost.excluded": "(Solicitudes {count} excluidas)", + "usage.cost.excludedOne": "(Solicitud {count} excluida)", + "logs.detail.section.basic": "Información básica", + "logs.detail.route.section": "Decisión de ruta", + "logs.detail.route.kind": "Tipo de ruta", + "logs.detail.route.profile": "Perfil", + "logs.detail.route.selected": "Seleccionado", + "logs.detail.route.candidates": "Candidatos", + "logs.detail.route.unknown": "No se registró ningún rastro de ruta para esta solicitud (fila previa a la traza).", + "logs.filter.protocol.label": "Ruta de protocolo", + "logs.filter.protocol.all": "Todos los caminos", + "logs.filter.protocol.none": "No hay datos de ruta", + "logs.protocol.mode.native": "Nativo", + "logs.protocol.mode.translated": "Traducido", + "logs.protocol.mode.legacyBridge": "Puente heredado", + "logs.protocol.mode.blocked": "Bloqueado", + "logs.protocol.disposition.passthrough": "Pasó por", + "logs.protocol.disposition.translated": "Traducido", + "logs.protocol.disposition.degraded": "Degradación", + "logs.protocol.disposition.unsupported": "Caído", + "logs.protocol.wire.responses": "Responses", + "logs.protocol.wire.chat": "Chatear", + "logs.protocol.wire.messages": "Messages", + "logs.protocol.wire.other": "Otros adaptadores", + "logs.protocol.hop.ir": "IR", + "logs.protocol.hop.internal": "Responses (interno)", + "logs.protocol.badgeTitle": "Ruta del protocolo: {path} ({mode})", + "logs.detail.protocol.section": "Ruta de protocolo", + "logs.detail.protocol.inbound": "Cliente API", + "logs.detail.protocol.mode": "Modo de entrega", + "logs.detail.protocol.upstream": "Alambre corriente arriba", + "logs.detail.protocol.requestPath": "Ruta de solicitud", + "logs.detail.protocol.responsePath": "Ruta de respuesta", + "logs.detail.protocol.reasons": "Motivos", + "logs.detail.protocol.features": "Efectos de función", + "logs.detail.protocol.attempts": "Intento de rutas", + "logs.detail.protocol.attempt": "Intentar {ordinal}", + "logs.detail.protocol.none": "No hay datos de ruta registrados para esta solicitud.", + "logs.detail.section.performance": "Rendimiento", + "logs.detail.section.cost": "API list-price equivalente", + "logs.detail.section.costBilled": "Costo estimado", + "logs.detail.section.attempts": "Intentos upstream", + "logs.detail.section.usage": "Uso crudo", + "logs.detail.ttft": "TTFT", + "logs.detail.decodeTokPerSec": "Tasa de descodificación (est.)", + "logs.decodeBasis.generation": "Ventana de generación", + "logs.decodeBasis.legacy": "Después de la salida visible", + "logs.decodeBasis.unknown": "Tiempo desconocido", + "logs.detail.decodeGeneration": "Velocidad de salida durante la generación (est.)", + "logs.detail.decodeLegacy": "Velocidad de salida después de la primera salida visible (est.)", + "logs.detail.decodeUnknown": "Tasa de salida (est.; método de temporización desconocido)", + "logs.detail.decodeBasisHint.generation": "Estimación usando el tiempo desde la primera salida observada por el proxy, incluyendo el razonamiento, hasta la última delta de salida.", + "logs.detail.decodeBasisHint.legacy": "Estimado utilizando el tiempo desde la primera salida visible hasta el final de la solicitud, mientras se cuenta toda la salida reportada tokens, incluido el razonamiento.", + "logs.detail.decodeBasisHint.unknown": "El servidor no informó qué método de temporización se usó para esta estimación.", + "logs.detail.endToEndTokPerSec": "Tok/s de salida de extremo a extremo", + "logs.detail.reason.ttft_missing": "No se registró ningún tiempo hasta el primero token para esta solicitud, por lo que no hay una ventana de decodificación que medir.", + "logs.detail.reason.decode_window_missing": "No se observó una ventana de generación completa.", + "logs.detail.reason.decode_window_too_short": "La ventana de salida medida estaba por debajo de un segundo, que es demasiado corto para estimar una velocidad de decodificación.", + "logs.detail.costTotal": "Equivalente de precio de lista", + "logs.detail.costSubtotal": "Subtotal del costo conocido", + "logs.detail.creditBasis": "Base de facturación", + "logs.detail.creditCharge": "{credits} créditos × {price} por crédito", + "logs.detail.creditMixed": "Mixto: no todos los intentos se facturaron igual, o sus créditos combinados no se pueden expresar como un solo número; solo los costos por intento tienen desglose.", + "logs.detail.creditTotal": "Total con precio por crédito", + "logs.detail.mixedTotal": "Total combinado (base por intento)", + "logs.detail.totalTokens": "Tokens totales", + "logs.detail.matchedKey": "Llave de precio coincidente", + "logs.detail.priceSource": "Fuente de precios", + "logs.detail.unavailableReason": "Motivo no disponible", + "logs.detail.copyRequestId": "Copiar ID de solicitud", + "logs.detail.copied": "Copiado", + "logs.detail.source.jawcode": "jawcode catálogo", + "logs.detail.source.expected": "Superposición del precio esperado", + "logs.detail.source.user": "Superposición de precios configurada por proveedor", + "logs.detail.verification.verified": "Verificado", + "logs.detail.verification.derived": "Derivado del modelo base", + "logs.detail.attempt.target": "Proveedor / modelo", + "logs.detail.attempt.account": "Cuenta", + "logs.detail.attempt.reason": "Resultado / razón", + "logs.detail.attempt.completed": "Finalizado", + "logs.detail.attempt.e2eNote": "Tok/s de nivel superior es de extremo a extremo; cada intento usa su propia duración.", + "logs.detail.attempt.recovery.transient5xx": "Transitorio 5xx", + "logs.detail.attempt.recovery.connectionReset": "Restablecimiento de conexión", + "logs.detail.attempt.recovery.offlineResend": "Reenvío al restablecerse la conexión", + "logs.detail.attempt.recovery.oauth401": "Re-autenticación de OAuth", + "logs.detail.attempt.recovery.key429": "Tasa de clave limitada (429)", + "logs.detail.attempt.recovery.rateLimit429": "Límite de solicitudes alcanzado (429)", + "logs.detail.attempt.recovery.anthropicOauth429": "Anthropic OAuth tasa limitada (429)", + "logs.detail.attempt.recovery.image413": "Carga útil de imagen demasiado grande (413)", + "logs.detail.attempt.recovery.emptyCompletion": "Reintentar la terminación vacía", + "logs.detail.attempt.recovery.consoleGoUpload": "Reintentar carga de consola", + "logs.detail.attempt.recovery.key401": "Re-autenticación de clave API", + "logs.detail.attempt.recovery.oauthAccount403": "Validación de cuenta requerida (403)", + "logs.detail.attempt.recovery.oauthAccount429": "Cuenta limitada (429)", + "logs.detail.attempt.recovery.oauthAccount402": "Cuota de cuenta agotada (402)", + "logs.detail.attempt.recovery.opaqueBlobRejection": "Estado cifrado estático caído", + "logs.detail.attempt.recovery.reasoningEffortDowngrade": "El esfuerzo de razonamiento degradado", + "logs.detail.attempt.recovery.anthropicFastDowngrade": "El modo rápido rechazó, intentó de nuevo a la velocidad estándar", + "logs.detail.outcome.label": "Resultado", + "logs.detail.outcome.completed": "Finalizado", + "logs.detail.outcome.failed": "Falló", + "logs.detail.outcome.incomplete": "Incompleta", + "logs.detail.outcome.aborted": "Abortado", + "logs.detail.sends.label": "Envíos ascendentes", + "logs.detail.sends.unavailable": "No disponible", + "logs.detail.retries.label": "Reintentos", + "logs.detail.sends.unresolved": "sin resolver", + "logs.detail.attempt.recovery.unknown": "Razón de recuperación desconocida", + "logs.detail.cause.label": "Causa del fracaso", + "logs.detail.stage.label": "alcanzado", + "logs.detail.resend.label": "Reenviar", + "logs.detail.cause.transportUnsent": "Nunca enviado upstream", + "logs.detail.cause.transportAmbiguous": "Conexión perdida, estado ascendente desconocido", + "logs.detail.cause.upstreamDeclined": "Proveedor de origen declinó comenzar", + "logs.detail.cause.rateLimit": "Límite de solicitudes alcanzado", + "logs.detail.cause.quotaExhausted": "Cuota agotada", + "logs.detail.cause.credentialRejected": "Credenciales rechazadas", + "logs.detail.cause.policyRefusal": "Rechazado por la política de contenido", + "logs.detail.cause.parameterRejected": "Parámetro de solicitud rechazado", + "logs.detail.cause.ciphertextRefusal": "Estado cifrado rechazado", + "logs.detail.cause.payloadTooLarge": "Carga útil demasiado grande", + "logs.detail.cause.payloadRejected": "Carga útil rechazada", + "logs.detail.cause.upstreamFault": "Falla de origen", + "logs.detail.cause.emptyOutput": "No hay salida utilizable", + "logs.detail.cause.clientCancelled": "Cancelado por el cliente", + "logs.detail.cause.localRefusal": "Rechazado por este proxy", + "logs.detail.stage.preHeader": "sin cabeza de respuesta", + "logs.detail.stage.headersOnly": "Solo encabezados", + "logs.detail.stage.protocolPrelude": "Preludio del protocolo", + "logs.detail.stage.semanticOutput": "salida entregada", + "logs.detail.stage.sideEffect": "efecto secundario emitido", + "logs.detail.stage.terminal": "Respuesta entregada", + "logs.detail.resend.permitted": "Podría ser resentido", + "logs.detail.resend.permittedAfterRepair": "Podría ser reenviado después de la reparación", + "logs.detail.resend.refusedAmbiguous": "No reenviado: estado ascendente desconocido", + "logs.detail.resend.refusedCommitted": "No reenviado: llamante ya vio salida", + "logs.detail.resend.refusedFutile": "No reenviar: la misma solicitud fallaría de nuevo", + "logs.detail.reason.usage_missing": "El uso no fue reportado.", + "logs.detail.reason.usage_unsupported": "Este proveedor no informa el uso.", + "logs.detail.reason.output_missing": "No se informó ningún recuento de token de salida positiva.", + "logs.detail.reason.invalid_duration": "La duración de la solicitud no es válida.", + "logs.detail.reason.price_unmatched": "No se encontró ningún precio.", + "logs.detail.reason.invalid_cache_breakdown": "Caché token detalles conflicto con la entrada total tokens.", + "logs.detail.reason.invalid_usage": "El uso contiene un valor token no válido.", + "logs.detail.reason.combo_attempt_unavailable": "No se pudo calcular el precio de al menos un intento upstream.", + "logs.detail.reason.credit_cost_unrepresentable": "No hay una lectura de créditos utilizable, o el importe no se puede calcular a partir del número de créditos y el precio unitario.", + "logs.detail.estimate.usage_estimated": "Se estima el uso del proveedor.", + "logs.detail.estimate.cache_detail_missing": "Los detalles de la caché no estaban disponibles; la entrada es una estimación del límite superior.", + "logs.detail.estimate.expected_price_overlay": "Se utilizó un precio de lista esperado verificado.", + "logs.detail.estimate.provider_cost_overlay": "Se utilizó una superposición de precios configurada por el proveedor.", + "logs.detail.estimate.priority_lower_bound": "El precio Prioridad confirmado no está disponible; la estimación mostrada es un límite inferior conocido.", + "logs.col.error": "Error", + "logs.col.upstreamReason": "Razón ascendente", + "logs.col.failureDetail": "Detalle del fallo", + "logs.detail.condition.authFailed": "Credenciales rechazadas", + "logs.detail.condition.accessDenied": "Acceso denegado", + "logs.detail.condition.contextOverflow": "Se superó la ventana de contexto", + "logs.detail.condition.locationUnsupported": "Ubicación no admitida", + "logs.detail.condition.accountVerificationRequired": "Se necesita verificar la cuenta", + "logs.detail.condition.billingExhausted": "Cuota o créditos agotados", + "logs.detail.condition.modelUnavailable": "Modelo no disponible", + "logs.detail.condition.rateLimited": "Límite de solicitudes alcanzado", + "logs.detail.condition.upstreamUnavailable": "Proveedor no disponible", + "logs.detail.condition.upstreamFailed": "Fallo del proveedor", + "logs.detail.condition.requestRejected": "Solicitud rechazada", + "logs.failureDetail.providerError": "El proveedor devolvió un error", + "logs.failureDetail.providerErrorTyped": "El proveedor devolvió un error ({type})", + "logs.failureDetail.headerTimeout": "Se agotó el tiempo de espera de los encabezados de respuesta", + "logs.failureDetail.headerTimeoutAfter": "Se agotó el tiempo de espera de los encabezados de respuesta tras {value} ms", + "logs.failureDetail.connectTimeout": "Se agotó el tiempo de conexión con el proveedor tras {value} ms", + "logs.failureDetail.connectFailed": "No se pudo conectar con el proveedor", + "logs.failureDetail.clientClosed": "El cliente cerró la solicitud", + "logs.failureDetail.bodyStall": "El cuerpo de la respuesta se detuvo durante {value} ms", + "logs.failureDetail.bodyOverflow": "El cuerpo de la respuesta superó {value} bytes", + "logs.failureDetail.streamErrorStop": "El proveedor terminó el turno con un error", + "logs.failureDetail.streamEndedEarly": "El flujo de respuesta terminó antes de su evento final", + "logs.failureDetail.streamFailed": "Falló el flujo de respuesta", + "logs.failureDetail.outputLimit": "La salida alcanzó el límite de tokens solicitado", + "logs.failureDetail.stallTimeout": "El proveedor no envió datos dentro del tiempo de espera por inactividad", + "logs.failureDetail.adapterEof": "El flujo del proveedor terminó sin un evento final", + "logs.failureDetail.generationTimeout": "El modelo enrutado no respondió en {value} ms", + "logs.failureDetail.turnInactivity": "El turno estuvo inactivo durante {value} ms", + "logs.col.duration": "Duración", + "logs.modelTooltip.model": "modelo", + "logs.modelTooltip.resolvedModel": "Modelo resuelto", + "logs.modelTooltip.servedModel": "Modelo servido", + "logs.modelTooltip.wireModel": "modelo de alambre", + "logs.modelRerouteTitle": "Proveedor de origen sirvió un modelo diferente al enviado", + "logs.modelTooltip.requestedTier": "solicitado nivel", + "logs.modelTooltip.configuredTier": "nivel configurado", + "logs.modelTooltip.responseTier": "Nivel de respuesta", + "logs.modelTooltip.supportsTier": "soporte de nivel", + "logs.modelTooltip.tierOutcome.confirmed": "confirmado", + "logs.modelTooltip.tierOutcome.assumed": "asumido", + "logs.modelTooltip.tierOutcome.downgraded": "degradado", + "logs.modelTooltip.tierOutcome.unknown": "Desconocido", + "logs.tokens.reported": "comunicado", + "logs.tokens.unreported": "no declarado", + "logs.tokens.unsupported": "sin soporte", + "logs.tokens.estimated": "estimados", + "logs.tokens.input": "entrada", + "logs.tokens.output": "salida", + "logs.tokens.cacheRead": "lectura de caché (c)", + "logs.tokens.cacheWrite": "Escritura en caché (w)", + "logs.tokens.reasoning": "razonamiento", + "logs.tokens.noCache": "sin datos de caché", + "logs.tokens.contextTotal": "contexto activo", + "logs.tokens.noCacheNote": "este proveedor no reporta caché tokens", + "logs.tokens.noCacheCursor": "Cursor detalle de caché no reportado", + "logs.tokens.noCacheCursorNote": "Cursor no expone la cantidad de tokens de lectura y escritura de caché; el estado es desconocido y no confirma un fallo de caché.", + "logs.tokens.estimatedNote": "estimado (proveedor informa sin uso exacto)", + "logs.details": "Detalles", + "logs.detailTitle": "Solicitar detalles", + "logs.detailRaw": "Entrada de registro en bruto", + + "debug.title": "Depurar", + "debug.subtitle": "Opt-in proveedor de transporte y uso de extracción de diagnósticos. Los errores de solicitud y 502 permanecen en la pestaña Registros.", + "debug.debug": "Depuración del proveedor", + "debug.usage": "Extracción de uso", + "debug.injection": "Registro de inyección", + "debug.claude": "Claude entrante", + "debug.claudeInbound.title": "Claude solicitudes entrantes", + "debug.claudeInbound.sub": "Lo que Claude Code/Desktop realmente envía (pensamiento, esfuerzo, metadatos) — no se almacena texto de solicitud.", + "debug.claudeInbound.empty": "No hay solicitudes capturadas todavía. Envía un mensaje desde Claude mientras esto está activado.", + "debug.claudeInbound.time": "Hora", + "debug.claudeInbound.endpoint": "Punto de conexión", + "debug.claudeInbound.model": "Modelo", + "debug.claudeInbound.none": "ninguno", + "debug.reset": "Borrar anulaciones de tiempo de ejecución", + "debug.refresh": "Actualizar", + "debug.follow": "Seguir", + "debug.streamProvider": "Proveedor", + "debug.streamUsage": "Uso", + "debug.streamInjection": "Inyección", + "debug.loading": "Cargar configuración de depuración…", + "debug.loadFailed": "No se pudo cargar la configuración de depuración.", + "debug.emptyTitle": "El registro de depuración está desactivado", + "debug.empty": "Activa la depuración del proveedor o la extracción de uso en la tarjeta anterior. Las líneas aparecen aquí después de enviar una solicitud a través del proxy.", + "debug.noLinesTitle": "Esperando las líneas", + "debug.noLines.provider": "La depuración del proveedor está activada, pero solo registra anomalías de transporte (cuadros caídos o mal formados, y eventos de dial/retry Cursor). Una solicitud limpia a través de un proveedor como Anthropic no puede producir líneas.", + "debug.noLines.usage": "La extracción de uso está activada, pero aún no se ha capturado nada. Envíe un chat/solicitud a través de Codex y aparecerá aquí.", + "debug.noLines.injection": "El registro de inyección está activado, pero aún no se ha capturado nada. Registra las decisiones de inyección de guía multiagente y límite de esfuerzo en turnos de colaboración y subagente.", + + "usage.title": "Uso", + "usage.subtitle": "Contabilidad local token desde su proxy. El uso ausente nunca se muestra como cero.", + "usage.loading": "Cargando datos de uso…", + "usage.empty": "No hay uso registrado todavía. Envíe una solicitud a través del proxy para ver la actividad aquí.", + "usage.loadError": "No se pudo cargar los datos de uso.", + "usage.range.all": "Todos", + "usage.range.available": "Historial disponible", + "usage.historyTruncated": "Los totales cubren el historial disponible solo porque no se cargó el uso anterior.", + "usage.historyTruncatedWindow": "Las filas cargadas tienen tiempos de inicio de solicitud que van desde {start} a {end}. Las entradas de archivo anteriores se omitieron por el límite de lectura, por lo que cualquier rango seleccionado puede estar incompleto.", + "usage.range.30d": "30d", + "usage.range.7d": "7d", + "usage.card.requests": "Solicitudes", + "usage.card.measured": "Medidos", + "usage.card.reported": "Denunciado", + "usage.card.totalTokens": "Tokens totales", + "usage.card.cachedTokens": "Caché lee", + "usage.card.cachedTokensHint": "El indicador tokens se sirve desde la caché del proveedor (lecturas). Las escrituras en caché se muestran a continuación cuando están presentes.", + "usage.card.cacheWriteTokens": "cache escribe", + "usage.card.coverage": "Cobertura", + "usage.card.activeDays": "Días activos", + "usage.section.heatmap": "Actividad diaria", + "usage.section.overview": "Descripción general", + "usage.section.models": "Modelos", + "usage.section.providers": "Proveedores", + "usage.section.coverage": "Desglose de la cobertura", + "usage.section.companion": "Barra de menú & widget", + "usage.companion.title": "Barra de menú & widget", + "usage.companion.description": "La configuración aquí impulsa la aplicación de escritorio / barra de menú OpenCodex y su widget.", + "usage.companion.installGuide": "Guía de instalación", + "usage.companion.loading": "Cargando línea de tiempo…", + "usage.companion.timelineUnavailable": "Línea de tiempo no disponible", + "usage.companion.empty": "No hay uso en el último {hours}h", + "usage.companion.chartLabel": "Línea de tiempo de uso", + "usage.companion.olderRecordsSkipped": "Los récords más antiguos se han saltado", + "usage.companion.settingsUnavailable": "Configuración complementaria no disponible", + "usage.companion.corrupt": "El archivo de configuración complementario está dañado. Los controles muestran los valores predeterminados; el guardado se pone en pausa hasta que reemplace el archivo.", + "usage.companion.corruptReset": "Reemplazar con valores predeterminados", + "usage.companion.connected": "Aplicación de barra de menús conectada · {age}", + "usage.companion.connectedDesktop": "Aplicación de escritorio conectada · {age}", + "usage.companion.installTitle": "Instalar la aplicación de escritorio", + "usage.companion.installOs": "Sistema operativo", + "usage.companion.osMac": "macOS", + "usage.companion.osWindows": "Windows", + "usage.companion.osLinux": "Linux", + "usage.companion.runningInDesktop": "Usted está en el OpenCodex aplicación de escritorio {version}", + "usage.companion.openInBrowser": "Abrir en el navegador", + "usage.companion.installMacStep1": "Descargue OpenCodex- .version>-macos.dmg desde la última versión y arrastre OpenCodex.app a Aplicaciones.", + "usage.companion.installMacStep2": "Primer inicio: haz clic derecho en OpenCodex.app → Abrir (Gatekeeper lo pide una vez mientras la aplicación no esté notarizada).", + "usage.companion.installMacStep3": "La aplicación encuentra este proxy por su cuenta; el widget aparece en la galería de widgets una vez que la aplicación se ha ejecutado.", + "usage.companion.installWinStep1": "Descargue OpenCodex- .versión>-windows-x64.msi de la última versión y ejecútelo.", + "usage.companion.installWinStep2": "Si SmartScreen advierte, elija Más información → Ejecutar de todos modos (el instalador aún no está firmado por código).", + "usage.companion.installWinStep3": "OpenCodex aparece en la bandeja del sistema y se conecta a este proxy, o inicia el incluido.", + "usage.companion.installLinuxStep1": "Descargar OpenCodex- .versión>-linux-x86_64.AppImage (o el .deb) de la última versión.", + "usage.companion.installLinuxStep2": "chmod +x la AppImage y ejecutarlo; un icono de bandeja requiere un escritorio con capacidad AppIndicator.", + "usage.companion.installLinuxStep3": "La aplicación se conecta a este proxy, o inicia su uno incluido.", + "usage.companion.notConnected": "Ninguna aplicación de la barra de menús se ha conectado a este proxy todavía.", + "usage.companion.lastSeen": "Visto por última vez {age}", + "usage.companion.installAnother": "Instalar en otro dispositivo", + "usage.companion.saved": "Guardado · {time}", + "usage.companion.saveFailed": "No se pudo guardar: {error}", + "usage.companion.reset": "Restablecer a los valores predeterminados", + "usage.companion.footer": "El widget muestra las solicitudes de hoy, tokens y el costo más el gráfico configurado aquí, y se actualiza cuando la aplicación sondea.", + "usage.companion.menuBarShows": "Muestra la barra de menús", + "usage.companion.menuRequests": "Solicitudes", + "usage.companion.menuTokens": "Tokens", + "usage.companion.menuCost": "Coste", + "usage.companion.menuQuota": "Contingente", + "usage.companion.menuNone": "Iconos solamente", + "usage.companion.window": "Ventana", + "usage.companion.window6": "6h", + "usage.companion.window24": "24h", + "usage.companion.window72": "3d", + "usage.companion.window168": "7d", + "usage.companion.style": "Estilo", + "usage.companion.styleLine": "Línea", + "usage.companion.styleStacked": "Apiladas", + "usage.companion.metric": "Métrica", + "usage.companion.metricTotal": "Total", + "usage.companion.metricInput": "Entrada", + "usage.companion.metricOutput": "Salida", + "usage.companion.metricCached": "En caché", + "usage.companion.groupBy": "Grupo por", + "usage.companion.groupModel": "Modelo", + "usage.companion.groupAccount": "Modelo + cuenta", + "usage.companion.popoverSections": "Secciones popover", + "usage.companion.sectionToday": "Hoy", + "usage.companion.sectionChart": "Gráfico", + "usage.companion.sectionModels": "Modelos", + "usage.companion.sectionCost": "Coste", + "usage.companion.sectionAccounts": "Cuentas", + "usage.companion.advanced": "Avanzado", + "usage.companion.aggregation": "Agregación", + "usage.companion.aggregationSum": "Suma", + "usage.companion.aggregationAverage": "Promedio", + "usage.companion.aggregationMax": "Máx.", + "usage.companion.menuText": "Texto de la barra de menú", + "usage.companion.placeholders": "Marcadores de posición:", + "usage.companion.modelsOnChart": "Modelos en el gráfico", + "usage.companion.modelsCount": "{selected} de {total} en el gráfico", + "usage.companion.modelsShowAll": "Mostrar todo", + "usage.companion.hideProviders": "Ocultar proveedores", + "usage.workspace.report": "Informe de uso", + "usage.workspace.sections": "Secciones de uso", + "usage.coverage.measured": "Medidos", + "usage.coverage.reported": "Proveedor informó", + "usage.coverage.estimated": "Estimaciones", + "usage.coverage.note": "Las entradas medidas incluyen recuentos de tokens informados por el proveedor o estimados. Se registran las solicitudes sin datos informados o sin medición compatible, pero nunca se les atribuyen cero tokens.", + "usage.search.models": "Buscar modelos…", + "usage.col.requests": "Solicitudes", + "usage.col.measured": "Medidos", + "usage.col.reported": "Denunciado", + "usage.col.inputTokens": "Entrada tokens", + "usage.col.outputTokens": "Salida tokens", + "usage.col.tokPerSec": "Tok/s de salida", + "usage.col.cacheHits": "Caché hits", + "usage.col.cacheWrites": "Caché escribe", + "usage.col.cacheHitRate": "Tasa de éxito", + "usage.throughput.title": "Rendimiento de salida de extremo a extremo: suma de los tokens de salida dividida entre la suma del tiempo transcurrido en {samples} intentos medidos. Incluye la espera anterior a la decodificación, por lo que resulta menor que la velocidad de decodificación sostenida; se excluyen las solicitudes sin tokens o duración medidos.", + "usage.throughput.unmeasured": "Ninguna solicitud para esta fila informó tanto la salida tokens como la duración, por lo que no hay rendimiento promedio.", + "usage.cacheHitRate.partial": "Promedio calculado sobre {measured} de los {total} tokens de entrada; las solicitudes restantes no informaron detalles de caché.", + "usage.cacheHitRate.unmeasured": "Ninguna solicitud para esta fila informó detalles de caché, por lo que no hay tasa de aciertos promedio.", + "usage.unavailable": "—", + "usage.col.tokens": "Tokens", + "usage.col.apiListPrice": "API lista-precio", + "usage.col.share": "Compartir", + "usage.heatmap.less": "Menos", + "usage.heatmap.more": "Más", + "usage.dayMon": "Lun", + "usage.dayWed": "Mierda", + "usage.dayFri": "Vie", + "usage.heatmap.tooltipTokens": "{tokens} tokens", + "usage.chart.dayDetail": "{date}: {requests} solicitudes, {tokens} tokens", + "usage.heatmap.keyboardLabel": "Usar arriba y abajo para moverse durante el día; Izquierda y derecha para moverse por semana.", + "usage.heatmap.tooltipRequests": "Solicitudes {requests}", + + "nav.storage": "Almacenamiento", + "storage.title": "Almacenamiento", + "storage.subtitle": "Vea lo que está usando CODEX_HOME. La limpieza nunca toca las sesiones activas.", + "storage.loading": "Almacenamiento de escaneo…", + "storage.empty": "CODEX_HOME está vacía o le falta — nada que informar.", + "storage.error": "Se ha producido un error en el análisis de almacenamiento. Comprueba que CODEX_HOME apunta a un directorio válido.", + "storage.refresh": "Volver a analizar", + "storage.rescanned": "Escanear completo.", + "storage.card.total": "Tamaño total", + "storage.card.files": "Archivos", + "storage.card.home": "CODEX_HOME", + "storage.snapshot.lastScan": "Ultima exploración", + "storage.snapshot.scanning": "Escaneo…", + "storage.snapshot.unavailable": "Aún no hay escáner.", + "storage.cleanupCard.title": "Libera espacio", + "storage.cleanupCard.tabs": "Opciones de limpieza", + "storage.cleanupCard.tab.policy": "Política", + "storage.cleanupCard.tab.quarantine": "Cuarentena", + "storage.cleanup.noArchives": "No hay sesiones archivadas para limpiar.", + "storage.section.buckets": "Categorías", + "storage.section.largest": "Los archivos más grandes", + "storage.workspace.overview": "Descripción general", + "storage.workspace.selectBucket": "Selecciona un depósito de la lista para ver su desglose.", + "storage.col.bucket": "Cubo", + "storage.col.size": "Tamaño", + "storage.col.files": "Archivos", + "storage.col.oldest": "Los más antiguos", + "storage.col.newest": "Lo más reciente", + "storage.col.rows": "Filas de DB", + "storage.rows.unknown": "desconocido (bloqueado)", + "storage.bucket.sessions": "Sesiones activas", + "storage.bucket.archived_sessions": "Sesiones archivadas", + "storage.bucket.logs_db": "Base de datos de registros", + "storage.bucket.state_db": "Base de datos estatal", + "storage.bucket.attachments": "Adjuntos", + "storage.bucket.deletion_manifests": "Manifestaciones de eliminación", + "storage.bucket.other": "Otros", + "storage.cleanup.title": "Limpieza archivada", + "storage.cleanup.help": "Elimina las sesiones archivadas más antiguas por porcentaje. Las sesiones activas nunca se tocan. La cuarentena es el valor predeterminado de los archivos — que se mueven a CODEX_HOME/.trash.", + "storage.cleanup.slider": "El porcentaje más antiguo archivado", + "storage.cleanup.percent": "{percent}%", + "storage.cleanup.preset": "{percent}", + "storage.cleanup.preview": "Vista previa", + "storage.cleanup.confirmTitle": "Confirmar la limpieza archivada", + "storage.cleanup.confirmBody": "Esto procesará los archivos {count} archivados (~{size}), el {percent}% más antiguo.", + "storage.cleanup.moreFiles": "…y {n} más", + "storage.cleanup.permanent": "Eliminar permanentemente (saltar la cuarentena)", + "storage.cleanup.permanentWarn": "El borrado permanente no se puede deshacer.", + "storage.cleanup.quarantineNote": "Los archivos se mueven a .trash bajo CODEX_HOME. Puede restaurarlos desde la pestaña Cuarentena.", + "storage.cleanup.cancel": "Cancelar", + "storage.cleanup.confirmQuarantine": "Cuarentena", + "storage.cleanup.confirmPermanent": "Eliminar permanentemente", + "storage.cleanup.doneQuarantine": "Archivo(s) {count} en cuarentena ({size}).", + "storage.cleanup.donePermanent": "Borrado permanentemente archivo(s) {count} ({size}).", + "storage.cleanup.skippedReferenced": "Omitir archivo(s) de referencia {count}.", + "storage.cleanup.previewFailed": "Fallo de vista previa.", + "storage.cleanup.cleanupFailed": "La limpieza falló.", + "storage.cleanup.err.codex_busy": "Codex está usando state.sqlite. Cierra Codex y vuelve a intentarlo.", + "storage.cleanup.err.stale_preview": "Archivos archivados cambiados desde la vista previa — ejecutar Vista previa de nuevo.", + "storage.cleanup.err.restore_pending_overlap": "Los archivos seleccionados se superponen a una restauración de basura incompleta. Finalización — o restauración de reintento primero.", + "storage.cleanup.err.referenced_history": "Los archivos seleccionados todavía tienen referencias en el historial bifurcado o paginado.", + "storage.cleanup.err.invalid_digest": "El resumen de vista previa no está disponible o no es válido.", + "storage.cleanup.err.invalid_mode": "El modo de limpieza debe ser en cuarentena o permanente.", + "storage.cleanup.err.fs_failed": "Error en la limpieza del sistema de archivos. Es posible que ya se hayan aplicado algunos cambios — comprobar CODEX_HOME/.trash y cualquier ruta de recuperación mostrada.", + "storage.cleanup.err.fs_failed_trash": "Error en la limpieza del sistema de archivos. Algunos cambios ya se pueden aplicar — comprobar {trashDir} y manifest.json para los archivos recuperables.", + "storage.cleanup.err.db_reconcile_failed": "No se pudo actualizar la base de datos de estado Codex.", + "storage.cleanup.err.cleanup_failed": "La limpieza falló.", + + "storage.trash.title": "Cuarentena", + "storage.trash.help": "Las sesiones archivadas se trasladaron a CODEX_HOME/.trash. Restaurar pone archivos JSONL y filas de hilo hacia atrás.", + "storage.trash.empty": "No hay entradas en cuarentena.", + "storage.trash.loading": "Cargando cuarentena…", + "storage.trash.col.when": "Cuarentena", + "storage.trash.col.files": "Archivos", + "storage.trash.col.size": "Tamaño", + "storage.trash.col.mode": "Modo", + "storage.trash.col.id": "Entrada", + "storage.trash.restore": "Restaurar", + "storage.trash.confirmTitle": "¿Restaurar la entrada en cuarentena?", + "storage.trash.confirmBody": "Restaurar {count} archivo(s) (~{size}) desde {id} Volver a las sesiones archivadas.", + "storage.trash.cancel": "Cancelar", + "storage.trash.confirmRestore": "Restaurar", + "storage.trash.done": "Restaurado archivo(s) {count} ({size}).", + "storage.trash.restoreFailed": "La restauración falló.", + "storage.trash.listFailed": "No se pudo enumerar las entradas de cuarentena.", + "storage.trash.mode.quarantine": "cuarentena", + "storage.trash.mode.permanent": "permanente (incompleta)", + "storage.trash.err.codex_busy": "Codex está usando state.sqlite. Cierra Codex y vuelve a intentarlo.", + "storage.trash.err.invalid_trash": "El id de entrada de la basura no está disponible o es inválido.", + "storage.trash.err.missing_trash": "No se encontró la entrada de basura.", + "storage.trash.err.dest_exists": "Restaurar destino ya existe — eliminar o cambiar el nombre del archivo archivado y volver a intentar.", + "storage.trash.err.fs_failed": "Error en la restauración del sistema de archivos. Algunos archivos ya se pueden restaurar — comprobar archived_sessions y .trash.", + "storage.trash.err.db_reconcile_failed": "No se pudo restaurar las filas de la base de datos de estado Codex.", + "storage.trash.err.storage_mutation_busy": "Otra limpieza o restauración de almacenamiento está en curso. — vuelva a intentarlo en breve.", + "storage.trash.err.restore_failed": "La restauración falló.", + "storage.trash.err.restore_worker_timeout": "La restauración tomó demasiado tiempo (más de 10 minutos) y se detuvo.", + "storage.trash.err.restore_worker_aborted": "La restauración fue cancelada durante el cierre.", + "storage.trash.err.restore_worker_failed": "El trabajador de restauración se estrelló o falló inesperadamente.", + "storage.policy.title": "Política de autolimpieza", + "storage.policy.help": "Limpieza por lotes opcional cuando las sesiones archivadas superan un umbral. Desactivado por defecto — nunca habilitado automáticamente.", + "storage.policy.loading": "Política de carga…", + "storage.policy.loadFailed": "No se pudo cargar la política de limpieza.", + "storage.policy.saveFailed": "No se pudo guardar la política de limpieza.", + "storage.policy.runFailed": "La ejecución de la política falló.", + "storage.policy.alreadyRunning": "Una política de limpieza ya está en marcha.", + "storage.policy.invalid": "Valores de política no válidos.", + "storage.policy.enabled": "Habilitar la limpieza automática", + "storage.policy.enabledHint": "El valor predeterminado está desactivado. Habilitar se ejecuta solo en el horario que elija (o Ejecutar ahora).", + "storage.policy.threshold": "Cuando el tamaño de archivo excede (GiB)", + "storage.policy.trigger": "Desencadenante", + "storage.policy.target": "Objetivo de limpieza", + "storage.policy.targetPercent": "Eliminar el archivo más antiguo (%)", + "storage.policy.targetReduce": "Reducir el tamaño archivado a (GiB)", + "storage.policy.thresholdInc": "Aumentar el umbral", + "storage.policy.thresholdDec": "Reducir el umbral", + "storage.policy.percentInc": "Aumentar por ciento", + "storage.policy.percentDec": "Disminución porcentual", + "storage.policy.reduceInc": "Aumentar el tamaño reducido", + "storage.policy.reduceDec": "Disminuir el tamaño", + "storage.policy.schedule": "Calendario", + "storage.policy.schedule.manual": "Solo manual", + "storage.policy.schedule.startup": "Al iniciar proxy", + "storage.policy.schedule.daily": "Diario", + "storage.policy.schedule.weekly": "Semanal", + "storage.policy.mode": "Modo de eliminación", + "storage.policy.mode.quarantine": "Cuarentena (predeterminado)", + "storage.policy.mode.permanent": "Eliminación permanente", + "storage.policy.permanentWarn": "El modo permanente no se puede deshacer. Prefiere la cuarentena a menos que esté seguro.", + "storage.policy.lastRun": "Última ejecución", + "storage.policy.lastRunDetail": "Eliminado {count} · liberado {size}", + "storage.policy.nextRun": "Próxima ejecución", + "storage.policy.never": "Nunca", + "storage.policy.save": "Guardar", + "storage.policy.runNow": "Ejecutar ahora", + "storage.policy.running": "En ejecución…", + "storage.policy.saved": "Política salvada.", + "storage.policy.skippedDisabled": "La política está desactivada — Habilitarlo primero.", + "storage.policy.skippedUnder": "El tamaño archivado está por debajo del umbral — nada que hacer.", + "storage.policy.skippedEmpty": "No hay candidatos archivados que coincidan con el objetivo.", + "storage.policy.doneQuarantine": "Política de archivos {count} en cuarentena ({size}).", + "storage.policy.donePermanent": "Política de borrado permanente archivo(s) {count} ({size}).", + "storage.policy.metadataSaveWarning": "La ejecución de la directiva terminó, pero sus metadatos de programación no se pudieron guardar.", + + "modal.addNamed": "Añadir: {label}", + "modal.add": "Añadir proveedor", + "modal.search": "Buscar proveedores…", + "modal.logInWith": "Iniciar sesión con {label}", + "modal.sharedLoginNote": "{label} inicia sesión con tu inicio de sesión de {provider}. Un mismo inicio de sesión sirve a ambos proveedores, así que cerrar sesión de {provider} o cambiar sus cuentas afecta a los dos.", + "modal.addWithExistingLogin": "Añadir {label} con tu inicio de sesión de {provider}", + "modal.waitingBrowser": "Esperando a browser…", + "modal.providerName": "Nombre del proveedor", + "modal.adapter": "Adaptador", + "modal.baseUrl": "URL base", + "modal.endpoint": "Punto de conexión", + "modal.endpoint.tokenPlan": "Plan de tokens", + "modal.endpoint.payAsYouGo": "Paga como quieras", + "modal.endpoint.custom": "Personalizado", + "modal.defaultModel": "Modelo predeterminado (opcional)", + "modal.allowPrivateNetwork": "Permitir redes locales/privadas", + "modal.allowPrivateNetworkHint": "Habilitar solo para proveedores autoalojados intencionalmente. Los metadatos permanecen bloqueados.", + "modal.nameRequired": "Nombre del proveedor es obligatorio", + "modal.baseUrlRequired": "Base URL es necesario", + "modal.networkError": "Error de red — ¿Está funcionando el proxy?", + "modal.loginFailStart": "Inicio de sesión no pudo iniciar", + "modal.waitingLogin": "Esperando el inicio de sesión del navegador…", + "modal.loggingIn": "Registro en…", + "modal.loginTimeout": "Inicio de sesión agotado — intentarlo de nuevo.", + "modal.back": "Atrás", + "modal.badge.oauth": "OAuth", + "modal.customProvider": "Proveedor personalizado", + "modal.failedStatus": "Fallo ({status})", + "modal.loginError": "Error de inicio de sesión: {error}", + "modal.badge.codexLogin": "Codex inicio de sesión", + "modal.badge.local": "Local", + "modal.badge.apiKey": "Clave API", + "modal.badge.direct": "Direct", + "modal.badge.pool": "Pool", + "modal.badge.free": "Libre", + "modal.badge.sponsor": "Patrocinador", + "modal.badge.subscriptionCli": "Suscripción CLI", + "pws.sponsor.orcaTitle": "Un modelo para cada prontitud", + "pws.sponsor.orcaDescription": "Una pasarela compatible con OpenAI con enrutamiento adaptativo y conmutación por error automática.", + "pws.sponsor.tokenlabTitle": "Una llave API para los modelos líderes", + "pws.sponsor.tokenlabDescription": "Responses, Chat Completions, transmisión y llamada de herramientas para agentes de codificación, con su elección del modo de entrega y facturación de pago por uso.", + "pws.sponsor.visit": "Explora {provider}", + "pws.sponsor.console": "Abrir consola", + "modal.invalidPreset": "Este preajuste de proveedor integrado está incompleto. Reinicia el proxy y vuelva a intentarlo.", + "modal.freeTierTitle": "Nivel libre", + "modal.subscriptionCliTitle": "Suscripción CLI, no una clave API", + "modal.subscriptionCliWarning": "Este proveedor no usa una clave API. Controla el {cli} oficial con sesión iniciada en este equipo ({cmd}) y factura a esa cuenta de suscripción de {plan}. OpenCodex no guarda ninguna clave para él, y una clave introducida aquí nunca se usa. Para facturar con clave API, añade {apiProvider} en su lugar.", + "modal.subscriptionCliWarningAgy": "Este proveedor usa la CLI oficial de Antigravity con sesión iniciada en el host del proxy ({cmd}). El uso se factura a esa cuenta de Google Antigravity. Google solo permite un uso interactivo dirigido por el usuario. OpenCodex rechaza los turnos de subagentes, los combos y el enrutamiento de respaldo de subagentes, y comprueba la localidad a partir de la conexión que ve. Un relay de loopback no declarado puede hacer que las solicitudes remotas parezcan locales si no envía encabezados de reenvío. Para el listener público, declara el proxy inverso en dashboardTrustedProxy o mantén este puerto fuera del relay. No se necesita ni se guarda ninguna clave API. Para cargas programáticas o compartidas, añade {apiProvider} en su lugar.", + "modal.freeTierDefault": "No se requiere ninguna tecla API. Trabaja fuera de la caja.", + "modal.tab.accounts": "Cuentas", + "modal.tab.free": "Libre", + "modal.tab.local": "Local", + "modal.tab.paid": "Pagado", + "modal.noteMore": "Mostrar descripción completa", + "modal.searchResults": "Resultados de {count} en {tiers}", + "modal.accountsHint": "Inicie sesión en las cuentas de ChatGPT/Codex, los proveedores de OAuth y las cuentas clave de API aquí. OpenAI está construido en el registro — en lugar de agregarlo nuevamente.", + "modal.accountsCodexAuthLink": "Codex Autonomía", + "modal.notListed": "¿Proveedor no listado? Agregar un archivo personalizado", + "modal.catalogLoading": "Cargando catálogo…", + "modal.accountLogin": "Iniciar sesión", + "modal.accountLogout": "Cerrar sesión", + "modal.accountAdd": "Añadir cuenta", + "modal.accountManage": "Administrar", + "modal.accountCodexPool": "Grupo de cuentas ChatGPT", + "modal.accountLoggedIn": "Conectado", + "modal.accountLoggedOut": "No ha iniciado sesión", + "quota.fiveHourLimit": "Límite de 5 horas", + "quota.ageMinutes": "{n}m", + "quota.ageHours": "{n}h", + "quota.ageDays": "{n}d", + "quota.observedAgo": "Observado {age} hace", + "quota.observedHint": "Meta informa el uso solo durante una respuesta de transmisión, por lo que este es el último valor visto, no una lectura en vivo.", + "quota.weeklyLimit": "Límite semanal", + "quota.monthlyLimit": "Límite de 30 días", + "quota.cursorFirstParty": "Modelos propios", + "quota.cursorApiUsage": "Uso de API", + "quota.totalSubscriptionCredits": "Total de créditos de suscripción", + "quota.workbuddy.amount": "{amount} créditos", + "quota.workbuddy.usage": "Usados: {used} de {total} créditos", + "quota.workbuddy.plan_base": "Créditos base del plan", + "quota.workbuddy.plan_bonus": "Créditos extra del plan", + "quota.workbuddy.addon": "Créditos de recarga", + "quota.workbuddy.benefit": "Créditos de regalo", + "quota.workbuddy.other": "Otros créditos", + "quota.workbuddy.frozen": "Créditos reservados", + "quota.workbuddy.expiring": "{amount} créditos vencen el {date}", + "quota.creditsBalance": "Saldo de créditos", + "quota.creditsPeriodEnds": "El período de facturación finaliza {date}", + "quota.usedPercent": "{pct}% usado", + "quota.weeklyShare": "Hasta el {pct} % de tu límite semanal", + "quota.notInEffect": "No está vigente", + "quota.notInEffectHint": "Claude informa que este límite no restringe el uso en este momento. Se muestra como referencia; el routing de cuentas solo usa los límites vigentes.", + "quota.limitReached": "Límite alcanzado", + "quota.resetsToday": "Restablecimientos hoy en {time}", + "quota.resetsTomorrow": "Restablece mañana en {time}", + "quota.resetsAt": "Restablece {when}", + "quota.resetsRelativeMinutes": "Restablecimientos en {n} min", + "quota.resetsRelativeHours": "Restablecimientos en {n} h", + "pws.status.ready": "Listo", + "pws.status.needsSetup": "Necesita configuración", + "pws.status.needsAttention": "Necesita atención", + "pws.auth.chatgptPassthrough": "Paso ChatGPT", + "pws.auth.noKey": "No se necesita ninguna clave", + "pws.freeTitle": "Precio gratuito (una clave todavía puede ser necesaria)", + "pws.localTitle": "Tiempo de ejecución local", + "pws.modelCountOne": "1 modelo", + "pws.modelCount": "{count} modelos", + "pws.rail.suffixDefault": " · por defecto", + "pws.rail.suffixLocal": " · local", + "pws.rail.suffixFree": " · gratis", + "pws.rail.selectAria": "Seleccionar {name} — {status}{suffix}", + "pws.searchPlaceholder": "Buscar proveedores…", + "pws.filterAria": "Filtrar proveedores", + "pws.providerFiltersAria": "Filtros de proveedores", + "pws.filters": "Filtros", + "pws.filterStatus": "Estado", + "pws.pricing": "Precios", + "pws.paid": "Pagado", + "pws.filterType": "Tipo", + "pws.type.cloud": "Nube", + "pws.type.local": "Local", + "pws.type.selfHosted": "Auto-alojado", + "pws.type.login": "Inicio de sesión", + "pws.sort": "Ordenar", + "pws.sortProvidersAria": "Ordenar proveedores", + "pws.sort.az": "A–Z", + "pws.sort.za": "Z–A", + "pws.sort.freePaid": "Libre primero", + "pws.sort.paidFree": "Pagado primero", + "pws.sort.accountsFirst": "Cuentas primero", + "pws.resetAll": "Restablecer todo", + "pws.providerList": "Lista de proveedores", + "pws.providersAria": "Proveedores", + "pws.groupReady": "Listo ({count})", + "pws.groupNeedsSetup": "Necesita configuración ({count})", + "pws.groupDisabled": "Deshabilitado ({count})", + "pws.noSearchResults": "No hay proveedores que coincidan con su búsqueda.", + "pws.noMatchFilters": "Ningún proveedor coincide con los filtros.", + "pws.noProvidersConfigured": "No hay proveedores configurados.", + "pws.workspaceMainAria": "Detalles del proveedor", + "pws.detailComingSoon": "La vista de detalle próximamente — utiliza la vista clásica para administrar este proveedor.", + "pws.selectPrompt": "Selecciona un proveedor de la lista.", + "pws.connectFirst": "Conecta a tu primer proveedor", + "pws.empty.browseFree": "Navegar por proveedores gratuitos", + "pws.empty.browseFreeDesc": "Comience sin una suscripción", + "pws.empty.connectAccount": "Conectar una cuenta", + "pws.empty.connectAccountDesc": "Usa su ChatGPT o inicio de sesión del proveedor", + "pws.empty.addEndpoint": "Agregar un punto final", + "pws.empty.addEndpointDesc": "Base personalizada URL y API clave", + "pws.tab.overview": "Descripción general", + "pws.tab.models": "Modelos", + "pws.tab.usage": "Uso", + "pws.tab.accounts": "Cuentas", + "pws.tab.settings": "Configuración", + "pws.connection": "Conexión", + "pws.status.connected": "Conectado", + "pws.attentionTitle": "Necesita atención", + "pws.attention.reauth": "La cuenta activa necesita una nueva autenticación", + "pws.attention.reauthForward": "Activo Codex cuenta necesita re-autenticación — Abrir cuentas para arreglarlo", + "pws.attention.missingCredentials": "Faltan credenciales", + "pws.cell.auth": "Autenticación", + "pws.cell.note": "Nota", + "pws.cell.defaultModel": "Modelo predeterminado", + "pws.statsAria": "Estadísticas de proveedores", + "pws.statsTitle": "Estadísticas", + "pws.stats.totalRequests": "Solicitudes (30d)", + "pws.stats.totalTokens": "Tokens (30d)", + "pws.stats.quotaUpdated": "Cuota actualizada", + "pws.stats.quotaTracked": "Límites de velocidad rastreados en la pestaña Uso.", + "pws.stats.source": "Fuente", + "pws.usageLast30d": "Uso (últimos 30 días)", + "pws.estimatedCost": "Coste estimado", + "pws.costDisclaimer": "API estimación de precio de lista, no un cargo real.", + "pws.unresolvedRequestedModel": "Incluye el uso del modelo solicitado no resuelto", + "pws.currentAccountUsage": "Uso de la cuenta corriente", + "pws.quotaUnsupported": "No se admite la búsqueda de cuotas para esta cuenta.", + "pws.quotaUnobserved": "No hay observación de uso todavía.", + "pws.quotaLastRead": "Última lectura", + "pws.quotaCheckCompleted": "Control de cuotas completado", + "pws.modelBreakdown": "Desglose del modelo", + "pws.col.model": "Modelo", + "pws.col.cost": "Coste est.", + "pws.col.tokens": "Tokens", + "pws.col.requests": "Req.", + "pws.col.share": "Compartir", + "pws.tokenInput": "Entrada", + "pws.tokenOutput": "Salida", + "pws.metricRequests": "solicitudes", + "pws.metricTokens": "tokens", + "pws.usageUnavailable": "No hay uso registrado todavía.", + "pws.rateLimits": "Límites de solicitudes", + "pws.quotaUnavailable": "No hay datos de cuota para este proveedor.", + "pws.accountQuotaUnavailable": "Los datos de límite de velocidad no están disponibles temporalmente; mostrando los últimos valores conocidos cuando están presentes.", + "pws.quotaFailure.account_unavailable": "Los detalles de la cuenta no están disponibles para esta verificación de cuota.", + "pws.quotaFailure.access_denied": "El proveedor denegó el acceso a los datos de cuota.", + "pws.quotaFailure.rate_limited": "El proveedor limitó la comprobación de cuotas.", + "pws.quotaFailure.upstream_error": "El proveedor no pudo completar la verificación de cuotas.", + "pws.quotaFailure.redirect_blocked": "El punto final de la cuota devolvió una redirección bloqueada.", + "pws.quotaFailure.destination_blocked": "El destino de la cuota fue bloqueado por la política de red.", + "pws.quotaFailure.dns_failed": "No se pudo resolver el nombre de host de la cuota.", + "pws.quotaFailure.timeout": "La solicitud de cuota se agotó.", + "pws.quotaFailure.transport_error": "La conexión de cuota falló.", + "pws.quotaFailure.response_unusable": "El proveedor devolvió datos de cuota inutilizables.", + "pws.selected": "Seleccionado", + "pws.copyModelId": "Copiar ID", + "pws.modelCopied": "¡Copiado!", + "pws.modelsAvailable": "{count} disponible", + "pws.modelSearchPlaceholder": "Filtro modelos…", + "pws.modelsLoading": "Cargando modelos…", + "pws.modelsLoadFailed": "No se pudo cargar modelos.", + "pws.modelsNeedsReauth": "La cuenta necesita volver a iniciar sesión antes de que funcione el descubrimiento de modelos en vivo. Mostrando modelos configurados por ahora.", + "pws.modelsConfiguredFallback": "Mostrando modelos configurados (descubrimiento en vivo no disponible).", + "pws.modelsTruncated": "Mostrando primero {shown} de {total} Filtrar para reducir la lista.", + "pws.retry": "Reintentar", + "pws.noModels": "No se han encontrado modelos para este proveedor.", + "pws.noModelMatch": "Ningún modelo coincide con el filtro.", + "pws.adapterBaseRequired": "Se requieren adaptador y base URL.", + "pws.addAccount": "Añadir cuenta", + "pws.addKey": "Agregar clave API", + "pws.apiKeys": "Claves API", + "pws.authMode": "Modo de autenticación", + "pws.availableAccounts": "Cuentas disponibles", + "pws.accountOrdinal": "Cuenta {count}", + "pws.accountsLoading": "Cargando cuentas…", + "pws.accountsLoadFailed": "Las cuentas no se podían cargar.", + "pws.retryAccounts": "Reintentar", + "pws.noAccounts": "Aún no hay cuentas conectadas.", + "pws.geminiNativePassthrough": "Passthrough nativo de Gemini", + "pws.geminiNativePassthroughDesc": "Conserva las solicitudes y respuestas de Gemini en las rutas OAuth de Antigravity que lo admiten.", + "pws.geminiNativePassthroughLoadFailed": "No se pudo cargar la configuración nativa de Gemini.", + "pws.cockpitImportDescription": "Importa una exportación JSON de Antigravity de Cockpit Tools desde este dispositivo. El contenido del archivo no se muestra.", + "pws.cockpitImportFileLabel": "Exportación JSON de Antigravity de Cockpit Tools", + "pws.cockpitImportChooseFile": "Elige el archivo JSON", + "pws.cockpitImporting": "Importar…", + "pws.cockpitImportInvalid": "El archivo seleccionado no es una exportación válida de JSON o es demasiado grande.", + "pws.cockpitImportFailed": "No se pudo completar la importación de la cuenta.", + "pws.cockpitImportComplete": "Importación completa: {imported} importado, {updated} actualizado, {failed} fallido, {unsupported} no compatible.", + "pws.accountSwitching": "Conmutación…", + "pws.accountCurrent": "Cuenta corriente", + "pws.accountPausedHint": "Se excluye de la selección automática, reintentos, recuperación de tiempo de reutilización, selección manual y actualización proactiva token hasta que se reanude.", + "pws.resumeAndActivateKey": "Reactivar y usar", + "pws.defaultModelNone": "Ninguno (usar proveedor predeterminado)", + "pws.discardSettings": "Descartar cambios", + "pws.jsonEditorDesc": "Editar la configuración del proveedor JSON. Los cambios se guardan inmediatamente.", + "pws.jsonEditorTitle": "Editor JSON — {name}", + "pws.jsonRestore": "Restaurar", + "pws.jsonSave": "Guardar", + "pws.loggedInTitle": "Conectado", + "pws.notLoggedInTitle": "No ha iniciado sesión", + "pws.note": "Nota", + "pws.responsesReasoningReplay": "Replay razonamiento de texto plano", + "pws.responsesReasoningReplayHint": "Desactivado por defecto. Envía razonamiento de texto plano previo a este punto final y puede aumentar el uso de token. Habilitar solo si el punto final acepta la repetición de razonamiento.", + "pws.allowPrivateNetwork": "Permitir redes locales/privadas", + "pws.liveModels": "Descubre modelos de proveedor", + "pws.liveModelsDesc": "Obtenga el catálogo de modelos en vivo del proveedor. Apague esto para usar solo modelos configurados/estáticos.", + "pws.xaiChatOptIn": "Usar Chat Completions para Grok 4.5 y 4.6", + "pws.xaiChatOptInDesc": "Desactivar selecciona Responses. OAuth Las solicitudes Responses lo usan de forma predeterminada. Otros modelos Grok y el comportamiento de nivel no se modifican.", + "pws.xaiChatOptInMixed": "Solo un modelo utiliza el chat.", + "pws.subscriptionRetries": "Reintentos con el mismo modelo antes de la salida", + "pws.subscriptionRetriesDefault": "Predeterminado (reintentos principales desactivados)", + "pws.cursorTransport": "Transporte Cursor", + "pws.cursorTransportHttp2": "HTTP/2 (predeterminado)", + "pws.cursorTransportHttp1": "HTTP/1.1 (compatibilidad proxy)", + "pws.cursorTransportDesc": "Usa HTTP/1.1 cuando su proxy no pueda transmitir de forma fiable la secuencia Cursor HTTP/2.", + "pws.optionalPlaceholder": "Opcional", + "pws.providerId": "ID del proveedor", + "pws.reauth": "Necesita re-auth", + "pws.reauthenticate": "Re-autenticar", + "pws.copyDoctor": "Copiar ocx doctor", + "pws.doctorCopied": "Copiado", + "pws.doctorCopyUnavailable": "Clipboard no disponible", + "pws.healthCooldownHint": "Espere hasta que termine el tiempo de reutilización. No sondee esta cuenta todavía.", + "pws.healthLabel.rateLimited": "Límite de solicitudes alcanzado", + "pws.healthLabel.quotaLimited": "Cuota limitada", + "pws.healthLabel.accountSuspended": "Cuenta suspendida", + "pws.healthLabel.reauthRequired": "Reautenticación requerida", + "pws.healthLabel.refreshFailed": "Actualización fallida", + "pws.healthLabel.metadataMismatch": "Desajuste de metadatos", + "pws.healthLabel.validationPending": "Validación pendiente", + "pws.healthSummary.validationPending": "{provider} {account}: registrado mientras está limitado por cuota. Después de que se recupere la cuota, actualice las cuotas para ejecutar una pequeña solicitud de validación. El enrutamiento permanece desactivado hasta que tenga éxito.", + "pws.healthLabel.credentialConflict": "Conflicto de credenciales", + "pws.healthSummary.rateLimited": "{provider} {account}: límite de solicitudes alcanzado hasta {until}. El enrutamiento de esta cuenta se pausa hasta entonces.", + "pws.healthSummary.quotaLimited": "{provider} {account}: cuota limitada hasta {until}. El enrutamiento para esta cuenta se pausa hasta entonces.", + "pws.healthSummary.accountSuspended": "{provider} {account}: el proveedor suspendió esta cuenta. Presenta una apelación ante el proveedor antes de volver a iniciar sesión.", + "pws.healthSummary.reauthRequired": "{provider} {account}: se requiere reautenticación.", + "pws.healthSummary.credentialConflict": "{provider} {account}: conflicto de credenciales.", + "pws.healthSummary.metadataMismatch": "{provider} {account}: discrepancia de metadatos.", + "pws.healthSummary.staleCredentials": "{provider} {account}: credenciales incompletas.", + "pws.removeConfirm": "Quitar", + "pws.removeConfirmBody": "¿Quitar proveedor \"{name}\"? Esto no se puede deshacer.", + "pws.removeDefaultConfirmBody": "¿Eliminar el proveedor predeterminado \"{name}\"? \"{defaultProvider}\" se convertirá en el proveedor predeterminado. Esto no se puede deshacer.", + "pws.removeConfirmTitle": "Eliminar proveedor", + "pws.saveSettings": "Guardar", + "pws.keySelection": "Selección de claves API", + "pws.keyActive": "Clave activa (comportamiento existente)", + "pws.keyLimitInvalid": "Los límites por clave deben ser positivos y dentro del rango admitido; el intervalo y la concurrencia deben ser números enteros.", + "pws.keyRoundRobin": "Round-robin", + "pws.keyLimits": "Límites por tecla", + "pws.keySharedQuota": "Los límites de los proveedores aún se aplican a todas las claves. Las claves en el mismo proyecto pueden compartir cuotas; RPM Los límites no se aplican token o presupuestos diarios.", + "pws.keyHandle": "ID de clave", + "pws.keyStarts": "Inicio", + "pws.keyInFlight": "En vuelo", + "pws.keyWait": "Espere", + "pws.keyCooldown": "Enfriamiento", + "pws.pacingTitle": "Solicitar ritmo", + "pws.pacingDesc": "Retrasar uniformemente el inicio de la solicitud de salida para este proveedor. Las respuestas de transmisión pueden superponerse.", + "pws.pacingEnabled": "Activado", + "pws.pacingRpm": "Solicitudes por minuto", + "pws.pacingConcurrency": "Máximo de solicitudes concurrentes", + "pws.pacingRpmUnit": "RPM", + "pws.pacingCapUnit": "×", + "pws.pacingDelay": "Intervalo mínimo (ms)", + "pws.pacingSlowerWins": "Gana el límite de proveedores más lento. Las anulaciones de modelo solo pueden agregar más demoras o reducir el límite de concurrencia.", + "pws.pacingQueued": "en cola", + "pws.pacingNextSlot": "hasta la siguiente ranura", + "pws.pacingLastModel": "último modelo", + "pws.pacingNone": "Ninguno", + "pws.pacingModelOverrides": "Anulaciones del modelo", + "pws.pacingModel": "Modelo", + "pws.pacingAdd": "Añadir anulación", + "pws.pacingRemove": "Quitar", + "pws.pacingRemoveModel": "Eliminar anulación de estimulación de solicitud para {model}", + "pws.pacingRuleRequired": "Habilitar el ritmo de solicitud solo después de establecer un límite de proveedor o una anulación de modelo.", + "pws.pacingCapInvalid": "Las solicitudes simultáneas máximas deben ser un número entero de 1 o más.", + "pws.pacingValueInvalid": "Introduce un valor válido para controlar el ritmo: entre 1/60 y 60.000 RPM, una demora de 1 a 3.600.000 ms o una concurrencia de al menos 1.", + "pws.saving": "Guardando…", + "pws.settingsSaved": "Configuración guardados.", + "pws.accountModeSaved": "Modo de cuenta guardado.", + "pws.accountModeFailed": "No se pudo cambiar el modo de cuenta.", + "pws.accountModeConfirm": "Cambiar el modo de cuenta OpenAI? La ejecución de las conversaciones se reasignará al conjunto de cuentas del otro modo y el uso de la cuota se rastreará contra el nuevo modo.", + "pws.settingsUnsavedBar": "Tienes cambios no salvos.", + "pws.draftTarget": "Editando {target}", + "pws.draftConflict": "La configuración guardada en este servidor cambió mientras editabas. Tu borrador se conserva. Elige qué valores mantener.", + "pws.draftConflictFields": "Estos campos cambiaron tanto en el servidor como en el borrador. Edita el borrador o usa los valores guardados:", + "pws.draftConflictUseSaved": "Usar valores guardados", + "pws.draftConflictKeepDraft": "Conservar mi borrador", + "pws.draftConflictResolveFirst": "Elige qué valores conservar antes de guardar.", + "pws.unsavedLeaveBody": "Tienes cambios no salvos. ¿Salvarlos antes de partir?", + "pws.unsavedLeaveTitle": "Cambios no guardados", + "pws.attentionRequired": "Atención requerida", + "pws.attentionAria": "{name}: {reason}", + "pws.missingCredentials": "Faltan credenciales", + "pws.editJsonDesc": "Editar la configuración del proxy como JSON", + "pws.updatesUnavailable": "Las actualizaciones de proveedores no están disponibles.", + "pws.dashboard.title": "Visión general de los proveedores", + "pws.dashboard.subtitle": "Administre todos sus proveedores de modelos en un solo lugar.", + "pws.dashboard.rateLimits": "LÍMITES DE SOLICITUDES", + "pws.capacity.estimate": "Estimación de grupo de peso configurado", + "pws.capacity.currentAccount": "Cuenta efectiva actual", + "pws.capacity.nextRecovery": "Próxima recuperación de capacidad", + "pws.capacity.recoveryShare": "+{percent}% de capacidad de la grupo", + "pws.capacity.incomplete": "Cobertura incompleta: cuenta(s) {excluded} excluidas", + "pws.capacity.uncalibratedPlan": "Las cuentas {count} en un plan no calibrado se cuentan al peso del asiento de referencia, por lo que esta estimación puede ser conservadora", + "pws.capacity.partial": "Cobertura parcial de la ventana: las cuentas {count} no informan todas las ventanas de límite mostradas", + "pws.capacity.windowPartial": "Parcial", + "pws.capacity.windowPartialA11y": "{window}: cobertura incompleta de la cuenta", + "pws.dashboard.recentlyUsed": "USADOS RECIENTEMENTE", + "pws.dashboard.requests": "Solicitudes {count}", + "pws.dashboard.checkedAgo": "Comprobado {time}", + "pws.dashboard.noQuota": "Sin datos de cuota", + "pws.dashboard.noUsage": "No hay datos de uso todavía", + "pws.dashboard.noRateLimits": "Todavía no hay datos de límite de velocidad", + "pws.allProviders": "Resumen del proveedor", + "pws.enabledLabel": "Activado", + "pws.testConnection": "Conexión de prueba", + "pws.testing": "Probando…", + "pws.connectionOk": "Conexión OK", + "pws.connectionFailed": "Conexión fallida", + "pws.connectionNotApplicable": "No aplicable — este proveedor utiliza un catálogo de modelo estático.", + "pws.editSettings": "Editar configuración", + "pws.viewUsage": "Ver uso detallado", + "pws.allSystemsOk": "Todos los servicios funcionan correctamente", + "pws.apiKeyConfigured": "API clave configurada", + "pws.addApiKey": "Agregar clave API", + "pws.loggedInAs": "Inicia sesión como {email}", + "pws.notLoggedIn": "No ha iniciado sesión", + "pws.passthrough": "Paso Codex", + "pws.notes": "NOTAS", + "pws.notePlaceholder": "Añadir una nota sobre este proveedor...", + "pws.noteSaved": "Nota guardada", + "pws.authSummary": "AUTENTICACIÓN", + "time.justNow": "Justo ahora.", + "time.notChecked": "No comprobado", + "time.minutesAgo": "Hace {n}m", + "time.hoursAgo": "Hace {n}h", + "time.daysAgo": "Hace {n}d", + "modal.noMatch": "No hay coincidencia.", + "modal.oauthDefaultNote": "Inicie sesión con su cuenta — sin necesidad de la clave API.", + "modal.oauthComingSoon": "El inicio de sesión de OAuth para {label} llega en la próxima actualización. Usa una clave API por ahora.", + "modal.oauthComingSoonShort": "OAuth inicio de sesión para este proveedor llega en la próxima actualización — utilizar una clave API por ahora.", + "modal.useApiKeyInstead": "Usa una clave API en su lugar", + "modal.setupGuide": "Guía de configuración", + "modal.setupStep1Prefix": "Ir a", + "modal.setupDashboardLink": "Panel de control {label}", + "modal.setupStep1Suffix": "y copia tu clave API", + "modal.setupStep2": "Pegarlo en el campo clave API a continuación", + "modal.setupStep3": "Haga clic en Añadir proveedor Los modelos — se descubren automáticamente", + "modal.namePlaceholder": "p. ej., openrouter", + "modal.duplicateWarn": "El proveedor \"{name}\" existe y será sobrescrito.", + "modal.forwardHintPrefix": "No se necesita ninguna clave — el proxy reenvía su", + "modal.forwardCredentials": "inicio de sesión del codex", + "modal.forwardHintSuffix": "credenciales de este proveedor.", + "modal.localHint": "No se almacena ninguna clave API. Esto agrega el catálogo de modelos públicos estáticos de Cursor para Codex, pero el transporte en vivo de Cursor y la ejecución nativa de archivos / shell permanecen deshabilitados hasta que se auditan.", + "modal.getApiKey": "Obtenga su clave {label} API", + "modal.apiKey": "Clave API", + "modal.vertexProject": "ID del proyecto (opcional)", + "modal.vertexStaticHint": "Usa la lista de modelos configurada. La prueba de conexión no verifica las credenciales de Vertex.", + "modal.vertexLocation": "Ubicación (opcional)", + "pws.vertexUnverified": "Credenciales sin verificar", + "pws.vertexSavedUnverified": "Guardado · Credenciales del proxy sin verificar", + "pws.vertexHostAuth": "Credenciales del equipo anfitrión o clave API", + "modal.vertexAdcHint": "Deja vacía la clave API para usar las credenciales predeterminadas de la aplicación en el equipo del proxy si GOOGLE_CLOUD_API_KEY no está definida. El proyecto y la ubicación también se pueden tomar del entorno del proxy.", + "modal.apiKeyTransport": "API encabezado de la clave", + "modal.apiKeyTransportNative": "x-api-key (Anthropic nativo)", + "modal.apiKeyTransportBearer": "Autorización: Bearer", + "modal.apiKeyPlaceholder": "sk-… (o $ENV_VAR)", + "modal.defaultModelPlaceholder": "p. ej., gpt-5.5", + "modal.baseUrlPlaceholder": "https://...", + "modal.baseUrlPlaceholderError": "Base URL contiene un {placeholder} no resuelto. Reemplazarlo con su valor real.", + "modal.baseUrlPlaceholderHint": "Reemplace el {placeholder} en la base URL con su ID de cuenta real antes de agregar.", + "modal.adding": "Adición…", + "modal.useOauthLogin": "Usar el inicio de sesión de OAuth", + "nav.codexAuth": "Codex Autonomía", + "nav.codexSet": "Codex", + "nav.connect": "Enrutamiento", + "nav.usageLogs": "Uso y registros", + "nav.sectionNavigation": "Páginas de la sección", + "codexSet.tab.multiauth": "Múltiples cuentas", + "codexSet.tab.prompt": "Instrucciones", + "codexSet.prompt.title": "Capas rápidas", + "codexSet.prompt.timing": "Se aplica a las sesiones recién iniciadas. Las sesiones en ejecución mantienen su configuración de solicitud actual.", + "codexSet.prompt.staleRevision": "La configuración cambió en otros lugares. La lista fue recargada.", + "codexSet.prompt.writeFailed": "El cambio no se pudo salvar.", + "codexSet.prompt.loadFailed": "Las capas de prompt no se pudieron cargar.", + "codexSet.prompt.repair": "Reparar", + "codexSet.prompt.repairFailed": "La reparación no pudo completarse.", + "codexSet.prompt.remeasure": "Re-medida", + "codexSet.drift.journalPresent": "Un escrito anterior no terminó. La recuperación se ejecuta automáticamente en la siguiente escritura.", + "codexSet.drift.projectionStale": "Las capas guardadas y el valor en config.toml no están de acuerdo. Repair reescribe el valor de las capas.", + "codexSet.drift.storeMissing": "El archivo de capa se ha ido mientras las instrucciones permanecen en config.toml. Repair mantiene el texto como una capa y escribe primero una copia de seguridad.", + "codexSet.drift.ownedMalformed": "La línea generada en config.toml fue remodelada a mano, por lo que ya no es seguro volver a escribir.", + "codexSet.custom.adoptUnsupported": "El valor en la línea {path} {line} no es una cadena de una sola línea, por lo que no se puede importar. Muévalo a mano para manejarlo aquí.", + "codexSet.prompt.unreadable": "El archivo de configuración Codex existe pero no se puede leer, por lo que se rechazan los cambios.", + "codexSet.layer.permissions": "Permisos", + "codexSet.layer.collaboration": "Modo de colaboración", + "codexSet.layer.environment": "Contexto ambiental", + "codexSet.layer.apps": "Aplicaciones", + "codexSet.layer.skills": "Habilidades", + "codexSet.prompt.extensionsUnknown": "Las extensiones pueden agregar sus propias capas. Codex no los expone, por lo que no se pueden enumerar aquí.", + "codexSet.group.transition": "Notificaciones de transición", + "codexSet.group.transitionDesc": "Estos anuncian un cambio en lugar de describir el estado, por lo que aparecen solo cuando la sesión entra en tiempo real o cambia de modelo. Sus números mantienen el orden de la asamblea, por lo que la lista anterior se salta.", + "codexSet.custom.slotNote": "Las capas personalizadas se unen en una sección en este orden.", + "codexSet.row.alwaysOn": "Siempre encendido", + "codexSet.row.onChange": "Incendios en el cambio", + "codexSet.row.featureGated": "Configurado en [features]", + "codexSet.row.openFeatures": "Abrir configuración", + "codexSet.row.resetDefault": "Restablecer a {value}", + "codexSet.dialog.setValue": "{value} (por defecto, {fallback})", + "codexSet.dialog.copyKey": "Copiar clave", + "codexSet.dialog.unknownLayer": "Esta compilación no tiene descripción para esta capa. Viene de un tiempo de ejecución Codex más nuevo que el panel de control.", + "codexSet.custom.heading": "Capas personalizadas", + "codexSet.custom.add": "+ Añadir capa", + "codexSet.custom.newTitle": "Nueva capa", + "codexSet.custom.editTitle": "Editar capa", + "codexSet.custom.titleLabel": "Título", + "codexSet.custom.bodyLabel": "Instrucciones", + "codexSet.custom.bodySize": "{bytes} de bytes {max}", + "codexSet.custom.normalized": "Las pestañas se convirtieron en cuatro espacios y los finales de línea se convirtieron en LF.", + "codexSet.custom.titleRequired": "Introduzca un título.", + "codexSet.custom.titleTooLong": "El título es {count} caracteres; el límite es {max}.", + "codexSet.custom.titleMultiline": "Un título debe ser una sola línea.", + "codexSet.custom.bodyTooLarge": "Esta capa es {bytes} bytes; el límite es {max}.", + "codexSet.custom.composedTooLarge": "Juntas, las capas habilitadas serían bytes {bytes}, por encima del límite.", + "codexSet.custom.invalidCharacter": "No se puede guardar un carácter de control en la posición {position}.", + "codexSet.custom.discardPrompt": "¿Descartar los cambios?", + "codexSet.custom.discardOthersAndSave": "¿Desechar ediciones no guardadas a otras capas y guardar esta capa?", + "codexSet.custom.keepEditing": "Sigue editando", + "codexSet.custom.delete": "Eliminar {title}", + "codexSet.custom.deleteConfirm": "¿Eliminar esta capa? Puedes deshacerlo por un corto tiempo.", + "codexSet.custom.layerGone": "Esa capa fue eliminada en otro lugar, por lo que el editor fue cerrado.", + "codexSet.custom.deleteConfirmNamed": "¿Eliminar “{title}”? Puedes deshacerlo por un corto tiempo.", + "codexSet.custom.deletedNamed": "Eliminado “{title}”.", + "codexSet.custom.moveUp": "Mover {title} hacia arriba", + "codexSet.custom.prevLayer": "Capa anterior", + "codexSet.custom.nextLayer": "Siguiente capa", + "codexSet.custom.navPosition": "{position} / {total}", + "codexSet.custom.moveDown": "Mover {title} hacia abajo", + "codexSet.custom.limitReached": "Puede mantener hasta capas personalizadas {max}.", + "codexSet.custom.composedSize": "Compuesto: {bytes} de bytes {max}", + "codexSet.custom.composedPreview": "Mostrar el compuesto developer_instructions", + "codexSet.custom.notOwned": "developer_instructions fue escrito fuera de opencodex, por lo que no se edita desde aquí. Importa para gestionarlo como una capa.", + "codexSet.custom.adopt": "Importar instrucciones existentes", + "codexSet.custom.adoptConfirm": "Importación como capa", + "codexSet.custom.adoptRefused": "El valor existente no pudo ser importado.", + "codexSet.custom.baseReplaced": "model_instructions_file se establece en {path}, por lo que algo fuera de opencodex ha reemplazado el indicador base.", + "codexSet.custom.baseReplacedOpen": "Gestionarlo", + "codexSet.lint.identity": "Esto reclama una identidad diferente de la que establece Codex.", + "codexSet.lint.foreignTool": "Las herramientas provienen del registro; nombrar una aquí no la crea.", + "codexSet.lint.placeholder": "Las instrucciones no pasan por un motor de plantillas, por lo que este texto se envía literalmente.", + "codexSet.lint.applyPatch": "apply_patch está definido por el registro de la herramienta, no por las instrucciones.", + "codexSet.lint.approvalVocab": "Codex inyecta su propio vocabulario de aprobación; esto puede contradecirlo.", + "codexSet.lint.environment": "Los hechos ambientales se generan más tarde y pueden contradecir esto.", + "codexSet.lint.size": "Esta capa tiene más de 8 KB. Todavía ahorra, pero cuesta tokens en cada solicitud.", + "codexSet.lint.secret": "Parece una credencial o clave API: se almacenaría en texto sin formato en config.toml.", + "codexSet.lint.ignoreInstructions": "Decirle a Codex que ignore sus propias instrucciones puede quitar su guía incorporada.", + "codexSet.preset.blank": "Capa en blanco", + "codexSet.preset.concise.name": "Salida concisa", + "codexSet.preset.concise.description": "Respuestas cortas, sin preámbulo, formato mínimo.", + "codexSet.preset.concise.provenance": "Adaptado de las directivas de brevedad de Claude Code. Nuestra redacción, no una copia.", + "codexSet.preset.planFirst.name": "Planificar antes de editar", + "codexSet.preset.planFirst.description": "Establece el plan, luego haz el cambio.", + "codexSet.preset.planFirst.provenance": "Adaptado de la postura de planificación de Claude Code. Nuestra redacción, no una copia.", + "codexSet.preset.explainWhy.name": "Explicar el razonamiento", + "codexSet.preset.explainWhy.description": "Di por qué, no solo qué.", + "codexSet.preset.explainWhy.provenance": "Adaptado del estilo de confirmación de Grok Build. Nuestra redacción, no una copia.", + "codexSet.preset.testFirst.name": "Prueba primero", + "codexSet.preset.testFirst.description": "Escribe la prueba que falla antes de la corrección.", + "codexSet.preset.testFirst.provenance": "Adaptado de la práctica de agente común. Nuestra redacción, no una copia.", + "codexSet.preset.korean.name": "Respuestas coreanas", + "codexSet.preset.korean.description": "Contesta en coreano cualquiera que sea el idioma que use la solicitud.", + "codexSet.preset.korean.provenance": "Escrito para opencodex desde un elemento básico solicitado por el usuario. Nuestra redacción, no una copia.", + "codexSet.dialog.class": "Tipo", + "codexSet.dialog.key": "Tecla de configuración", + "codexSet.dialog.fileValue": "Valor en este archivo", + "codexSet.dialog.absentDefault": "no establecido (por defecto a {value})", + "codexSet.dialog.noRenderedText": "Codex no expone el texto ensamblado de una capa incorporada, por lo que este diálogo describe la capa y nombra su clave en lugar de mostrar su contenido.", + "codexSet.dialog.probeNotFound": "No se pudo medir el texto renderizado: no se encontró el ejecutable codex.", + "codexSet.dialog.probeUnsupported": "No se pudo medir: esta versión de Codex no admite el comando de medición.", + "codexSet.dialog.probeInvalid": "No se pudo medir: La salida Codex no se pudo analizar.", + "codexSet.dialog.probeFailed": "No se pudo medir: la sonda Codex no terminó.", + "codexSet.dialog.probeBusy": "Otra medición aún está terminando. Reintentar en un momento.", + "codexSet.dialog.sourceText": "Texto enviado al modelo", + "codexSet.dialog.sourceBytes": "{bytes} bytes", + "codexSet.dialog.notRendered": "Esta capa no envió nada en el turno que leímos. Las secciones solo se vuelven a enviar cuando cambian, por lo que una capa sin cambios está ausente de una sola muestra.", + "codexSet.dialog.emptySource": "El archivo en {path} existe pero está vacío, por lo que esta capa no envía nada.", + "codexSet.dialog.notExposed": "El indicador base se desplaza fuera de la lista de mensajes que Codex puede imprimir, por lo que no se puede mostrar aquí. Reemplazarlo es posible a través de model_instructions_file.", + "codexSet.dialog.unmapped": "Esta capa no tiene ninguna asignación confirmada en la salida de solicitud, por lo que su texto aún no se puede mostrar aquí.", + "codexSet.dialog.textUnavailable": "El indicador Codex no se pudo leer en esta máquina, por lo que el texto no está disponible.", + "codexSet.class.base": "Instrucciones de base", + "codexSet.class.config-toggle": "Conmutable aquí", + "codexSet.class.feature-gated": "Característica", + "codexSet.class.runtime-conditional": "Tiempo de ejecución-condicional", + "codexSet.class.extension-unknown": "Capa de extensión", + "codexSet.layer.base-instructions": "Instrucciones de base", + "codexSet.layer.model-switch": "Aviso de cambio de modelo", + "codexSet.layer.personality": "Personalidad", + "codexSet.layer.context-window-guidance": "Guía de ventana de contexto", + "codexSet.layer.realtime": "En tiempo real", + "codexSet.layer.agents-md": "AGENTS.md", + "codexSet.layer.environments-instructions": "Medio ambiente", + "codexSet.layer.plugins": "Complementos", + "codexSet.layer.tools": "Herramientas", + "codexSet.layer.multi-agent-mode": "Modo multiagente", + "codexSet.layer.git-attribution": "Comprometer la atribución", + "codexSet.about.base-instructions": "Instrucciones propias de Codex. Viajan con la solicitud en sí y no se pueden desactivar.", + "codexSet.about.model-switch": "Añadido cuando la sesión cambia de modelo a mitad de conversación.", + "codexSet.about.personality": "Guía de tono y voz, gobernada por una bandera de característica.", + "codexSet.about.context-window-guidance": "Orientación sobre el presupuesto de contexto restante, controlada por una opción de activación.", + "codexSet.about.realtime": "Añadido para sesiones en tiempo real.", + "codexSet.about.agents-md": "Los archivos AGENTS.md de su proyecto. Esta página informa de la capa; nunca edita los documentos del proyecto.", + "codexSet.about.permissions": "Explica el aislamiento y la configuración de aprobación vigentes.", + "codexSet.about.collaboration": "Explica el modo de colaboración activa.", + "codexSet.about.environment": "Directorio de trabajo, plataforma y otros hechos del entorno.", + "codexSet.about.environments-instructions": "Guía para entornos de ejecución diferida, gobernados por una bandera de característica.", + "codexSet.about.apps": "Cómo usar las apps conectadas.", + "codexSet.about.plugins": "Añadido cuando se selecciona un plugin o cualquier plugin anuncia una capacidad.", + "codexSet.about.tools": "Descripciones de herramientas diferidas, gobernadas por una bandera de característica.", + "codexSet.about.skills": "La lista de habilidades disponibles.", + "codexSet.about.multi-agent-mode": "Instrucciones de subagente, gobernadas por un indicador de característica.", + "codexSet.about.git-attribution": "Indica al modelo que añada el trailer Co-authored-by: Codex a los commits que cree y la línea Generated with Codex. a los PR que abra. Codex lo decide a partir de tu cuenta: no hay un ajuste aquí ni en [features]. Si está desactivado en tu cuenta, Codex envía la instrucción opuesta en lugar de omitirla.", + "codexSet.condition.model-switch": "Emitido solo después de un cambio de modelo a mitad de sesión.", + "codexSet.condition.realtime": "Emitido solo en una sesión en tiempo real.", + "codexSet.condition.agents-md": "Emitido cuando se encuentra un documento de proyecto para el directorio de trabajo.", + "codexSet.condition.plugins": "Emitido cuando se selecciona un complemento o cualquier complemento anuncia una capacidad.", + "codexSet.condition.git-attribution": "Establecido por la política de atribución de tu cuenta.", + "codexSet.base.title": "Prompt base", + "codexSet.base.prev": "Opción anterior", + "codexSet.base.next": "Siguiente opción", + "codexSet.base.position": "{position} / {total}", + "codexSet.base.swipeHint": "Desliza el dedo hacia los lados, usa las teclas de flecha o presiona las flechas para moverte entre las opciones. Se aplica a las sesiones recién iniciadas.", + "codexSet.base.defaultTitle": "Prompt base propia de Codex", + "codexSet.base.defaultBody": "El valor predeterminado no se almacena aquí, por lo que no hay nada que editar o eliminar: elegirlo simplemente elimina model_instructions_file de su configuración, y Codex utiliza el indicador con el que se envía.", + "codexSet.base.variantTitle": "Nombre", + "codexSet.base.variantBody": "Instrucciones", + "codexSet.base.replacesWarning": "Este REPLACES Codex propio indicador de base en lugar de añadir a la misma. Un breve aviso aquí significa un modelo con instrucciones cortas.", + "codexSet.base.use": "Usa este", + "codexSet.base.inUse": "En uso", + "codexSet.base.externalBlocked": "model_instructions_file ya apunta a {path}, que opencodex no escribió. Límpialo tú mismo antes de elegir una opción aquí — o importarlo en una variante.", + "codexSet.base.import": "Importarlo como variante", + "codexSet.base.importPreview": "El archivo en {path} se convierte en una variante administrada y se instala exactamente como se muestra a continuación —, el título se convierte en una línea de encabezado `#` y el cuerpo se normaliza (CRLF se convierte en LF, las pestañas se convierten en 4 espacios).", + "codexSet.base.importFormat": "Almacenado textualmente: {serializedBytes} bytes totales (cuerpo {bodyBytes} bytes). Codex lee el archivo completo, encabezado incluido.", + "codexSet.base.importTitle": "Variante de título", + "codexSet.base.importTitlePending": "Refrescando la vista previa para este título…", + "codexSet.base.importConfirm": "Importación y gestión", + "codexSet.base.importFailed": "No se pudo importar el archivo.", + "codexSet.base.importChanged": "El archivo o el título ha cambiado desde que fue previsualizado. Vista previa de nuevo.", + "nav.api": "API", + "nav.openMenu": "Abrir menú", + "nav.closeMenu": "Cerrar menú", + "nav.goHome": "Ir al panel", + "nav.collapseSidebar": "Contraer barra lateral", + "nav.expandSidebar": "Ampliar la barra lateral", + "pws.refreshAllQuotas": "Actualizar todas las cuotas", + "pws.quotaRefreshDone": "Comprobación de cuota completa", + "integrations.subtitle": "Conectar clientes a opencodex, administrar credenciales y restaurar la configuración del cliente.", + "integrations.tabsLabel": "Superficies de integración", + "integrations.tab.overview": "Descripción general", + "integrations.tab.keys": "Claves", + "integrations.tab.codex": "Codex", + "integrations.tab.claude": "Claude", + "integrations.tab.grok": "Grok Build", + "integrations.tab.cursor": "Cursor", + "integrations.tab.opencode": "OpenCode", + "integrations.tab.pi": "Pi", + "integrations.tab.gentleShell": "Gentle Shell", + "integrations.semantics.gentleShell": "Reinicia Gentle Shell para cargar el catálogo de su directorio de datos guardado. Los directorios enlazados o compartidos usan la integración de Pi.", + "integrations.tab.omp": "OMP", + "integrations.tab.hermes": "Hermes", + "integrations.tab.openclaw": "OpenClaw", + "integrations.tab.kimi": "Kimi Code", + "integrations.tab.gajae": "gjc", + "integrations.tab.dsh": "DSH", + "integrations.tab.mcode": "MiniMax Code", + "integrations.tab.zcode": "ZCode", + "integrations.tab.commandcode": "Command Code", + "integrations.tab.prime": "Prime Agent", + "integrations.tab.aside": "Aside", + "integrations.tab.raycast": "Raycast", + "integrations.tab.omo": "omo", + "integrations.tab.qoderCn": "Qoder CN", + "integrations.semantics.qoderCn": "Gestiona los modelos de OpenCodex en ~/.qoder-cn/settings.json. Requiere acceso por loopback. Se conserva el resto de la configuración; Deshacer restaura la copia guardada.", + "integrations.tab.workbuddy": "WorkBuddy (CN)", + "integrations.semantics.workbuddy": "Gestiona los modelos de OpenCodex en ~/.workbuddy/models.json. Requiere acceso por loopback. Se conserva el resto de la configuración; Deshacer restaura la copia guardada.", + "integrations.tab.workbuddyAi": "WorkBuddy AI", + "integrations.semantics.workbuddyAi": "Gestiona los modelos de OpenCodex en ~/.workbuddy-ai/models.json. Requiere acceso por loopback. Se conserva el resto de la configuración; Deshacer restaura la copia guardada.", + "integrations.tab.qoder": "Qoder", + "integrations.tab.t3code": "T3 Code", + "api.clientConfig.clientQoder": "Qoder", + "api.clientConfig.clientT3code": "T3 Code", + "integrations.semantics.qoder": "Administra los proveedores y modelos personalizados de OpenCodex en ~/.qoder/settings.json. Requiere acceso por bucle local. Se conserva el resto de la configuración; Deshacer restaura la instantánea.", + "integrations.semantics.t3code": "Añade una instancia del proveedor Claude llamada opencodex a ~/.t3/userdata/settings.json (T3CODE_HOME permite cambiar su ubicación). Los modelos enrutados aparecen en el selector de T3 Code. Las conversaciones de Codex solo usan el proxy si la integración de Codex está habilitada y T3 Code comparte el mismo CODEX_HOME. Requiere acceso por loopback. Se conserva el resto de la configuración; Deshacer restaura la copia guardada.", + "integrations.tab.cline": "Cline CLI", + "integrations.tab.kilo": "Kilo", + "integrations.tab.droid": "Factory Droid", + "integrations.droidReasoning.title": "Esfuerzo de razonamiento por defecto", + "integrations.droidReasoning.description": "Un valor predeterminado se usa solo cuando una solicitud omite su esfuerzo de razonamiento. Desactive Factory Droid para eliminar estos valores predeterminados guardados.", + "integrations.droidReasoning.noDefault": "Sin valores predeterminados", + "integrations.droidReasoning.noEfforts": "No hay opciones de esfuerzo razonable disponibles", + "integrations.droidReasoning.noModels": "No hay modelos exportados disponibles.", + "integrations.droidReasoning.modelDefault": "Esfuerzo de razonamiento predeterminado para {model}", + "integrations.droidReasoning.unsupportedTitle": "Algunos valores predeterminados guardados ya no son compatibles. Borrarlos, luego guardar / revisar los cambios para aplicar.", + "integrations.droidReasoning.unsupportedEffort": "Esfuerzo no soportado: {effort}", + "integrations.droidReasoning.clear": "Borrar predeterminado", + "integrations.droidReasoning.saveReview": "Guardar / revisar cambios", + "integrations.aside.profilesTitle": "Perfiles Aside", + "integrations.aside.profilesHint": "Elige qué perfiles reciben los modelos seleccionados. El perfil activo de Aside permanece sin cambios.", + "integrations.aside.all": "Sincronizar todos los perfiles", + "integrations.aside.syncNow": "Sincronizar ahora", + "integrations.aside.applied": "{count} de perfiles {total} aplicados", + "integrations.aside.current": "Perfil actual", + "integrations.aside.profile": "Perfil {id}", + "integrations.aside.toggle": "Sincronizar {name}", + "integrations.aside.details": "Administrar {name}", + "integrations.aside.back": "Todos los perfiles Aside", + "integrations.aside.empty": "Abra Aside y cree un perfil para conectarlo.", + "integrations.aside.partial": "Algunos perfiles necesitan atención. Tus opciones de sincronización se guardan; comprueba el estado de cada perfil.", + "integrations.aside.pending": "Sincronice la opción guardada; actualización de archivo pendiente.", + "integrations.aside.retry": "Reintentar {name}", + "integrations.aside.loadError": "No se pudo cargar los perfiles de Aside. Reintentar comprobar su estado.", + "integrations.hermes.profilesTitle": "Perfiles de Hermes", + "integrations.hermes.profilesHint": "Cada perfil de Hermes conserva su propio config.yaml. Elige un perfil para conectarlo. Los demás no cambian.", + "integrations.hermes.defaultProfile": "Perfil predeterminado", + "integrations.hermes.select": "Administrar {name}", + "integrations.hermes.loadError": "No se pudieron cargar los perfiles de Hermes. Vuelve a intentarlo para comprobar su estado.", + "integrations.hermes.profileTitle": "Perfil de Hermes: {name}", + "integrations.codex.title": "Codex CLI", + "integrations.codex.body": "El cableado Codex es propiedad del servicio proxy. Al iniciar opencodex se aplica; al detener el servicio se restaura el enrutamiento nativo.", + "integrations.codex.openService": "Controles de servicio abiertos", + "integrations.state.notInstalled": "No instalado", + "integrations.state.unknown": "Comprobación…", + "integrations.detail.codexRouted": "Las solicitudes Codex pasan por este proxy", + "integrations.detail.codexAbsent": "Codex aún no se enruta a través de este proxy", + "integrations.detail.keyCount": "{count} clave (s) emitida", + "integrations.detail.keyNone": "No se han emitido claves", + "integrations.detail.keyChecking": "Comprobación…", + "integrations.detail.keyUnavailable": "Estado de clave no disponible", + "integrations.detail.claudeOff": "La conexión está apagada", + "integrations.detail.desktopCurrent": "El escritorio está ejecutando este perfil", + "integrations.detail.desktopStale": "El archivo de perfil cambió después de aplicarlo", + "integrations.detail.desktopNotServed": "El perfil existe, pero Desktop sirve a otro", + "integrations.detail.desktopAbsent": "No se aplica ningún perfil", + "integrations.detail.desktopDesiredOff": "La integración con Claude Desktop está desactivada", + "integrations.detail.desktopDesiredOffCleanupPending": "Claude Desktop sigue utilizando la puerta de enlace; la limpieza está pendiente", + "integrations.detail.desktopDesiredOnNotApplied": "La integración está activada, pero Desktop no utiliza el perfil de puerta de enlace", + "integrations.detail.desktopSelectedElsewhere": "El escritorio está usando otro perfil", + "integrations.detail.desktopProfileDrift": "El perfil de escritorio seleccionado ha cambiado", + "integrations.detail.desktopObservedUnsafe": "El perfil de escritorio seleccionado no se puede cambiar de forma segura", + "integrations.detail.desktopNotInstalled": "La biblioteca de configuración de Claude Desktop no está instalada", + "integrations.detail.grokModels": "modelo(s) {count} cableado", + "integrations.detail.grokAbsent": "No hay bloque opencodex en la configuración", + "integrations.detail.cursorSeen": "Cursor llamó a este proxy recientemente", + "integrations.detail.cursorNeverSeen": "Inferencia privada instalada; aún no se ha visto ninguna solicitud", + "integrations.detail.cursorAbsent": "No se encontró la configuración de Cursor.", + "integrations.cursor.title": "Cursor", + "integrations.cursor.intro": "Cursor Private Inference dirige su agente a nivel local y habla con opencodex en bucle. Regular Cursor no puede: su backend llama al endpoint personalizado y necesita un HTTPS URL. Esta página nunca escribe a Cursor; pegar los valores de abajo en Cursor Tú mismo.", + "integrations.cursor.loading": "Lectura Cursor estado…", + "integrations.cursor.unavailable": "No se pudo leer el estado Cursor desde el proxy.", + "integrations.cursor.detection": "Instalado construye", + "integrations.cursor.privateInference": "Inferencia privada de Cursor", + "integrations.cursor.regular": "Normal", + "integrations.cursor.detected": "Detectados", + "integrations.cursor.notFound": "No se encontró la página", + "integrations.cursor.regularOnly": "Solo se encontró Cursor regular. Enruta los puntos finales personalizados a través de los servidores de Cursor, por lo que un proxy de bucle invertido es inalcanzable sin un túnel público. Consulte la guía para la construcción de inferencia privada.", + "integrations.cursor.installerIntro": "Cursor Private Inference es una compilación de modo local separada. El canal de actualización de Cursor anuncia su instalador, versión {version}; instálelo, luego pegue la clave Base URL y API a continuación en Configuración > Modelos > Gateway.", + "integrations.cursor.installerOpen": "Descargar el instalador", + "integrations.cursor.installerUnavailable": "El instalador de Private Inference no se pudo resolver desde el canal de actualización de Cursor para este equipo. Los valores de puerta de enlace a continuación se aplican una vez que se instala.", + "integrations.cursor.installerCheck": "Busque el instalador de Inferencia privada", + "integrations.cursor.installerChecking": "Comprobando el canal de actualización de Cursor…", + "integrations.cursor.nothingFound": "No se encontró ninguna instalación de Cursor en las ubicaciones habituales. Si se instala en otro lugar, los valores a continuación siguen siendo aplicables.", + "integrations.cursor.gateway": "Valores de pasarela", + "integrations.cursor.gatewayHint": "En Cursor Private Inference, abra Configuración Modelos > > Gateway, pegue estos dos valores y presione Actualizar lista de modelos.", + "integrations.cursor.baseUrl": "URL base", + "integrations.cursor.apiKey": "API clave", + "integrations.cursor.apiKeyCredential": "Una de sus claves opencodex API (este enlace requiere una credencial)", + "integrations.cursor.copy": "Copiar", + "integrations.cursor.copied": "Copiado", + "integrations.cursor.connection": "Conexión", + "integrations.cursor.seen": "última solicitud de Cursor: {time} ({ua})", + "integrations.cursor.neverSeen": "No hay solicitud de Cursor desde que se inició el proxy. Después de guardar la puerta de enlace, presione Actualizar lista de modelos en Cursor.", + "integrations.cursor.models": "Lo que Cursor mostrará", + "integrations.cursor.modelsHint": "Cursor elige la escalera de razonamiento de su propia tabla de modelos, por lo que opencodex solo puede predecirla. El contexto muestra el valor predeterminado y la ventana opt-in (modo máximo de Cursor).", + "integrations.cursor.ladderFromBundle": "Niveles de razonamiento leídos de la instalación de Cursor Private Inference {version}. Cursor decide los niveles; opencodex solo muestra su tabla.", + "integrations.cursor.ladderFromStatic": "Las escaleras de razonamiento son un espejo estático de Cursor 3.18.25 (no se encontró ningún paquete de inferencia privada legible). El contexto muestra el valor predeterminado y la ventana opt-in.", + "integrations.cursor.unknownVersion": "Versión desconocida", + "integrations.cursor.noControl": "—", + "integrations.cursor.singleWindow": "Una sola ventana", + "integrations.cursor.noControlTitle": "Este id no está en la tabla de esfuerzo integrada de Cursor, por lo que Cursor no muestra control de Razonamiento.", + "integrations.cursor.effortRowsOne": "1 esfuerzo fila publicado", + "integrations.cursor.effortRowsMany": "{n} filas de esfuerzo publicadas", + "integrations.cursor.effortRowsOff": "sin filas de esfuerzo", + "integrations.cursor.tableLessHint": "Las filas marcadas con — no tienen control de razonamiento en Cursor. Activa cursorEffortRows para publicar una entrada del selector por esfuerzo (id--effort), o configura modelDefaultReasoningEfforts en el proveedor para fijar un valor predeterminado.", + "integrations.cursor.colModel": "Modelo", + "integrations.cursor.colReasoning": "Razonamiento", + "integrations.cursor.colContext": "Contexto", + "integrations.cursor.guide": "Abrir la guía de inferencia privada Cursor", + "integrations.dialog.codex.title": "¿Deshabilitar la integración Codex?", + "integrations.dialog.codex.changes": "opencodex eliminará su enrutamiento de {path}, eliminará su perfil generado, restaurará el catálogo de modelos nativo y volverá a etiquetar los hilos reanudables para Codex nativo.", + "integrations.dialog.codex.breakage": "El comando codex sin envoltorio se conectará directamente a OpenAI y los modelos enrutados desde otros proveedores desaparecerán de Codex. El proxy y /v1/responses seguirán disponibles para otros clientes.", + "integrations.dialog.codex.undo": "Al volver a activarlo, se reconstruye el catálogo enrutado de los modelos disponibles en ese momento e inyecta Codex nuevamente. El historial de reanudación se hace utilizable en la dirección correspondiente, pero sus archivos no se restauran byte por byte.", + "integrations.dialog.codex.sideEffect": "Si elegiste un modelo raíz enrutado después de que opencodex inyectara la configuración, desactivar la integración elimina esa selección. Al reactivarla no se puede reconstruir: debes volver a elegir el modelo. Si un model_provider externo administra Codex, opencodex solo elimina su registro de cambios obsoleto y conserva la configuración, el catálogo y el historial.", + "integrations.dialog.codex.confirm": "Desactivar", + "integrations.dialog.grok.title": "¿Deshabilitar la integración Grok Build?", + "integrations.dialog.grok.changes": "Solo el bloque marcado con opencodex se eliminará de {path}. El contenido escrito fuera del bloque permanecerá sin cambios.", + "integrations.dialog.grok.breakage": "Deshabilitar elimina los alias de modelo opencodex de Grok Build. Los modelos utilizados con su cuenta xAI permanecen disponibles.", + "integrations.dialog.grok.undo": "Si opencodex se está ejecutando en una dirección de loopback, volver a activar escribe un nuevo bloque de los modelos disponibles actualmente.", + "integrations.dialog.grok.confirm": "Desactivar", + "integrations.dialog.desktop.title": "¿Desactivar la integración con Claude Desktop?", + "integrations.dialog.desktop.changes": "Si {path} contiene un perfil de puerta de enlace administrado por opencodex, Desktop primero seleccionará un nuevo perfil estándar sin credenciales y luego eliminará el perfil anterior y la copia de seguridad.", + "integrations.dialog.desktop.breakage": "Claude Desktop volverá a utilizar Claude estándar en lugar de modelos enrutados mediante opencodex.", + "integrations.dialog.desktop.undo": "Al volver a activarlo, se regenera el perfil opencodex de las asignaciones de modelo guardadas.", + "integrations.dialog.desktop.restart": "Claude Desktop lee esta configuración solo en el inicio. Retírelo completamente y vuelva a abrirlo para que este cambio tenga efecto.", + "integrations.dialog.desktop.confirm": "Desactivar", + "integrations.native.msg.nonLoopbackRemoved": "Grok Build se puede registrar automáticamente solo mientras opencodex se ejecuta en una dirección de loopback. El bloque anterior que apuntaba a loopback fue eliminado.", + "integrations.native.msg.nonLoopbackRemovedNoop": "Grok Build se puede registrar automáticamente solo mientras opencodex se ejecuta en una dirección de loopback. No había ningún bloque anterior que eliminar.", + "integrations.native.msg.nonLoopbackSuperseded": "Grok Build se puede registrar automáticamente solo mientras opencodex se ejecuta en una dirección de loopback. Mientras tanto, otro proceso escribió un nuevo bloque, por lo que el bloque ahora en el archivo no fue creado por esta solicitud.", + "integrations.native.error.orphanedMarker": "{path} tiene un marcador de inicio opencodex pero no un marcador de fin. El archivo se dejó sin cambios porque opencodex no puede determinar dónde termina su bloque.", + "integrations.native.error.homeMismatch": "El servicio de inicio instalado no coincide con el hogar actual, por lo que el archivo se dejó sin cambios.", + "integrations.native.error.notInstalled": "Grok Build no está instalado, así que no hay nada que cambiar.", + "integrations.native.error.configBusy": "La configuración se guarda en otro lugar y no se puede cambiar. Vuelva a intentarlo en breve.", + "integrations.native.error.desktopUnsafeMetadata": "Los metadatos de Claude Desktop en {path} no se pudieron leer de forma segura, así que su biblioteca no se modificó.", + "integrations.native.error.desktopCleanupIncomplete": "Claude Desktop apunta al modo estándar, pero quedan archivos antiguos de credenciales de opencodex en: {paths}.", + "integrations.native.msg.desktopDisabled": "Integración con Claude Desktop deshabilitada.", + "integrations.native.msg.desktopEnabled": "Integración con Claude Desktop habilitada.", + "integrations.state.absent": "No se aplica", + "integrations.state.current": "Aplicado", + "integrations.state.stale": "Actualización necesaria", + "integrations.state.conflict": "Conflicto", + "integrations.state.unsafe": "No se puede verificar", + "integrations.summary.detected": "Clientes detectados", + "integrations.summary.applied": "Clientes configurados", + "integrations.summary.stale": "Actualización necesaria", + "integrations.summary.lastChange": "Ultimo cambio", + "integrations.summary.disableAll": "Desactivar todo…", + "integrations.onboarding": "La aplicación escribe un bloque de proveedor opencodex después de guardar una copia de seguridad. Desactivar solo elimina ese bloque y se puede restaurar una instantánea retenida.", + "integrations.empty.title": "No se detectaron clientes instalados", + "integrations.empty.body": "Instale un cliente compatible, luego vuelva aquí para aplicar opencodex.", + "integrations.action.apply": "Aplicar", + "integrations.action.disable": "Desactivar", + "integrations.action.refresh": "Actualizar", + "integrations.action.settings": "Configuración", + "integrations.action.manageKeys": "Administrar claves", + "integrations.action.restore": "Restaurar…", + "integrations.action.undo": "Deshacer", + "integrations.action.restorePoint": "Restaurar este punto…", + "integrations.action.snapshotExpired": "La copia de seguridad expiró", + "integrations.rollback.title": "Centro de restauración", + "integrations.rollback.empty": "Todavía no hay cambios aplicados", + "integrations.rollback.emptyBody": "Cada escritura exitosa mantiene una instantánea de pre-escritura primero.", + "integrations.catalog.title": "Clientes", + "integrations.rollback.older": "Operaciones anteriores", + "integrations.rollback.showMore": "Mostrar {n} más", + "integrations.rollback.failed": "No se pudo cargar el historial de reversión.", + "integrations.rollback.delete": "Eliminar", + "integrations.rollback.deleteAria": "Eliminar el punto de restauración de {at}", + "integrations.rollback.deleteNewest": "La entrada más reciente de este cliente se mantiene para que aún pueda deshacerla.", + "integrations.rollback.deleteGone": "Esta entrada ya fue eliminada. La lista se actualizará.", + "integrations.dialog.deleteEntry.title": "¿Eliminar este punto de restauración?", + "integrations.dialog.deleteEntry.changes": "Esta entrada desaparece de la lista de reversión, y cualquier copia de seguridad que todavía tiene para {path} se elimina del disco.", + "integrations.dialog.deleteEntry.breakage": "Ya no podrá restaurar el archivo a este punto. Las entradas más nuevas y el archivo en sí no se tocan.", + "integrations.dialog.deleteEntry.undo": "Esto no se puede deshacer. La entrada más reciente para cada cliente se mantiene y no se puede eliminar.", + "integrations.dialog.deleteEntry.confirm": "Eliminar entrada", + "integrations.restore.title": "¿Restaurar esta instantánea?", + "integrations.restore.body": "Primero se realiza una copia de seguridad del archivo actual, luego la instantánea seleccionada lo reemplaza.", + "integrations.restore.driftTitle": "Se detectaron ediciones más recientes", + "integrations.restore.driftBody": "Los cambios realizados después de esta instantánea serán respaldados, luego el archivo será reemplazado.", + "integrations.restore.confirm": "Restaurar", + "integrations.restore.confirmDrift": "Copia de seguridad de ediciones más recientes y restaurar", + "integrations.restore.pending": "Restauración…", + "integrations.restore.manual": "Falló la restauración automática: {reason}. Restaurar manualmente desde {path}.", + "integrations.error.load": "No se pudo cargar el estado de integración.", + "integrations.error.stale": "La última actualización falló. Los valores a continuación pueden ser obsoletos.", + "integrations.error.busy": "Otro cambio para este cliente todavía se está ejecutando. Vuelva a intentarlo en breve.", + "integrations.error.conflict": "La configuración cambió después de que opencodex la escribió. Nada fue eliminado.", + "integrations.error.unsafe": "La configuración no se puede cambiar de forma segura.", + "integrations.error.generic": "El cambio de integración ha fracasado. Tu estado anterior se mantuvo.", + "integrations.error.nonLoopback": "{client} solo puede llegar a un proxy en localhost — su configuración no tiene dónde poner el encabezado de admisión que requiere un enlace remoto, por lo que escribir uno a mano tampoco ayudaría. Dale acceso de bucle en su lugar, a través de un túnel o un promotor local.", + "integrations.status.installed": "Instalado", + "integrations.status.notInstalled": "No instalado", + "integrations.status.appliedAt": "Aplicado", + "integrations.status.supersededStore": "Este cliente ahora lee a sus proveedores desde {path}, que opencodex no escribe, por lo que habilitarlo aquí no cambiaría nada de lo que carga.", + "integrations.status.missingStore": "Este cliente mantiene a sus proveedores en {path}, que falta. opencodex no escribirá el archivo de configuración antiguo del cliente, ya que el cliente mueve ese archivo a un lado y lo importa en su próximo inicio. Crear {path} que contenga {document} y, a continuación, pulse Aplicar de nuevo.", + "integrations.status.candidateConflict": "Otro archivo de configuración Kilo, {path}, también define provider.opencodex. Quita provider.opencodex de ese archivo antes de aplicar.", + "integrations.status.backup": "Copia de seguridad", + "integrations.status.lastRestore": "Ultima restauración", + "integrations.status.unknown": "Desconocido", + "integrations.bulk.title": "¿Deshabilitar integraciones de clientes aplicados?", + "integrations.bulk.body": "Solo se elimina el bloque propiedad de opencodex. Se mantiene una instantánea de pre-escritura para cada cliente.", + "integrations.bulk.partial": "Algunos clientes no se pueden desactivar: {clients}", + "integrations.bulk.success": "Las integraciones de clientes aplicados fueron deshabilitadas.", + "integrations.retention.degraded": "La limpieza de la copia de seguridad está detrás; copias de seguridad más antiguas todavía pueden estar en el disco.", + "integrations.error.residual": "El archivo puede estar en un estado intermedio: {message} Restablecerlo desde {path}.", + "integrations.error.residualNoSnapshot": "{message} La recuperación automática no terminó. Comprueba la configuración del cliente antes de volver a intentarlo.", + "integrations.error.recover": "{message} Una copia de seguridad está en {path}.", + "integrations.kind.apply": "Aplicado", + "integrations.kind.disable": "Desactivado", + "integrations.kind.refresh": "Actualizado", + "integrations.kind.restore": "Restaurado", + "integrations.kind.overwrite": "Sobrescrito", + "integrations.dialog.overwrite.title": "¿Reemplazar el bloque en esta configuración?", + "integrations.dialog.overwrite.changesUnowned": "Un bloque que no escribimos ocupa la configuración que opencodex necesita en {path}. La aplicación lo reemplaza con el bloque que escribiría opencodex.", + "integrations.dialog.overwrite.changesForeign": "Su edición dentro del bloque opencodex en {path} se descartará y se reemplazará con el bloque opencodex escribiría.", + "integrations.dialog.overwrite.breakage": "Cualquier cosa que el otro bloque configurado deje de surtir efecto. El contenido en otras partes del archivo se deja solo.", + "integrations.dialog.overwrite.undo": "Primero se guarda una instantánea, por lo que esto aparece en la lista de reversión a continuación y se puede deshacer.", + "integrations.dialog.overwrite.confirm": "Sustituir", + "integrations.action.overwrite": "Sustituir", + "integrations.preview.loading": "Cargar el cambio exacto plan…", + "integrations.preview.failed": "El plan de cambio no se pudo cargar. Nada había cambiado.", + "integrations.preview.stale": "La integración cambió mientras confirmaba. Revisa el plan actualizado y confirme de nuevo.", + "integrations.preview.catalogUnavailable": "El catálogo de modelos aún no está cargado, por lo que no se puede preparar este cambio. Cárgalo para continuar.", + "integrations.preview.loadCatalogRetry": "Cargar catálogo y reintentar", + "integrations.preview.recovering": "Cargando catálogo…", + "integrations.action.chooseProfile": "Elegir perfil", + "integrations.dialog.apply.title": "¿Aplicar esta integración?", + "integrations.dialog.apply.changes": "opencodex agregará su configuración de proveedor administrado a la configuración del cliente.", + "integrations.dialog.apply.breakage": "El cliente utilizará los modelos actualmente expuestos por esta instancia opencodex.", + "integrations.dialog.apply.undo": "Primero se guarda una copia de seguridad y el cambio se puede deshacer desde el centro de reversión.", + "integrations.dialog.apply.confirm": "Aplicar", + "integrations.dialog.disable.title": "¿Desactivar esta integración?", + "integrations.dialog.disable.changes": "Solo se quitará la configuración gestionada por OpenCodex.", + "integrations.dialog.disable.breakage": "El cliente dejará de usar los modelos enrutados a través de esta instancia opencodex.", + "integrations.dialog.disable.undo": "Primero se guarda una copia de seguridad y el cambio se puede deshacer desde el centro de reversión.", + "integrations.dialog.disable.confirm": "Desactivar", + "integrations.plan.heading": "Plan de cambio del servidor", + "integrations.plan.operation": "Operación: {operation}", + "integrations.plan.operation.apply": "Aplicar", + "integrations.plan.operation.overwrite": "Sustituir", + "integrations.plan.operation.disable": "Desactivar", + "integrations.plan.operation.restore": "Restaurar", + "integrations.plan.change.add": "Añadir", + "integrations.plan.change.replace": "Sustituir", + "integrations.plan.change.remove": "Quitar", + "integrations.plan.change.snapshot": "Guardar copia de seguridad", + "integrations.plan.change.ownership": "Actualizar el registro de propiedad", + "integrations.plan.change.journal": "Registrar un punto de restauración", + "integrations.plan.foreign.none": "No se detectaron ediciones externas.", + "integrations.plan.foreign.unowned": "Se reemplazará un bloque de configuración que no es propiedad de opencodex.", + "integrations.plan.foreign.foreignEdit": "Las ediciones dentro del bloque administrado por opencodex serán reemplazadas.", + "integrations.plan.foreign.drift": "El archivo ha cambiado desde este punto de restauración.", + "integrations.plan.noop.applied": "No se necesitan cambios en el documento del cliente administrado; sus configuración de integración ya están presentes.", + "integrations.plan.noop.disabled": "No se necesitan cambios en el documento del cliente administrado; sus configuración de integración ya están ausentes.", + "integrations.plan.noop.profilePreference": "La preferencia de sincronización del perfil se guardará cuando confirme.", + "integrations.plan.refused": "El servidor no puede aplicar este plan de forma segura.", + "integrations.plan.refusal.notInstalled": "El cliente no está instalado. Instálelo, actualice esta página y obtenga una vista previa del cambio nuevamente.", + "integrations.plan.refusal.conflict": "La configuración administrada entra en conflicto con el archivo actual. Revisa el archivo o usa Reemplazar cuando esa acción esté disponible.", + "integrations.plan.refusal.unsafe": "La configuración del cliente no se puede cambiar de forma segura. Repare o reemplace el archivo antes de volver a intentarlo.", + "integrations.plan.refusal.nonLoopback": "Este cliente requiere una dirección proxy de bucle. Usa el acceso localhost, un túnel o un reenviador local antes de volver a intentarlo.", + "integrations.plan.refusal.supersededStore": "Este cliente ahora lee a sus proveedores desde un archivo que opencodex no escribe, por lo que esta operación no cambiaría nada de lo que carga.", + "integrations.plan.refusal.missingStore": "Falta el archivo en el que este cliente mantiene a sus proveedores, y opencodex no escribirá el archivo de configuración antiguo del cliente, porque el cliente lo apartará en su siguiente inicio. Cree el archivo que contiene {document} y, a continuación, presione Aplicar de nuevo.", + "integrations.plan.refusal.driftRequiresConfirm": "El archivo cambió después de este punto de restauración. Revise el plan que tiene en cuenta esos cambios antes de restaurarlo.", + "integrations.plan.refusal.snapshotExpired": "La copia de seguridad de este punto de restauración ha caducado y ya no se puede restaurar.", + "integrations.plan.refusal.writeFailed": "El servidor no pudo preparar una escritura segura. Actualizar el estado de integración antes de volver a intentarlo.", + "integrations.mutation.pending": "Aplicar el cambio confirmado…", + "integrations.bulk.breakage": "Cada cliente dejará de usar los modelos enrutados a través de esta instancia opencodex.", + "integrations.bulk.undo": "Cada cliente mantiene su propia entrada de backup y rollback.", + "integrations.bulk.confirm": "Deshabilitar todo", + "integrations.semantics.opencode": "Solo afecta a los inicios directos desde el disco; la inyección de entorno de ocx opencode tiene prioridad.", + "integrations.semantics.pi": "Se aplica a nuevas sesiones.", + "integrations.semantics.omp": "Reinicia OMP para cargar el catálogo.", + "integrations.semantics.hermes": "Se aplica a nuevas sesiones.", + "integrations.semantics.openclaw": "Se aplica inmediatamente a una puerta de enlace en ejecución.", + "integrations.semantics.kimi": "Reinicia o ejecute /reload para aplicarlo (v2 observa el archivo).", + "integrations.semantics.gajae": "Se aplica a una nueva sesión o al abrir /model.", + "integrations.semantics.dsh": "OpenCodex solo administra el proveedor opencodex de la fila llm-pi-ai en $DSH_HOME/profiles/desktop/cordis.patch.yml, el perfil Desktop que lee DSH 0.1.7+ ($DSH_HOME/settings.yaml mientras ese perfil no exista). DSH recarga este proveedor en caliente; tu modelo predeterminado y deepseek-official no cambian. Actualmente solo se admite la interfaz de bucle local; no se escribe ninguna credencial real.", + "integrations.semantics.mcode": "Solo administra custom_provider.opencodex. Su modelo predeterminado y el inicio de sesión MiniMax permanecen sin cambios.", + "integrations.semantics.zcode": "Gestiona solo provider.opencodex en ~/.zcode/v2/config.json. Su inicio de sesión de Z.ai y otros proveedores permanecen sin cambios. Reinicia ZCode después de los cambios.", + "integrations.semantics.commandcode": "Administra solo la entrada del proveedor OpenCodex en ~/.commandcode/providers.json.. Sus otros proveedores y configuración permanecen sin cambios.", + "integrations.semantics.prime": "Gestiona solo providers.opencodex en models.json de Prime Agent — ~/.prime/agent a menos que PRIME_AGENT_CODING_AGENT_DIR lo redirija. Sus otros proveedores y modelos anulados permanecen sin cambios. Se aplica a nuevas sesiones.", + "integrations.semantics.aside": "Solo administra providers.opencodex en ~/.aside/u//models.json de este perfil. Tus otros proveedores no cambian. Cierra Aside por completo y vuelve a abrirlo después de aplicar los cambios.", + "integrations.semantics.raycast": "Agrega una entrada de proveedor OpenCodex al providers.yaml de Raycast para que cada modelo enrutado aparezca en el selector de modelos de IA de Raycast. Se requiere Raycast Pro.", + "integrations.semantics.omo": "Gestiona solo providers.opencodex en models.json de omo — ~/.omo/agent a menos que OMO_CODING_AGENT_DIR, SENPI_CODING_AGENT_DIR o PI_CODING_AGENT_DIR lo redirija. Sus otros proveedores permanecen sin cambios. Se aplica a nuevas sesiones.", + "integrations.lazycodexRoles.title": "modelos de rol omo (Codex / LazyCodex)", + "integrations.lazycodexRoles.hint": "Elige el modelo y el esfuerzo en el que se ejecuta cada rol. Guardando actualizaciones de su archivo en $CODEX_HOME/agents, y omo.jsonc de LazyCodex cuando se puede reescribir de forma segura; El esfuerzo de herencia deja el esfuerzo a Codex.", + "integrations.lazycodexRoles.role": "Papel", + "integrations.lazycodexRoles.current": "Corriente", + "integrations.lazycodexRoles.model": "Nuevo modelo", + "integrations.lazycodexRoles.modelFor": "Modelo para {role}", + "integrations.lazycodexRoles.effort": "Esfuerzo de razonamiento", + "integrations.lazycodexRoles.effortFor": "Esfuerzo de razonamiento ({role})", + "integrations.lazycodexRoles.effortDefault": "Heredar el esfuerzo", + "integrations.lazycodexRoles.none": "Sin pin de modelo", + "integrations.lazycodexRoles.choose": "Elige un modelo", + "integrations.lazycodexRoles.empty": "No se encontraron funciones de agente Codex.", + "integrations.lazycodexRoles.loadFailed": "No se pudo cargar los roles de agente Codex.", + "integrations.lazycodexRoles.saveFailed": "No se pudo guardar el modelo para {role}.", + "integrations.lazycodexRoles.saved": "{role} ahora se ejecuta en {model}.", + "integrations.lazycodexRoles.omoAbsent": "{role} ahora se ejecuta en {model}. No se encontró omo.jsonc, por lo que solo se modificó el archivo de rol.", + "integrations.lazycodexRoles.omoComments": "{role} ahora se ejecuta en {model}. omo.jsonc contiene comentarios que se perderían al guardarlo, por lo que no se modificó; establezca [codex].agents.{role} manualmente en ese archivo.", + "integrations.lazycodexRoles.omoInvalid": "{role} ahora se ejecuta en {model}. omo.jsonc se dejó solo porque no es válido JSON en la forma que lee LazyCodex.", + "integrations.lazycodexRoles.omoFailed": "{role} ahora se ejecuta en {model}, pero omo.jsonc no se pudo escribir.", + "integrations.lazycodexRoles.retryMirror": "Reintentar omo.jsonc", + "integrations.lazycodexRoles.history.title": "Historial de cambios", + "integrations.lazycodexRoles.history.hint": "Aquí se conservan las 50 operaciones de guardado y asignación automática más recientes de esta sección, en lotes completos. Restaurar guarda el modelo y el nivel de razonamiento anteriores, por lo que también aparece en la lista. Si un rol no tenía un modelo fijado, conserva el actual y solo recupera su nivel de razonamiento.", + "integrations.lazycodexRoles.history.unavailable": "No se pudo leer el historial de cambios. Aún puedes editar roles, pero no puedes restaurarlos.", + "integrations.lazycodexRoles.history.restore": "Restaurar", + "integrations.lazycodexRoles.history.restored": "Se restauraron {count} roles al estado anterior a {time}.", + "integrations.lazycodexRoles.history.partial": "La restauración se detuvo en {role}. Se restauraron {count} de {total} roles; los demás mantienen su configuración. Corrige el error de arriba y vuelve a restaurar.", + "integrations.lazycodexRoles.omoCommentsState": "omo.jsonc tiene comentarios, por lo que guardar aquí solo actualiza los archivos de rol. Establece [codex].agents en omo.jsonc tú mismo.", + "integrations.lazycodexRoles.auto.button": "Asignación automática", + "integrations.lazycodexRoles.auto.running": "Papeles de tamaño…", + "integrations.lazycodexRoles.auto.hint": "Sugiere el modelo más barato y el esfuerzo que se ajuste a cada rol. Nada cambia hasta que se aplica.", + "integrations.lazycodexRoles.auto.failed": "No se pudo dimensionar los roles de agente de Codex.", + "integrations.lazycodexRoles.auto.title": "Modelos propuestos", + "integrations.lazycodexRoles.auto.sizedWith": "Tamaño con {model}", + "integrations.lazycodexRoles.auto.applyAll": "Aplicar todo", + "integrations.lazycodexRoles.auto.discard": "Descartar cambios", + "integrations.lazycodexRoles.auto.sizingFailed": "Fallo en la llamada de dimensionamiento: {error}", + "integrations.lazycodexRoles.auto.appliedCount": "Aplicado {count} de propuestas {total}.", + "integrations.lazycodexRoles.auto.proposalFor": "Propuesta para {role}", + "integrations.lazycodexRoles.auto.tierEffort": "Nivel {tier}, esfuerzo {effort}", + "integrations.lazycodexRoles.auto.tierFast": "Rápido", + "integrations.lazycodexRoles.auto.tierStandard": "Norma", + "integrations.lazycodexRoles.auto.tierFrontier": "Frontera", + "integrations.lazycodexRoles.auto.effortGlance": "Mirar", + "integrations.lazycodexRoles.auto.effortMeasured": "medido", + "integrations.lazycodexRoles.auto.effortThorough": "completo", + "integrations.lazycodexRoles.auto.effortExhaustive": "Exhaustivo", + "integrations.lazycodexRoles.auto.unsized": "No tamaño: {reason}", + "integrations.lazycodexRoles.auto.unassigned": "No hay modelo: {reason}", + "integrations.lazycodexRoles.auto.applied": "Aplicado", + "integrations.lazycodexRoles.auto.alreadySet": "Ya establecido", + "integrations.lazycodexRoles.auto.apply": "Aplicar", + "integrations.lazycodexRoles.auto.moveUp": "Subir si: {text}", + "integrations.lazycodexRoles.auto.moveDown": "Bajar si: {text}", + "integrations.semantics.cline": "Gestiona OpenCodex en Cline CLI providers.json y models.json. Detenga Cline antes de cambiar o sincronizar estos archivos y, a continuación, reinicie. Deshacer restaura ambos originales. Su proveedor predeterminado permanece sin cambios; seleccione OpenCodex en Cline.", + "integrations.semantics.kilo": "Solo administra provider.opencodex en la configuración global de Kilo: el primer archivo existente entre kilo.jsonc, kilo.json, opencode.jsonc, opencode.json y config.json en ~/.config/kilo (XDG_CONFIG_HOME cambia la ubicación de ese directorio; se crea kilo.jsonc si no existe ninguno). Las demás claves no cambian. Aplicar reescribe el archivo completo, por lo que no se conservan los comentarios ni las comas finales. Selecciona opencodex/ en Kilo.", + "integrations.semantics.droid": "Añade modelos personalizados de OpenCodex a settings.json de Factory Droid. Desactivar solo elimina las filas administradas; Deshacer restaura el archivo guardado.", + "integrations.raycast.proRequired": "Los proveedores personalizados son una función de Raycast Pro. El archivo se escribirá, pero Raycast lo ignora hasta que una suscripción Pro esté activa.", + "integrations.raycast.planUnknown": "No se pudo determinar si Raycast Pro está activo; Los proveedores personalizados requieren Raycast Pro.", + "integrations.raycast.revealConfig": "Abre Raycast → Settings → AI y pulsa Reveal Providers Config una vez para crear la carpeta de proveedores.", + "codexAuth.mainAccount": "Cuenta Principal", + "codexAuth.logLabel": "Etiqueta de registro", + "codexAuth.codexApp": "Aplicación Codex", + "codexAuth.moreActions": "Mostrar más acciones", + "codexAuth.copyId": "Copiar ID de cuenta", + "codexAuth.appLogin": "Inicio de sesión de la aplicación", + "codexAuth.accountPool": "Cuenta Pool", + "codexAuth.accountModeTitle": "Modo de cuenta OpenAI", + "codexAuth.accountModePool": "Modo Pool", + "codexAuth.accountModePoolDesc": "Las principales cuentas de inicio de sesión y las cuentas añadidas elegibles rotan aquí.", + "codexAuth.accountModeDirect": "Modo Direct", + "codexAuth.accountModeDirectDesc": "Las solicitudes solo usan el inicio de sesión principal; las cuentas agregadas permanecen almacenadas para el modo Pool.", + "codexAuth.openaiMissing": "El proveedor integrado OpenAI no está configurado.", + "codexAuth.openaiDisabled": "El proveedor integrado OpenAI está desactivado.", + "codexAuth.openaiUnavailableDesc": "Sus cuentas OpenAI todavía están disponibles. Habilitar al proveedor para enrutar las solicitudes Codex.", + "codexAuth.enableOpenai": "Habilitar OpenAI", + "codexAuth.enablingOpenai": "Habilitando...", + "codexAuth.enableOpenaiFailed": "No se pudo habilitar el proveedor OpenAI.", + "codexAuth.openaiPresetLoadFailed": "No se pudo cargar el ajuste preestablecido del proveedor OpenAI.", + "codexAuth.openaiPresetUnavailable": "El ajuste preestablecido del proveedor OpenAI no está disponible.", + "codexAuth.openProviders": "Proveedores abiertos", + "codexAuth.changeAccountMode": "Cambiar modo de cuenta", + "codexAuth.add": "Añadir", + "codexAuth.credits": "Créditos", + "codexAuth.creditsRemaining": "restante", + "codexAuth.creditsUnlimited": "Ilimitado", + "codexAuth.creditsOverage": "Límite de exceso alcanzado", + "codexAuth.creditsApprox": "Mensajes aproximados: local {local} · nube {cloud}", + "codexAuth.creditsToggle": "Créditos Codex", + "codexAuth.creditsToggleHint": "Mostrar los créditos restantes de Codex en las tarjetas de cuenta. Oculta por defecto.", + "codexAuth.creditsShown": "Codex créditos mostrados", + "codexAuth.creditsHidden": "Codex créditos ocultos", + "codexAuth.creditsToggleFailed": "No se pudo cambiar la configuración de los créditos Codex", + "codexAuth.refreshQuota": "Actualizar las cuotas", + "codexAuth.ultraFastTitle": "Nivel de servicio ultra rápido", + "codexAuth.mainHardLockTitle": "Bloquear cuenta principal (5h {short}%, largo {long}%)", + "codexAuth.mainHardLockDesc": "Bloques en {short}% en la ventana de 5h o {long}% en la ventana semanal (mensualmente para cuentas solo mensuales). Se desbloquea una vez cada ventana de bloqueo por debajo de su umbral; la protección permanece activada. Por defecto.", + "codexAuth.mainHardLockConfirmTitle": "Habilitar la protección de la cuenta principal (5h {short}%, largo {long}%)?", + "codexAuth.mainHardLockConfirmBody": "Mientras esté bloqueada, la cuenta principal no puede usar Luna Reserve. Mantener el uso normal por debajo del agotamiento puede evitar la activación de la reserva. Las cuentas agregadas y otros proveedores permanecen disponibles. Las solicitudes en ejecución, las credenciales de asignación de claves sin igual y el tráfico fuera de este proxy no están protegidos.", + "codexAuth.mainHardLockConfirm": "Habilitar la protección", + "codexAuth.mainHardLockEnabled": "La protección está activada (5h {short}%, {long}% largo).", + "codexAuth.mainHardLockDisabled": "La protección de la cuenta principal está desactivada. Todavía se aplican otros límites de cuenta.", + "codexAuth.mainHardLockLoadFailed": "No se pudo cargar esta configuración. Intente comprobar su estado actual.", + "codexAuth.mainHardLockSaveFailed": "No se pudo confirmar que se guardara. Recarga la configuración antes de reintentar.", + "codexAuth.mainHardLockRefreshFailed": "Configuración guardada, pero el estado de la cuenta no se pudo actualizar. Por favor, vuelva a intentarlo.", + "codexAuth.mainHardLockBlocked": "Bloqueado por protección de cuenta principal (5h {short}%, largo {long}%)", + "codexAuth.mainHardLockUnknown": "Protección en el uso de · desconocido", + "codexAuth.mainHardLockMonitoring": "Protección en el monitoreo ·", + "codexAuth.mainExternalUsageWarning": "Posible uso fuera de opencodex. La cerradura puede no evitar el agotamiento.", + "codexAuth.mainHardLockManage": "Ajuste de protección de la vista", + "codexAuth.mainHardLockFallbackTitle": "Modelo alternativo durante el bloqueo", + "codexAuth.mainHardLockFallbackDesc": "Si bien está bloqueado y ninguna cuenta de Codex puede atender una solicitud, las solicitudes de modelos nativos de Codex se enrutan a este modelo en lugar de fallar. Déjalos vacíos para rechazarlos como de costumbre; la cerradura se libera por sí sola.", + "codexAuth.mainHardLockFallbackModel": "Modelo Fallback", + "codexAuth.mainHardLockFallbackEffort": "Esfuerzo de pensamiento", + "codexAuth.mainHardLockFallbackDefaultEffort": "Mantener el esfuerzo de solicitud", + "codexAuth.mainHardLockFallbackActive": "Bloqueando ahora — nativo Las solicitudes Codex se enrutan a {model}.", + "codexAuth.mainHardLockFallbackSaveFailed": "No se pudo confirmar que se guardara la opción de respaldo. Recarga la configuración antes de reintentar.", + "codexAuth.ultraFastDesc": "Agrega la opción de velocidad ultrarrápida a GPT-6 Astra y GPT-6.1 Sol en el selector de modelos Codex, y mantiene un nivel ultrarrápido que configuró usted mismo en los modelos enrutados cuando se regenera el catálogo. Ultrafast requiere un plan ChatGPT elegible; active esto solo si su plan lo incluye.", + "codexAuth.ultraFastLoadFailed": "No se pudo leer la configuración Ultra Fast.", + "codexAuth.ultraFastEnabled": "Nivel ultra rápido habilitado", + "codexAuth.ultraFastDisabled": "Nivel ultra rápido desactivado", + "codexAuth.ultraFastFailed": "No se pudo cambiar la configuración de Ultra Fast", + "codexAuth.refreshingQuota": "Refrescante...", + "codexAuth.quotaRefreshed": "Cuotas renovadas", + "codexAuth.quotaRefreshFailed": "No se pudo actualizar las cuotas", + "codexAuth.pauseExhausted": "Pausa agotada", + "codexAuth.pausingExhausted": "Control de cuotas...", + "codexAuth.pauseExhaustedSucceeded": "Cuentas en el límite pausado: {count}", + "codexAuth.pauseExhaustedNone": "Ninguna cuenta ha confirmado el 100% de uso.", + "codexAuth.pauseExhaustedFailed": "No se pudo comprobar y pausar las cuentas agotadas.", + "codexAuth.noPool": "No se han agregado cuentas de grupo todavía.", + "codexAuth.pause": "Pausa", + "codexAuth.resume": "Reanudar", + "codexAuth.paused": "EN PAUSA", + "codexAuth.planExcluded": "No auto-seleccionado", + "codexAuth.planExcludedHint": "Plan {plan} está excluido de la selección automática. Las rutas de cuentas explícitas siguen estando disponibles.", + "codexAuth.pauseSucceeded": "{email} está en pausa", + "codexAuth.resumeSucceeded": "{email} está disponible para la grupo de nuevo", + "codexAuth.pauseFailed": "No se pudo pausar {email}. Nada había cambiado.", + "codexAuth.resumeFailed": "No se pudo reanudar {email}. Nada había cambiado.", + "accountPause.tooltip": "{reason} · {date}", + "accountPause.submitAppeal": "Enviar apelación", + "accountPause.reason.organizationDisabled": "Organización deshabilitada", + "accountPause.reason.permissionDenied": "Permiso de cuenta denegado", + "accountPause.reason.subscriptionInactive": "Suscripción inactiva", + "accountPause.reason.subscriptionExpired": "La suscripción expiró", + "accountPause.reason.planDowngraded": "Plan degradado", + "prov.keyResumedSwitchFailed": "La clave se reanudó, pero la activación falló. La clave es elegible para la selección automática. Intente seleccionarlo de nuevo.", + "codexAuth.pausedHint": "Excluido de la conmutación automática, reintentos, recuperación de tiempo de reutilización y selección manual hasta que se reanude.", + "codexAuth.creditsAfterLimit": "Usar créditos después del límite", + "codexAuth.creditsAfterLimitHint": "Desactivado de forma predeterminada: una cuenta cuya ventana de uso llega al 100% se apaga hasta que se restablece, por lo que sus créditos ChatGPT no se gastan. Encienda una cuenta para que siga funcionando de sus créditos. Comienzan nuevas cuentas.", + "codexAuth.creditsAfterLimitAria": "Usar créditos después del límite de uso para {email}", + "codexAuth.creditsAfterLimitMainHint": "El bloqueo duro de la cuenta principal (activado por defecto) aún lo detiene primero. Apague el candado para permitir que la cuenta principal gaste créditos.", + "codexAuth.creditSpend": "Usar créditos", + "codexAuth.creditSpendAria": "Usar créditos ChatGPT después del límite de uso", + "codexAuth.creditsOn": "Utiliza créditos", + "codexAuth.creditsOnSucceeded": "{email} puede usar créditos después de su límite de uso.", + "codexAuth.creditsOffSucceeded": "{email} se cambiará a su límite de uso, por lo que sus créditos se mantienen.", + "codexAuth.creditsUpdateFailed": "No se pudo actualizar la configuración de créditos para {email}. Nada había cambiado.", + "codexAuth.creditsAllOnSucceeded": "Cada cuenta puede usar créditos después de su límite de uso.", + "codexAuth.creditsAllOffSucceeded": "Ninguna cuenta gastará créditos. Las cuentas se cambian al 100%.", + "codexAuth.creditsAllUpdateFailed": "No se pudo actualizar la configuración de créditos. Nada había cambiado.", + "codexAuth.pinned": "FIJADA", + "codexAuth.pinnedHint": "Usted seleccionó esta cuenta a mano, por lo que un orden de selección más alto no pasará de ella. El pin dura hasta que se agote esta cuenta, seleccione otro o cambie cualquier orden de selección.", + "codexAuth.unpinHint": "Selecciona de nuevo para soltar el pin y volver a la selección automática.", + "codexAuth.unpinTitle": "¿Liberar el pin?", + "codexAuth.unpinDesc": "Tiene efecto inmediato. Los hilos ya vinculados a una cuenta y las solicitudes en vuelo mantienen su cuenta capturada; las solicitudes nuevas o no vinculadas seleccionan una cuenta automáticamente del orden de selección y los umbrales.", + "codexAuth.unpinAction": "Alfiler de liberación", + "codexAuth.unpinned": "La selección automática — está de vuelta en", + "codexAuth.unpinFailed": "No se pudo confirmar la liberación del pin. Actualizar cuentas y comprobar la selección actual antes de volver a intentarlo.", + "codexAuth.unpinChanged": "El pin cambió mientras esta confirmación estaba abierta. Actualizar cuentas y revisar la selección actual antes de lanzar un pin.", + "codexAuth.fiveHour": "5h", + "codexAuth.weekly": "Semana", + "codexAuth.quotaAutoRefresh": "Activación automática de ventana", + "codexAuth.quotaAutoRefreshHint": "Envía una solicitud de calentamiento Codex mínima no almacenada cuando se restablece esta ventana de cuota.", + "codexAuth.quotaAutoRefreshUpdated": "Activación automática de la ventana actualizada.", + "codexAuth.quotaAutoRefreshFailed": "No se pudo actualizar la activación automática de la ventana.", + "codexAuth.monthly": "30d", + "codexAuth.resets": "se restablece", + "codexAuth.today": "Hoy", + "codexAuth.current": "ACTUAL", + "codexAuth.nextSession": "SELECCIONADA", + "codexAuth.poolPrepared": "PREPARADA PARA POOL", + "codexAuth.preparePoolTitle": "¿Preparar esta cuenta para el modo Pool?", + "codexAuth.preparePoolDesc": "Las solicitudes Direct siguen usando el inicio de sesión principal. Esta cuenta se convierte en la selección Pool preparada cuando el modo Pool está habilitado.", + "codexAuth.prepareForPool": "Prepárate para Pool", + "codexAuth.poolPreparedToast": "{email} está preparado para el modo Pool", + "codexAuth.switchTitle": "¿Cambiar de cuenta activa?", + "codexAuth.switchDesc": "Tiene efecto inmediato. Los hilos ya vinculados a una cuenta y las solicitudes en curso conservan la cuenta que tenían asignada. Las solicitudes nuevas o sin vincular usan el nivel de orden de la cuenta seleccionada; las cuentas con el mismo orden de selección siguen alternándose.", + "codexAuth.cacheWarning": "La caché del prompt se restablece al cambiar de cuenta. Una sesión nueva empieza con la caché vacía.", + "codexAuth.switchExceedsThresholdWarning": "El uso de esta cuenta cumple o excede el umbral de switch ({threshold}%). La selección fijada se liberará si no hay espacio libre de cuota disponible.", + "codexAuth.setAsNext": "Usa esta cuenta a continuación", + "codexAuth.cancel": "Cancelar", + "codexAuth.switchBack": "¿Volver a Main?", + "codexAuth.switchBackDesc": "Tiene efecto inmediato. Los hilos y las solicitudes de afinidad de cuenta existentes que ya están en vuelo mantienen su cuenta capturada; las solicitudes nuevas o no vinculadas usan el nivel de pedido de su cuenta de inicio de sesión de App, y las cuentas en el mismo orden de selección aún se turnan.", + "codexAuth.autoSwitch": "Cambio proactivo basado en el uso", + "codexAuth.autoSwitchQuotaDesc": "Contingente: en el uso de {threshold}% o superior, la siguiente solicitud no vinculada puede pasar a una cuenta elegible de menor uso. Las tareas vinculadas mantienen la afinidad de forma predeterminada y se mueven solo cuando la cuenta no puede servir, y solo hacia un margen de cuota genuino; Ir / uso libre 30d solamente.", + "codexAuth.autoSwitchQuotaOffDesc": "La conmutación proactiva basada en el uso está desactivada. La asignación nueva/no enlazada y la recuperación de fallos aún se aplican.", + "codexAuth.autoSwitchRoundRobinDesc": "La asignación round-robin no utiliza este umbral; continúa rotando tareas nuevas/no enlazadas.", + "codexAuth.autoSwitchFillFirstDesc": "Fill-first: al alcanzar el {threshold}% de uso, deja de asignar tareas nuevas o sin vincular a esa cuenta. Las tareas vinculadas a una cuenta disponible la conservan.", + "codexAuth.autoSwitchFillFirstOffDesc": "Fill-first no tiene punto de drenaje de uso para tareas nuevas/desvinculadas; el tiempo de reutilización, la reautenticación y la recuperación de fallas aún pueden mover el enrutamiento.", + "codexAuth.failureRecoveryNote": "La recuperación de fallos es independiente: una solicitud rechazada antes de la salida con 429/402, tiempo de reutilización, reautenticación, exclusión o conmutación por error transitoria configurada puede seleccionar otra cuenta elegible.", + "codexAuth.autoSwitchThreshold": "Umbral de uso", + "codexAuth.autoSwitchThresholdAria": "Umbral de uso, por ciento", + "codexAuth.autoSwitchThresholdInc": "Aumentar el umbral de uso", + "codexAuth.autoSwitchThresholdDec": "Reducir el umbral de uso", + "codexAuth.autoSwitchLoadFailed": "No se pudo cargar la configuración de conmutación basada en el uso.", + "codexAuth.autoSwitchThresholdInvalid": "Introduzca un número entero del 1 al 100", + "codexAuth.autoSwitchUpdated": "Actualización de la conmutación proactiva basada en el uso", + "codexAuth.autoSwitchUpdateFailed": "No se pudo confirmar la actualización de conmutación basada en el uso. Se muestra el último valor confirmado.", + "codexAuth.requestUserInput": "Solicitar entrada en modo Predeterminado", + "codexAuth.requestUserInputDesc": "Permite a Codex pausar una sesión en modo Predeterminado y hacerle preguntas con la herramienta request_user_input.", + "codexAuth.requestUserInputUpdated": "Indicador de característica actualizado: se aplica a nuevas sesiones.", + "codexAuth.requestUserInputUpdatedRestart": "Indicador de característica actualizado: se aplica a nuevas sesiones. Reinicia la aplicación Codex para recogerla.", + "codexAuth.requestUserInputUpdateFailed": "No se pudo actualizar el indicador de características. Nada había cambiado.", + "codexAuth.requestUserInputLoadFailed": "No se pudo leer el indicador de características de config.toml.", + "codexAuth.accountPickerTitle": "Apuntar a una cuenta específica de Codex desde el selector de modelos", + "codexAuth.accountPickerOffDesc": "Cuando está habilitado, las filas de selector GPT ordinarias se reemplazan por una entrada por selector de cuenta, para que pueda elegir la cuenta exacta para una conversación sin cerrar la sesión. Desactivarlo no elimina ninguna cuenta.", + "codexAuth.accountPickerOnDesc": "Cada selector es una etiqueta pública para una cuenta almacenada. Elegirlo bloquea esa conversación a la cuenta asignada: nunca gira o retrocede, y no cambia la cuenta activa de Pool.", + "codexAuth.accountPickerCompatibility": "La cuenta integrada de Codex App tiene su propio selector. Los mapas generados suelen llamarlo main y usan un sufijo sin colisiones, como main-2, cuando hace falta. Las cuentas añadidas reciben etiquetas estables que protegen su privacidad; las etiquetas personalizadas se conservan. Las conversaciones y selecciones de modelos existentes siguen enrutándose. Desactivar esta opción oculta las entradas generadas, pero conserva los selectores y las rutas exactas. Los identificadores GPT sin prefijo mantienen su comportamiento Pool o Direct.", + "codexAuth.accountPickerUpdated": "Se ha actualizado la segmentación de cuentas.", + "codexAuth.accountPickerUpdateFailed": "No se pudo actualizar la orientación de la cuenta. Se muestra la última configuración confirmada.", + "codexAuth.accountPickerLoadFailed": "No se pudo cargar la configuración de orientación de la cuenta.", + "codexAuth.accountPickerRefreshFailed": "No se pudo actualizar esta configuración. Todavía se muestra el último valor confirmado.", + "codexAuth.advancedSettings": "Configuración avanzada", + "codexAuth.advancedSettingsAria": "Mostrar u ocultar la configuración avanzada de Codex Auth", + "codexAuth.catalogRefreshPending": "El cambio se guardó, pero queda pendiente actualizar el catálogo de modelos de Codex. Ejecuta ocx sync para reintentar.", + + "anthropicPool.title": "Grupo de cuentas Claude (experimental)", + "anthropicPool.enabledDesc": "Las sesiones permanecen en la misma cuenta; las nuevas prefieren cuentas con un uso inferior a {threshold}% ({window}).", + "anthropicPool.enabledNoProactiveDesc": "Los umbrales de uso no mueven una sesión saludable existente o una cuenta activa saludable. Cuando la cuenta activa no está disponible y durante la recuperación de rechazo, se elige la cuenta con el uso más bajo ({window}).", + "anthropicPool.enabledFillFirstDesc": "Las sesiones permanecen en la misma cuenta. Las nuevas utilizan la cuenta activa hasta que esta alcanza {threshold}% ({window}), entra en un periodo de espera o necesita iniciar sesión; entonces pasan a la siguiente cuenta en orden. La recuperación tras un rechazo también utiliza la siguiente cuenta en orden.", + "anthropicPool.enabledFillFirstNoThresholdDesc": "Las sesiones permanecen en la misma cuenta. Las nuevas utilizan la cuenta activa hasta que esta entra en un periodo de espera o necesita iniciar sesión; entonces pasan a la siguiente cuenta en orden. La recuperación tras un rechazo también utiliza la siguiente cuenta en orden.", + "anthropicPool.enabledRoundRobinDesc": "Las sesiones permanecen en la misma cuenta. Las nuevas sesiones y la recuperación tras un rechazo se reparten por turnos entre las cuentas elegibles; no se usan el consumo, el umbral ni la ventana de cuota.", + "anthropicPool.disabledDesc": "La selección proactiva de cuentas está desactivada. OpenCodex utiliza la cuenta seleccionada y todavía puede cambiar tras una respuesta de límite de solicitudes (429) o un rechazo de cuenta clasificado, si hay otra cuenta apta con la sesión iniciada.", + "anthropicPool.experimentalWarning": "Usa solo suscripciones propias o que tengas autorización para usar. Anthropic no respalda la agrupación automática de cuentas, que sigue siendo experimental. Usa el cliente oficial de Claude Code con una persona supervisando la sesión y consulta los términos vigentes de Anthropic. Las cuentas pueden compartir la cuota de una organización; añadir una cuenta no siempre añade capacidad.", + "anthropicPool.detailsSummary": "Cómo funciona la selección de cuentas", + "anthropicPool.detailsEnabling": "Activar el grupo mantiene cada sesión en su cuenta mientras esa cuenta está sana, y permite que la estrategia seleccionada elija cuentas para nuevas sesiones y después de un rechazo.", + "anthropicPool.detailsFailover": "Apagarlo no desactiva la conmutación por error: después de un 429 o un rechazo de cuenta clasificada, una solicitud aún puede pasar a otra cuenta iniciada. Pausa una cuenta para mantenerla fuera de la conmutación por error.", + "anthropicPool.detailsActivity": "OpenCodex no envía solicitudes para mantener activa la conexión (keep-warm). De forma predeterminada, no renueva los tokens de Claude ni consulta el uso en segundo plano; solo lo consulta cuando lo solicita el dashboard, la aplicación de la barra de menús o un comando ocx.", + "anthropicPool.nativeMessagesLabel": "Conservar solicitudes nativas de Claude", + "anthropicPool.nativeMessagesHelp": "Con la agrupación activada, conserva el historial de Claude Code y los marcadores de caché en la ruta nativa Messages si el destino lo admite. Otras rutas pueden seguir traduciendo solicitudes. Cambiar de cuenta puede dejar la caché vacía; no se garantizan aciertos ni se comparten cachés entre cuentas. Se respetan las exclusiones explícitas del despliegue.", + "anthropicPool.saveWarning": "La configuración se guardó, pero falló la actualización del registro de cambios. Vuelve a cargar la configuración para confirmar el estado actual.", + "anthropicPool.saveStateUnknown": "No se pudo confirmar la configuración guardada. Vuelve a cargarla antes de hacer otro cambio.", + "anthropicPool.reloadSettings": "Recargar configuración", + "anthropicPool.detailsGuide": "Guía de la grupo de cuentas", + "anthropicPool.needTwoAccounts": "Agregue al menos dos cuentas Claude OAuth antes de habilitar el grupo.", + "anthropicPool.threshold": "Umbral de uso de nueva sesión", + "anthropicPool.thresholdAria": "Umbral de uso de nueva sesión, por ciento", + "anthropicPool.thresholdHelp": "Es una preferencia para elegir cuenta, no un límite estricto de uso o facturación. 0 desactiva el cambio proactivo por este umbral. Predeterminado: 80 %.", + "anthropicPool.thresholdInvalid": "Introduzca un número entero de 0 a 100", + "anthropicPool.loadFailed": "No se pudo cargar la configuración del grupo Claude.", + "anthropicPool.saveFailed": "No se pudo guardar la configuración del grupo Claude.", + "anthropicPool.on": "Activado", + "anthropicPool.off": "Desactivado", + + "accountPool.strategy": "Estrategia de rotación", + "accountPool.strategyDesc": "Cómo asigna OpenCodex una cuenta a una tarea nueva/no vinculada.", + "accountPool.strategyResetFirst": "Restablecimiento más próximo primero", + "accountPool.strategyResetNearWeighted": "Ponderado por el restablecimiento más próximo", + "accountPool.strategyHintResetFirst": "Prefiere el restablecimiento de 5 horas o semanal más cercano entre las cuentas por debajo del umbral de uso. Las tareas vinculadas siguen la política de afinidad configurada. Las cuotas modelo independientes utilizan la ordenación de cuotas.", + "accountPool.strategyHintResetNearWeighted": "Asigna aproximadamente la mitad de las nuevas asignaciones a la cuenta apta con el restablecimiento semanal más próximo. Si no hay ninguna cuenta apta, las asignaciones rotan de forma equitativa.", + "accountPool.strategyQuota": "Contingente", + "accountPool.strategyRoundRobin": "Round-robin", + "accountPool.strategyFillFirst": "Llenar primero", + "accountPool.strategyHintQuota": "Quota enlaza una tarea existente en el umbral de uso solo cuando `pool.cacheAffinity` está desactivado (está activado de forma predeterminada). De lo contrario, las tareas vinculadas permanecerán hasta que la cuenta no pueda servir, y luego solo en el margen de cuota genuino.", + "accountPool.strategyHintRoundRobin": "Round-robin rota solo tareas sin un enlace en vivo; el umbral de uso no cambia la rotación normal.", + "accountPool.strategyHintFillFirst": "Fill-first utiliza el umbral como punto de drenaje para las tareas no vinculadas; las tareas vinculadas saludables mantienen la afinidad.", + "accountPool.unboundDefinition": "Una tarea nueva o sin vincular es una solicitud sin una cuenta asignada actualmente. Una tarea existente y visible puede perder su vinculación después de restablecer el proxy o la afinidad.", + "accountPool.stickyLimit": "Asignaciones nuevas/no enlazadas antes de rotar", + "accountPool.stickyLimitAria": "Asignaciones nuevas/no enlazadas antes de rotar", + "accountPool.stickyLimitInc": "Aumentar el límite de afinidad", + "accountPool.stickyLimitDec": "Reducir el límite de afinidad", + "accountPool.stickyLimitHelp": "Conserva la cuenta seleccionada durante esta cantidad de asignaciones de tareas nuevas o sin vincular antes de pasar a la siguiente. El contador aumenta al vincular la tarea, sin esperar al resultado del proveedor de origen.", + "accountPool.stickyLimitInvalid": "Introduzca un número entero del 1 al 100", + "accountPool.strategyLoadFailed": "La estrategia de rotación no se pudo cargar.", + "accountPool.strategyUpdateFailed": "La estrategia de rotación no se pudo salvar.", + "accountPool.switchAtThreshold": "cambiar a {threshold}%", + "accountPool.drainAtThreshold": "drenaje en {threshold}%", + "accountPool.resetBelowThreshold": "restablecimiento más cercano por debajo de {threshold}%", + "accountPool.thresholdNotUsed": "umbral no utilizado", + "accountPool.proactiveSwitchingOff": "Apagado proactivo", + + "accountPool.quotaWindow": "Ventana de cuota", + "accountPool.quotaWindowDesc": "Qué barra de uso en caché controla la selección de nueva sesión basada en cuotas, las verificaciones de umbral de primer llenado y los reemplazos elegibles de 429.", + "accountPool.quotaWindowFiveHour": "Bar de 5 horas", + "accountPool.quotaWindowWeekly": "Bar semanal", + "accountPool.quotaWindowMaxUtilization": "Barra más alta", + "accountPool.quotaWindowHint": "Semanal omite las cuentas cuya ventana de 5 horas está agotada mientras haya otra cuenta apta, pero vuelve a considerarlas si no queda ninguna. En un empate semanal se prefiere el menor uso de 5 horas. El uso semanal de cada cuenta solo se conoce después de que la página Proveedores lo consulte.", + "accountPool.quotaWindowInert": "Solo la cuota — o relleno primero por encima de un umbral 0 — puntúa una barra de uso, por lo que esta configuración no cambia nada para la estrategia de rotación actual.", + + "accountPool.priority": "Orden de selección", + "accountPool.priorityAria": "Orden de selección para esta cuenta", + "accountPool.priorityHint": "Primero se usan números más altos. El grupo se mueve a un número inferior solo cuando todas las cuentas anteriores se agotan o no están disponibles.", + "accountPool.priorityFirst": "Primero", + "accountPool.priorityEarlier": "Anterior", + "accountPool.priorityNormal": "Normal", + "accountPool.priorityLater": "Más tarde", + "accountPool.priorityLast": "Ultima", + "accountPool.priorityOption": "{name} ({value})", + "accountPool.priorityCustom": "Personalizado", + "accountPool.priorityUpdated": "Orden de selección actualizado para {email}", + "accountPool.priorityUpdateFailed": "No se pudo guardar el orden de selección para {email}. Se muestra el último valor confirmado.", + "accountPool.autoSwitchThreshold": "Umbral de cuenta personalizado", + "accountPool.autoSwitchThresholdAria": "Umbral de uso para {email}", + "accountPool.autoSwitchOverrideAria": "Anular el umbral de uso global para {email}", + "accountPool.autoSwitchHint": "Anula el umbral global para esta cuenta. 0 desactiva el cambio proactivo basado en el uso desde esta cuenta.", + "accountPool.autoSwitchUpdated": "Umbral de uso actualizado para {email}", + "accountPool.autoSwitchUpdateFailed": "No se pudo guardar el umbral de uso para {email}. Se muestra el último valor confirmado.", + + "codexAuth.switched": "{email} está seleccionado para la siguiente solicitud", + "codexAuth.loadFailed": "La configuración de la cuenta Codex no se pudo cargar.", + "codexAuth.accountsRefreshFailed": "La última actualización de la cuenta falló. Las cuentas de abajo son las últimas confirmadas.", + "codexAuth.switchFailed": "La cuenta no se pudo cambiar. Su selección anterior no ha cambiado.", + "codexAuth.removeConfirm": "¿Eliminar {id}?", + "codexAuth.removeFailed": "No se pudo eliminar la cuenta. Nada había cambiado.", + "codexAuth.addTitle": "Agregar cuenta de Codex", + "codexAuth.addIdLabel": "ID de cuenta (slug)", + "codexAuth.addIdPlaceholder": "codex-work, codex-alt, team...", + "codexAuth.resetCreditsAria": "{count} restablecer crédito(s)", + "codexAuth.addJsonLabel": "Contenido auth.json", + "codexAuth.addHelp": "Copia el archivo ~/.codex/auth.json de otro equipo o utiliza codex-auth export.", + "codexAuth.importBtn": "Importación", + "codexAuth.importInvalidJson": "Inválido JSON", + "codexAuth.importMissingTokens": "Falta access_token o refresh_token en JSON", + "codexAuth.importMissingId": "Se requiere identificación de cuenta", + "codexAuth.accountAdded": "Cuenta añadida al pool", + "codexAuth.addPickDesc": "Inicie sesión con otra cuenta ChatGPT para agregarla al grupo.", + "codexAuth.oauthLogin": "OAuth Inicio de sesión", + "codexAuth.oauthDesc": "Abre inicio de sesión de ChatGPT en el navegador", + "codexAuth.deviceLogin": "Inicio de sesión con código de dispositivo", + "codexAuth.deviceDesc": "Para un proxy sin cabeza o remoto: ingrese un código corto en otro dispositivo", + "codexAuth.importAuthJson": "Importar auth.json", + "codexAuth.importAuthJsonDesc": "Desde otra instalación de Codex o desde codex-auth export", + "codexAuth.back": "Atrás", + "codexAuth.oauthAlreadyInProgress": "Iniciar sesión ya está en curso. Complétalo en tu navegador.", + "codexAuth.oauthWaiting": "Esperando que el inicio de sesión de ChatGPT se complete en su navegador...", + "codexAuth.deviceOnlyEnforced": "Este proxy solo permite el inicio de sesión con código de dispositivo para las cuentas del pool de Codex (codexAuthMethod: device-only).", + "codexAuth.oauthSubmittingCode": "Envío de código…", + "codexAuth.oauthCodeSubmitted": "Código enviado — a la espera de inicio de sesión para terminar…", + "codexAuth.oauthStatusRetrying": "Error de red o proxy al comprobar el estado de inicio de sesión — retrying…", + "codexAuth.oauthCancelled": "El login fue cancelado.", + "codexAuth.loginFailed": "Inicio de sesión fallido", + "codexAuth.needsReauth": "Volver a iniciar sesión", + "codexAuth.reauthenticate": "Re-autenticar", + "codexAuth.tokenExpired": "Token expirado — reautenticar esta cuenta", + "codexAuth.weeklyConflict": "Se recibieron dos ventanas semanales: {first} y {second}. Es posible que el restablecimiento indicado arriba no reponga toda la cuota.", + "codexAuth.mainTokenExpired": "Token expiró — volver a iniciar sesión con un código de dispositivo a continuación, o mediante Codex App login", + "codexAuth.mainReauthSucceeded": "Firmado en", + "codexAuth.mainReauthFailed": "Error en el inicio de sesión", + "codexAuth.mainReauthCancel": "Cancelar", + "codexAuth.mainReauthCode": "Código", + "codexAuth.mainReauthOpen": "Abrir", + "codexAuth.mainReauthPending": "Esperando el inicio de sesión…", + "codexAuth.mainReauthDevice": "Volver a iniciar sesión con el código del dispositivo", + "codexAuth.emailCollision": "Esta cuenta coincide con su inicio de sesión Codex principal. Usa una cuenta diferente.", + + "codexAuth.resetCreditsTitle": "Restablecer créditos", + "codexAuth.resetCreditsAvailable": "Tienes crédito(s) de restablecimiento {count} disponibles.", + "codexAuth.resetCreditsDesc": "Cada crédito restablece sus límites de uso actuales por hora y semanalmente al instante.", + "codexAuth.noResetCredits": "No tienes créditos de reinicio.", + "codexAuth.earnCreditsHint": "Los créditos se obtienen mensualmente y a través del programa de referencia.", + "codexAuth.creditsExpireNote": "Los créditos expiran 30 días después de ganar.", + "codexAuth.useOneCredit": "Usar 1 crédito", + "codexAuth.confirmResetTitle": "¿Reiniciar el crédito?", + "codexAuth.confirmResetDesc": "Esto restablecerá inmediatamente sus límites de solicitudes actuales. Le quedan {count} créditos.", + "codexAuth.irreversible": "Esta acción no se puede deshacer.", + "codexAuth.useCredit": "Uso Crédito", + "codexAuth.redeeming": "Restablecimiento...", + "codexAuth.resetSuccess": "¡Límites de velocidad restablecidos! {remaining} crédito(s) restante.", + "codexAuth.resetSuccessGeneric": "¡Límites de velocidad restablecidos!", + "codexAuth.resetAlreadyRedeemed": "Este crédito ya fue redimido. Créditos sin cambios.", + "codexAuth.resetNothingToReset": "Ninguna ventana de límite de velocidad necesita reiniciarse en este momento.", + "codexAuth.resetNoCredit": "No hay créditos de reinicio disponibles.", + "codexAuth.resetError": "No se pudo canjear el crédito de restablecimiento. Por favor, inténtalo de nuevo.", + "codexAuth.fifoNote": "El crédito más antiguo se utiliza primero.", + "codexAuth.confirmWhichCredit": "Se utilizará el crédito de {date}.", + "codexAuth.creditNext": "Siguiente a usar", + "codexAuth.creditLabel": "Créditos: .{n}", + "codexAuth.creditNextBadge": "SIGUIENTE", + "codexAuth.creditGranted": "Otorgado {date}", + "codexAuth.creditExpires": "Caduca {date} ({days}d izquierda)", + "codexAuth.creditNoExpiry": "Sin vencimiento", + + "grokCoupon.badgeAria": "{count} Grok reset cupón (es)", + "grokCoupon.badgeErrorAria": "Los cupones de restablecimiento Grok no se pueden leer", + "grokCoupon.title": "Grok restablecer cupones", + "grokCoupon.available": "Esta cuenta tiene cupón(es) de restablecimiento {count}.", + "grokCoupon.desc": "Un cupón restablece la ventana de uso de esta cuenta Grok inmediatamente.", + "grokCoupon.none": "Esta cuenta no tiene cupones de reinicio.", + "grokCoupon.loadFailed": "No se pudo leer los cupones de restablecimiento para esta cuenta.", + "grokCoupon.loadFailedAuth": "Inicie sesión en esta cuenta xAI nuevamente para leer sus cupones.", + "grokCoupon.retry": "Inténtalo de nuevo", + "grokCoupon.couponLabel": "Cupón +- {n}", + "grokCoupon.couponNext": "Siguiente a usar", + "grokCoupon.couponNextBadge": "SIGUIENTE", + "grokCoupon.validFrom": "Válido desde {date}", + "grokCoupon.expires": "Caduca {date} ({days}d izquierda)", + "grokCoupon.useOne": "Utilizar 1 cupón", + "grokCoupon.fifoNote": "El cupón más cercano a la expiración se utiliza primero.", + "grokCoupon.confirmTitle": "¿Usar un cupón de restablecimiento?", + "grokCoupon.confirmDesc": "Esto restablece la ventana de uso Grok de esta cuenta ahora. Tienes cupón(es) {count}.", + "grokCoupon.confirmWhich": "Se utilizará el cupón que expira {date}.", + "grokCoupon.irreversible": "Esta acción no se puede deshacer.", + "grokCoupon.redeem": "Usar cupón", + "grokCoupon.redeeming": "Canjeando…", + "grokCoupon.redeemSuccess": "Cupón canjeado. {count} cupón(es) que quedan.", + "grokCoupon.redeemReplayed": "Esta redención ya se resolvió antes. Nada se volvió a consumir.", + "grokCoupon.redeemFailed": "La redención falló. Revisa la lista de cupones antes de volver a intentarlo.", + "grokCoupon.authFailed": "Inicie sesión en esta cuenta xAI de nuevo para utilizar sus cupones.", + "grokCoupon.noAccount": "No hay ninguna cuenta xAI disponible para este canje.", + "grokCoupon.noneAvailable": "No hay cupones de reinicio disponibles para canjear.", + "grokCoupon.identityMismatch": "Esa redención pertenece a otra cuenta. Cierre este cuadro de diálogo y vuelva a empezar.", + "grokCoupon.networkError": "No se pudo llegar al proxy.", + "grokCoupon.capacity": "El diario de la redención está lleno ahora mismo. Inténtalo de nuevo en un momento.", + "grokCoupon.noOperationId": "Este navegador no puede generar un ID de canje, por lo que el canje está desactivado aquí.", + "grokCoupon.unknownOutcome": "El resultado de la redención es desconocido. Vuelva a leer la cuenta para inspeccionar la disponibilidad del cupón; esto no puede confirmar el intento original.", + "grokCoupon.checkResult": "Volver a leer la cuenta", + "grokCoupon.checking": "Re-lectura…", + "grokCoupon.consumedElsewhere": "El cupón ya no aparece. La redención original permanece sin confirmar; no se enviará ninguna otra redención.", + "grokCoupon.unresolved": "El cupón todavía está en la lista. La redención original aún puede completarse; no se enviará ninguna otra redención.", + "anthropicGrant.badgeAria": "{count} Restablecimiento de uso Claude", + "anthropicGrant.badgeErrorAria": "No se pudieron leer los restablecimientos de uso de Claude", + "anthropicGrant.title": "restablecimientos de uso Claude", + "anthropicGrant.available": "Esta cuenta tiene reinicio(s) de uso {count}.", + "anthropicGrant.desc": "Un restablecimiento repone de inmediato los límites de Claude que figuran en la concesión. El día del reinicio semanal se mantiene.", + "anthropicGrant.none": "Esta cuenta no tiene reseteos de uso.", + "anthropicGrant.ineligible": "Esta cuenta no es elegible para restablecimientos de uso en este momento.", + "anthropicGrant.loadFailed": "No se pudo leer el restablecimiento de uso para esta cuenta.", + "anthropicGrant.loadFailedAuth": "Inicie sesión en esta cuenta Anthropic nuevamente para leer sus reinicios.", + "anthropicGrant.retry": "Inténtalo de nuevo", + "anthropicGrant.resetsLeft": "{left} de {total} izquierda", + "anthropicGrant.validFrom": "Válido desde {date}", + "anthropicGrant.expires": "Caduca {date} ({days}d izquierda)", + "anthropicGrant.windowFiveHour": "5 horas {percent}%", + "anthropicGrant.windowWeekly": "Semanal {percent}%", + "anthropicGrant.windowOverage": "{percent}% adicional", + "anthropicGrant.paused": "Detenido", + "anthropicGrant.notUsable": "Todavía no se puede utilizar", + "anthropicGrant.requiresLimit": "Usable una vez que esta cuenta alcanza un límite", + "anthropicGrant.chooseLabel": "Elige un restablecimiento", + "anthropicGrant.pickHint": "Está seleccionado el restablecimiento que vence primero. Puedes elegir otro.", + "anthropicGrant.exhausted": "No quedan restablecimientos", + "anthropicGrant.confirmExpires": "Vence el {date}", + "anthropicGrant.confirmClears": "Restablece: {windows}", + "anthropicGrant.confirmClearsUnknown": "No se informaron los límites que repone este restablecimiento.", + "anthropicGrant.clearsFiveHour": "Límite de 5 horas", + "anthropicGrant.clearsWeekly": "Límite semanal", + "anthropicGrant.clearsOverage": "Uso adicional", + "anthropicGrant.useOne": "Usar 1 reinicio", + "anthropicGrant.confirmTitle": "¿Reiniciar los límites de uso ahora?", + "anthropicGrant.confirmDesc": "Esto rellena los límites de uso Claude de esta cuenta ahora y usa un restablecimiento.", + "anthropicGrant.confirmWhich": "Usos: {label}", + "anthropicGrant.irreversible": "Esta acción no se puede deshacer.", + "anthropicGrant.redeem": "Restablecer límites", + "anthropicGrant.redeeming": "Restablecimiento…", + "anthropicGrant.resultReset": "Límites restablecidos. {count} Reset(s) izquierda.", + "anthropicGrant.resultAlreadyUsed": "Este restablecimiento ya se ha utilizado.", + "anthropicGrant.resultNotLimited": "Esta cuenta no está en un límite, por lo que no se utilizó nada.", + "anthropicGrant.resultCooldown": "Los reinicios se están enfriando para esta cuenta. No se utilizó nada.", + "anthropicGrant.resultIneligible": "Esta cuenta ya no es elegible. No se utilizó nada.", + "anthropicGrant.resultUnavailable": "Los resets no están disponibles en este momento. No se utilizó nada.", + "anthropicGrant.resultRateLimited": "Demasiadas peticiones. No se usó nada; inténtalo de nuevo en un minuto.", + "anthropicGrant.resultAuthError": "Inicie sesión en esta cuenta Anthropic de nuevo. No se utilizó nada.", + "anthropicGrant.replayed": "Este restablecimiento ya se resolvió antes. No se volvió a utilizar nada.", + "anthropicGrant.notUsableNow": "Este restablecimiento no se puede usar ahora mismo. Vuelve a leer la cuenta.", + "anthropicGrant.inFlight": "Este restablecimiento aún se está procesando. Espera un momento, y luego vuelve a leer la cuenta.", + "anthropicGrant.unresolvedPrior": "Aún no se confirma un intento anterior de restablecimiento en esta cuenta. Reintenta esa operación antes de iniciar otra.", + "anthropicGrant.expired": "El primer intento no pudo ser confirmado a tiempo. Vuelva a leer la cuenta antes de usar un restablecimiento.", + "anthropicGrant.identityMismatch": "Ese restablecimiento pertenece a otra cuenta. Cierre este cuadro de diálogo y vuelva a empezar.", + "anthropicGrant.sessionRequired": "Abra el panel de control desde su propio inicio de sesión para usar restablecimientos.", + "anthropicGrant.journalBusy": "El diario de reinicio está ocupado o no disponible. No se usó nada; inténtalo de nuevo en un momento.", + "anthropicGrant.failed": "La solicitud de restablecimiento falló. Revisa la cuenta antes de volver a intentarlo.", + "anthropicGrant.noOperationId": "Este navegador no puede generar un ID de solicitud, por lo que los restablecimientos se desactivan aquí.", + "anthropicGrant.unknownOutcome": "El reinicio no respondió a tiempo, por lo que se desconoce su resultado. El reintento envía el mismo ID de solicitud, por lo que no puede iniciar un segundo reinicio.", + "anthropicGrant.retrySame": "Reintentar la misma solicitud", + "anthropicGrant.checkResult": "Volver a leer la cuenta", + "anthropicGrant.checking": "Re-lectura…", + + "api.title": "Acceso API", + "api.subtitle": "Use las claves API generadas para acceder al proxy opencodex desde aplicaciones externas. Las claves se autentican mediante la cabecera {authHeader}; consulte la tabla para ver qué acepta cada endpoint.", + "api.baseUrl": "URL base", + "api.responsesEndpoint": "Responses API", + "api.chatCompletionsEndpoint": "Chat Completions API", + "api.messagesEndpoint": "Messages API", + "api.geminiEndpoint": "API de Gemini", + "api.modelsEndpoint": "Modelos API", + "api.surface.on": "Activado", + "api.surface.off": "Desactivado", + "api.surface.source.fixed": "Siempre servido", + "api.surface.source.default": "Activado de forma predeterminada", + "api.surface.source.explicit": "Configuración explícita", + "api.surface.source.inherited": "Heredado de la configuración Claude", + "api.surface.source.invalid": "Valor inválido — cerrado", + "api.surface.messagesToggle": "Servir el Messages API", + "api.surface.geminiToggle": "Servir la API de Gemini", + "api.surface.messagesCloseNote": "Desactivar Messages también desactiva la integración Claude, por lo que una versión anterior de opencodex mantiene el punto final cerrado también.", + "api.surface.openClaude": "Configuración de Claude", + "api.surface.toggleFailed": "La configuración Messages no se pudo guardar.", + "api.surface.toggleUnavailable": "Esta versión proxy no puede cambiar el Messages API aquí. Usa la página Claude en su lugar.", + "api.surface.geminiToggleFailed": "No se pudo guardar la configuración de la API de Gemini.", + "api.surface.geminiToggleUnavailable": "Esta versión del proxy no puede cambiar aquí la API de Gemini.", + "api.surface.closedNote": "Las solicitudes a este punto final se rechazan con 403.", + "api.endpointNote": "Usa la base URL con clientes compatibles con OpenAI. Responses y Chat Completions están expuestos bajo /v1.", + "api.endpointsTitle": "Puntos finales", + "api.authTitle": "Autenticación", + "api.authLoopback": "El acceso de loopback es específico para la ruta; los clientes de audio independientes requieren una clave de datos OpenCodex. Los enlaces remotos requieren una clave de datos o OPENCODEX_API_AUTH_TOKEN.", + "api.authBaseUrlNote": "Configure los clientes con el URL base y, a continuación, elija el punto final específico del protocolo a continuación.", + "api.newKeyTitle": "Nueva clave creada", + "api.newKeyNote": "Copia esta llave ahora. Puede volver a mostrarlo más tarde haciendo clic en él en la lista de claves.", + "api.copy": "Copiar", + "api.copied": "Copiado", + "api.dismiss": "Desestimar", + "api.generateTitle": "Generar clave", + "api.keyNamePlaceholder": "Nombre de la clave (opcional)", + "api.generate": "Generar", + "api.generating": "Creación de…", + "api.activeKeys": "Claves activas ({count})", + "api.activeKeysLoading": "Claves activas", + "api.noKeys": "Todavía no hay claves API. Genere una arriba.", + "api.workspace.sections": "Secciones API", + "api.section.keys": "Claves", + "api.section.connect": "Conectar", + "api.section.endpoints": "Puntos finales", + "api.section.models": "Modelos", + "api.section.examples": "Ejemplos", + "api.section.plan": "Vista previa de ruta", + "api.plan.title": "Vista previa de la ruta de una solicitud", + "api.plan.description": "Muestra la ruta que tomaría una solicitud de este modelo a través del proxy. Una vista previa no envía nada de origen y no cuesta nada.", + "api.plan.modeNote": "Native describe cómo se entrega una solicitud. No es un resultado de verificación.", + "api.plan.unavailable": "Esta versión proxy no ofrece vistas previas de rutas.", + "api.plan.noModels": "No hay modelos para previsualizar todavía.", + "api.plan.model": "Modelo", + "api.plan.inbound": "Cliente API", + "api.plan.features": "Características de la solicitud", + "api.plan.preview": "Vista previa", + "api.plan.previewing": "Previsualización…", + "api.plan.failed": "La vista previa no se pudo calcular.", + "api.plan.overallMode": "Entrega", + "api.plan.routeKind": "Ruta", + "api.plan.reasons": "Motivos", + "api.plan.guaranteed": "Garantizado por todos los candidatos", + "api.plan.partial": "Sólo algunos candidatos", + "api.plan.policyRevision": "Revisión de políticas", + "api.plan.noCandidates": "Ninguna ruta coincide con este modelo.", + "api.plan.ineligible": "Rechazado bajo la política actual", + "api.plan.requestPath": "Ruta de solicitud", + "api.plan.responsePath": "Ruta de respuesta", + "api.plan.fidelity": "Fidelidad", + "api.plan.none": "Ninguno", + "api.plan.noPath": "No hay camino", + "api.plan.noFeatures": "No se han seleccionado características de solicitud.", + "api.plan.mode.native": "Nativo", + "api.plan.mode.translated": "Traducido", + "api.plan.mode.legacyBridge": "Puente heredado", + "api.plan.mode.blocked": "Bloqueado", + "api.plan.fidelity.preserved": "Conservado", + "api.plan.fidelity.degraded": "Degradación", + "api.plan.fidelity.unknown": "Desconocido", + "api.plan.routeKind.direct": "Direct", + "api.plan.routeKind.combo": "Combo", + "api.plan.routeKind.policy": "Política de enrutamiento", + "api.plan.routeKind.unknown": "Modelo desconocido", + "api.plan.disposition.passthrough": "Pasó por", + "api.plan.disposition.translated": "Traducido", + "api.plan.disposition.degraded": "Degradación", + "api.plan.disposition.unsupported": "Caído", + "api.plan.disposition.unknown": "Desconocido", + "api.workspace.details": "Detalles de la clave API", + "api.workspace.keyDetails": "Detalles clave", + "api.workspace.keyPrefix": "Prefijo clave", + "api.workspace.deleteKey": "Eliminar clave", + "api.workspace.deleteConfirm": "¿Seguro que quieres borrar esta clave? Esto no se puede deshacer.", + "api.workspace.usageExamples": "Ejemplos de uso", + "api.copyUrlHint": "Haga clic para copiar URL", + "api.urlCopied": "URL copiado", + "api.copyExampleHint": "Haga clic para copiar el ejemplo", + "api.exampleCopied": "Ejemplo copiado", + "api.colName": "Nombre", + "api.colKey": "Clave", + "api.colActions": "Acciones", + "api.key.revealAria": "Mostrar la clave completa para {name}", + "api.key.hideAria": "Ocultar la clave completa para {name}", + "api.key.revealHint": "Haga clic para mostrar la clave completa", + "api.key.hideHint": "Haga clic para ocultar la clave completa", + "api.key.revealFailed": "No se pudo cargar la clave completa.", + "api.key.revealDenied": "Mostrar una clave almacenada requiere una sesión autorizada por el operador. Empareja este navegador para continuar o inicia sesión a través de una identidad Tailscale de confianza.", + "api.key.mutationHidden": "Se creó la clave o se inició su rotación, pero el valor de una sola vez se ocultó porque cambió la sesión o la vista.", + "api.key.copyFailedShort": "No podía copiar. Selecciona la clave y cópiela manualmente.", + "api.key.deleteRowAria": "Eliminar {name}", + "api.key.deleteShort": "Eliminar", + "api.colCreated": "Creado", + "api.confirm": "Confirmar", + "api.deleteAria": "Eliminar la clave API", + "api.modelsTitle": "Catálogo de modelos externos", + "api.modelsCount": "{count} disponibles para llamadas", + "api.modelsLoading": "Cargando modelos…", + "api.modelsSearch": "Modelos de búsqueda", + "api.modelsSubtitle": "Usa estos identificadores exactos de modelo con /v1/models y el protocolo de entrada que elijas.", + "api.modelsEmpty": "No hay modelos externamente accesibles todavía.", + "api.modelsNoMatch": "No hay modelos que coincidan con \"{query}\".", + "api.modelsLoadFailed": "No se pudo cargar el catálogo de modelos externos.", + "api.colModel": "Modelo", + "api.colSource": "Fuente", + "api.colProtocols": "Protocolos", + "api.sourceNative": "ChatGPT grupo", + "api.sourceCombo": "Ruta combinada", + "api.sourceCustom": "Personalizado", + "api.protocolResponses": "Responses", + "api.protocolChatCompletions": "Chat Completions", + "api.protocolMessages": "Messages", + "api.copyModelId": "Copiar ID", + "api.modelCopied": "Copiado", + "api.testModel": "Prueba", + "api.testingModel": "Probando…", + "api.testSucceeded": "OK", + "api.testFailed": "Falló", + "api.usageChatTitle": "Ejemplo de Chat Completions", + "api.usageResponsesTitle": "Ejemplo de Responses", + "api.usageMessagesTitle": "Ejemplo de Messages", + "api.usageGeminiTitle": "Ejemplo de Gemini", + "api.usageSampleInput": "¡Hola, mundo!", + "api.clientConfig.title": "Configuración del cliente", + "api.clientConfig.rowsLabel": "Conectar un cliente", + "api.clientConfig.details": "Detalles", + "api.clientConfig.detailsAria": "Detalles de la configuración de {client}", + "api.clientConfig.copyAria": "Copiar la configuración de {client}", + "api.clientConfig.downloadAria": "Descargar la configuración de {client}", + "api.clientConfig.rowMeta": "{destination} · {count} modelo(s)", + "api.clientConfig.rowError": "No se pudo construir la configuración {client}.", + "api.clientConfig.copiedAnnounceClient": "{client} config copiado al portapapeles.", + "api.clientConfig.clientOpencode": "OpenCode", + "api.clientConfig.clientPi": "Pi", + "api.clientConfig.clientOmp": "OMP", + "api.clientConfig.clientHermes": "Hermes", + "api.clientConfig.clientOpenclaw": "OpenClaw", + "api.clientConfig.clientKimi": "Kimi Code", + "api.clientConfig.clientGajae": "gjc", + "api.clientConfig.clientDsh": "DeepSeek Harness (DSH)", + "api.clientConfig.clientMcode": "MiniMax Code", + "api.clientConfig.clientZcode": "ZCode", + "api.clientConfig.clientCommandCode": "Command Code", + "api.clientConfig.clientPrime": "Prime Agent", + "api.clientConfig.clientAside": "Aside", + "api.clientConfig.clientRaycast": "Raycast", + "api.clientConfig.clientOmo": "omo", + "api.clientConfig.clientCline": "Cline CLI", + "api.clientConfig.clientKilo": "Kilo", + "api.clientConfig.clientDroid": "Factory Droid", + "api.clientConfig.clineBundle": "Este es un paquete de dos archivos, no un archivo de configuración de Cline. Incorpora la configuración a providers.json y el catálogo a models.json en el mismo directorio. Usa el interruptor de integración para escribir los cambios con copia de seguridad.", + "api.clientConfig.clineDownloaded": "Descargado {filename}. Nada ha cambiado todavía; la configuración y el catálogo pertenecen a dos archivos Cline separados.", + "api.clientConfig.copy": "Copiar configuración", + "api.clientConfig.download": "Descargar", + "api.clientConfig.loading": "Preparando la configuración del cliente…", + "api.clientConfig.jsonLabel": "Configuración de {client}", + "api.clientConfig.destination": "Archivo de destino", + "api.clientConfig.envHint": "Establecer la clave antes del lanzamiento", + "api.clientConfig.mergeWarning": "Combina esto en el archivo de destino. Reemplazarlo eliminaría la configuración de otros proveedores y MCP.", + "api.clientConfig.modelCount": "{count} modelo(s) exportados", + "api.clientConfig.missingLimits": "{count} de los modelos {total} se envía sin límite de contexto; el cliente aplica sus propios valores predeterminados.", + "api.clientConfig.noKeyYet": "{env} no tiene ninguna clave detrás de él todavía. Generar una clave de arriba antes de usar este loopback de configuración.", + "api.clientConfig.loadFailed": "No se pudo leer la lista de modelos, por lo que no se produjo ninguna configuración del cliente.", + "api.clientConfig.copiedAnnounce": "Configuración del cliente copiada en el portapapeles.", + "api.clientConfig.copyFailed": "No se pudo copiar la configuración del cliente.", + "api.clientConfig.downloadedAnnounce": "Descargado {filename}. Nada cambió aún — fusionarlo en {destination} usted mismo.", + "api.clientConfig.whereDisclosure": "A dónde va este archivo", + "api.clientConfig.whereBody": "El destino indicado arriba es la ruta global. Un archivo de configuración del proyecto en el directorio de trabajo tiene prioridad. El cliente lee la clave de la variable de entorno indicada en la configuración, nunca de este archivo.", + "api.keysLoadFailed": "No se pudieron cargar las claves API.", + "api.createFailed": "No se pudo crear la clave API.", + "api.deleteFailed": "No se pudo eliminar la clave API.", + "api.auth.endpoint": "Punto de conexión", + "api.auth.required": "Requerido", + "api.auth.accepted": "Aceptado", + "api.auth.rejected": "No se acepta", + "api.auth.testProtocol": "Prueba {protocol}", + "api.auth.testNeedsFreshKey": "Genere una clave y mantenga su valor único en la pantalla para ejecutar una prueba autenticada.", + "api.key.name": "Nombre clave", + "api.key.rename": "Renombrar", + "api.key.saveName": "Guardar nombre", + "api.key.renaming": "Guardando…", + "api.key.renameFailed": "No se pudo cambiar el nombre de la clave. Tu borrador se mantuvo.", + "api.key.deleting": "Borrar…", + "api.rotation.title": "Rotación de claves", + "api.rotation.description": "Emitir una clave de reemplazo mientras la clave actual sigue siendo válida para un breve solapamiento.", + "api.rotation.start": "Iniciar la rotación", + "api.rotation.starting": "Inicio…", + "api.rotation.pending": "La rotación está pendiente. Actualizar y verificar el cliente antes de comprometerse.", + "api.rotation.expires": "Caduca la superposición:", + "api.rotation.secretOnce": "Llave de repuesto — mostrada una vez. Copiado antes de cerrar este aviso.", + "api.rotation.commit": "Comprometer la rotación", + "api.rotation.abort": "Rotación del aborto", + "api.rotation.failed": "La acción de rotación no se completó. Refrésquese antes de volver a intentarlo.", + "api.rotation.startFailed": "No se pudo iniciar la rotación de claves.", + "api.key.copyFailed": "No se pudo copiar la clave. Selecciona y cópielo manualmente antes de descartar este panel.", + "api.attribution.title": "Uso atribuido", + "api.attribution.requests7d": "Solicitudes, últimos 7 días", + "api.attribution.totalRequests": "Total de solicitudes atribuidas", + "api.attribution.totalRequestsAvailable": "Solicitudes en el historial disponible", + "api.attribution.sinceAvailable": "Reconocimiento disponible desde", + "api.attribution.lastUsed": "Ultima vez usado", + "api.attribution.since": "Atribución desde", + "api.attribution.neverUsed": "No se utiliza desde que comenzó la atribución", + "api.attribution.unavailable": "Uso no disponible", + "api.attribution.unavailableDetail": "No se ha atribuido ningún uso todavía. Las solicitudes registradas antes de que comenzara la atribución no pueden asignarse retroactivamente.", + "api.attribution.ambiguous": "Dos claves comparten este ID, por lo que el uso no se puede atribuir a una de ellas. Dele a cada clave un ID único en el archivo de configuración.", + "api.attribution.railAmbiguous": "ID duplicado", + "claude.subtitle": "Enruta ocx claude a través de OpenCodex para que Claude Code use GPT, Gemini y otros modelos. Desactivarlo también detiene la interceptación, incluida la de proveedores oficiales, y la lista de modelos de Claude Desktop. Es la misma opción que el interruptor de Claude en la vista general de Conectar.", + "claude.pageTitle": "Claude Code", + "claude.workspace.settings": "General", + "claude.enabledLabel": "Conexión Claude", + "claude.saveBar.label": "Guardar la configuración de Claude Code", + "claude.saveBar.dirty": "Cambios no guardados", + "claude.saveBar.clean": "Sin cambios", + "claude.saveBar.revert": "Reversión", + "claude.enabledHint": "Cuando está apagado, Claude Code no puede usar este proxy.", + "claude.authMode": "Modo de autenticación", + "claude.authModeHint": "La suscripción requiere cuenta Claude, Proxy funciona sin cuenta Anthropic", + "claude.authModeSubscription": "Suscripción (cuenta Claude)", + "claude.authModeProxy": "Proxy (no se necesita cuenta)", + "claude.authModeAuto": "Auto (detectar la autenticación Claude)", + "claude.effectiveMode.label": "Efectivo en el próximo lanzamiento", + "claude.effectiveMode.manual": "Manual: {mode}", + "claude.effectiveMode.autoPresent": "Auto: suscripción — Claude autenticación encontrada a través de {source}", + "claude.effectiveMode.autoAbsent": "Auto: modo proxy — no se encuentra la autenticación Claude", + "claude.effectiveMode.autoUnknown": "Auto: la suscripción — no se pudo verificar", + "claude.effectiveMode.admissionKey": "La clave API de este proxy todavía se envía.", + "claude.authSource.claude-json-oauth": "Claude cuenta", + "claude.authSource.claude-credentials-file": "archivo de credenciales", + "claude.authSource.macos-keychain": "Llavero macOS", + "claude.authSource.exported-env": "variable de entorno", + "claude.authSource.unknown": "una credencial detectada", + "claude.systemEnv": "Auto-conexión", + "claude.systemEnvDesc": "Cuando está encendido, la ejecución de claude en cualquier terminal pasa automáticamente por el proxy.", + "claude.systemEnvUnsupported": "La conexión automática solo está disponible en macOS. En este sistema, inicie Claude con {cmd}.", + "claude.systemEnvWarn": "⚠ Debe cerrar completamente y volver a iniciar la aplicación de su terminal para que esto surta efecto. No se recomienda.", + "claude.fastMode": "Modo rápido (OpenAI)", + "claude.fastModeDesc": "Controla service_tier para los modelos OpenAI. ON : prioridad (más rápida). OFF : por defecto. Auto + passthrough (el cliente decide).", + "claude.fastAuto": "Automático", + "claude.fastOn": "ACTIVADO", + "claude.fastOff": "DESACTIVADO", + "claude.autoContext": "Usa el contexto grande automáticamente", + "claude.autoContextDesc": "Controla hasta dónde llega la marca 1M. ENCENDIDO: cualquier modelo cuya ventana pueda alojar el umbral de compactación obtiene una fila de gran contexto. OFF: solo los modelos verdaderos de 1M obtienen uno.", + "claude.autoContextInert": "Inactivo porque existe un valor de tamaño de contexto heredado (maxContextTokens) en el archivo de configuración. Quita allí para volver a habilitar.", + "claude.contextAccounting": "Contabilidad de contexto", + "claude.contextAccountingDesc": "1M: los modelos de ventana larga por defecto son 1M donde sea que opencodex elija el valor predeterminado. 200k: opencodex deja de marcar los modelos 1M automáticamente; una fila de 1M que elija usted mismo y una anulación de contexto que establezca siguen siendo aplicables.", + "claude.contextAccounting1m": "1M (predeterminado)", + "claude.contextAccounting200k": "200k", + "claude.autoCompactWindow": "Punto de resumen automático", + "claude.autoCompactDefault": "{value} (predeterminado)", + "claude.autoCompactWindowDesc": "Los mensajes más antiguos se resumen cuando el chat llega a este punto. Nunca excede el límite de cada modelo, por lo que los modelos de 200k no se ven afectados.", + "claude.autoCompactWindowWarn": "Cambiando esto se puede romper GPT modelos — establecido más alto que el límite real de un modelo, chats se error antes de que el resumen entra en juego.", + "claude.injectAgents": "Subagentes de registro automático", + "claude.injectAgentsDesc": "Registra los modelos seleccionados en la pestaña Subagentes (más el modelo predeterminado actual) como agentes despachables Claude Code (ocx-*). Se aplica desde la siguiente sesión.", + "claude.nativePassthrough": "Passthrough nativo de Claude", + "claude.nativePassthroughDesc": "Activado (predeterminado): un ID de modelo de Claude sin alias ni mapeo va directamente a Anthropic con el inicio de sesión propio de Claude Code cuando Claude Code lo envía; las demás solicitudes se enrutan. Desactivado: esos modelos pasan por el enrutamiento de modelos normal de OpenCodex. Cuando ese enrutamiento elige un proveedor OAuth de Anthropic, sus cuentas guardadas los atienden y se aplica el pool de cuentas de Claude si está activado. Los alias del selector de Claude y de Claude Desktop se resuelven antes de modelMap. Un ID sin procesar reclamado por modelMap sigue su mapeo en cualquiera de los dos modos. Reinicia las sesiones de Claude Code que ya estén en ejecución.", + "claude.nativePassthroughLoadFailed": "No se pudo cargar la configuración de passthrough.", + "claude.webSearchSidecar": "Anulación de búsqueda web sidecar", + "claude.webSearchSidecarHint": "Invalide el sidecar de búsqueda web principal para las solicitudes Claude Code.", + "claude.visionSidecar": "Anulación del sidecar de visión", + "claude.visionSidecarHint": "Anule el sidecar de visión principal para las solicitudes Claude Code.", + "claude.useMainSetting": "Usa la configuración principal", + "claude.sidecarModelPlaceholder": "Modelo de configuración principal", + "claude.quickstart": "Empezar", + "claude.quickstartHint": "{cmd} abre Claude Code a través del proxy. Su inicio de sesión claude.ai permanece activo.", + "claude.manualEnv": "Configuración manual (avanzada)", + "claude.smallFastModel": "Modelo de ayudante de fondo", + "claude.smallFastModelHint": "Modelo que Claude Code usa para tareas en segundo plano, como resumir chats o detectar temas. El alias de subagente haiku también lo usa. Vacío = valor predeterminado de Claude (Haiku).", + "claude.smallFastModelAccurateHint": "El modelo Claude Code utiliza para el trabajo en segundo plano, como resúmenes de chat y detección de temas. El alias del subagente haiku también lo usa.", + "claude.smallFastModelUnsetOption": "Deje que Claude Code elija (modelo nativo)", + "claude.smallFastModelNativeWarning": "Cuando no está activado, OpenCodex deja sin activar las anulaciones del modelo de ayuda. Claude Code puede usar su modelo de Sonet nativo, lo que puede incurrir en cargos de su proveedor nativo.", + "claude.slotUnset": "Usar Claude predeterminado", + "claude.modelMap": "Interceptación modelo", + "claude.modelMapHint": "Intercepta las solicitudes de un modelo específico y las redirige al que elija. Vaciar por defecto — no pasa nada hasta que se agrega una regla.", + "claude.mapFrom": "Modelo original (e.g. claude-sonnet-4-5)", + "claude.mapTo": "Cambiar a (e.g. gemini/gemini-3-pro)", + "claude.addMapping": "Añadir regla", + "claude.removeMapping": "Eliminar regla", + "claude.aliases": "Modelos disponibles", + "claude.aliasesHint": "Modelos que aparecen en el menú /model de Claude Code.", + "claude.aliasProviderOther": "Otros", + "claude.loading": "Cargando…", + "claude.loadFail": "No se pudo cargar la configuración de Claude", + "claude.saved": "Guardado.", + "claude.saveFailed": "Guardar falló", + "claude.networkError": "Error de red — ¿Está funcionando el proxy?", + "claude.toggleAria": "Activar la conexión Claude", + "claude.none": "Ninguno", + + "cws.loading": "Cargando combos…", + "cws.loadFailed": "No se pudo cargar combos.", + "cws.saveFailed": "No se pudo guardar el combo.", + "cws.removeFailed": "No se pudo eliminar el combo.", + "cws.saved": "Combo guardado.", + "cws.created": "Creado {model}.", + "cws.removed": "Eliminado combo/{id}.", + "cws.renamed": "Se cambió el nombre de {from} a {to}.", + "cws.add": "Añadir combo", + "cws.addTitle": "Añadir combo", + "cws.addSubtitle": "Cree un modelo virtual entre proveedores y elija el nombre exacto del modelo que los clientes solicitarán.", + "cws.create": "Crear combo", + "cws.jev.create": "Crear JEV Auto", + "cws.jev.exists": "JEV Auto ya existe.", + "cws.jev.setupHint": "Crea un combo opcional y totalmente editable. JEV elige un objetivo permitido y un esfuerzo de razonamiento para cada solicitud.", + "cws.jev.decisionService": "Servicio de decisión", + "cws.jev.decisionServiceDefault": "TypeSafe JEV (por defecto)", + "cws.err.invalidDecisionProvider": "No se puede utilizar el servicio de decisión {name} ({reason}). Elige otro servicio o TypeSafe JEV.", + "cws.jev.decisionIssue.missing": "no configurado", + "cws.jev.decisionIssue.notDecision": "No es un servicio de decisión", + "cws.jev.decisionIssue.disabled": "desactivado", + "cws.jev.decisionIssue.endpoint": "base URL debe terminar en /systemone", + "cws.jev.decisionIssue.model": "Sin modelo por defecto", + "cws.jev.decisionServiceDefaultHint": "El servicio de decisión alojado TypeSafe, autenticado con la clave del proveedor jev.", + "cws.jev.decisionServiceHint": "Servicio de decisión auto-alojado. Solo la clave API de este proveedor se envía a su punto final:", + "cws.jev.decisionServicesTitle": "Servicios de decisión JEV", + "cws.jev.sessionPin": "Mantener el destino elegido para la sesión", + "cws.jev.sessionPinTtl": "Ventana de inactividad (ms)", + "cws.jev.sessionPinHint": "Reutiliza el destino y el nivel de razonamiento elegidos hasta que la sesión quede inactiva. Cada turno completado renueva la ventana. Intervalo permitido: {min}–{max} ms (de 1 minuto a 24 horas).", + "cws.err.invalidSessionPin": "La ventana de inactividad del destino fijo debe ser un entero entre {min} y {max} ms.", + "cws.jev.decisionTimeout": "Tiempo de espera de decisión (ms)", + "cws.jev.decisionTimeoutHint": "Dejar vacío por defecto ({default} ms); permitido {min}–{max} ms. Cuando expira, JEV vuelve al primer objetivo elegible. Levántelo para modelos autoalojados lentos o fríos.", + "cws.jev.decisionTimeoutShort": "Tiempo de espera {ms} ms", + "cws.jev.decisionTimeoutDefaultShort": "Tiempo de espera predeterminado", + "cws.jev.decisionMethod": "Método de decisión", + "cws.jev.method.typesafe": "TypeSafe JEV (por defecto)", + "cws.jev.method.systemone": "Servidor compatible con System One", + "cws.jev.method.model": "Modelo opencodex", + "cws.jev.method.systemoneEmpty": "No se ha configurado ningún servidor de System One. Agregue un proveedor con el adaptador jev-decision cuya base URL termine en /systemone, por ejemplo un servidor Ollama que ejecute tev1.", + "cws.jev.decisionModel": "Modelo de decisión", + "cws.jev.decisionModelHint": "Cualquier modelo al que OpenCodex pueda enrutar. Recibe el estado de decisión acotado y las opciones permitidas, y debe responder en JSON con la clave de una opción. Utiliza las credenciales guardadas en su proveedor, nunca las de quien realiza la solicitud, y no puede ser este combo ni otro combo JEV.", + "cws.err.invalidDecisionModel": "Elige un modelo de decisión que opencodex pueda enrutar. No puede ser este combo u otro combo JEV.", + "cws.jev.test": "Prueba", + "cws.jev.testing": "Probando…", + "cws.jev.testHint": "Envía una tarea sintética con opciones de marcador de posición al método seleccionado. Nada se salva.", + "cws.jev.testOk": "Respondida en {ms} ms vía {backend}.", + "cws.jev.testFailOpen": "Fallo al abrir ({gate}) después de {ms} ms. Las solicitudes usarían el primer objetivo elegible.", + "cws.jev.testError": "No se pudo ejecutar la prueba: {error}", + "cws.jev.backend.typesafe": "TypeSafe", + "cws.jev.backend.systemone": "Servidor System One", + "cws.jev.backend.model": "Modelo opencodex", + "cws.jev.backend.unknown": "Desconocido (discos más antiguos)", + "cws.jev.stats.backends": "Decisiones por método", + "cws.jev.stats.backend": "Método", + "cws.jev.stats.applied": "Aplicado", + "cws.jev.stats.latency": "Latencia media", + "cws.err.invalidDecisionTimeout": "El tiempo de espera de decisión debe ser un entero de {min} a {max} ms, o vacío para el valor predeterminado.", + "cws.jev.failOpen": "Objetivo abierto por error", + "cws.jev.modelProfile": "Notas de modelo adicionales para JEV", + "cws.jev.modelProfilePlaceholder": "Opcional: dejar en blanco por ninguna nota adicional.", + "cws.jev.modelProfileHint": "Notas opcionales que complementan (nunca reemplazan) el perfil estándar incorporado: capacidad, contexto y costo de suscripción relativo. Enviado al servicio de decisión seleccionado con cada decisión JEV.", + "cws.err.invalidModelProfile": "Las notas del modelo deben tener como máximo 512 caracteres; los saltos de línea y las tabulaciones son los únicos caracteres de control permitidos.", + "cws.jev.allowedEfforts": "JEV puede seleccionar", + "cws.jev.efforts": "Razonamiento esfuerzos: {efforts}", + "cws.jev.effortsUnknown": "Razonamiento esfuerzos no anunciados", + "cws.jev.effortsNone": "Ningún esfuerzo de razonamiento explícito", + "cws.jev.stats.tab": "Estadísticas", + "cws.jev.stats.range": "JEV rango de estadísticas", + "cws.jev.stats.refresh": "Actualizar", + "cws.jev.stats.loading": "Cargando las estadísticas de JEV", + "cws.jev.stats.loadFailed": "No se pudieron cargar las estadísticas de JEV.", + "cws.jev.stats.historyIncomplete": "Algunos registros JEV más antiguos se omitieron, por lo que estos totales pueden estar incompletos.", + "cws.jev.stats.emptyTitle": "No JEV decisiones todavía", + "cws.jev.stats.emptyBody": "Ejecuta este combo para grabar selecciones y el uso del modelo token. Las decisiones tomadas antes de que se instalara el soporte de estadísticas no están disponibles.", + "cws.jev.stats.decisions": "Decisión", + "cws.jev.stats.appliedAndFailOpen": "{applied} aplicado · {failOpen} fail-ope", + "cws.jev.stats.modelTokens": "Modelo tokens", + "cws.jev.stats.decisionTokens": "JEV decisión tokens", + "cws.jev.stats.measuredAttempts": "{measured}/{total} intentos medidos", + "cws.jev.stats.measuredDecisions": "{measured}/{total} decisiones informó el uso", + "cws.jev.stats.successful": "Solicitudes exitosas de {count}", + "cws.jev.stats.fallbackOne": "{count} modelo de reserva", + "cws.jev.stats.fallbackMany": "Modelo {count}", + "cws.jev.stats.averageLatency": "Latencia promedio de JEV: {value}", + "cws.jev.stats.averageConfidence": "Confianza media: {value}", + "cws.jev.stats.gates": "JEV puertas de decisión", + "cws.jev.stats.model": "Modelo", + "cws.jev.stats.otherModels": "Otros modelos", + "cws.jev.stats.picks": "Selecciones", + "cws.jev.stats.efforts": "Medidas adoptadas", + "cws.jev.stats.attempts": "Intentos", + "cws.jev.stats.input": "Entrada", + "cws.jev.stats.output": "Salida", + "cws.jev.stats.reasoning": "Razonamiento", + "cws.jev.stats.cacheReadWrite": "Caché R/W", + "cws.jev.stats.total": "Total", + "cws.jev.stats.noEffort": "ninguno", + "cws.jev.stats.measuredShort": "medido", + "cws.jev.stats.tokenFootnote": "Los tokens del modelo proceden de los intentos en destinos reales, incluidos reintentos y rutas alternativas. El servicio de decisión informa por separado los tokens de decisión JEV.", + "cws.railAria": "Lista combinada", + "cws.searchPlaceholder": "Buscar combos u objetivos…", + "cws.noSearchResults": "No hay combos que coincidan con tu búsqueda.", + "cws.group.failover": "Conmutación por error", + "cws.group.roundRobin": "Round-robin", + "cws.group.other": "Otras estrategias", + "cws.targetCount": "Objetivos {count}", + "cws.targetCountOne": "1 objetivo", + "cws.overviewTitle": "Combos", + "cws.overviewBlurb": "Modelos virtuales que se enrutan a través de objetivos de proveedor/modelo con conmutación por error, round-robin, aleatorio ponderado, menos usado o el restablecimiento de cuota más rápido.", + "cws.count.total": "Total", + "cws.count.failover": "Conmutación por error", + "cws.count.roundRobin": "Round-robin", + "cws.count.other": "Otros", + "cws.howTitle": "Cómo funciona", + "cws.howBody": "Solicita a Codex el nombre público del modelo del combo. Si no se ha definido uno, el valor predeterminado es combo/. OpenCodex selecciona un destino y cambia a otro solo ante fallos del proveedor que admitan reintento. Si no queda ningún destino disponible, rechaza la solicitud sin recurrir al proveedor global predeterminado.", + "cws.attentionTitle": "Necesita atención", + "cws.attention.empty": "No hay objetivos configurados", + "cws.attention.few": "Solo un destino de conmutación por error — no tiene dónde saltar", + "cws.attention.catalogOmitted": "Las capacidades de los miembros de — que faltan en el catálogo de modelos son incompletas o incompatibles (ventana de contexto/metadatos faltantes o intersección de modalidad vacía). El enrutamiento por alias sigue funcionando", + "cws.attention.allTargetsExhausted": "Todos los objetivos habilitados están fuera de cuota", + "cws.emptyTitle": "Crea tu primer combo", + "cws.empty.createDesc": "Añade al menos un destino. Usa dos o más para tener alternativas si uno falla.", + "cws.backToAll": "Volver a todos los combos", + "cws.allCombos": "Todos los combos", + "cws.copyModel": "Copiar id", + "cws.copied": "Copiado", + "cws.tabsLabel": "Secciones de detalle combo", + "cws.tab.config": "Configuración", + "cws.tab.about": "Acerca de", + "cws.strategy": "Estrategia", + "cws.strategy.failover": "Conmutación por error", + "cws.strategy.roundRobin": "Round-robin", + "cws.strategy.random": "Al azar", + "cws.strategy.leastUsed": "Menos utilizados", + "cws.strategy.resetWindow": "Reiniciar-ventana", + "cws.strategy.jev": "JEV", + "cws.strategy.failoverHint": "Prueba los objetivos en orden. Si el primero falla con un error reintentable (límite de velocidad, interrupción, puerta de suscripción), salte al siguiente.", + "cws.strategy.roundRobinHint": "Equilibrar el tráfico por peso. Mantenga cada destino seleccionado para un lote de solicitudes exitosas y luego avance.", + "cws.strategy.randomHint": "Selecciona un destino elegible por solicitud, con una probabilidad proporcional a su peso. No mantiene afinidad entre solicitudes.", + "cws.strategy.leastUsedHint": "Enruta cada solicitud al objetivo elegible con el menor número de éxitos registrados. Cuentas reiniciar con el proxy.", + "cws.strategy.resetWindowHint": "Prefiere el objetivo elegible cuya ventana de cuota se restablezca lo antes posible. Vuelve al orden de configuración cuando faltan datos de cuota.", + "cws.strategy.jevHint": "Solicite al servicio de decisión JEV seleccionado que elija un objetivo elegible y un esfuerzo compatible. Si la decisión no está disponible, utilice el primer objetivo elegible.", + "cws.field.id": "Identificación combinada", + "cws.field.idHint": "Los clientes solicitarán {model}", + "cws.field.idInternalHint": "ID de combo interno. Puedes cambiarlo después de la creación.", + "cws.field.idHintEdit": "Cambiar el nombre del combo a un nuevo id. Los clientes solicitan {model}.", + "cws.field.alias": "Nombre de modelo público", + "cws.field.aliasPlaceholder": "deepseek-v4-flash o proveedor/modelo", + "cws.field.aliasHint": "Opcional. Usa un nombre sin prefijo, un prefijo personalizado como vendor/model, o deja el campo vacío para usar combo/.", + "cws.field.nativeAlias": "Alias nativo OpenAI", + "cws.field.nativeAliasHint": "Deje que este combo posea un identificador de modelo OpenAI nativo no calificado compatible. Las rutas OpenAI calificadas por cuenta y proveedor permanecen separadas.", + "cws.field.displayName": "Mostrar nombre", + "cws.field.displayNameHint": "Etiqueta del selector para este combo. Requerido cuando el alias nativo OpenAI está habilitado.", + "cws.field.stickyLimit": "Solicitudes exitosas con afinidad antes de rotar", + "cws.field.stickyLimitHint": "Conserve el objetivo seleccionado para estas muchas solicitudes exitosas antes de que avance el selector ponderado.", + "cws.field.defaultEffort": "Razonamiento por defecto", + "cws.field.defaultEffortNone": "Ninguno (objetivo predeterminado)", + "cws.field.defaultEffortHint": "Se usa solo cuando el cliente omite el esfuerzo de razonamiento. Las opciones son la intersección de los esfuerzos anunciados de los objetivos seleccionados; los metadatos de los objetivos sin esfuerzo de catálogo no ofrecen ninguno.", + "cws.capability.imageInputUnavailable": "Elige cada objetivo del catálogo primero — modelos desconocidos no pueden ser cubiertos por el Sidecar Visión.", + "cws.capability.imageInputHint": "Activado de forma predeterminada cuando cada destino admite imágenes. Desactivar para aceptar solo texto.", + "cws.capability.imageInputSidecarHint": "Por defecto. {models} se declarará solo texto al guardar y usar el sidecar Visión para imágenes.", + "cws.capability.imageInputSidecarDisabled": "Las imágenes — enviadas a {models} se reemplazan con una nota de omisión y la solicitud continúa sin ellas. Habilitarlo en la configuración del panel de control para restaurar las descripciones de las imágenes.", + "cws.capability.imageInputBlockedHint": "{models} no puede ser cubierto por el sidecar Visión: sus modalidades de entrada son desconocidas o no tienen texto.", + "cws.capability.imageInput": "Imagen / multimodal", + "cws.capability.adaptiveEffort": "Escala de razonamiento adaptativo", + "cws.capability.adaptiveEffortHint": "Off: un objetivo sin control de razonamiento oculta el selector de esfuerzo para todo el combo. Activado: esos objetivos permanecen utilizables y el selector mantiene los niveles que comparten los objetivos restantes.", + "cws.capabilities": "Capacidades", + "cws.field.defaultEffortUnsupported": "Este esfuerzo no se encuentra en la escalera común de los objetivos —, será ignorado o ajustado en el momento de la solicitud.", + "cws.field.defaultEffortUnsupportedOption": "No en la intersección", + "cws.targets": "Objetivos", + "cws.targets.failoverHint": "— primero es primario.", + "cws.targets.roundRobinHint": "Las pesas controlan la selección relativa determinista; el orden rompe los lazos en el anillo de rotación.", + "cws.targets.randomHint": "Las pesas controlan las probabilidades de cada sorteo; el orden no importa.", + "cws.targets.leastUsedHint": "El orden solo rompe los lazos entre objetivos igualmente utilizados.", + "cws.targets.resetWindowHint": "El orden se aplica cuando faltan datos de cuota o están vinculados.", + "cws.targets.jevHint": "Solo se pueden seleccionar estos objetivos. El orden determina el objetivo de apertura por error y el combo posterior.", + "cws.target.provider": "Proveedor", + "cws.target.model": "Modelo", + "cws.target.weight": "Peso", + "cws.target.pickProvider": "Seleccionar proveedor…", + "cws.target.pickProviderFirst": "Selecciona un proveedor primero…", + "cws.target.pickModel": "Seleccionar modelo…", + "cws.target.noModels": "No hay modelos para este proveedor", + "cws.target.modelPlaceholder": "ID de modelo", + "cws.target.add": "Añadir destino", + "cws.target.drag": "Arrastrar para reordenar", + "cws.target.moveUp": "Sube", + "cws.target.moveDown": "Baja", + "cws.quota.available": "Disponible", + "cws.quota.exhausted": "Fuera de cuota", + "cws.quota.unknown": "Cuota desconocida", + "cws.quota.allExhausted": "Todos los objetivos habilitados están fuera de cuota. Elige otro objetivo o espere a que se recupere la cuota.", + "cws.aboutTitle": "Entorno de ejecución", + "cws.aboutBody": "Los destinos que fallan entran brevemente en un periodo de espera que respeta Retry-After. Los errores de contexto o de solicitud no provocan un cambio de destino. Cada destino adapta el esfuerzo a sus capacidades; si se agotan los destinos del combo, se rechaza la solicitud. Los registros y Uso conservan el orden de los intentos reales y el consumo de cada uno.", + "cws.removeConfirmTitle": "¿Eliminar {model}?", + "cws.removeConfirmDesc": "Esto elimina el modelo virtual de la configuración y el catálogo Codex. No elimina a ningún proveedor.", + "cws.unsavedTitle": "Cambios no guardados", + "cws.unsavedDesc": "¿Descartar ediciones a este combo y continuar?", + "cws.keepEditing": "Sigue editando", + "cws.err.missingId": "Se requiere identificación combinada.", + "cws.err.invalidId": "Id debe comenzar con una letra o un número y usar solo letras, números, puntos, guiones bajos o guiones (máx. 64).", + "cws.err.duplicateId": "Un combo con este id ya existe.", + "cws.err.invalidAlias": "Los alias deben usar letras, números, puntos, guiones bajos o guiones con un segmento \"/\" como máximo.", + "cws.err.aliasReservedNamespace": "El alias no debe usar el espacio de nombres reservado \"combo/\".", + "cws.err.aliasNativeFamily": "Los alias sin prefijo no pueden usar las familias nativas de OpenAI (gpt-*, o1-*, o3-*, o4-*, codex-*).", + "cws.err.unsupportedNativeAlias": "El alias nativo debe ser un identificador de modelo de OpenAI sin prefijo que sea compatible actualmente.", + "cws.err.missingNativeAliasDisplayName": "Se requiere un nombre de visualización para los alias nativos.", + "cws.err.invalidDisplayName": "El nombre visible debe tener como máximo 128 caracteres y no contener caracteres de control.", + "cws.err.duplicateAlias": "Otro combo ya usa este alias.", + "cws.err.noTargets": "Añade al menos un objetivo.", + "cws.err.incompleteTarget": "Cada objetivo necesita un proveedor y un modelo.", + "cws.target.disabled": "{name} (deshabilitado)", + "cws.err.reservedNamespace": "Un proveedor físico llamado combo debe ser renombrado antes de crear combos.", + "cws.err.providerCollision": "El ID combinado entra en conflicto con un nombre de proveedor configurado.", + "cws.err.unknownProvider": "Cada target debe utilizar un proveedor configurado.", + "cws.err.duplicateTarget": "El mismo objetivo de proveedor/modelo puede aparecer solo una vez.", + "cws.err.invalidStickyLimit": "El número de solicitudes exitosas con afinidad debe ser un entero entre 1 y 100.", + "cws.err.invalidWeight": "Cada peso round-robin debe ser un número entero de 1 a 10000.", + "cws.err.invalidReasoningEfforts": "Cada objetivo JEV debe permitir al menos un esfuerzo de razonamiento soportado único.", + "cws.err.noEnabledTarget": "Al menos un objetivo debe usar un proveedor habilitado.", + "claude.tabsLabel": "Cliente Claude", + "claudeDesktop.title": "Claude Desktop", + "claudeDesktop.subtitle": "Enruta cada familia de modelos Claude a través de un modelo disponible en el puerto proxy {port}.", + "claudeDesktop.importJson": "Importar JSON", + "claudeDesktop.exportJson": "Exportar JSON", + "claudeDesktop.loading": "Cargando el perfil de Claude Desktop…", + "claudeDesktop.loadFail": "No se pudo cargar el perfil de Claude Desktop.", + "claudeDesktop.retry": "Reintentar", + "claudeDesktop.saveFailed": "No se pudo guardar el perfil de Claude Desktop.", + "claudeDesktop.applyFailed": "El perfil se guardó, pero no se pudo aplicar.", + "claudeDesktop.updateFailed": "No se pudo actualizar Claude Desktop.", + "claudeDesktop.savedApplied": "Perfil guardado y aplicado a Claude Desktop.", + "claudeDesktop.appliedMarkerUnsaved": "Se aplicó a Claude Desktop, pero no se guardó el registro de aplicación. El estado guardado/aplicado puede aparecer desactualizado hasta que vuelva a aplicarlo.", + "claudeDesktop.savedAppliedAnnounce": "Perfil de Claude Desktop guardado y aplicado.", + "claudeDesktop.saved": "Perfil guardado.", + "claudeDesktop.savedAnnounce": "Perfil de Claude Desktop guardado.", + "claudeDesktop.exported": "Perfil exportado como JSON.", + "claudeDesktop.importExpected": "Se esperaba un perfil de Claude Desktop de versión 1.", + "claudeDesktop.importReady": "JSON importado. Revisar el borrador, luego guardarlo y aplicarlo.", + "claudeDesktop.importedAnnounce": "Perfil JSON importado. Los cambios no guardados están listos para su revisión.", + "claudeDesktop.importInvalid": "El archivo seleccionado no es un perfil válido.", + "claudeDesktop.importFailed": "La importación falló. {error}", + "claudeDesktop.moved": "{route} se trasladó a {family}.", + "claudeDesktop.unsaved": "Cambios no guardados", + "claudeDesktop.upToDate": "Se guardaron todos los cambios", + "claudeDesktop.saving": "Guardando…", + "claudeDesktop.applying": "Aplicación…", + "claudeDesktop.saveApply": "Guardar y aplicar", + "claudeDesktop.emptyTitle": "No hay modelos disponibles", + "claudeDesktop.emptyHint": "Añada o active un proveedor y vuelva para asignar las rutas de Claude Desktop.", + "claudeDesktop.assignmentsLabel": "Asignaciones de familia de modelos Claude", + "claudeDesktop.family.opus": "Opus", + "claudeDesktop.family.fable": "Fable", + "claudeDesktop.family.sonnet": "Sonnet", + "claudeDesktop.family.haiku": "Haiku", + "claudeDesktop.modelCountOne": "Modelo {count}", + "claudeDesktop.modelCountMany": "{count} modelos", + "claudeDesktop.chooseDefault": "Elige un valor predeterminado", + "claudeDesktop.temporaryDefault": "Default temporal", + "claudeDesktop.laneEmpty": "Suelta un modelo aquí o usa su control de movimiento.", + "claudeDesktop.laneNoMatch": "Ningún modelo de esta familia coincide con tu búsqueda.", + "nav.grok": "Grok", + "grok.title": "Grok Build", + "grok.subtitle": "Modelos opencodex se ha registrado en su configuración de Grok.", + "grok.loading": "Cargando Grok estado…", + "grok.loadFail": "No se pudo leer la configuración de Grok.", + "grok.notConfiguredTitle": "Grok Build no está conectado", + "grok.notConfiguredHint": "Inicie o reinicie el proxy con Grok instalado y opencodex escribe un bloque administrado en:", + "grok.endpoint": "Punto de conexión", + "grok.colModel": "Modelo", + "grok.colAlias": "Alias Grok", + "grok.colContext": "Contexto", + "grok.groupNative": "Modelos nativos", + "grok.groupRouted": "Modelos enrutados", + "grok.enabledCount": "{on} de {total} registrado", + "grok.saved": "Selección guardada.", + "grok.savedApplied": "Selección guardada y escrita en su configuración Grok.", + "grok.saveFailed": "No se pudo guardar la selección Grok.", + "grok.applyFailed": "Selección guardada, pero la configuración Grok no se pudo actualizar.", + "grok.applySkipped": "Selección guardada. La configuración Grok no se modificó.", + "grok.saveApply": "Guardar y aplicar", + "grok.saving": "Guardando…", + "grok.applying": "Aplicación…", + "grok.unsaved": "Cambios no guardados", + "grok.upToDate": "La selección está actualizada", + "grok.toggleModel": "Registrar {id} con Grok", + "claudeDesktop.available": "Disponible", + "claudeDesktop.defaultBadge": "Predeterminado", + "claudeDesktop.roles.title": "Modelos", + "claudeDesktop.roles.default": "Modelo predeterminado", + "claudeDesktop.roles.defaultDesc": "Listado primero en Claude Desktop y enviado como el nivel Opus.", + "claudeDesktop.roles.quick": "Modelo de tarea rápida", + "claudeDesktop.roles.quickDesc": "Respuestas a las solicitudes de Haiku-tier de Claude Desktop.", + "claudeDesktop.roles.unset": "No establecido", + "claudeDesktop.roles.pick": "Elige un modelo", + "claudeDesktop.roles.unavailableOption": "{route} (no disponible)", + "claudeDesktop.roles.gatewayScope": "Estas opciones se aplican al modo de puerta de enlace, que escribe la lista de modelos de Claude Desktop.", + "claudeDesktop.roles.listTitle": "Lista de modelos de escritorio", + "claudeDesktop.roles.listHint": "Elige qué modelos muestra Claude Desktop. Solo cambia Claude Desktop; los demás clientes y la configuración del proveedor conservan sus modelos.", + "claudeDesktop.status.pendingApply": "Guardado · Aplica los cambios para actualizar Desktop", + "claudeDesktop.visibility.search": "Modelos de búsqueda", + "claudeDesktop.visibility.provider": "Proveedor", + "claudeDesktop.visibility.allProviders": "Todos los proveedores", + "claudeDesktop.visibility.selectShown": "Seleccionar todas las coincidencias", + "claudeDesktop.visibility.clearShown": "Deseleccionar todos los modelos que coinciden", + "claudeDesktop.visibility.toggle": "Mostrar {model} en Claude Desktop", + "claudeDesktop.visibility.selected": "{n} seleccionado", + "claudeDesktop.visibility.available": "Disponibles: {n}", + "claudeDesktop.visibility.applied": "Aplicados: {n}", + "claudeDesktop.visibility.appliedUnknown": "Se desconoce la lista aplicada", + "claudeDesktop.visibility.selectedUnavailable": "Seleccionados sin disponibilidad: {n}", + "claudeDesktop.visibility.newModels": "Modelos recién detectados", + "claudeDesktop.visibility.newShow": "Mostrar automáticamente", + "claudeDesktop.visibility.newHide": "Mantener ocultos hasta seleccionarlos", + "claudeDesktop.visibility.noneSelected": "Selecciona al menos un modelo disponible.", + "claudeDesktop.visibility.noMatch": "Ningún modelo coincide con este filtro.", + "claudeDesktop.visibility.previewTitle": "Al aplicar los cambios", + "claudeDesktop.visibility.previewAdds": "Añade: {models}", + "claudeDesktop.visibility.previewRemoves": "Quita: {models}", + "claudeDesktop.visibility.previewSame": "El perfil contiene los mismos ID de modelo. Aplica los cambios del perfil antes de reiniciar Desktop.", + "claudeDesktop.visibility.replaceNote": "Al aplicar los cambios, se sustituye la lista de modelos del perfil OpenCodex para Claude Desktop, aunque la hayas editado a mano. La asignación por nivel en Avanzado sigue siendo opcional. El modo de solo detección ignora esta selección.", + "claudeDesktop.roles.quickBadge": "Tareas rápidas", + "claudeDesktop.advanced.title": "Avanzado: Asignación de niveles Claude", + "claudeDesktop.advanced.desc": "Elige como qué nivel de Claude (Opus, Fable, Sonnet, Haiku) trata Claude Desktop a cada modelo.", + "claudeDesktop.advanced.empty": "vacío", + "claudeDesktop.supports1m": "1M", + "claudeDesktop.unavailable": "No disponible", + "claudeDesktop.contextM": "{n}M contexto", + "claudeDesktop.contextK": "{n}k contexto", + "claudeDesktop.contextUnknown": "contexto desconocido", + "claudeDesktop.alias": "Alias", + "claudeDesktop.useAsDefault": "Usar como {family} predeterminado", + "claudeDesktop.moveTo": "Mover a", + "claudeDesktop.move": "Mover", + "claudeDesktop.removeUnavailable": "Quitar", + "claudeDesktop.removeAllUnavailable": "Quitar los no disponibles ({n})", + "claudeDesktop.removeUnavailableHint": "Quita esta asignación y su alias. Guardar conserva el cambio; Guardar y aplicar también actualiza Claude Desktop.", + "claudeDesktop.removeUnavailableTierHint": "También quita {n} modelos no disponibles de este nivel, porque el modelo predeterminado debe estar disponible. Guardar conserva el cambio; Guardar y aplicar también actualiza Claude Desktop.", + "claudeDesktop.removedUnavailable": "Se quitaron {n} modelos no disponibles. Guarda para conservar el cambio, o guarda y aplica para actualizar Claude Desktop.", + "claudeDesktop.status.applied": "Aplicado al escritorio", + "claudeDesktop.status.stale": "La configuración de Desktop está desactualizada. Vuelve a aplicarla.", + "claudeDesktop.status.notApplied": "No se aplica", + "claudeDesktop.status.notActiveProfile": "El escritorio está sirviendo otro perfil — volver a aplicar", + "claudeDesktop.status.disabled": "La integración con Claude Desktop está desactivada. Cierra Desktop por completo y vuelve a abrirlo después de activarla.", + "claudeDesktop.enableApply": "Habilitar y aplicar", + "claudeDesktop.switchModeApply": "Cambiar el modo & aplicar", + "claudeDesktop.status.appliedFirstParty": "Primera parte: pestaña Código de escritorio enrutada a través del proxy local", + "claudeDesktop.mode.legend": "Modo de conexión", + "claudeDesktop.mode.firstParty": "Primera parte", + "claudeDesktop.mode.gateway": "Gateway (terceros)", + "claudeDesktop.mode.defaultBadge": "predeterminado", + "claudeDesktop.mode.current": "corriente", + "claudeDesktop.mode.firstPartyHint": "Desktop mantiene la sesión iniciada en claude.ai. Su pestaña Código usa OpenCodex cuando el modo first-party de Desktop está activado; la CLI independiente tiene su propio interruptor. Ambos leen el mismo env de configuración.", + "claude.intercept.start": "Iniciar interceptación", + "claude.intercept.starting": "Iniciando intercepción…", + "claude.intercept.reason.disabled": "Habilite el enrutamiento y la interceptación Claude primero.", + "claude.intercept.reason.client_role": "Este proceso es un cliente hub. Habilitar la interceptación en un servidor local.", + "claude.intercept.reason.ephemeral_port": "Establece claudeCode.intercept.port cuando el puerto público sea efímero.", + "claude.intercept.reason.port_in_use": "El puerto {port} está en uso. Libre o cambiar claudeCode.intercept.port.", + "claude.intercept.reason.port_mismatch": "Esta ejecución utiliza el puerto {bound}; puerto configurado {configured} difiere. Usa el puerto enlazado o restaure el valor configurado.", + "claude.intercept.reason.failed": "La intercepción no pudo comenzar. Vuelva a intentar después de comprobar la configuración del proxy local.", + "claude.intercept.reason.stopped": "El ciclo de vida de la intercepción se ha detenido. Inicie un servicio OpenCodex en ejecución.", + "claude.firstParty.label": "Claude Code CLI de primera mano", + "claude.firstParty.desc": "Permite que la claude independiente CLI mantenga su inicio de sesión Claude mientras su tráfico pasa a través del proxy de intercepción local.", + "claude.firstParty.aria": "Alternar Claude Code CLI de primera mano", + "claude.firstParty.risk": "Riesgo de la cuenta: la primera parte dirige el tráfico de suscripción Claude a través de un proxy de interceptación local. Anthropic puede tratar esto como una violación de los términos y suspender la cuenta.", + "claude.firstParty.shared": "Cuando se aplica el env proxy compartido, el otro Claude cliente también transita el proxy local como un relé sin cambios; TLS termina localmente. Establecer NO_PROXY='*' en el shell para uso terminal completamente nativo.", + "claude.firstParty.deadProxy": "La configuración de Claude env apunta a un proxy que no se está ejecutando. Inicie opencodex, o desactive Desktop/CLI first-party para eliminar la configuración antes de usar claude simple.", + "claude.firstParty.notApplied": "CLI first-party está activado, pero no se aplican sus configuración de proxy. Comprueba la configuración de Claude env antes de usar claude simple.", + "claude.firstParty.brokenProxy": "La intercepción no pudo comenzar. Vuelva a intentar después de comprobar la configuración del proxy local.", + "claude.firstParty.residual": "La configuración de Claude todavía apunta a un proxy OpenCodex, aunque no está activado el modo first-party de Desktop ni el de la CLI. Elimina la configuración de proxy restante o ejecuta `ocx ensure`.", + "claude.firstParty.routingOff": "opencodex no está sirviendo la intercepción Claude en su configuración actual (el enrutamiento Claude o la intercepción están desactivados, o esta máquina es un cliente de otro concentrador opencodex), por lo que estos configuración apuntan a un proxy que no los servirá. Vuelva a encenderlo en esta máquina o apague la configuración de primera persona para eliminar la configuración.", + "claude.firstParty.disabled": "Habilite el enrutamiento y la interceptación Claude primero.", + "claude.firstParty.foreign": "~/.claude/settings.json apunta al proxy opencodex pero confía en un certificado que opencodex no gestiona, por lo que las solicitudes fallan. Arreglar HTTPS_PROXY / NODE_EXTRA_CA_CERTS allí a mano.", + "claude.firstParty.local": "~/.claude/settings.json envía Claude Code a través de un proxy local en 127.0.0.1 que opencodex no puede confirmar como propio. Si ya no lo utiliza, quitar HTTPS_PROXY allí.", + "claude.firstParty.unknown": "opencodex no pudo determinar si ~/.claude/settings.json todavía apunta a su proxy.", + "claude.firstParty.refusal.interceptDisabled": "El proxy de intercepción está desactivado.", + "claude.firstParty.refusal.interceptUnavailable": "La intercepción no pudo comenzar. Vuelva a intentar después de comprobar la configuración del proxy local.", + "claude.firstParty.refusal.foreignEnv": "Otro programa posee la configuración del proxy Claude.", + "claude.firstParty.refusal.caUnavailable": "La autoridad de certificación local no está disponible.", + "claude.firstParty.refusal.unreadable": "La configuración de Claude no se pudo leer.", + "claude.firstParty.refusal.writeFailed": "La configuración de Claude no se pudo escribir.", + "claudeDesktop.mode.firstPartyRisk": "Riesgo de cuenta: la primera parte envía su tráfico de suscripción Claude a través de un proxy de intercepción local. Anthropic puede tratar esto como una violación de los términos y suspender la cuenta. Gateway es el valor predeterminado.", + "claudeDesktop.mode.gatewayHint": "Toda la aplicación cambia a OpenCodex como su puerta de enlace. El chat se ejecuta localmente; Las características de claude.ai no están disponibles.", + "claudeDesktop.mode.switchNote": "Al cambiar se reemplaza la configuración del otro modo. Después, cierra Desktop por completo y vuelve a abrirlo.", + "claudeDesktop.firstParty.proxyRunning": "Proxy local en 127.0.0.1:{port}", + "claudeDesktop.firstParty.proxyStopped": "La intercepción no pudo comenzar. Vuelva a intentar después de comprobar la configuración del proxy local. ({port})", + "claudeDesktop.firstParty.interceptDisabled": "El proxy de intercepción está deshabilitado en la configuración (claudeCode.intercept.enabled)", + "claudeDesktop.picker.title": "Selector de Claude Desktop", + "claudeDesktop.picker.hint": "Mostrar modelos OpenCodex en el selector de pestañas Código del escritorio a través del proxy local dedicado.", + "claudeDesktop.picker.toggle": "Activar el selector de Claude Desktop", + "claudeDesktop.picker.state.active": "Picker está activo", + "claudeDesktop.picker.state.restart": "Cierre completamente Claude Desktop y vuelva a abrirlo para terminar de aplicar el perfil del selector.", + "claudeDesktop.picker.state.trustPending": "Esperando la confianza del certificado", + "claudeDesktop.picker.state.trustDeclined": "La confianza del certificado fue rechazada", + "claudeDesktop.picker.state.proxyUnavailable": "El proxy del selector no se está ejecutando", + "claudeDesktop.picker.state.unsupported": "El modo Selector no es compatible con este sistema operativo", + "claudeDesktop.picker.state.notFirstParty": "El selector solo está disponible en modo first party", + "claudeDesktop.picker.state.profileFailed": "El perfil del selector no se pudo aplicar", + "claudeDesktop.picker.models": "Modelos de {count} disponibles en el selector", + "claudeDesktop.picker.offlineNote": "Con el selector activo, Claude Desktop accede a la red mediante OpenCodex. Si OpenCodex se detiene, Desktop pierde la conexión hasta que se reinicie OpenCodex o se desactive el selector.", + "claudeDesktop.firstParty.bindings.title": "Encuadernación de modelo de pestaña de código", + "claudeDesktop.firstParty.bindings.hint": "Claude Desktop conserva los nombres de Anthropic en el selector de la pestaña Code. Vincula una entrada del selector con un modelo de OpenCodex para que ese modelo atienda sus solicitudes. Solo el tráfico de Claude Code que pasa por el proxy local (la pestaña Code de Desktop y la CLI claude) usa estas vinculaciones; ocx claude no cambia. Se aplican en la siguiente solicitud, sin cerrar y volver a abrir la aplicación.", + "claudeDesktop.firstParty.bindings.empty": "Sin ataduras aún Los modelos de selector — siguen su ruta predeterminada.", + "claudeDesktop.firstParty.bindings.pickerLabel": "Selector de modelo id", + "claudeDesktop.firstParty.bindings.pickerPlaceholder": "claude-sonnet-4-6", + "claudeDesktop.firstParty.bindings.routeLabel": "Modelo OpenCodex", + "claudeDesktop.firstParty.bindings.routePlaceholder": "Elige un modelo", + "claudeDesktop.firstParty.bindings.add": "Añadir enlace", + "claudeDesktop.firstParty.bindings.remove": "Eliminar la vinculación {id}", + "claudeDesktop.firstParty.bindings.saveFailed": "No se pudo guardar las fijaciones del modelo", + "claudeDesktop.health.lastRequest": "Ultima solicitud", + "claudeDesktop.health.stats": "{count} req / {errors} err", + "claudeDesktop.effort.supported": "esfuerzo", + "claudeDesktop.effort.displayOnly": "Esfuerzo (solo visualización)", + + "lab.title": "Laboratorio de compatibilidad", + "lab.subtitle": "Matriz de veredicto de compatibilidad de solo lectura a partir de pruebas de proyección de laboratorio.", + "lab.loadFailed": "No se pudo cargar los datos de laboratorio de compatibilidad", + "lab.projectionUnavailable": "La proyección de laboratorio no está disponible. Ejecutar la conformidad o sondas vivas primero.", + "lab.projectionIncompatible": "El esquema de proyección de laboratorio es incompatible. Reconstruir la proyección.", + "lab.statusTitle": "Estado de proyección", + "lab.matrixTitle": "Matriz de compatibilidad", + "lab.verdictsTitle": "Registros de veredicto", + "lab.filter.layer": "Capa de evidencia", + "lab.filter.verdict": "Veredicto", + "lab.filter.subject": "Identificación del sujeto", + "lab.filter.all": "Todos", + "lab.col.subject": "Sujeto", + "lab.col.layer": "Capa", + "lab.col.suite": "Suite", + "lab.col.verdict": "Veredicto", + "lab.col.asOf": "Datos al", + "lab.col.protocol": "Conformidad del protocolo", + "lab.col.live": "Compatibilidad de ruta en vivo", + "lab.col.task": "Eficacia de la tarea", + "lab.empty": "Todavía no hay veredictos de compatibilidad en la proyección.", + "lab.subjectKind": "Tipo", + "lab.observationCount": "Observaciones", + "lab.eventCount": "Eventos", + "lab.verdictCount": "Veredictos", + "lab.subjectCount": "Temas", + "lab.builtAt": "Construido", + "lab.loading": "Cargando compatibilidad evidence…", + "lab.loadMore": "Cargar más", + "lab.detailTitle": "Detalle del veredicto", + "lab.detailClose": "Cerrar", + "lab.detailSubject": "Asunto", + "lab.detailObservations": "Observaciones", + "lab.detailEvents": "Contribuyendo eventos", + "lab.detailArtifacts": "Metadatos de artefactos", + "lab.production.title": "Tráfico de producción observado", + "lab.production.notVerification": "No verificación de laboratorio", + "lab.production.attempts": "Intentos", + "lab.production.successes": "Éxitos", + "lab.production.routeErrors": "Errores de ruta", + "lab.production.lastObserved": "La última vez que se observó", + "lab.detailLoadFailed": "No se pudo cargar el detalle del veredicto", + "lab.refresh": "Actualizar", + "lab.verdict.UNKNOWN": "Desconocido", + "lab.verdict.CLAIMED": "Declarado", + "lab.verdict.PROBED": "Sondeado", + "lab.verdict.VERIFIED": "Verificado", + "lab.verdict.DEGRADED": "Degradado", + "lab.verdict.BLOCKED": "Bloqueado", + "lab.verdict.UNSUPPORTED": "No compatible", + "lab.layer.protocol_conformance": "Conformidad del protocolo", + "lab.layer.live_route_compatibility": "Compatibilidad de ruta en vivo", + "lab.layer.task_effectiveness": "Eficacia de la tarea", + + "models.newPolicyGlobal": "Los modelos nuevos empiezan desactivados", + "models.newPolicyProvider": "Política para modelos nuevos", + "models.fastProvider": "Modo rápido", + "models.fastProviderHint": "Usa créditos al doble del precio (2×)", + "models.fastEnabled": "Modo rápido activado", + "models.fastDisabled": "Modo rápido desactivado", + "models.fastSaveFailed": "No se pudo guardar el modo rápido", + "models.newPolicy_inherit": "Heredar", + "models.newPolicy_off": "Desactivado", + "models.newPolicy_on": "Activado", + "models.newPolicy_admit": "Admitir", + "models.newBadge": "NUEVO", + "models.newCount": "Nuevos sin activar: {count}", + "models.aliases": "Alias", + "models.aliasesTable": "Mesa de alias", + "models.aliasPrompt": "Alias del proveedor (dejar vacío para borrar)", + "models.modelAliasPrompt": "Alias de modelo (dejar vacío para borrar)", + "models.aliasSaved": "Alias salvados", + "models.aliasConflict": "Que alias entra en conflicto con un nombre existente", + "models.editProviderAlias": "Editar alias de proveedor", + "models.editModelAlias": "Editar alias de modelo", + "models.useDefaultAliases": "Usar alias predeterminados", + "models.useDefaultAliasesGlobal": "Usar globalmente los alias predeterminados", + "models.aliasAuto": "auto", + "models.aliasUser": "usuario", + "models.aliasStale": "rancio", + "connection.discovering": "Descubriendo objetivos locales y compartidos…", + "connection.machineUnavailable": "El avión de la máquina local no está disponible. Las solicitudes compartidas no se redireccionaron localmente.", + "connection.clientStateChanged": "Falta la conexión de Remote Link guardada en este Child, o ahora apunta a otro Home u otro enlace. Por eso ya no coincide con el Child en ejecución. Detén o reinicia este Child y comprueba su conexión antes de volver a enlazarlo.", + "connection.linkManaged": "Gestionado por Home {home} mediante Remote Link ({linkId}). Este panel muestra la configuración y la cuota de Home en modo de solo lectura; realiza los cambios en Home.", + "connection.linkManagedUnnamed": "Gestionado por su Home mediante Remote Link ({linkId}). Este panel muestra la configuración y la cuota de Home en modo de solo lectura; realiza los cambios en Home.", + "connection.disconnect": "Desconectar del hub", + "connection.disconnectConfirm": "Desconecte esta máquina del concentrador y reiníciela en modo independiente.", + "connection.pairing.hub": "Hub", + "connection.pairing.getCode": "Ejecuta este comando en el concentrador para este navegador:", + "connection.pairing.askOperator": "Si alguien más opera el concentrador, envíale este comando y pide un código de emparejamiento único.", + "connection.pairing.notApiKey": "Pegue aquí un código de emparejamiento de un solo uso. Las claves de la API de datos y los tokens de administración no corresponden a este campo.", + "connection.pairing.networkError": "No se pudo llegar al hub. Comprueba la conexión y vuelva a intentarlo; su código todavía está aquí.", + "connection.pairing.requestError": "El concentrador no pudo completar la solicitud de emparejamiento. Comprueba su estado y vuelva a intentarlo.", + "connection.pairing.responseError": "El Hub no devolvió una respuesta de emparejamiento válida. Vuelva a intentarlo o póngase en contacto con el operador.", + "dash.authRequired": "Se requiere autenticación del navegador para ver este panel.", + "dash.permissionDenied": "Este navegador no está autorizado a leer el panel de control. Comprueba la configuración de acceso con el operador del servidor.", + "dash.dataUnavailable": "No se pudieron cargar los datos del panel. Comprueba la conexión y vuelva a intentarlo.", + "dash.staleData": "Mostrar los últimos datos recibidos; puede estar desactualizado.", + "connection.pairing.title": "Conecte este panel al concentrador", + "connection.pairing.body": "Pegue el código de emparejamiento único creado en el concentrador.", + "connection.pairing.relayWarning": "Este código se intercambia a través del relé de concentrador fijo. El relé no puede ser redirigido a otro host.", + "connection.pairing.code": "Código de emparejamiento único", + "connection.pairing.retryValidation": "Reintentar validación", + "connection.pairing.validationPending": "El código fue intercambiado, pero la validación de la sesión no pudo completarse. Mantenga esta página abierta y use la validación de Retry; no se necesita ningún código nuevo.", + "connection.pairing.submit": "Conectar", + "connection.pairing.submitting": "Conectando…", + "connection.pairing.error": "El Hub rechazó el código. Puede estar caducado, ya usado o creado para un origen de navegador diferente. Pida al operador un código nuevo para esta dirección exacta HTTPS.", + "connection.pairing.originDenied": "El Hub rechazó esta solicitud de emparejamiento (HTTP 403). Pídale al operador que permita el origen de este navegador y emita un código para esta dirección HTTPS exacta.", + "connection.pairing.cloudflareChallenge": "Cloudflare interceptó la solicitud de emparejamiento con un desafío del navegador. Abra el panel de control en su navegador, complete la verificación de Cloudflare allí y luego vuelva a intentarlo.", + "connection.pairing.sessionNotAuthorized": "El código fue intercambiado, pero esta sesión todavía no puede administrar Remote Link. Mantenga la página abierta y pida al operador del Hub un código de emparejamiento para este origen exacto del navegador.", + "connection.machine.title": "Esta máquina", + "connection.machine.shimHealthy": "El shim de Codex funciona correctamente.", + "connection.machine.shimNeedsAttention": "El shim de Codex requiere atención.", + "connection.machine.repairShim": "Cojín de reparación", + "connection.machine.removeShim": "Eliminar calza", + "connection.clients.title": "Clientes conectados", + "connection.clients.none": "No hay estado de cliente disponible", + "connection.clients.sync": "Sincronizar ahora", + "connection.clients.syncing": "Sincronización…", + "connection.sessionLogout": "Cerrar sesión remota", + "connection.sessionLoggingOut": "Cerrar sesión remota…", + "connection.sessionLogoutFailed": "No se pudo cerrar la sesión remota. Se mantuvo el período de sesiones en curso.", + "usage.source.connected": "Fuente: Hub User", + "usage.source.local": "Fuente: local usage.jsonl", + "usage.scope.label": "Ámbito de uso", + "usage.scope.machine": "Esta máquina", + "usage.scope.hub": "Todo el Hub", + "usage.hubOffline": "El uso de Hub no está disponible. El uso local no fue sustituido.", + "models.displayNameSavedRefreshFailed": "El cambio se guardó, pero la lista de modelos no se pudo actualizar. Intenta refrescarlo.", + "models.displayNameOutcomeUnknown": "La solicitud no terminó. Es posible que el cambio se haya guardado. Reintenta para comprobar el nombre actual antes de hacer otro cambio.", + "models.displayNameCurrentUnavailable": "Nombre actual no disponible hasta la actualización", + "models.displayNameReloaded": "Lista de modelos actualizada", + "models.displayNameAction": "Nombre", + "models.displayNameActionLabel": "Editar nombre amigable para {model}", + "models.displayNameTitle": "Nombre amistoso", + "models.displayNameModelId": "ID del modelo", + "models.displayNameCurrent": "Nombre actual", + "models.displayNameSourceOperator": "Tu nombre", + "models.displayNameSourceProvider": "Nombre del proveedor", + "models.displayNameSourceFallback": "Modelo ID fallback", + "models.displayNameField": "Nombre amistoso", + "models.displayNamePlaceholder": "p. ej., Grok 4.6", + "models.displayNameHelp": "Solo cambia la presentación. El enrutamiento permanece {model}.", + "models.displayNameReset": "Restablecer nombre", + "models.displayNameSaved": "Mostrar nombre guardado", + "models.displayNameResetDone": "Restablecimiento de nombre", + "models.displayNameSaveFailed": "No se pudo guardar el nombre de visualización", + "models.displayNameRequired": "Introduzca un nombre amigable o utilice Restablecer nombre.", + "models.displayNameTooLong": "El nombre amistoso debe tener 128 caracteres o menos.", + "models.displayNameNoSlash": "El nombre amistoso no puede contener /.", + "models.displayNameNoControl": "El nombre amistoso no puede contener caracteres de control.", + "pricing.override.action": "Precio", + "pricing.override.actionLabel": "Editar precio para {model}", + "pricing.override.badge": "Precio manual", + "pricing.override.title": "Precio del modelo", + "pricing.override.modelId": "ID del modelo", + "pricing.override.promptTitle": "Precios a largo plazo", + "pricing.override.promptHelp": "Los tokens de entrada y las lecturas y escrituras de caché de una solicitud determinan la banda; toda la solicitud utiliza las tarifas de esa banda. Los tokens de salida no cuentan. Las tarifas corresponden a la velocidad estándar.", + "pricing.override.help": "USD por 1M de tokens. Introduzca las tarifas de entrada y salida; las tarifas de caché vacías usan 0. Se permiten tarifas de cero.", + "pricing.override.input": "Entrada", + "pricing.override.output": "Salida", + "pricing.override.cacheRead": "Caché leído", + "pricing.override.cacheWrite": "Escribir caché", + "pricing.override.modeAutomatic": "Automático", + "pricing.override.modeFlat": "Tarifa fija", + "pricing.override.modeCustom": "Umbral personalizado", + + "pricing.override.modeAutomaticHelp": "Utiliza las reglas de longitud de prompt del catálogo con las tasas base anteriores. Se siguen aplicando configuración rápidos y prioritarios.", + "pricing.override.modeFlatHelp": "Utiliza las tasas base anteriores en cada longitud de solicitud, reemplazando las reglas de longitud de solicitud del catálogo. Se siguen aplicando configuración rápidos y prioritarios.", + "pricing.override.threshold": "Umbral de prontitud (tokens)", + "pricing.override.bandTitle": "Tarifas de la banda de contexto largo", + "pricing.override.bandHelp": "Estas son las tasas de velocidad estándar. Todavía se aplican las reglas de catálogo rápido y prioridad. Las cifras de costos son estimaciones.", + "pricing.override.comparison": "Umbral de comparación", + "pricing.override.comparisonGt": "Mayor que (>)", + "pricing.override.comparisonGte": "Mayor o igual que (≥)", + "pricing.override.modeCustomHelp": "Introduzca cuatro tarifas absolutas por 1M de tokens. La longitud del prompt incluye la entrada en caché y excluye la salida. Estas tarifas sustituyen la regla de longitud del catálogo para toda la solicitud. Los ajustes Fast y Priority siguen aplicándose. Los costos son estimaciones.", + "pricing.override.customInvalid": "Introduzca un umbral de tokens que sea un entero positivo seguro y cuatro tarifas finitas entre 0 y 1.000.000. Las tarifas pueden ser 0.", + "pricing.override.loading": "Cargando precio guardado…", + "pricing.override.loadFailed": "No se pudo cargar el precio ahorrado. Vuelva a cargar para intentarlo de nuevo.", + "pricing.override.outcomeUnknown": "La solicitud no terminó de manera confiable. El precio puede haber cambiado. Vuelva a cargar el precio guardado antes de volver a editar.", + "pricing.override.recoveryFailed": "No se pudo recuperar el precio ahorrado. La edición permanece bloqueada; vuelve a cargar para volver a intentarlo.", + "pricing.override.recovered": "El último precio ahorrado cargado. La solicitud anterior u otro cliente aún puede cambiarla.", + "pricing.override.refreshFailed": "El precio se guardó, pero la lista de modelos no se pudo actualizar. Vuelva a intentar la actualización de lista.", + "pricing.override.invalid": "Introduce las tarifas de entrada y salida. Cada tarifa debe ser un número finito de 0 a 1.000.000.", + "pricing.override.reset": "Restablecer a automático", + "pricing.override.save": "Guardar", + "pricing.override.saving": "Guardando…", + "pricing.override.reload": "Precio de recarga", + "pricing.override.refresh": "Actualizar lista", + "pricing.override.cancel": "Cancelar", + "pricing.override.close": "Cerrar", + "usage.range.custom": "Rango de fechas personalizado", + "usage.range.start": "Inicio (hora local)", + "usage.range.end": "Fin (hora local)", + "usage.range.apply": "Aplicar", + "usage.range.clear": "Limpiar", + "usage.range.help": "Hora local. Incluye todo el minuto final.", + "usage.range.required": "Introduzca una fecha y hora de inicio y finalización.", + "usage.range.invalid": "Introduzca fechas y horas locales válidas, el o después de 1970-01-01 UTC.", + "usage.range.reversed": "El final debe ser en o después del comienzo.", + "usage.range.applied": "Intervalo seleccionado: {start} – {end} (ambos inclusive).", + "models.pickerOrder.editorHint": "Reordena los modelos enrutados y luego guarda tu borrador. Las filas destacadas son fijas; no se muestran los modelos nativos.", + "models.pickerOrder.nativeLocked": "Este orden guardado incluye modelos nativos. Aplica un preajuste o Predeterminado enrutado antes de editar Personalizado.", + "models.pickerOrder.unknownChosen": "Las opciones destacadas son desconocidas. Recargar antes de editar.", + "models.pickerOrder.changed": "Se ha cambiado la configuración del selector. El borrador se mantiene; recarga para descartarlo y usa la configuración actual.", + "models.pickerOrder.savedReload": "Orden guardada. Vuelva a cargar la configuración actual antes de volver a editar.", + "models.pickerOrder.requestFailed": "Solicitud fallida. Su borrador se mantiene; reintente o vuelva a cargar.", + "models.pickerOrder.empty": "No hay modelos enrutados disponibles.", + "models.pickerOrder.dragModel": "Arrastrar {model}", + "models.pickerOrder.featured": "Destacados", + "models.pickerOrder.upModel": "Mover {model} hacia arriba", + "models.pickerOrder.downModel": "Mover {model} hacia abajo", + "models.pickerOrder.position": "{model}: posición {position} de {total}", + "models.pickerOrder.saveDraft": "Guardar borrador", + "models.pickerOrder.reloadDraft": "Recargar y descartar borrador", + "models.pickerOrder.catalogRequired": "Las identidades modelo faltan o son ambiguas. Vuelva a cargar la página Modelos para actualizar su catálogo antes de editar Personalizado.", + "nav.remote": "Enlace remoto", + "nav.remoteWorkspace": "Espacio de trabajo remoto", + "link.title": "Enlace remoto", + "link.subtitle": "Conecte otro equipo OpenCodex a través de SSH.", + "link.switch": "Enlace remoto", + "link.switchOffHint": "Activa el enlace para elegir el rol de este equipo.", + "link.role.title": "Elige el rol de esta computadora", + "link.role.hint": "Home comparte los proveedores de este equipo con los equipos Child. Child conecta este equipo a un Home cuando este equipo se ejecuta de forma independiente.", + "link.role.home": "Home", + "link.role.homeHint": "Administre los equipos secundarios desde este panel.", + "link.role.child": "Child", + "link.role.childHint": "Usa la configuración OpenCodex de otra computadora.", + "link.continue": "Continuar", + "link.sessionRequired": "Inicie sesión en el panel de control local para administrar los enlaces.", + "link.workspaceUnavailable": "El espacio de trabajo remoto no está disponible en esta instalación.", + "link.loading": "Cargando…", + "link.loadFailed": "No se pudo cargar el estado del enlace remoto.", + "link.refresh": "Actualizar", + "link.children": "Ordenadores Child", + "link.addChild": "Añadir equipo Child", + "link.sheetTitle": "Añadir un ordenador infantil", + "link.candidates": "Hospedadores SSH", + "link.setup.relationship": "El Child utilizará los proveedores Home de este OpenCodex a través de SSH.", + "link.setup.requirements": "Requiere SSH basado en claves de Home a Child, OpenCodex 2.66.0+ en el Child y macOS o Linux en ambos equipos.", + "link.setup.emptyHome": "Los alias provienen de este Home de ~/.ssh/config. Agregar una entrada de host, luego volver a escanear o ingresar un alias existente a continuación.", + "link.setup.emptyLocal": "Los alias provienen de ~/.ssh/config. de este equipo. Agregar una entrada de host, luego volver a escanear o ingresar un alias existente a continuación.", + "link.setup.guide": "Guía de configuración de Remote Link", + "link.discoveryFailed": "No se pudo cargar los hosts SSH", + "link.rescan": "Volver a buscar equipos", + "link.aliasRequired": "Selecciona o introduzca un alias para habilitar la conexión de prueba.", + "link.probeHelp": "Comprueba la razón arriba. Para los problemas de acceso SSH, ejecute esto en un terminal en este equipo, reemplazando ?alias> con su alias SSH y vuelva a intentarlo.", + "link.noCandidates": "No SSH Se encontraron candidatos anfitriones.", + "link.alias": "Alias de host SSH", + "link.aliasPlaceholder": "Introduzca un alias desde su configuración SSH", + "link.probe": "Conexión de prueba", + "link.probing": "Prueba de conexión…", + "link.hostFingerprint": "Huella dactilar clave de host", + "link.confirmFingerprint": "Reconozco esta clave de host", + "link.confirming": "Confirmando…", + "link.confirm": "Confirmar host", + "link.ocxVersion": "OpenCodex versión {version}", + "link.apply": "Conectar equipo Child", + "link.applying": "Conectando…", + "link.retry": "Reintentar", + "link.disconnect": "Desconectar", + "link.disconnectConfirm": "¿Desconectar {alias}? Su clave de enlace será revocada.", + "link.close": "Cerrar", + "link.cancel": "Cancelar", + "remoteLink.childDisabled": "Los enlaces Child solo se pueden iniciar desde un tiempo de ejecución independiente.", + "remoteLink.findHome.title": "Encontrar Home", + "remoteLink.findHome.body": "Elige el ordenador Home para conectar este Child a.", + "remoteLink.findHome.action": "Encontrar Home", + "remoteLink.findHome.connect": "Conectar como Child", + "remoteLink.findHome.notice": "La conexión reinicia OpenCodex en este equipo. Codex gira ya corriendo fin primero, y las nuevas solicitudes pueden fallar hasta por un minuto. Posteriormente Codex mantiene la misma dirección local, y el Home lo sirve con sus propios proveedores y cuentas.", + "remoteLink.findHome.empty": "Aún no está conectado a un Home.", + "remoteLink.joining": "Unirse a Home…", + "remoteLink.restart.title": "Este equipo se reiniciará para conectarse como Child.", + "remoteLink.restart.body": "Ejecutando Codex se termina primero, luego OpenCodex se reinicia como Child. Esta página se recarga por sí misma cuando el Child está listo.", + "remoteLink.restart.waiting": "Esperando a que esta computadora se vuelva a conectar como Child…", + "remoteLink.restart.slow": "Reiniciar lleva más tiempo de lo habitual. Esta página sigue comprobando y recarga por sí misma una vez que las respuestas Child. Si OpenCodex se ha detenido, inícielo de nuevo.", + "remoteLink.error.standalone_required": "Los enlaces Child solo se pueden iniciar desde un tiempo de ejecución independiente.", + "remoteLink.error.join_tunnel_failed": "No se pudo iniciar el túnel a Home. Comprueba SSH acceso y reintento.", + "remoteLink.error.admission_failed": "Home no aceptó el nuevo enlace. Comprueba que se está ejecutando y vuelva a intentarlo.", + "remoteLink.error.join_issue_failed": "Home no pudo emitir un enlace. Comprueba que OpenCodex se está ejecutando en Home y vuelva a intentarlo.", + "remoteLink.error.join_in_progress": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.join_port_failed": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.join_port_mismatch": "OpenCodex no se está ejecutando en su puerto configurado, por lo que no puede reiniciarse como Child. Reinicia OpenCodex en su puerto configurado y vuelva a intentarlo.", + "remoteLink.joinDenied.pairing_required": "Empareje esta máquina primero para unirse como Child. Abra el panel de control de loopback de esta computadora e ingrese un código de emparejamiento de un solo uso creado por el operador.", + "remoteLink.joinDenied.unavailable": "Unirse como Child no está disponible para esta sesión del panel de control. Actualiza el estado y compruebe la configuración de emparejamiento y tiempo de ejecución de esta máquina.", + "remoteLink.error.join_rollback_failed": "Falló la conexión y no se pudo eliminar el vínculo en Home. Reintenta la limpieza o ejecuta ocx link revoke en Home.", + "remoteLink.error.join_restart_failed": "El enlace está listo. Reinicia OpenCodex en este equipo para finalizar la conexión como Child.", + "remoteLink.error.join_connect_failed": "No se pudo completar la solicitud de enlace remoto.", + "link.noChildren": "No hay computadoras infantiles conectadas.", + "remoteLink.status.connecting": "Conectar", + "remoteLink.status.connected": "Conectado", + "remoteLink.status.reconnecting": "Reconexión", + "remoteLink.status.failed": "La conexión necesita atención", + "remoteLink.status.idle": "Inactivo", + "remoteLink.role.standalone": "Independiente", + "remoteLink.role.home": "Home", + "remoteLink.role.child": "Child", + "remoteLink.direction.hub": "Hub iniciado", + "remoteLink.direction.client": "Cliente iniciado", + "remoteLink.error.admission_timeout": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.compensation_failed": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.fingerprint_failed": "No se pudo leer la clave de host SSH. Vuelva a probar la conexión.", + "remoteLink.error.forbidden": "Esta sesión de panel no puede administrar enlaces remotos. Abra el panel de control en este equipo (instalación independiente) o utilice una sesión Hub emparejada.", + "remoteLink.error.host_confirmation_expired": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.host_fingerprint_mismatch": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.host_not_confirmed": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.invalid_alias": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.invalid_body": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.invalid_link_id": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.key_issue_failed": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.key_revoke_failed": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.link_apply_failed": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.link_exists": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.link_not_found": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.link_remove_failed": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.link_unavailable": "Enlace remoto no está disponible en esta ejecución. Reinicia OpenCodex y vuelve a intentarlo.", + "remoteLink.error.listener_unavailable": "El oyente de Remote Link no pudo iniciarse en este equipo. Comprueba si hay un conflicto de puerto y vuelva a intentarlo.", + "remoteLink.error.probe_failed": "No se pudo conectar al host SSH. Comprueba que acepta su clave SSH y que cualquier ayudante de ProxyCommand está instalado.", + "remoteLink.error.remote_connect_failed": "El equipo remoto no pudo conectarse a este Home. Comprueba su servicio y reintento OpenCodex.", + "remoteLink.error.remote_disconnect_failed": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.purge_unsupported": "Este equipo remoto tiene una instalación completa de OpenCodex. No hay un ejecutable de agente ligero instalado por el enlace. Desconecta sin borrar el ejecutable.", + "remoteLink.error.remote_ocx_missing": "No se encontró ocx en el equipo remoto. Instale OpenCodex allí, o asegúrese de que ocx esté en la PATH de sesiones SSH no interactivas.", + "remoteLink.error.remote_ocx_outdated": "La versión de OpenCodex del equipo remoto es demasiado antigua para Remote Link. Ejecuta allí ocx update para instalar la versión 2.66.0 o posterior y vuelve a intentarlo.", + "remoteLink.error.remote_ocx_unrecognized": "El equipo remoto no informó de una versión OpenCodex. Enlace remoto necesita OpenCodex 2.66.0 o posterior en macOS o Linux.", + "remoteLink.error.remote_port_failed": "El equipo remoto no pudo informar su puerto de enlace. Comprueba que OpenCodex 2.66.0 o posterior se está ejecutando allí y vuelva a intentarlo.", + "remoteLink.error.tailscale_session_refused": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.error.version_probe_failed": "No se pudo ejecutar ocx en el equipo remoto a través de SSH. Comprueba el acceso y reintento de SSH.", + "remoteLink.error.link_pin_conflict": "Un enlace iniciado por Home ya tiene fijada otra clave de host para este alias. Quita ese enlace antes de confiar en una clave nueva.", + "remoteLink.error.host_key_changed": "La clave de host confirmada ya no coincide con la de confianza de este alias. Prueba la conexión y vuelve a confirmar el host.", + "remoteLink.error.trust_file_unexpected": "El archivo known_hosts de Remote Link contiene un patrón, una lista de hosts, un marcador o una línea no válida. Quita esa línea, prueba la conexión y vuelve a confirmar el host.", + "remoteLink.error.key_cleanup_failed": "No se completó el registro y Home no pudo revocar la clave de enlace emitida. Revoca esa clave en Claves API antes de reintentar.", + "remoteLink.error.link_cleanup_uncertain": "No se completó el registro y Home no pudo deshacerlo: se desconoce si se guardó el enlace y no se pudo revocar su clave. Si el enlace aparece aquí, desconéctalo. Si la clave de enlace permanece en Claves API, revócala.", + "remoteLink.residual.purge": "Es posible que el Child siga conectado. Ejecuta {cmd} en el Child antes de reintentar.", + "remoteLink.residual.purgeWindows": "Es posible que el Child siga conectado. En el Símbolo del sistema del Child, ejecuta {cmd} antes de reintentar.", + "remoteLink.residual.purgeWindowsFallback": "Si LOCALAPPDATA no está definida, ejecuta {cmd} en su lugar.", + "remoteLink.residual.purgeNotFound": "Si el comando no se encuentra en esa ruta, el ejecutable no está instalado: la instalación se interrumpió antes de copiarlo o se eliminó después. Ningún ocx-child de este intento mantiene el vínculo con el Child. No queda nada que deshacer allí y puedes reintentar.", + "remoteLink.residual.purgeAny": "Es posible que el Child siga conectado. En macOS o Linux, ejecuta {cmd} en el Child antes de reintentar.", + "remoteLink.residual.purgeAnyWindows": "En Windows, ejecuta {cmd} en el Símbolo del sistema del Child.", + "remoteLink.residual.ephemeral": "Es posible que el Child siga conectado. Ejecuta {cmd} en el Child antes de reintentar.", + "remoteLink.residual.full": "Es posible que el Child siga conectado. Ejecuta {cmd} en el Child y, si se desconecta, ejecuta ocx restart antes de reintentar.", + "remoteLink.residual.unknown": "Es posible que el Child siga conectado. En una instalación completa, ejecuta {cmd} y, si se desconecta, ejecuta ocx restart antes de reintentar.", + "remoteLink.residual.unknownLightweight": "Si es un Child ligero, ejecuta {cmd} en su lugar.", + "remoteLink.residual.lightweightPlaced": "Si copiaste el ejecutable a mano, ejecuta el mismo comando desde ~/.local/bin/ocx-child (en Windows, %USERPROFILE%\\.local\\bin\\ocx-child.exe). Home prueba primero esa ruta, aunque no esté en PATH. Si lo instalaste en otra ruta, usa la que muestra {cmd} (where.exe ocx-child en Windows).", + "remoteLink.residual.lightweightPlacedWindows": "Si copiaste el ejecutable a mano, ejecuta el mismo comando desde %USERPROFILE%\\.local\\bin\\ocx-child.exe. Home prueba primero esa ruta, aunque no esté en PATH. Si lo instalaste en otra ruta, usa la que muestra {cmd}.", + "remoteLink.residual.bound": "Cada paso solo actúa si los registros del Child indican el enlace de este intento ({linkId}) o no indican ninguno. Deja intacto cualquier Child que pertenezca a otro enlace, a un hub o a otro Home.", + "remoteLink.residual.olderFull": "Una versión de OpenCodex anterior a esa opción la rechaza antes de modificar el enlace. En ese caso, ejecuta ocx disconnect y ocx restart solo si {cmd} muestra {linkId}, justo después de comprobarlo. De lo contrario, deja intacto el Child.", + "remoteLink.residual.olderLightweight": "Una versión de ocx-child anterior a esa opción la rechaza antes de actuar. En ese caso, deja intacto el Child: su estado no puede mostrar la conexión interrumpida de otro enlace, y una desconexión sin esa opción la restauraría y después la quitaría.", + "remoteLink.residual.noLink": "Es posible que el Child siga conectado. Esta respuesta no indica el ID del enlace del intento. No se puede limitar ninguna operación a ese enlace, así que deja intacto el Child.", + "remoteLink.error.generic": "No se pudo completar la solicitud de enlace remoto.", + "remoteLink.reason.auth": "La autenticación falló.", + "remoteLink.reason.hostkey": "No se pudo verificar la clave del host.", + "remoteLink.reason.forward": "Fallo en el reenvío de puertos.", + "remoteLink.reason.timeout": "La conexión se agotó.", + "remoteLink.reason.bind": "El puerto local no podía ser atado.", + "remoteLink.reason.persist": "El estado del enlace no se pudo guardar.", + "remoteLink.reason.compensation_failed": "La limpieza después de la vinculación falló.", + "remoteLink.reason.staleTunnel": "Un túnel viejo todavía puede contener el puerto.", + "remoteLink.reason.generic": "Motivo:", + "remoteLink.workspaceMoved.title": "Remote Workspace tiene su propia página ahora", + "remoteLink.workspaceMoved.body": "Usa la página de espacio de trabajo remoto separada.", + "remoteLink.workspaceMoved.open": "Abrir espacio de trabajo remoto", + "remoteLink.forceRemove.title": "Esta máquina no pudo alcanzar {alias}", + "remoteLink.forceRemove.body": "¿Quitar el enlace solo en este equipo? Después ejecuta {cmd} en {alias}. Solo lo desconectará si {alias} sigue conectado a este enlace; mantendrá intactos los equipos de otro enlace, hub o Home.", + "remoteLink.forceRemove.ephemeralBody": "¿Quitar el enlace solo en este equipo? Cuando {alias} responda, ejecuta {cmd} aquí. Solo actúa si los registros de {alias} indican este enlace o ninguno, y se niega a actuar en un equipo que pertenezca a otro enlace.", + "remoteLink.forceRemove.confirm": "Eliminar aquí solamente", + "remoteLink.forceRemoved.unknownFallback": "Cada opción solo actúa mientras el equipo pertenezca a este enlace. Una versión anterior a esa opción la rechaza antes de actuar. En una instalación completa, ejecuta primero {cmd}. Si el Child es ligero, déjalo intacto: su estado no muestra una conexión interrumpida de otro enlace, y una desconexión sin esa opción la restauraría y después la quitaría.", + "remoteLink.forceRemoved.fullBound": "Se quitó {alias} solo en este equipo (enlace {linkId}). Cuando responda {alias}, ejecuta {cmd} allí. Solo desconectará a {alias} si sigue conectado a este enlace.", + "remoteLink.forceRemove.refusal.expect_link_unsupported": "Usa una versión que no admite comprobar el enlace, y otro enlace de este Home podría llegar al mismo equipo.", + "remoteLink.forceRemove.refusal.child_disconnect_pending": "Tiene una desconexión sin terminar que no pudo asociar a este enlace.", + "remoteLink.forceRemove.refusal.child_residual": "Conserva registros que no puede restaurar. Uno podría corresponder a la conexión interrumpida de otro enlace.", + "remoteLink.forceRemove.refusal.child_link_mismatch": "Pertenece a otro enlace, hub o Home, o hay una conexión o rotación de clave en curso, o no se pudo leer su estado.", + "remoteLink.forceRemove.refusedTitle": "{alias} se negó a desconectarse de este enlace", + "remoteLink.forceRemove.unknownBody": "¿Quitar el enlace solo en este equipo? Este Home no registró si {alias} usa la instalación completa o el agente ligero, por lo que no tendrá datos para recuperarlo. Las instrucciones para comprobar {alias} quedan en esta página hasta que las descartes o salgas.", + "remoteLink.forceRemove.noteId": "Anota ahora el ID de enlace {linkId}. Una vez quitado el enlace, este Home ya no lo registrará.", + "remoteLink.forceRemoved.ephemeral": "Se quitó {alias} solo en este equipo (enlace {linkId}). Cuando responda {alias}, ejecuta {cmd} aquí. Solo actúa si los registros de {alias} indican este enlace o ninguno, y se niega a actuar en un equipo que pertenezca a otro enlace.", + "remoteLink.forceRemoved.fullCheck": "Una versión de OpenCodex anterior a esa opción la rechaza antes de actuar sobre el enlace. En ese caso, ejecuta {cmd} en el equipo.", + "remoteLink.forceRemoved.fullDisconnect": "Haz la comprobación y la desconexión de inmediato, una tras otra: si se registra un enlace entre ambas, se eliminará. Ejecuta {cmd} allí solo si aparece Link: {linkId} o se indica que el equipo no está conectado. Si aparece otro enlace, hub u otro Home, o no se puede leer el estado, deja intacto el equipo. Este Home ya revocó su propio enlace.", + "remoteLink.forceRemoved.unknownCheck": "Se quitó {alias} solo en este equipo (enlace {linkId}). Este Home no registró si usa la instalación completa o el agente ligero (ocx-child), por lo que no tendrá datos para recuperarlo. Cuando responda {alias}, ejecuta {cmd} si usa una instalación completa.", + "remoteLink.forceRemoved.unknownLocate": "El agente de un Child ligero es ocx-child. La copia instalada por el enlace está en ~/.cache/opencodex/bin/ocx-child (en el Símbolo del sistema de Windows, %LOCALAPPDATA%\\opencodex\\bin\\ocx-child.exe o %USERPROFILE%\\.cache\\opencodex\\bin\\ocx-child.exe si LOCALAPPDATA no está definida). Una copia instalada a mano está en ~/.local/bin o en otra ubicación de PATH. {cmd} muestra la que está en PATH (where.exe ocx-child en Windows).", + "remoteLink.forceRemoved.unknownLightweight": "En un Child ligero, ejecuta {cmd} en su lugar. Usa la ruta del ocx-child en uso si no es la copia instalada por el enlace (en Windows, la ruta de ocx-child.exe indicada arriba).", + "remoteLink.forceRemoved.unknownDisconnect": "Haz la comprobación y la desconexión de inmediato, una tras otra: si se registra un enlace entre ambas, se eliminará. Ejecuta {cmd} allí solo si la salida indica el enlace {linkId} o que el equipo no está conectado. Si indica otro enlace, hub u otro Home, o no se puede leer el estado, deja intacto el equipo. Este Home ya revocó su propio enlace.", + "remote.title": "Espacio de trabajo remoto", + "remote.subtitle": "Ejecuta Codex, Claude Code o Pi desde este concentrador mientras los archivos, comandos, pruebas y compilaciones permanecen en el equipo que seleccione.", + "remote.loading": "Cargando espacio de trabajo remoto…", + "remote.loadFailed": "No se pudo cargar el espacio de trabajo remoto.", + "remote.hubRequired": "Usa el modo Hub e inicie el Hub con OCX_REMOTE_WORKSPACE_ENABLED .1 para habilitar el espacio de trabajo remoto.", + "remote.refresh": "Actualizar", + "remote.addComputer": "Agregar una computadora", + "remote.addComputerHint": "Aprobar una o más carpetas localmente y, a continuación, mantener el ejecutor solo OCX conectado a este concentrador.", + "remote.createPairing": "Crear código de emparejamiento", + "remote.pairingCode": "Código de emparejamiento único", + "remote.pairingExpires": "Expira en {time}", + "remote.pairingCommand": "Ejecutar en el equipo que está agregando", + "remote.pairingCommandPosix": "Terminal de Linux / macOS", + "remote.pairingCommandWindows": "Windows PowerShell", + "remote.copyCommand": "Copiar comando", + "remote.copied": "Copiado", + "remote.devices": "Ordenadores", + "remote.noDevices": "No hay computadoras emparejadas todavía.", + "remote.online": "En línea", + "remote.offline": "Fuera de línea", + "remote.revoke": "Revocar computadora", + "remote.revokeConfirm": "¿Revocar {name}? Las sesiones activas en este equipo se detendrán.", + "remote.newSession": "Nueva sesión remota", + "remote.device": "Ordenador", + "remote.folder": "Carpeta de espacio de trabajo", + "remote.runtime": "Agente de codificación", + "remote.access": "Acceso al espacio de trabajo", + "remote.access.readOnly": "Solo lectura", + "remote.access.workspace": "Editar archivos y ejecutar comandos", + "remote.access.workspaceFilesOnly": "Editar solo archivos", + "remote.unavailable": "No disponible", + "remote.capability.full": "Archivos + comandos sandboxed", + "remote.capability.files": "Solo herramientas de archivo", + "remote.runsOnHub": "Modele e inicie sesión permanezca en este Hub", + "remote.runsReadOnly": "Los archivos solo se pueden leer en este equipo", + "remote.runsFilesCommands": "Archivos, compilaciones y comandos se ejecutan aquí", + "remote.runsFilesOnly": "Las herramientas de archivo se ejecutan aquí; sandbox de comandos no disponible", + "remote.execUnavailable": "Este equipo puede editar archivos, pero las compilaciones y los comandos del terminal están deshabilitados porque no hay una caja de arena del sistema operativo compatible disponible.", + "remote.notResumable": "Esta sesión se detuvo antes de que el agente de codificación creara un historial duradero. Iniciar una nueva sesión remota.", + "remote.startSession": "Iniciar sesión remota", + "remote.sessionStarted": "La sesión remota está lista.", + "remote.split.hint": "Arrastre una sesión a un borde del panel para dividir la vista.", + "remote.split.right": "Dividir a la derecha", + "remote.split.down": "Dividir a continuación", + "remote.split.close": "Cerrar panel", + "remote.split.resize": "Redimensionar paneles", + "remote.split.limit": "Se pueden mostrar hasta cuatro sesiones a la vez.", + "remote.split.left": "Dividir izquierda", + "remote.split.up": "Dividir por encima", + "remote.split.open": "Sesión abierta", + "remote.split.title": "Vista dividida", + "remote.sessions": "Sesiones", + "remote.noSessions": "Elige una computadora, carpeta y agente de codificación en línea para comenzar.", + "remote.events": "Actividad de sesión remota", + "remote.noEvents": "No hay actividad todavía.", + "remote.prompt": "Mensaje", + "remote.promptPlaceholder": "Pida al agente Hub que trabaje dentro de la carpeta remota seleccionada…", + "remote.send": "Enviar", + "remote.stop": "Detener sesión", + "remote.requestFailed": "Se ha fallado la solicitud de espacio de trabajo remoto.", + "remote.submissionUnknown": "El estado de la presentación es desconocido. Comprueba la sesión antes de enviarla de nuevo.", + "remote.status.starting": "Inicio", + "remote.status.ready": "Listo", + "remote.status.running": "Correr", + "remote.status.waiting": "Ejecutor offline", + "remote.status.failed": "Falló", + "remote.status.stopped": "Detenido", + "remote.event.status": "Estado", + "remote.event.tool": "Herramienta remota", + "remote.event.error": "Error", + "quotaSummary.aria": "Resumen de cuotas de proveedores", + "quotaSummary.updated": "Actualizado {time}", + "quotaSummary.dataAt": "Datos de {time}", + "quotaSummary.observedAt": "Observado en {time}", + "quotaSummary.warn": "70% + utilizado", + "quotaSummary.critical": "90% + utilizado", + "quotaSummary.credits": "Créditos", + "quotaSummary.creditsUnavailable": "Créditos no disponibles", + "quotaSummary.refreshFailed": "Fallo en la última actualización; mostrando la lectura anterior", + "quotaSummary.scrollPrev": "Desplazar proveedores a la izquierda", + "quotaSummary.scrollNext": "Derecho de proveedores de Scroll", + "quotaSummary.account": "Clave observada {n}", + "quotaSummary.perMinute": "por minuto", + "quotaSummary.perDay": "por día", + "quotaSummary.perMonth": "por mes", + "quotaSummary.remainingLimit": "Restante / límite", + "quotaSummary.openAccounts": "Gestión de cuentas abiertas", + "quotaLive.title": "Actualizaciones de cuota en vivo", + "quotaLive.hint": "Vuelve a leer periódicamente la cuota en caché del proxy. Solo se consulta de nuevo a un proveedor cuando vence esa caché, no en cada actualización.", + "quotaLive.interval": "Cada", + "quotaLive.intervalAria": "Intervalo de actualización de cuota en vivo en segundos ({min}–{max})", + "quotaLive.intervalInc": "Aumentar intervalo", + "quotaLive.intervalDec": "Reducir intervalo", + "quotaLive.unit": "s", + "pws.protocol.title": "Alambre corriente arriba", + "pws.protocol.note": "El formato API opencodex habla con este proveedor. No activa o desactiva ningún cliente API; la página API los controla.", + "pws.protocol.adapterLabel": "Alambre ascendente que recibe este proveedor", + "pws.protocol.source": "Decidido por", + "pws.protocol.source.hardPin": "Corregido por opencodex para este modelo", + "pws.protocol.source.operator": "Su configuración", + "pws.protocol.source.registry": "Catálogo de proveedores", + "pws.protocol.source.providerDefault": "Proveedor predeterminado", + "pws.protocol.pending": "Después de guardar, este proveedor recibe {adapter}.", + "pws.protocol.overrides": "Modelos en otro alambre", + "pws.protocol.noOverrides": "Todos los modelos utilizan el cable del proveedor.", + "pws.protocol.overridesTruncated": "Mostrando los primeros modelos {count}.", + "pws.protocol.col.model": "Modelo", + "pws.protocol.col.wire": "Cable", + "pws.protocol.col.source": "Decidido por", + "pws.protocol.loadFailed": "No se pudo cargar el cable de origen.", + "compatProtocol.filter.inbound": "Cliente API", + "compatProtocol.filter.upstream": "Alambre corriente arriba", + "compatProtocol.anyProtocol": "cualquiera", + "compatProtocol.pair": "{inbound} → {upstream}", + "compatProtocol.loading": "Leyendo el par de protocolos de cada sujeto…", + "compatProtocol.unverified": "No hay evidencia de laboratorio para {pair} todavía. El par no está verificado, no ha fallado.", + "compatProtocol.unresolved": "No se pudo leer el par de protocolos de {count} sujetos; se excluyen de este filtro.", + "compatProtocol.axisNote": "Estos son veredictos de laboratorio solamente. La vista previa de la ruta de solicitud muestra cómo se entrega una solicitud (nativa o traducida) en la página API.", + "protocolLinks.labEvidence": "Pruebas de laboratorio para esta pareja", + "protocolLinks.providerSettings": "Configuración del proveedor", + "cws.plan.title": "Rutas candidatas", + "cws.plan.description": "Pregunta al proxy cómo cada destino llevaría una solicitud con cada característica que el cliente API puede expresar y qué características mantienen todos los objetivos. Nada es enviado upstream.", + "cws.plan.run": "Mostrar rutas candidatas", + "cws.plan.savedOnly": "Muestra el combo guardado. Guarda los cambios para obtener una vista previa de ellos.", + "fallback.title": "Fallback", + "fallback.desc": "Cuando falla un modelo o proveedor, OpenCodex puede enviar la solicitud al siguiente de un combo, perfil de enrutamiento o cadena de subagentes. Desactiva un tipo de fallback para recibir un error claro en su lugar.", + "fallback.model": "Fallback de modelo", + "fallback.modelHint": "Otro modelo del mismo proveedor", + "fallback.provider": "Fallback de proveedor", + "fallback.providerHint": "Otro proveedor", + "fallback.rotationNote": "Cambiar entre cuentas o claves de un mismo proveedor no es fallback y sigue habilitado.", + "fallback.overrides": "Excepciones", + "fallback.scope.provider": "Proveedor {name}", + "fallback.scope.route": "Ruta {name}", + "fallback.state.on": "activado", + "fallback.state.off": "desactivado", + "fallback.state.inherit": "heredar", + "fallback.clear": "Borrar", + "fallback.last": "Último fallback", + "fallback.last.none": "No hubo ningún fallback desde que se inició el proxy.", + "fallback.last.taken": "ejecutado", + "fallback.last.refused": "rechazado", + "fallback.loadFailed": "No se pudo cargar la configuración de fallback.", + "fallback.saveFailed": "No se pudo guardar el ajuste de fallback.", + "fallback.devices.title": "Fallback por dispositivo", + "fallback.devices.desc": "El fallback local permite que GOAT use los proveedores de un dispositivo para atender su trabajo mientras este Home no esté disponible. OpenCodex nunca atiende a un dispositivo con sus proveedores locales. Desactivar las cadenas rechaza el fallback de modelos y proveedores para ese dispositivo.", + "fallback.devices.childNote": "Estos ajustes se guardan en el Home de este dispositivo. Mientras el Home no esté disponible, las solicitudes fallan en lugar de usar los proveedores de este dispositivo.", + "fallback.devices.empty": "No hay dispositivos enlazados con este Home.", + "fallback.devices.device": "Dispositivo", + "fallback.devices.local": "Fallback local", + "fallback.devices.chains": "Cadenas de fallback", + "fallback.devices.localFor": "Fallback local para {name}", + "fallback.devices.chainsFor": "Cadenas de fallback para {name}", + "link.plant.title": "Listo para instalar el agente ligero", + "link.plant.body": "OpenCodex aún no está instalado en este equipo. Instala por SSH el ejecutable independiente ocx-child (~0,9 MB, sin Node ni Bun) en ~/.cache/opencodex/bin y conéctalo de inmediato. Puedes eliminarlo al desconectar.", + "link.plant.apply": "Instalar agente ligero y conectar", + "link.plant.applying": "Instalando y conectando…", + "link.plant.unavailable": "No se encontró OpenCodex en este host ({arch}) ni hay un ejecutable verificado de ocx-child disponible localmente para instalarlo.", + "link.plant.artifactHelp": "Para instalarlo, este Home necesita una compilación verificada. Coloca {file} y un archivo SHA256SUMS que lo incluya en la carpeta indicada por OPENCODEX_CHILD_BIN_DIR o en $OPENCODEX_HOME/cache/ocx-child//. Luego vuelve a confirmar el host.", + "link.plant.unknownArch": "arquitectura desconocida", + "link.ephemeralReady": "Agente ligero listo (ocx-child {version})", + "remoteLink.badge.ephemeral": "Ligero", + "remoteLink.badge.full": "Instalación completa", + "remoteLink.parity.synced": "Configuración de Home sincronizada", + "remoteLink.parity.outdated": "Requiere sincronización", + "remoteLink.disconnect.ephemeralBody": "¿Desconectar {alias}? Se restaurará su configuración de Codex y el relay se detendrá enseguida (0 procesos en segundo plano). De forma predeterminada, el ejecutable de ocx-child se conserva en ~/.cache/opencodex/bin para facilitar la reconexión.", + "remoteLink.disconnect.purgeLabel": "Eliminar también el ejecutable del agente ligero instalado en el equipo remoto", + "remoteLink.disconnect.purgeConfirm": "Eliminar y desconectar", + "remoteLink.error.child_port_busy": "Otro proceso está usando el puerto de destino (10100) en el equipo Child. No se modificaron archivos en el Child. Libera el puerto o detén el proceso y vuelve a intentarlo.", + "remoteLink.error.child_external_provider_conflict": "Otro proveedor de modelos o una URL base personalizada ya gestiona ~/.codex/config.toml en el equipo Child. No se modificaron archivos en el Child.", + "remoteLink.error.remote_plant_failed": "No se pudo instalar el agente ligero ocx-child por SSH. Comprueba el espacio en disco remoto y los permisos de ~/.cache, y vuelve a intentarlo.", + "remoteLink.error.remote_plant_timeout": "Se agotó el tiempo de espera al instalar el agente ligero ocx-child por SSH. Comprueba la conexión SSH y vuelve a intentarlo.", + "remoteLink.error.remote_plant_unavailable": "No hay un ejecutable verificado de ocx-child disponible localmente para la arquitectura del equipo remoto.", + "remoteLink.child.skew.same": "Misma versión que Home", + "remoteLink.child.skew.behind": "Anterior a Home ({version})", + "remoteLink.child.skew.ahead": "Más reciente que Home", + "remoteLink.child.kind.desktopApp": "Aplicación de escritorio", + "remoteLink.child.kind.goat": "GOAT", + "remoteLink.child.kind.source": "Copia del código fuente", + "remoteLink.child.updateAvailable": "Actualización disponible: {version}", + "remoteLink.child.catalog.current": "Catálogo al día", + "remoteLink.child.catalog.behind": "Catálogo desactualizado", + "remoteLink.child.codex.restartNeeded": "Requiere reiniciar Codex ({count})", + "remoteLink.child.codex.notRunning": "Codex no está en ejecución", + "remoteLink.child.ownerAction.legacy-ocx": "Actualiza OpenCodex manualmente en este Child", + "remoteLink.child.ownerAction.desktop-app-owned": "Usa Buscar actualizaciones en OpenCodex Desktop en este Child", + "remoteLink.child.ownerAction.goat": "GOAT mantiene actualizado este Child", + "remoteLink.child.ownerAction.launcher-node-missing": "Falta Node.js en este Child. Instálalo y actualiza OpenCodex allí.", + "remoteLink.child.ownerAction.launcher-bypassed": "El iniciador de este Child omite el actualizador de OpenCodex. Actualízalo manualmente.", + "remoteLink.child.ownerAction.mise-managed": "mise gestiona OpenCodex en este Child. Actualízalo con mise.", + "remoteLink.child.ownerAction.source-checkout": "Este Child se ejecuta desde una copia del código fuente. Actualízalo manualmente.", + "remoteLink.child.ownerAction.installer-unknown": "Se desconoce el método de instalación de este Child. Actualízalo desde el propio equipo.", + "remoteLink.child.check": "Comprobar", + "remoteLink.child.checkAll": "Comprobar todos", + "remoteLink.child.syncNow": "Sincronizar ahora", + "remoteLink.child.restartCodex": "Reiniciar Codex", + "remoteLink.child.update": "Actualizar", + "remoteLink.child.updateAll": "Actualizar todos", + "remoteLink.child.updateConfirm": "¿Actualizar {alias} a {version}? OpenCodex se reiniciará en ese Child y terminará cualquier turno que se esté retransmitiendo. Las actualizaciones automáticas esperan a que el Child quede inactivo.", + "remoteLink.child.updateAllConfirm": "Actualiza {count} Children a {version}, uno por uno. OpenCodex se reiniciará en cada Child y terminará cualquier turno que se esté retransmitiendo. Las actualizaciones automáticas esperan a que el Child quede inactivo.", + "remoteLink.child.upToDate": "Hasta la fecha", + "remoteLink.child.disconnectBlocked": "Espera a que termine la operación en curso", + "remoteLink.restart.scope.appServer": "Servidores de aplicación de Codex", + "remoteLink.restart.scope.appServerBody": "Reinicia los servidores de aplicación de Codex en segundo plano para que carguen el catálogo nuevo. Para actualizar también el servidor propio de Codex Desktop, reinicia la aplicación.", + "remoteLink.restart.scope.codex": "Aplicación de escritorio de Codex", + "remoteLink.restart.scope.codexBody": "Cierra y vuelve a abrir Codex Desktop en {alias}. Las conversaciones abiertas terminan. Se necesita una sesión de escritorio iniciada en ese equipo.", + "remoteLink.restart.confirm": "Reiniciar", + "remoteLink.job.active.observe": "Comprobación…", + "remoteLink.job.active.sync": "Sincronización…", + "remoteLink.job.active.restartCodex": "Reiniciando Codex…", + "remoteLink.job.active.update": "Actualizando…", + "remoteLink.job.state.queued": "En cola", + "remoteLink.job.state.running": "Correr", + "remoteLink.job.state.succeeded": "Completado", + "remoteLink.job.state.upToDate": "Hasta la fecha", + "remoteLink.job.state.busy": "Ocupado", + "remoteLink.job.state.offline": "Fuera de línea", + "remoteLink.job.state.refused": "Rechazado", + "remoteLink.job.state.ownerAction": "Requiere acción del propietario", + "remoteLink.job.state.unsupported": "No compatible", + "remoteLink.job.state.failed": "Falló", + "remoteLink.job.state.uncertain": "Resultado desconocido", + "remoteLink.job.restart.requested": "Reinicio solicitado", + "remoteLink.job.restart.unsupported": "No se admite el reinicio", + "remoteLink.job.restart.notRun": "No se reinició", + "remoteLink.job.restart.skipped": "No se reinició porque había una solicitud en curso en este Child.", + "remoteLink.job.sync.synced": "Sincronizado", + "remoteLink.job.sync.skipped": "Sincronización omitida", + "remoteLink.job.sync.failed": "Falló la sincronización", + "remoteLink.job.sync.timedOut": "Se agotó el tiempo de espera de sincronización", + "remoteLink.job.last": "Última operación: {op} · {state}", + "remoteLink.job.op.observe": "Comprobación", + "remoteLink.job.op.sync": "Sincronización", + "remoteLink.job.op.restartCodex": "Reinicio de Codex", + "remoteLink.job.op.update": "Actualizar", + "remoteLink.job.notFound": "Este Home se reinició, por lo que se perdió el progreso de la tarea. Las filas de abajo muestran el estado actual de cada Child.", + "remoteLink.job.automatic": "Automático", + "remoteLink.policy.title": "Automatización de Children", + "remoteLink.policy.catalogFanout": "Distribución del catálogo", + "remoteLink.policy.catalogFanout.auto": "Automático", + "remoteLink.policy.catalogFanout.manual": "Manual", + "remoteLink.policy.childCodexRestart": "Reinicio de Codex", + "remoteLink.policy.childCodexRestart.never": "Nunca", + "remoteLink.policy.childCodexRestart.whenIdle": "Servidores de aplicación cuando no haya actividad", + "remoteLink.policy.updates": "Actualizaciones", + "remoteLink.policy.updates.off": "Desactivado", + "remoteLink.policy.updates.notify": "Solo notificar", + "remoteLink.policy.updates.autoWhenIdle": "Automáticas durante la inactividad", + "remoteLink.policy.idleMinutes": "Inactivo después de (minutos)", + "remoteLink.policy.save": "Guardar", + "remoteLink.policy.saved": "Guardado", + "remoteLink.policy.updatesInactive": "La configuración se guarda ahora. Las actualizaciones automáticas comenzarán cuando se publique la comprobación periódica; por el momento no se actualiza nada automáticamente.", + "remoteLink.policy.loadFailed": "No se pudo cargar la automatización de Children.", + "remoteLink.policy.invalid": "El archivo de políticas estaba dañado. Se desactivaron la distribución automática del catálogo y las actualizaciones automáticas. Vuelve a elegir cada modo automático y guarda para reactivarlos.", + "remoteLink.error.invalid_job_id": "El ID de operación no es válido.", + "remoteLink.error.job_not_found": "Ya no se reconoce la operación. Es posible que Home se haya reiniciado.", + "remoteLink.error.link_operation_in_progress": "Hay otra operación en curso en este Child.", + "remoteLink.error.no_eligible_links": "No hay ningún Child iniciado por Home disponible para esta operación.", + "remoteLink.error.policy_write_failed": "No se pudo guardar la política de Children.", + "remoteLink.error.runtime_role_client": "Este equipo es un Child. Solo un Home puede operar Children.", + "remoteLink.error.link_not_home_initiated": "Este Child inició su propio enlace. Realiza la operación desde ese equipo.", + "comboSuggest.edit.moveUp": "Subir {name}", + "comboSuggest.edit.moveDown": "Bajar {name}", + "comboSuggest.edit.remove": "Quitar {name}", + "comboSuggest.title": "Combos sugeridos", + "comboSuggest.lede": "Modelos que más de uno de tus proveedores ofrece con el mismo nombre. Genera un combo para enrutar un nombre de modelo entre todos ellos.", + "comboSuggest.servedBy": "ofrecido por {count} proveedores", + "comboSuggest.canAdd": "también puede usar {providers}", + "comboSuggest.generate": "Generar", + "comboSuggest.addTo": "Añadir al combo", + "comboSuggest.dismiss": "Descartar", + "comboSuggest.exclude.button": "Excluir proveedores…", + "comboSuggest.exclude.active": "Excluidos: {names}", + "comboSuggest.exclude.head": "Dejar fuera de los combos sugeridos", + "comboSuggest.exclude.hint": "Sus modelos no se incluyen en ningún combo sugerido; los combos que ya creaste los conservan.", + "comboSuggest.exclude.saveFailed": "No se pudieron guardar los proveedores excluidos.", + "comboSuggest.exclude.none": "No hay sugerencias para mostrar.", + "comboSuggest.exclude.loadFailed": "No se pudieron cargar los proveedores excluidos.", + "comboSuggest.saveChanged": "La configuración de sugerencias cambió o no se pudo verificar. Actualiza Combos y vuelve a intentarlo.", + "comboSuggest.showAll": "Mostrar los {count}", + "comboSuggest.showFewer": "Mostrar menos", + "comboSuggest.tier.ownSubscription": "suscripción del fabricante", + "comboSuggest.tier.subscription": "suscripción", + "comboSuggest.tier.vertex": "crédito de Vertex", + "comboSuggest.tier.metered": "pago por uso", + "comboSuggest.draft.id": "ID del combo", + "comboSuggest.draft.orderHint": "Se prueban de arriba abajo: primero las suscripciones, luego el crédito de Vertex, y al final las claves de pago por uso y los relays. Reordena o quita antes de guardar.", + "comboSuggest.draft.left": "Queda {percent}%", + "comboSuggest.draft.strategy": "Estrategia: failover. Cámbiala en la fila después de guardar.", + "comboSuggest.allowPaid": "Permitir destinos de pago (obligatorio para guardar). Estos destinos pueden facturar créditos de pago o uso.", + "comboSuggest.enablePaid": "Ejecuta {command} para permitir destinos de pago. Las sugerencias recogen el cambio en la siguiente actualización de combos.", + "comboSuggest.draft.save": "Guardar combo", + "comboSuggest.draft.saving": "Guardando…", + +} satisfies Record; diff --git a/gui/src/i18n/gateway-clients-copy.ts b/gui/src/i18n/gateway-clients-copy.ts index 40b4880f134..9185e032d06 100644 --- a/gui/src/i18n/gateway-clients-copy.ts +++ b/gui/src/i18n/gateway-clients-copy.ts @@ -4,49 +4,49 @@ * server sends a code for every note, override and refusal; this table is what the user reads. * File paths and diagnostics without a specific translation can be shown as sent. */ -type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; -const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; -type Row = readonly [string, string, string, string, string, string, string, string, string, string, string]; +type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt" | "es"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt", "es"]; +type Row = readonly [string, string, string, string, string, string, string, string, string, string, string, string]; const rows = { - tab: ["Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity"], - title: ["Antigravity and agy","Antigravity 및 agy","Antigravity und agy","Antigravity et agy","Antigravity 和 agy","Antigravity 與 agy","Antigravity и agy","Antigravity と agy","Antigravity ve agy","Antigravity và agy","Antigravity e agy"], - intro: ["Send Google's Antigravity desktop app and the agy CLI through this proxy. Connect writes their gateway settings and keeps a copy of what was there; Disconnect puts it back.","Google의 Antigravity 데스크톱 앱과 agy CLI가 이 프록시를 거치게 해요. 연결하면 게이트웨이 설정을 쓰고 기존 내용을 보관하며, 연결 해제하면 되돌려요.","Leitet Googles Antigravity-Desktop-App und die agy-CLI über diesen Proxy. Verbinden schreibt ihre Gateway-Einstellungen und sichert den vorherigen Stand; Trennen stellt ihn wieder her.","Fait passer l’application de bureau Antigravity de Google et la CLI agy par ce proxy. Connecter écrit leurs réglages de passerelle et conserve l’état précédent ; Déconnecter le rétablit.","让 Google 的 Antigravity 桌面应用和 agy 命令行经由此代理。连接会写入它们的网关设置并保留原有内容;断开会恢复原样。","讓 Google 的 Antigravity 桌面應用程式和 agy 命令列經由此代理。連線會寫入它們的閘道設定並保留原有內容;中斷連線會還原。","Направляет настольное приложение Google Antigravity и CLI agy через этот прокси. Подключение записывает настройки шлюза и сохраняет прежнее содержимое; отключение возвращает его.","Google の Antigravity デスクトップアプリと agy CLI をこのプロキシ経由にします。接続するとゲートウェイ設定を書き込み、元の内容を保管します。切断すると元に戻します。","Google'ın Antigravity masaüstü uygulamasını ve agy CLI'ını bu proxy üzerinden geçirir. Bağlan, ağ geçidi ayarlarını yazar ve önceki hâlini saklar; Bağlantıyı kes onu geri yükler.","Cho ứng dụng Antigravity trên máy tính của Google và CLI agy đi qua proxy này. Kết nối sẽ ghi cài đặt cổng và giữ bản cũ; Ngắt kết nối sẽ khôi phục lại.","Faz o app de desktop Antigravity do Google e a CLI agy passarem por este proxy. Conectar grava as configurações de gateway e guarda o estado anterior; Desconectar o restaura."], - loading: ["Reading client status…","클라이언트 상태를 읽는 중…","Clientstatus wird gelesen…","Lecture de l’état des clients…","正在读取客户端状态…","正在讀取用戶端狀態…","Чтение состояния клиентов…","クライアントの状態を読み込み中…","İstemci durumu okunuyor…","Đang đọc trạng thái máy khách…","Lendo o status dos clientes…"], - connected: ["Connected","연결됨","Verbunden","Connecté","已连接","已連線","Подключено","接続済み","Bağlı","Đã kết nối","Conectado"], - notConnected: ["Not connected","연결 안 됨","Nicht verbunden","Non connecté","未连接","未連線","Не подключено","未接続","Bağlı değil","Chưa kết nối","Não conectado"], - unavailable: ["Could not read the Antigravity and agy status.","Antigravity 및 agy 상태를 읽지 못했어요.","Der Status von Antigravity und agy konnte nicht gelesen werden.","Impossible de lire l’état d’Antigravity et d’agy.","无法读取 Antigravity 和 agy 的状态。","無法讀取 Antigravity 與 agy 的狀態。","Не удалось прочитать состояние Antigravity и agy.","Antigravity と agy の状態を読み取れませんでした。","Antigravity ve agy durumu okunamadı.","Không đọc được trạng thái của Antigravity và agy.","Não foi possível ler o status do Antigravity e do agy."], - files: ["Files it changes","변경하는 파일","Geänderte Dateien","Fichiers modifiés","会修改的文件","會修改的檔案","Изменяемые файлы","変更するファイル","Değiştirdiği dosyalar","Các tệp sẽ thay đổi","Arquivos alterados"], - fileMissing: ["not created yet","아직 없음","noch nicht angelegt","pas encore créé","尚未创建","尚未建立","ещё не создан","未作成","henüz oluşturulmadı","chưa được tạo","ainda não criado"], - overrideAdminGateway: ["Your organization's admin_settings.json sets a gateway, so this connection has no effect.","조직의 admin_settings.json이 게이트웨이를 지정하고 있어 이 연결은 적용되지 않아요.","Die admin_settings.json Ihrer Organisation legt ein Gateway fest, daher wirkt diese Verbindung nicht.","Le fichier admin_settings.json de votre organisation définit une passerelle ; cette connexion n’a donc aucun effet.","你所在组织的 admin_settings.json 指定了网关,因此此连接不会生效。","你所屬組織的 admin_settings.json 指定了閘道,因此此連線不會生效。","admin_settings.json вашей организации задаёт шлюз, поэтому это подключение не действует.","組織の admin_settings.json がゲートウェイを指定しているため、この接続は効きません。","Kuruluşunuzun admin_settings.json dosyası bir ağ geçidi belirliyor, bu yüzden bu bağlantının etkisi yok.","admin_settings.json của tổ chức bạn đã đặt cổng, nên kết nối này không có tác dụng.","O admin_settings.json da sua organização define um gateway, então esta conexão não tem efeito."], - overrideAdminUnreadable: ["An admin_settings.json exists but could not be read, so an organization gateway may override this connection.","admin_settings.json이 있지만 읽을 수 없어, 조직 게이트웨이가 이 연결보다 우선할 수 있어요.","Eine admin_settings.json ist vorhanden, konnte aber nicht gelesen werden; ein Gateway der Organisation könnte diese Verbindung übersteuern.","Un fichier admin_settings.json existe mais n’a pas pu être lu ; une passerelle de l’organisation pourrait primer sur cette connexion.","存在 admin_settings.json 但无法读取,组织网关可能会覆盖此连接。","存在 admin_settings.json 但無法讀取,組織閘道可能會覆蓋此連線。","Файл admin_settings.json есть, но прочитать его не удалось; шлюз организации может перекрыть это подключение.","admin_settings.json はありますが読み取れませんでした。組織のゲートウェイがこの接続より優先されるかもしれません。","Bir admin_settings.json var ama okunamadı; kuruluşun ağ geçidi bu bağlantının önüne geçebilir.","Có admin_settings.json nhưng không đọc được, nên cổng của tổ chức có thể ghi đè kết nối này.","Existe um admin_settings.json, mas não foi possível lê-lo; um gateway da organização pode se sobrepor a esta conexão."], - overrideEnv: ["AGY_LLM_GATEWAY_URL is set in the environment OpenCodex runs in and takes precedence over this connection.","OpenCodex가 실행되는 환경에 AGY_LLM_GATEWAY_URL이 설정되어 있어 이 연결보다 우선해요.","AGY_LLM_GATEWAY_URL ist in der Umgebung von OpenCodex gesetzt und hat Vorrang vor dieser Verbindung.","AGY_LLM_GATEWAY_URL est défini dans l’environnement d’OpenCodex et prime sur cette connexion.","OpenCodex 运行环境中设置了 AGY_LLM_GATEWAY_URL,它优先于此连接。","OpenCodex 執行環境中設定了 AGY_LLM_GATEWAY_URL,它優先於此連線。","В окружении OpenCodex задана AGY_LLM_GATEWAY_URL, и она имеет приоритет над этим подключением.","OpenCodex の実行環境で AGY_LLM_GATEWAY_URL が設定されており、この接続より優先されます。","OpenCodex'in çalıştığı ortamda AGY_LLM_GATEWAY_URL ayarlı ve bu bağlantının önüne geçiyor.","Môi trường chạy OpenCodex có đặt AGY_LLM_GATEWAY_URL, và biến này được ưu tiên hơn kết nối này.","AGY_LLM_GATEWAY_URL está definida no ambiente do OpenCodex e tem prioridade sobre esta conexão."], - noteNoGoogleSignIn: ["While connected, the app does not use your Google sign-in.","연결된 동안 앱은 Google 로그인을 사용하지 않아요.","Solange die Verbindung besteht, nutzt die App Ihre Google-Anmeldung nicht.","Tant qu’elle est connectée, l’application n’utilise pas votre connexion Google.","连接期间,应用不使用你的 Google 登录。","連線期間,應用程式不使用你的 Google 登入。","Пока подключение активно, приложение не использует ваш вход в Google.","接続中、アプリは Google のサインインを使いません。","Bağlıyken uygulama Google oturumunuzu kullanmaz.","Khi đã kết nối, ứng dụng không dùng đăng nhập Google của bạn.","Enquanto conectado, o app não usa o seu login do Google."], - noteAgyFollowsApp: ["agy also follows this setting unless it is connected on its own.","agy를 따로 연결하지 않으면 agy도 이 설정을 따라요.","agy folgt dieser Einstellung ebenfalls, solange es nicht eigens verbunden ist.","agy suit aussi ce réglage, sauf s’il est connecté séparément.","除非单独连接 agy,否则 agy 也会遵循此设置。","除非單獨連線 agy,否則 agy 也會遵循此設定。","agy тоже следует этой настройке, если не подключён отдельно.","agy を個別に接続しない限り、agy もこの設定に従います。","agy ayrıca bağlanmadıkça o da bu ayarı izler.","agy cũng theo cài đặt này, trừ khi được kết nối riêng.","O agy também segue esta configuração, a menos que seja conectado à parte."], - noteSettingsNotJson: ["settings.json is not plain JSON (it has comments, trailing commas or a syntax error), so OpenCodex will not change it. Fix the file, then connect again.","settings.json이 순수 JSON이 아니라서(주석, 끝 쉼표 또는 문법 오류) OpenCodex가 바꾸지 않아요. 파일을 고친 뒤 다시 연결하세요.","settings.json ist kein reines JSON (Kommentare, nachgestellte Kommas oder ein Syntaxfehler), daher ändert OpenCodex sie nicht. Korrigieren Sie die Datei und verbinden Sie erneut.","settings.json n’est pas du JSON pur (commentaires, virgules finales ou erreur de syntaxe) ; OpenCodex ne le modifiera pas. Corrigez le fichier, puis reconnectez.","settings.json 不是纯 JSON(含注释、末尾逗号或语法错误),OpenCodex 不会修改它。修好文件后再连接。","settings.json 不是純 JSON(含註解、結尾逗號或語法錯誤),OpenCodex 不會修改它。修好檔案後再連線。","settings.json — не чистый JSON (комментарии, лишние запятые или синтаксическая ошибка), поэтому OpenCodex его не изменит. Исправьте файл и подключитесь снова.","settings.json が純粋な JSON ではない(コメント、末尾のカンマ、構文エラー)ため、OpenCodex は変更しません。ファイルを直してから再接続してください。","settings.json düz JSON değil (yorumlar, sondaki virgüller ya da bir söz dizimi hatası), bu yüzden OpenCodex onu değiştirmez. Dosyayı düzeltip yeniden bağlanın.","settings.json không phải JSON thuần (có chú thích, dấu phẩy thừa hoặc lỗi cú pháp), nên OpenCodex sẽ không sửa nó. Hãy sửa tệp rồi kết nối lại.","settings.json não é JSON puro (comentários, vírgulas finais ou erro de sintaxe), então o OpenCodex não vai alterá-lo. Corrija o arquivo e conecte de novo."], - noteSettingsNotObject: ["settings.json does not contain a JSON object, so OpenCodex will not change it.","settings.json에 JSON 객체가 없어서 OpenCodex가 바꾸지 않아요.","settings.json enthält kein JSON-Objekt, daher ändert OpenCodex sie nicht.","settings.json ne contient pas d’objet JSON ; OpenCodex ne le modifiera pas.","settings.json 不包含 JSON 对象,OpenCodex 不会修改它。","settings.json 不包含 JSON 物件,OpenCodex 不會修改它。","settings.json не содержит JSON-объект, поэтому OpenCodex его не изменит.","settings.json に JSON オブジェクトがないため、OpenCodex は変更しません。","settings.json bir JSON nesnesi içermiyor, bu yüzden OpenCodex onu değiştirmez.","settings.json không chứa đối tượng JSON, nên OpenCodex sẽ không sửa nó.","settings.json não contém um objeto JSON, então o OpenCodex não vai alterá-lo."], - noteNoRestoreRecord: ["This was connected outside OpenCodex, so Disconnect cannot bring back your earlier settings.","OpenCodex 밖에서 연결되어 있어 연결 해제로 이전 설정을 되돌릴 수 없어요.","Die Verbindung wurde außerhalb von OpenCodex eingerichtet; Trennen kann Ihre früheren Einstellungen daher nicht zurückholen.","La connexion a été faite hors d’OpenCodex ; Déconnecter ne peut donc pas rétablir vos réglages précédents.","这是在 OpenCodex 之外连接的,断开无法恢复你之前的设置。","這是在 OpenCodex 之外連線的,中斷連線無法還原你先前的設定。","Подключение сделано вне OpenCodex, поэтому отключение не вернёт ваши прежние настройки.","OpenCodex の外で接続されたため、切断しても以前の設定には戻せません。","Bu bağlantı OpenCodex dışında yapılmış, bu yüzden Bağlantıyı kes önceki ayarlarınızı geri getiremez.","Kết nối này được tạo bên ngoài OpenCodex, nên Ngắt kết nối không thể khôi phục cài đặt cũ.","Isto foi conectado fora do OpenCodex, então Desconectar não consegue trazer de volta suas configurações anteriores."], - noteAgyVersion: ["Needs agy 1.2.15 or newer.","agy 1.2.15 이상이 필요해요.","Erfordert agy 1.2.15 oder neuer.","Nécessite agy 1.2.15 ou plus récent.","需要 agy 1.2.15 或更新版本。","需要 agy 1.2.15 或更新版本。","Нужна agy 1.2.15 или новее.","agy 1.2.15 以降が必要です。","agy 1.2.15 veya daha yenisi gerekir.","Cần agy 1.2.15 trở lên.","Requer agy 1.2.15 ou mais recente."], - noteWindowsUnverified: ["Google documents this for macOS and Linux. The Windows build reads the same settings, but this has not been tested end to end on Windows.","Google은 macOS와 Linux용으로만 문서화했어요. Windows 빌드도 같은 설정을 읽지만 Windows에서 처음부터 끝까지 검증하지는 않았어요.","Google dokumentiert dies für macOS und Linux. Die Windows-Version liest dieselben Einstellungen, unter Windows wurde das aber nicht durchgängig getestet.","Google le documente pour macOS et Linux. La version Windows lit les mêmes réglages, mais cela n’a pas été testé de bout en bout sous Windows.","Google 只为 macOS 和 Linux 提供了文档。Windows 版也会读取同样的设置,但尚未在 Windows 上完整验证。","Google 只為 macOS 和 Linux 提供了文件。Windows 版也會讀取同樣的設定,但尚未在 Windows 上完整驗證。","Google описывает это для macOS и Linux. Сборка для Windows читает те же настройки, но под Windows это не проверено полностью.","Google が文書化しているのは macOS と Linux です。Windows 版も同じ設定を読みますが、Windows では通しで検証していません。","Google bunu macOS ve Linux için belgeliyor. Windows sürümü aynı ayarları okur ama Windows'ta uçtan uca test edilmedi.","Google chỉ mô tả cho macOS và Linux. Bản Windows cũng đọc cùng cài đặt, nhưng chưa được kiểm thử đầy đủ trên Windows.","O Google documenta isto para macOS e Linux. A versão para Windows lê as mesmas configurações, mas isso não foi testado de ponta a ponta no Windows."], - noteAgyEnvExported: ["AGY_LLM_GATEWAY_URL is set globally; the agy command set up here overrides it for agy only.","AGY_LLM_GATEWAY_URL이 전역으로 설정되어 있어요. 여기서 설정한 agy 명령은 agy에서만 이를 덮어써요.","AGY_LLM_GATEWAY_URL ist global gesetzt; der hier eingerichtete agy-Befehl übersteuert sie nur für agy.","AGY_LLM_GATEWAY_URL est défini globalement ; la commande agy installée ici le remplace pour agy seulement.","AGY_LLM_GATEWAY_URL 已全局设置;这里设置的 agy 命令只对 agy 覆盖它。","AGY_LLM_GATEWAY_URL 已全域設定;這裡設定的 agy 命令只對 agy 覆蓋它。","AGY_LLM_GATEWAY_URL задана глобально; настроенная здесь команда agy переопределяет её только для agy.","AGY_LLM_GATEWAY_URL がグローバルに設定されています。ここで設定した agy コマンドは agy に対してだけそれを上書きします。","AGY_LLM_GATEWAY_URL genel olarak ayarlı; burada kurulan agy komutu onu yalnızca agy için geçersiz kılar.","AGY_LLM_GATEWAY_URL đang được đặt toàn cục; lệnh agy thiết lập ở đây chỉ ghi đè nó cho agy.","AGY_LLM_GATEWAY_URL está definida globalmente; o comando agy configurado aqui a substitui só para o agy."], - model: ["Default model (optional)","기본 모델(선택)","Standardmodell (optional)","Modèle par défaut (facultatif)","默认模型(可选)","預設模型(選填)","Модель по умолчанию (необязательно)","デフォルトモデル(任意)","Varsayılan model (isteğe bağlı)","Mô hình mặc định (không bắt buộc)","Modelo padrão (opcional)"], - modelHint: ["Leave empty to keep the current setting.","비워 두면 현재 설정을 유지해요.","Leer lassen, um die aktuelle Einstellung zu behalten.","Laissez vide pour garder le réglage actuel.","留空则保留当前设置。","留空則保留目前設定。","Оставьте пустым, чтобы сохранить текущую настройку.","空欄にすると現在の設定を保ちます。","Mevcut ayarı korumak için boş bırakın.","Để trống để giữ cài đặt hiện tại.","Deixe vazio para manter a configuração atual."], - connect: ["Connect","연결","Verbinden","Connecter","连接","連線","Подключить","接続","Bağlan","Kết nối","Conectar"], - disconnect: ["Disconnect","연결 해제","Trennen","Déconnecter","断开","中斷連線","Отключить","切断","Bağlantıyı kes","Ngắt kết nối","Desconectar"], - working: ["Working…","처리 중…","Wird ausgeführt…","En cours…","处理中…","處理中…","Выполняется…","処理中…","İşleniyor…","Đang xử lý…","Processando…"], - doneConnected: ["Connected.","연결했어요.","Verbunden.","Connecté.","已连接。","已連線。","Подключено.","接続しました。","Bağlandı.","Đã kết nối.","Conectado."], - doneUnchanged: ["Already connected; nothing changed.","이미 연결되어 있어 바뀐 것이 없어요.","Bereits verbunden; nichts geändert.","Déjà connecté ; rien n’a changé.","已经连接,没有改动。","已經連線,沒有變動。","Уже подключено; ничего не изменилось.","すでに接続済みです。変更はありません。","Zaten bağlı; hiçbir şey değişmedi.","Đã kết nối sẵn; không có gì thay đổi.","Já conectado; nada mudou."], - doneRestored: ["Disconnected, and your earlier settings were put back.","연결을 해제하고 이전 설정을 되돌렸어요.","Getrennt; Ihre früheren Einstellungen wurden wiederhergestellt.","Déconnecté ; vos réglages précédents ont été rétablis.","已断开,并恢复了你之前的设置。","已中斷連線,並還原了你先前的設定。","Отключено, прежние настройки восстановлены.","切断し、以前の設定に戻しました。","Bağlantı kesildi ve önceki ayarlarınız geri getirildi.","Đã ngắt kết nối và khôi phục cài đặt cũ.","Desconectado, e suas configurações anteriores foram restauradas."], - doneRestoredPartly: ["Disconnected. The file was edited after connecting, so only the OpenCodex entries were removed and your other edits were kept.","연결을 해제했어요. 연결 후 파일이 수정되어 OpenCodex 항목만 지우고 다른 수정은 그대로 두었어요.","Getrennt. Die Datei wurde nach dem Verbinden bearbeitet, daher wurden nur die OpenCodex-Einträge entfernt und Ihre übrigen Änderungen behalten.","Déconnecté. Le fichier a été modifié après la connexion ; seules les entrées OpenCodex ont été retirées et vos autres modifications conservées.","已断开。连接后文件被修改过,所以只移除了 OpenCodex 的条目,你的其他改动都保留了。","已中斷連線。連線後檔案被修改過,所以只移除了 OpenCodex 的項目,你的其他變更都保留了。","Отключено. После подключения файл менялся, поэтому удалены только записи OpenCodex, а остальные ваши правки сохранены.","切断しました。接続後にファイルが編集されたため、OpenCodex の項目だけを削除し、ほかの編集は残しました。","Bağlantı kesildi. Dosya bağlandıktan sonra düzenlenmiş, bu yüzden yalnızca OpenCodex girdileri kaldırıldı ve diğer düzenlemeleriniz korundu.","Đã ngắt kết nối. Tệp đã bị sửa sau khi kết nối, nên chỉ các mục của OpenCodex được gỡ và các chỉnh sửa khác của bạn được giữ lại.","Desconectado. O arquivo foi editado depois da conexão, então só as entradas do OpenCodex foram removidas e suas outras edições foram mantidas."], - doneNothing: ["Nothing to undo; no file was changed.","되돌릴 것이 없어 파일을 바꾸지 않았어요.","Nichts rückgängig zu machen; keine Datei wurde geändert.","Rien à annuler ; aucun fichier n’a été modifié.","没有需要撤销的内容,未修改任何文件。","沒有需要復原的內容,未修改任何檔案。","Отменять нечего; ни один файл не изменён.","元に戻すものはなく、ファイルは変更していません。","Geri alınacak bir şey yok; hiçbir dosya değişmedi.","Không có gì để hoàn tác; không tệp nào bị thay đổi.","Nada a desfazer; nenhum arquivo foi alterado."], - hintAntigravity: ["Restart Antigravity to apply it.","적용하려면 Antigravity를 다시 시작하세요.","Starten Sie Antigravity neu, damit es wirkt.","Redémarrez Antigravity pour l’appliquer.","重启 Antigravity 后生效。","重新啟動 Antigravity 後生效。","Перезапустите Antigravity, чтобы применить.","反映するには Antigravity を再起動してください。","Uygulamak için Antigravity'yi yeniden başlatın.","Khởi động lại Antigravity để áp dụng.","Reinicie o Antigravity para aplicar."], - hintAgy: ["Open a new terminal to apply it.","적용하려면 새 터미널을 여세요.","Öffnen Sie ein neues Terminal, damit es wirkt.","Ouvrez un nouveau terminal pour l’appliquer.","打开新的终端后生效。","開啟新的終端機後生效。","Откройте новый терминал, чтобы применить.","反映するには新しいターミナルを開いてください。","Uygulamak için yeni bir terminal açın.","Mở terminal mới để áp dụng.","Abra um novo terminal para aplicar."], - refusedCredential: ["This proxy's address requires an API key, and OpenCodex will not write a real key into these files. Turn on unauthenticatedLoopbackListener or bind the proxy to loopback.","이 프록시 주소는 API 키가 필요하고, OpenCodex는 실제 키를 이 파일들에 쓰지 않아요. unauthenticatedLoopbackListener를 켜거나 프록시를 루프백에 바인딩하세요.","Diese Proxy-Adresse verlangt einen API-Schlüssel, und OpenCodex schreibt keinen echten Schlüssel in diese Dateien. Aktivieren Sie unauthenticatedLoopbackListener oder binden Sie den Proxy an Loopback.","L’adresse de ce proxy exige une clé d’API, et OpenCodex n’écrira pas de vraie clé dans ces fichiers. Activez unauthenticatedLoopbackListener ou liez le proxy à la boucle locale.","此代理地址需要 API 密钥,而 OpenCodex 不会把真实密钥写进这些文件。请开启 unauthenticatedLoopbackListener,或把代理绑定到回环地址。","此代理位址需要 API 金鑰,而 OpenCodex 不會把真實金鑰寫進這些檔案。請開啟 unauthenticatedLoopbackListener,或把代理繫結到回環位址。","Адрес этого прокси требует ключ API, а OpenCodex не запишет настоящий ключ в эти файлы. Включите unauthenticatedLoopbackListener или привяжите прокси к loopback.","このプロキシのアドレスは API キーを必要としますが、OpenCodex は本物のキーをこれらのファイルに書きません。unauthenticatedLoopbackListener を有効にするか、プロキシをループバックにバインドしてください。","Bu proxy adresi bir API anahtarı istiyor ve OpenCodex bu dosyalara gerçek bir anahtar yazmaz. unauthenticatedLoopbackListener'ı açın ya da proxy'yi loopback'e bağlayın.","Địa chỉ proxy này cần khóa API, và OpenCodex sẽ không ghi khóa thật vào các tệp này. Hãy bật unauthenticatedLoopbackListener hoặc gắn proxy vào loopback.","O endereço deste proxy exige uma chave de API, e o OpenCodex não grava uma chave real nesses arquivos. Ative unauthenticatedLoopbackListener ou vincule o proxy ao loopback."], - refusedModel: ["The model must be one line of at most 200 characters.","모델은 200자 이하의 한 줄이어야 해요.","Das Modell muss eine Zeile mit höchstens 200 Zeichen sein.","Le modèle doit tenir sur une ligne de 200 caractères au plus.","模型必须是不超过 200 个字符的单行文本。","模型必須是不超過 200 個字元的單行文字。","Модель должна быть одной строкой не длиннее 200 символов.","モデルは 200 文字以内の 1 行にしてください。","Model en fazla 200 karakterlik tek bir satır olmalı.","Mô hình phải là một dòng tối đa 200 ký tự.","O modelo deve ser uma linha de no máximo 200 caracteres."], - refusedFile: ["settings.json could not be read as a JSON object, so OpenCodex left it untouched. Fix the file, then try again.","settings.json을 JSON 객체로 읽을 수 없어 OpenCodex가 그대로 두었어요. 파일을 고친 뒤 다시 시도하세요.","settings.json konnte nicht als JSON-Objekt gelesen werden, daher hat OpenCodex sie nicht verändert. Korrigieren Sie die Datei und versuchen Sie es erneut.","settings.json n’a pas pu être lu comme un objet JSON ; OpenCodex n’y a pas touché. Corrigez le fichier, puis réessayez.","无法把 settings.json 读成 JSON 对象,OpenCodex 没有改动它。修好文件后重试。","無法把 settings.json 讀成 JSON 物件,OpenCodex 沒有變動它。修好檔案後重試。","settings.json не удалось прочитать как JSON-объект, поэтому OpenCodex его не тронул. Исправьте файл и попробуйте снова.","settings.json を JSON オブジェクトとして読めなかったため、OpenCodex は変更していません。ファイルを直してからやり直してください。","settings.json bir JSON nesnesi olarak okunamadı, bu yüzden OpenCodex ona dokunmadı. Dosyayı düzeltip yeniden deneyin.","Không đọc được settings.json như một đối tượng JSON, nên OpenCodex không động vào nó. Hãy sửa tệp rồi thử lại.","Não foi possível ler settings.json como um objeto JSON, então o OpenCodex não o alterou. Corrija o arquivo e tente de novo."], - refusedIo: ["Could not write the client files:","클라이언트 파일을 쓰지 못했어요:","Die Clientdateien konnten nicht geschrieben werden:","Impossible d’écrire les fichiers du client :","无法写入客户端文件:","無法寫入用戶端檔案:","Не удалось записать файлы клиента:","クライアントのファイルを書き込めませんでした:","İstemci dosyaları yazılamadı:","Không ghi được các tệp của máy khách:","Não foi possível gravar os arquivos do cliente:"], - refused: ["The proxy refused the change:","프록시가 변경을 거부했어요:","Der Proxy hat die Änderung abgelehnt:","Le proxy a refusé la modification :","代理拒绝了此更改:","代理拒絕了此變更:","Прокси отклонил изменение:","プロキシが変更を拒否しました:","Proxy değişikliği reddetti:","Proxy đã từ chối thay đổi:","O proxy recusou a alteração:"], - actionFailed: ["Could not confirm whether the change was applied. Check the client status before trying again.","변경이 적용됐는지 확인하지 못했어요. 다시 시도하기 전에 클라이언트 상태를 확인하세요.","Es ließ sich nicht bestätigen, ob die Änderung übernommen wurde. Prüfen Sie den Client-Status, bevor Sie es erneut versuchen.","Impossible de confirmer si la modification a été appliquée. Vérifiez l’état du client avant de réessayer.","无法确认更改是否已生效。请先检查客户端状态再重试。","無法確認變更是否已生效。請先檢查用戶端狀態再重試。","Не удалось подтвердить, применено ли изменение. Проверьте состояние клиента, прежде чем повторять попытку.","変更が適用されたか確認できませんでした。再試行する前にクライアントの状態を確認してください。","Değişikliğin uygulanıp uygulanmadığı doğrulanamadı. Yeniden denemeden önce istemci durumunu kontrol edin.","Không xác nhận được thay đổi đã được áp dụng hay chưa. Hãy kiểm tra trạng thái client trước khi thử lại.","Não foi possível confirmar se a alteração foi aplicada. Verifique o status do cliente antes de tentar novamente."], + tab: ["Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity","Antigravity", "Antigravity"], + title: ["Antigravity and agy","Antigravity 및 agy","Antigravity und agy","Antigravity et agy","Antigravity 和 agy","Antigravity 與 agy","Antigravity и agy","Antigravity と agy","Antigravity ve agy","Antigravity và agy","Antigravity e agy", "Antigravity y agy"], + intro: ["Send Google's Antigravity desktop app and the agy CLI through this proxy. Connect writes their gateway settings and keeps a copy of what was there; Disconnect puts it back.","Google의 Antigravity 데스크톱 앱과 agy CLI가 이 프록시를 거치게 해요. 연결하면 게이트웨이 설정을 쓰고 기존 내용을 보관하며, 연결 해제하면 되돌려요.","Leitet Googles Antigravity-Desktop-App und die agy-CLI über diesen Proxy. Verbinden schreibt ihre Gateway-Einstellungen und sichert den vorherigen Stand; Trennen stellt ihn wieder her.","Fait passer l’application de bureau Antigravity de Google et la CLI agy par ce proxy. Connecter écrit leurs réglages de passerelle et conserve l’état précédent ; Déconnecter le rétablit.","让 Google 的 Antigravity 桌面应用和 agy 命令行经由此代理。连接会写入它们的网关设置并保留原有内容;断开会恢复原样。","讓 Google 的 Antigravity 桌面應用程式和 agy 命令列經由此代理。連線會寫入它們的閘道設定並保留原有內容;中斷連線會還原。","Направляет настольное приложение Google Antigravity и CLI agy через этот прокси. Подключение записывает настройки шлюза и сохраняет прежнее содержимое; отключение возвращает его.","Google の Antigravity デスクトップアプリと agy CLI をこのプロキシ経由にします。接続するとゲートウェイ設定を書き込み、元の内容を保管します。切断すると元に戻します。","Google'ın Antigravity masaüstü uygulamasını ve agy CLI'ını bu proxy üzerinden geçirir. Bağlan, ağ geçidi ayarlarını yazar ve önceki hâlini saklar; Bağlantıyı kes onu geri yükler.","Cho ứng dụng Antigravity trên máy tính của Google và CLI agy đi qua proxy này. Kết nối sẽ ghi cài đặt cổng và giữ bản cũ; Ngắt kết nối sẽ khôi phục lại.","Faz o app de desktop Antigravity do Google e a CLI agy passarem por este proxy. Conectar grava as configurações de gateway e guarda o estado anterior; Desconectar o restaura.", "Haz que la aplicación de escritorio Antigravity de Google y la CLI agy pasen por este proxy. Conectar escribe su configuración de gateway y guarda una copia de lo que había; Desconectar la restaura."], + loading: ["Reading client status…","클라이언트 상태를 읽는 중…","Clientstatus wird gelesen…","Lecture de l’état des clients…","正在读取客户端状态…","正在讀取用戶端狀態…","Чтение состояния клиентов…","クライアントの状態を読み込み中…","İstemci durumu okunuyor…","Đang đọc trạng thái máy khách…","Lendo o status dos clientes…", "Leyendo el estado de los clientes…"], + connected: ["Connected","연결됨","Verbunden","Connecté","已连接","已連線","Подключено","接続済み","Bağlı","Đã kết nối","Conectado", "Conectado"], + notConnected: ["Not connected","연결 안 됨","Nicht verbunden","Non connecté","未连接","未連線","Не подключено","未接続","Bağlı değil","Chưa kết nối","Não conectado", "No conectado"], + unavailable: ["Could not read the Antigravity and agy status.","Antigravity 및 agy 상태를 읽지 못했어요.","Der Status von Antigravity und agy konnte nicht gelesen werden.","Impossible de lire l’état d’Antigravity et d’agy.","无法读取 Antigravity 和 agy 的状态。","無法讀取 Antigravity 與 agy 的狀態。","Не удалось прочитать состояние Antigravity и agy.","Antigravity と agy の状態を読み取れませんでした。","Antigravity ve agy durumu okunamadı.","Không đọc được trạng thái của Antigravity và agy.","Não foi possível ler o status do Antigravity e do agy.", "No se pudo leer el estado de Antigravity y agy."], + files: ["Files it changes","변경하는 파일","Geänderte Dateien","Fichiers modifiés","会修改的文件","會修改的檔案","Изменяемые файлы","変更するファイル","Değiştirdiği dosyalar","Các tệp sẽ thay đổi","Arquivos alterados", "Archivos que modifica"], + fileMissing: ["not created yet","아직 없음","noch nicht angelegt","pas encore créé","尚未创建","尚未建立","ещё не создан","未作成","henüz oluşturulmadı","chưa được tạo","ainda não criado", "todavía no creado"], + overrideAdminGateway: ["Your organization's admin_settings.json sets a gateway, so this connection has no effect.","조직의 admin_settings.json이 게이트웨이를 지정하고 있어 이 연결은 적용되지 않아요.","Die admin_settings.json Ihrer Organisation legt ein Gateway fest, daher wirkt diese Verbindung nicht.","Le fichier admin_settings.json de votre organisation définit une passerelle ; cette connexion n’a donc aucun effet.","你所在组织的 admin_settings.json 指定了网关,因此此连接不会生效。","你所屬組織的 admin_settings.json 指定了閘道,因此此連線不會生效。","admin_settings.json вашей организации задаёт шлюз, поэтому это подключение не действует.","組織の admin_settings.json がゲートウェイを指定しているため、この接続は効きません。","Kuruluşunuzun admin_settings.json dosyası bir ağ geçidi belirliyor, bu yüzden bu bağlantının etkisi yok.","admin_settings.json của tổ chức bạn đã đặt cổng, nên kết nối này không có tác dụng.","O admin_settings.json da sua organização define um gateway, então esta conexão não tem efeito.", "El admin_settings.json de tu organización define un gateway, así que esta conexión no tiene efecto."], + overrideAdminUnreadable: ["An admin_settings.json exists but could not be read, so an organization gateway may override this connection.","admin_settings.json이 있지만 읽을 수 없어, 조직 게이트웨이가 이 연결보다 우선할 수 있어요.","Eine admin_settings.json ist vorhanden, konnte aber nicht gelesen werden; ein Gateway der Organisation könnte diese Verbindung übersteuern.","Un fichier admin_settings.json existe mais n’a pas pu être lu ; une passerelle de l’organisation pourrait primer sur cette connexion.","存在 admin_settings.json 但无法读取,组织网关可能会覆盖此连接。","存在 admin_settings.json 但無法讀取,組織閘道可能會覆蓋此連線。","Файл admin_settings.json есть, но прочитать его не удалось; шлюз организации может перекрыть это подключение.","admin_settings.json はありますが読み取れませんでした。組織のゲートウェイがこの接続より優先されるかもしれません。","Bir admin_settings.json var ama okunamadı; kuruluşun ağ geçidi bu bağlantının önüne geçebilir.","Có admin_settings.json nhưng không đọc được, nên cổng của tổ chức có thể ghi đè kết nối này.","Existe um admin_settings.json, mas não foi possível lê-lo; um gateway da organização pode se sobrepor a esta conexão.", "Existe un admin_settings.json, pero no se pudo leer, así que un gateway de la organización podría anular esta conexión."], + overrideEnv: ["AGY_LLM_GATEWAY_URL is set in the environment OpenCodex runs in and takes precedence over this connection.","OpenCodex가 실행되는 환경에 AGY_LLM_GATEWAY_URL이 설정되어 있어 이 연결보다 우선해요.","AGY_LLM_GATEWAY_URL ist in der Umgebung von OpenCodex gesetzt und hat Vorrang vor dieser Verbindung.","AGY_LLM_GATEWAY_URL est défini dans l’environnement d’OpenCodex et prime sur cette connexion.","OpenCodex 运行环境中设置了 AGY_LLM_GATEWAY_URL,它优先于此连接。","OpenCodex 執行環境中設定了 AGY_LLM_GATEWAY_URL,它優先於此連線。","В окружении OpenCodex задана AGY_LLM_GATEWAY_URL, и она имеет приоритет над этим подключением.","OpenCodex の実行環境で AGY_LLM_GATEWAY_URL が設定されており、この接続より優先されます。","OpenCodex'in çalıştığı ortamda AGY_LLM_GATEWAY_URL ayarlı ve bu bağlantının önüne geçiyor.","Môi trường chạy OpenCodex có đặt AGY_LLM_GATEWAY_URL, và biến này được ưu tiên hơn kết nối này.","AGY_LLM_GATEWAY_URL está definida no ambiente do OpenCodex e tem prioridade sobre esta conexão.", "AGY_LLM_GATEWAY_URL está definida en el entorno donde se ejecuta OpenCodex y tiene prioridad sobre esta conexión."], + noteNoGoogleSignIn: ["While connected, the app does not use your Google sign-in.","연결된 동안 앱은 Google 로그인을 사용하지 않아요.","Solange die Verbindung besteht, nutzt die App Ihre Google-Anmeldung nicht.","Tant qu’elle est connectée, l’application n’utilise pas votre connexion Google.","连接期间,应用不使用你的 Google 登录。","連線期間,應用程式不使用你的 Google 登入。","Пока подключение активно, приложение не использует ваш вход в Google.","接続中、アプリは Google のサインインを使いません。","Bağlıyken uygulama Google oturumunuzu kullanmaz.","Khi đã kết nối, ứng dụng không dùng đăng nhập Google của bạn.","Enquanto conectado, o app não usa o seu login do Google.", "Mientras está conectada, la aplicación no usa tu inicio de sesión de Google."], + noteAgyFollowsApp: ["agy also follows this setting unless it is connected on its own.","agy를 따로 연결하지 않으면 agy도 이 설정을 따라요.","agy folgt dieser Einstellung ebenfalls, solange es nicht eigens verbunden ist.","agy suit aussi ce réglage, sauf s’il est connecté séparément.","除非单独连接 agy,否则 agy 也会遵循此设置。","除非單獨連線 agy,否則 agy 也會遵循此設定。","agy тоже следует этой настройке, если не подключён отдельно.","agy を個別に接続しない限り、agy もこの設定に従います。","agy ayrıca bağlanmadıkça o da bu ayarı izler.","agy cũng theo cài đặt này, trừ khi được kết nối riêng.","O agy também segue esta configuração, a menos que seja conectado à parte.", "agy también sigue esta configuración, salvo que se conecte por separado."], + noteSettingsNotJson: ["settings.json is not plain JSON (it has comments, trailing commas or a syntax error), so OpenCodex will not change it. Fix the file, then connect again.","settings.json이 순수 JSON이 아니라서(주석, 끝 쉼표 또는 문법 오류) OpenCodex가 바꾸지 않아요. 파일을 고친 뒤 다시 연결하세요.","settings.json ist kein reines JSON (Kommentare, nachgestellte Kommas oder ein Syntaxfehler), daher ändert OpenCodex sie nicht. Korrigieren Sie die Datei und verbinden Sie erneut.","settings.json n’est pas du JSON pur (commentaires, virgules finales ou erreur de syntaxe) ; OpenCodex ne le modifiera pas. Corrigez le fichier, puis reconnectez.","settings.json 不是纯 JSON(含注释、末尾逗号或语法错误),OpenCodex 不会修改它。修好文件后再连接。","settings.json 不是純 JSON(含註解、結尾逗號或語法錯誤),OpenCodex 不會修改它。修好檔案後再連線。","settings.json — не чистый JSON (комментарии, лишние запятые или синтаксическая ошибка), поэтому OpenCodex его не изменит. Исправьте файл и подключитесь снова.","settings.json が純粋な JSON ではない(コメント、末尾のカンマ、構文エラー)ため、OpenCodex は変更しません。ファイルを直してから再接続してください。","settings.json düz JSON değil (yorumlar, sondaki virgüller ya da bir söz dizimi hatası), bu yüzden OpenCodex onu değiştirmez. Dosyayı düzeltip yeniden bağlanın.","settings.json không phải JSON thuần (có chú thích, dấu phẩy thừa hoặc lỗi cú pháp), nên OpenCodex sẽ không sửa nó. Hãy sửa tệp rồi kết nối lại.","settings.json não é JSON puro (comentários, vírgulas finais ou erro de sintaxe), então o OpenCodex não vai alterá-lo. Corrija o arquivo e conecte de novo.", "settings.json no es JSON puro (tiene comentarios, comas finales o un error de sintaxis), así que OpenCodex no lo modificará. Corrige el archivo y vuelve a conectar."], + noteSettingsNotObject: ["settings.json does not contain a JSON object, so OpenCodex will not change it.","settings.json에 JSON 객체가 없어서 OpenCodex가 바꾸지 않아요.","settings.json enthält kein JSON-Objekt, daher ändert OpenCodex sie nicht.","settings.json ne contient pas d’objet JSON ; OpenCodex ne le modifiera pas.","settings.json 不包含 JSON 对象,OpenCodex 不会修改它。","settings.json 不包含 JSON 物件,OpenCodex 不會修改它。","settings.json не содержит JSON-объект, поэтому OpenCodex его не изменит.","settings.json に JSON オブジェクトがないため、OpenCodex は変更しません。","settings.json bir JSON nesnesi içermiyor, bu yüzden OpenCodex onu değiştirmez.","settings.json không chứa đối tượng JSON, nên OpenCodex sẽ không sửa nó.","settings.json não contém um objeto JSON, então o OpenCodex não vai alterá-lo.", "settings.json no contiene un objeto JSON, así que OpenCodex no lo modificará."], + noteNoRestoreRecord: ["This was connected outside OpenCodex, so Disconnect cannot bring back your earlier settings.","OpenCodex 밖에서 연결되어 있어 연결 해제로 이전 설정을 되돌릴 수 없어요.","Die Verbindung wurde außerhalb von OpenCodex eingerichtet; Trennen kann Ihre früheren Einstellungen daher nicht zurückholen.","La connexion a été faite hors d’OpenCodex ; Déconnecter ne peut donc pas rétablir vos réglages précédents.","这是在 OpenCodex 之外连接的,断开无法恢复你之前的设置。","這是在 OpenCodex 之外連線的,中斷連線無法還原你先前的設定。","Подключение сделано вне OpenCodex, поэтому отключение не вернёт ваши прежние настройки.","OpenCodex の外で接続されたため、切断しても以前の設定には戻せません。","Bu bağlantı OpenCodex dışında yapılmış, bu yüzden Bağlantıyı kes önceki ayarlarınızı geri getiremez.","Kết nối này được tạo bên ngoài OpenCodex, nên Ngắt kết nối không thể khôi phục cài đặt cũ.","Isto foi conectado fora do OpenCodex, então Desconectar não consegue trazer de volta suas configurações anteriores.", "Esta conexión se hizo fuera de OpenCodex, así que Desconectar no puede recuperar tu configuración anterior."], + noteAgyVersion: ["Needs agy 1.2.15 or newer.","agy 1.2.15 이상이 필요해요.","Erfordert agy 1.2.15 oder neuer.","Nécessite agy 1.2.15 ou plus récent.","需要 agy 1.2.15 或更新版本。","需要 agy 1.2.15 或更新版本。","Нужна agy 1.2.15 или новее.","agy 1.2.15 以降が必要です。","agy 1.2.15 veya daha yenisi gerekir.","Cần agy 1.2.15 trở lên.","Requer agy 1.2.15 ou mais recente.", "Requiere agy 1.2.15 o posterior."], + noteWindowsUnverified: ["Google documents this for macOS and Linux. The Windows build reads the same settings, but this has not been tested end to end on Windows.","Google은 macOS와 Linux용으로만 문서화했어요. Windows 빌드도 같은 설정을 읽지만 Windows에서 처음부터 끝까지 검증하지는 않았어요.","Google dokumentiert dies für macOS und Linux. Die Windows-Version liest dieselben Einstellungen, unter Windows wurde das aber nicht durchgängig getestet.","Google le documente pour macOS et Linux. La version Windows lit les mêmes réglages, mais cela n’a pas été testé de bout en bout sous Windows.","Google 只为 macOS 和 Linux 提供了文档。Windows 版也会读取同样的设置,但尚未在 Windows 上完整验证。","Google 只為 macOS 和 Linux 提供了文件。Windows 版也會讀取同樣的設定,但尚未在 Windows 上完整驗證。","Google описывает это для macOS и Linux. Сборка для Windows читает те же настройки, но под Windows это не проверено полностью.","Google が文書化しているのは macOS と Linux です。Windows 版も同じ設定を読みますが、Windows では通しで検証していません。","Google bunu macOS ve Linux için belgeliyor. Windows sürümü aynı ayarları okur ama Windows'ta uçtan uca test edilmedi.","Google chỉ mô tả cho macOS và Linux. Bản Windows cũng đọc cùng cài đặt, nhưng chưa được kiểm thử đầy đủ trên Windows.","O Google documenta isto para macOS e Linux. A versão para Windows lê as mesmas configurações, mas isso não foi testado de ponta a ponta no Windows.", "Google lo documenta para macOS y Linux. La versión de Windows lee la misma configuración, pero esto no se ha probado de principio a fin en Windows."], + noteAgyEnvExported: ["AGY_LLM_GATEWAY_URL is set globally; the agy command set up here overrides it for agy only.","AGY_LLM_GATEWAY_URL이 전역으로 설정되어 있어요. 여기서 설정한 agy 명령은 agy에서만 이를 덮어써요.","AGY_LLM_GATEWAY_URL ist global gesetzt; der hier eingerichtete agy-Befehl übersteuert sie nur für agy.","AGY_LLM_GATEWAY_URL est défini globalement ; la commande agy installée ici le remplace pour agy seulement.","AGY_LLM_GATEWAY_URL 已全局设置;这里设置的 agy 命令只对 agy 覆盖它。","AGY_LLM_GATEWAY_URL 已全域設定;這裡設定的 agy 命令只對 agy 覆蓋它。","AGY_LLM_GATEWAY_URL задана глобально; настроенная здесь команда agy переопределяет её только для agy.","AGY_LLM_GATEWAY_URL がグローバルに設定されています。ここで設定した agy コマンドは agy に対してだけそれを上書きします。","AGY_LLM_GATEWAY_URL genel olarak ayarlı; burada kurulan agy komutu onu yalnızca agy için geçersiz kılar.","AGY_LLM_GATEWAY_URL đang được đặt toàn cục; lệnh agy thiết lập ở đây chỉ ghi đè nó cho agy.","AGY_LLM_GATEWAY_URL está definida globalmente; o comando agy configurado aqui a substitui só para o agy.", "AGY_LLM_GATEWAY_URL está definida de forma global; el comando agy configurado aquí la anula solo para agy."], + model: ["Default model (optional)","기본 모델(선택)","Standardmodell (optional)","Modèle par défaut (facultatif)","默认模型(可选)","預設模型(選填)","Модель по умолчанию (необязательно)","デフォルトモデル(任意)","Varsayılan model (isteğe bağlı)","Mô hình mặc định (không bắt buộc)","Modelo padrão (opcional)", "Modelo predeterminado (opcional)"], + modelHint: ["Leave empty to keep the current setting.","비워 두면 현재 설정을 유지해요.","Leer lassen, um die aktuelle Einstellung zu behalten.","Laissez vide pour garder le réglage actuel.","留空则保留当前设置。","留空則保留目前設定。","Оставьте пустым, чтобы сохранить текущую настройку.","空欄にすると現在の設定を保ちます。","Mevcut ayarı korumak için boş bırakın.","Để trống để giữ cài đặt hiện tại.","Deixe vazio para manter a configuração atual.", "Déjalo vacío para mantener la configuración actual."], + connect: ["Connect","연결","Verbinden","Connecter","连接","連線","Подключить","接続","Bağlan","Kết nối","Conectar", "Conectar"], + disconnect: ["Disconnect","연결 해제","Trennen","Déconnecter","断开","中斷連線","Отключить","切断","Bağlantıyı kes","Ngắt kết nối","Desconectar", "Desconectar"], + working: ["Working…","처리 중…","Wird ausgeführt…","En cours…","处理中…","處理中…","Выполняется…","処理中…","İşleniyor…","Đang xử lý…","Processando…", "Procesando…"], + doneConnected: ["Connected.","연결했어요.","Verbunden.","Connecté.","已连接。","已連線。","Подключено.","接続しました。","Bağlandı.","Đã kết nối.","Conectado.", "Conectado."], + doneUnchanged: ["Already connected; nothing changed.","이미 연결되어 있어 바뀐 것이 없어요.","Bereits verbunden; nichts geändert.","Déjà connecté ; rien n’a changé.","已经连接,没有改动。","已經連線,沒有變動。","Уже подключено; ничего не изменилось.","すでに接続済みです。変更はありません。","Zaten bağlı; hiçbir şey değişmedi.","Đã kết nối sẵn; không có gì thay đổi.","Já conectado; nada mudou.", "Ya estaba conectado; no cambió nada."], + doneRestored: ["Disconnected, and your earlier settings were put back.","연결을 해제하고 이전 설정을 되돌렸어요.","Getrennt; Ihre früheren Einstellungen wurden wiederhergestellt.","Déconnecté ; vos réglages précédents ont été rétablis.","已断开,并恢复了你之前的设置。","已中斷連線,並還原了你先前的設定。","Отключено, прежние настройки восстановлены.","切断し、以前の設定に戻しました。","Bağlantı kesildi ve önceki ayarlarınız geri getirildi.","Đã ngắt kết nối và khôi phục cài đặt cũ.","Desconectado, e suas configurações anteriores foram restauradas.", "Desconectado, y se restauró tu configuración anterior."], + doneRestoredPartly: ["Disconnected. The file was edited after connecting, so only the OpenCodex entries were removed and your other edits were kept.","연결을 해제했어요. 연결 후 파일이 수정되어 OpenCodex 항목만 지우고 다른 수정은 그대로 두었어요.","Getrennt. Die Datei wurde nach dem Verbinden bearbeitet, daher wurden nur die OpenCodex-Einträge entfernt und Ihre übrigen Änderungen behalten.","Déconnecté. Le fichier a été modifié après la connexion ; seules les entrées OpenCodex ont été retirées et vos autres modifications conservées.","已断开。连接后文件被修改过,所以只移除了 OpenCodex 的条目,你的其他改动都保留了。","已中斷連線。連線後檔案被修改過,所以只移除了 OpenCodex 的項目,你的其他變更都保留了。","Отключено. После подключения файл менялся, поэтому удалены только записи OpenCodex, а остальные ваши правки сохранены.","切断しました。接続後にファイルが編集されたため、OpenCodex の項目だけを削除し、ほかの編集は残しました。","Bağlantı kesildi. Dosya bağlandıktan sonra düzenlenmiş, bu yüzden yalnızca OpenCodex girdileri kaldırıldı ve diğer düzenlemeleriniz korundu.","Đã ngắt kết nối. Tệp đã bị sửa sau khi kết nối, nên chỉ các mục của OpenCodex được gỡ và các chỉnh sửa khác của bạn được giữ lại.","Desconectado. O arquivo foi editado depois da conexão, então só as entradas do OpenCodex foram removidas e suas outras edições foram mantidas.", "Desconectado. El archivo se editó después de conectar, así que solo se quitaron las entradas de OpenCodex y se conservaron tus otros cambios."], + doneNothing: ["Nothing to undo; no file was changed.","되돌릴 것이 없어 파일을 바꾸지 않았어요.","Nichts rückgängig zu machen; keine Datei wurde geändert.","Rien à annuler ; aucun fichier n’a été modifié.","没有需要撤销的内容,未修改任何文件。","沒有需要復原的內容,未修改任何檔案。","Отменять нечего; ни один файл не изменён.","元に戻すものはなく、ファイルは変更していません。","Geri alınacak bir şey yok; hiçbir dosya değişmedi.","Không có gì để hoàn tác; không tệp nào bị thay đổi.","Nada a desfazer; nenhum arquivo foi alterado.", "No hay nada que deshacer; no se modificó ningún archivo."], + hintAntigravity: ["Restart Antigravity to apply it.","적용하려면 Antigravity를 다시 시작하세요.","Starten Sie Antigravity neu, damit es wirkt.","Redémarrez Antigravity pour l’appliquer.","重启 Antigravity 后生效。","重新啟動 Antigravity 後生效。","Перезапустите Antigravity, чтобы применить.","反映するには Antigravity を再起動してください。","Uygulamak için Antigravity'yi yeniden başlatın.","Khởi động lại Antigravity để áp dụng.","Reinicie o Antigravity para aplicar.", "Reinicia Antigravity para aplicarlo."], + hintAgy: ["Open a new terminal to apply it.","적용하려면 새 터미널을 여세요.","Öffnen Sie ein neues Terminal, damit es wirkt.","Ouvrez un nouveau terminal pour l’appliquer.","打开新的终端后生效。","開啟新的終端機後生效。","Откройте новый терминал, чтобы применить.","反映するには新しいターミナルを開いてください。","Uygulamak için yeni bir terminal açın.","Mở terminal mới để áp dụng.","Abra um novo terminal para aplicar.", "Abre una terminal nueva para aplicarlo."], + refusedCredential: ["This proxy's address requires an API key, and OpenCodex will not write a real key into these files. Turn on unauthenticatedLoopbackListener or bind the proxy to loopback.","이 프록시 주소는 API 키가 필요하고, OpenCodex는 실제 키를 이 파일들에 쓰지 않아요. unauthenticatedLoopbackListener를 켜거나 프록시를 루프백에 바인딩하세요.","Diese Proxy-Adresse verlangt einen API-Schlüssel, und OpenCodex schreibt keinen echten Schlüssel in diese Dateien. Aktivieren Sie unauthenticatedLoopbackListener oder binden Sie den Proxy an Loopback.","L’adresse de ce proxy exige une clé d’API, et OpenCodex n’écrira pas de vraie clé dans ces fichiers. Activez unauthenticatedLoopbackListener ou liez le proxy à la boucle locale.","此代理地址需要 API 密钥,而 OpenCodex 不会把真实密钥写进这些文件。请开启 unauthenticatedLoopbackListener,或把代理绑定到回环地址。","此代理位址需要 API 金鑰,而 OpenCodex 不會把真實金鑰寫進這些檔案。請開啟 unauthenticatedLoopbackListener,或把代理繫結到回環位址。","Адрес этого прокси требует ключ API, а OpenCodex не запишет настоящий ключ в эти файлы. Включите unauthenticatedLoopbackListener или привяжите прокси к loopback.","このプロキシのアドレスは API キーを必要としますが、OpenCodex は本物のキーをこれらのファイルに書きません。unauthenticatedLoopbackListener を有効にするか、プロキシをループバックにバインドしてください。","Bu proxy adresi bir API anahtarı istiyor ve OpenCodex bu dosyalara gerçek bir anahtar yazmaz. unauthenticatedLoopbackListener'ı açın ya da proxy'yi loopback'e bağlayın.","Địa chỉ proxy này cần khóa API, và OpenCodex sẽ không ghi khóa thật vào các tệp này. Hãy bật unauthenticatedLoopbackListener hoặc gắn proxy vào loopback.","O endereço deste proxy exige uma chave de API, e o OpenCodex não grava uma chave real nesses arquivos. Ative unauthenticatedLoopbackListener ou vincule o proxy ao loopback.", "La dirección de este proxy requiere una clave API, y OpenCodex no escribirá una clave real en estos archivos. Activa unauthenticatedLoopbackListener o vincula el proxy a loopback."], + refusedModel: ["The model must be one line of at most 200 characters.","모델은 200자 이하의 한 줄이어야 해요.","Das Modell muss eine Zeile mit höchstens 200 Zeichen sein.","Le modèle doit tenir sur une ligne de 200 caractères au plus.","模型必须是不超过 200 个字符的单行文本。","模型必須是不超過 200 個字元的單行文字。","Модель должна быть одной строкой не длиннее 200 символов.","モデルは 200 文字以内の 1 行にしてください。","Model en fazla 200 karakterlik tek bir satır olmalı.","Mô hình phải là một dòng tối đa 200 ký tự.","O modelo deve ser uma linha de no máximo 200 caracteres.", "El modelo debe ser una sola línea de 200 caracteres como máximo."], + refusedFile: ["settings.json could not be read as a JSON object, so OpenCodex left it untouched. Fix the file, then try again.","settings.json을 JSON 객체로 읽을 수 없어 OpenCodex가 그대로 두었어요. 파일을 고친 뒤 다시 시도하세요.","settings.json konnte nicht als JSON-Objekt gelesen werden, daher hat OpenCodex sie nicht verändert. Korrigieren Sie die Datei und versuchen Sie es erneut.","settings.json n’a pas pu être lu comme un objet JSON ; OpenCodex n’y a pas touché. Corrigez le fichier, puis réessayez.","无法把 settings.json 读成 JSON 对象,OpenCodex 没有改动它。修好文件后重试。","無法把 settings.json 讀成 JSON 物件,OpenCodex 沒有變動它。修好檔案後重試。","settings.json не удалось прочитать как JSON-объект, поэтому OpenCodex его не тронул. Исправьте файл и попробуйте снова.","settings.json を JSON オブジェクトとして読めなかったため、OpenCodex は変更していません。ファイルを直してからやり直してください。","settings.json bir JSON nesnesi olarak okunamadı, bu yüzden OpenCodex ona dokunmadı. Dosyayı düzeltip yeniden deneyin.","Không đọc được settings.json như một đối tượng JSON, nên OpenCodex không động vào nó. Hãy sửa tệp rồi thử lại.","Não foi possível ler settings.json como um objeto JSON, então o OpenCodex não o alterou. Corrija o arquivo e tente de novo.", "settings.json no se pudo leer como objeto JSON, así que OpenCodex no lo tocó. Corrige el archivo y vuelve a intentarlo."], + refusedIo: ["Could not write the client files:","클라이언트 파일을 쓰지 못했어요:","Die Clientdateien konnten nicht geschrieben werden:","Impossible d’écrire les fichiers du client :","无法写入客户端文件:","無法寫入用戶端檔案:","Не удалось записать файлы клиента:","クライアントのファイルを書き込めませんでした:","İstemci dosyaları yazılamadı:","Không ghi được các tệp của máy khách:","Não foi possível gravar os arquivos do cliente:", "No se pudieron escribir los archivos del cliente:"], + refused: ["The proxy refused the change:","프록시가 변경을 거부했어요:","Der Proxy hat die Änderung abgelehnt:","Le proxy a refusé la modification :","代理拒绝了此更改:","代理拒絕了此變更:","Прокси отклонил изменение:","プロキシが変更を拒否しました:","Proxy değişikliği reddetti:","Proxy đã từ chối thay đổi:","O proxy recusou a alteração:", "El proxy rechazó el cambio:"], + actionFailed: ["Could not confirm whether the change was applied. Check the client status before trying again.","변경이 적용됐는지 확인하지 못했어요. 다시 시도하기 전에 클라이언트 상태를 확인하세요.","Es ließ sich nicht bestätigen, ob die Änderung übernommen wurde. Prüfen Sie den Client-Status, bevor Sie es erneut versuchen.","Impossible de confirmer si la modification a été appliquée. Vérifiez l’état du client avant de réessayer.","无法确认更改是否已生效。请先检查客户端状态再重试。","無法確認變更是否已生效。請先檢查用戶端狀態再重試。","Не удалось подтвердить, применено ли изменение. Проверьте состояние клиента, прежде чем повторять попытку.","変更が適用されたか確認できませんでした。再試行する前にクライアントの状態を確認してください。","Değişikliğin uygulanıp uygulanmadığı doğrulanamadı. Yeniden denemeden önce istemci durumunu kontrol edin.","Không xác nhận được thay đổi đã được áp dụng hay chưa. Hãy kiểm tra trạng thái client trước khi thử lại.","Não foi possível confirmar se a alteração foi aplicada. Verifique o status do cliente antes de tentar novamente.", "No se pudo confirmar si el cambio se aplicó. Revisa el estado del cliente antes de volver a intentarlo."], refusedAgyProfile: [ "OpenCodex could not verify the agy profile at {path}. Restore the complete marked agy block or the saved original profile, then retry.", "OpenCodex가 {path}의 agy 프로필을 확인하지 못했어요. 마커가 포함된 agy 블록 전체나 저장된 원본 프로필을 복원한 뒤 다시 시도하세요.", @@ -59,6 +59,7 @@ const rows = { "OpenCodex, {path} konumundaki agy profilini doğrulayamadı. İşaretleyicileriyle birlikte agy bloğunun tamamını veya kaydedilmiş özgün profili geri yükleyip yeniden deneyin.", "OpenCodex không xác minh được hồ sơ agy tại {path}. Hãy khôi phục toàn bộ khối agy cùng các dấu đánh dấu hoặc hồ sơ gốc đã lưu, rồi thử lại.", "O OpenCodex não conseguiu verificar o perfil do agy em {path}. Restaure o bloco completo do agy com seus marcadores ou o perfil original salvo e tente novamente.", + "OpenCodex no pudo verificar el perfil de agy en {path}. Restaura el bloque marcado completo de agy o el perfil original guardado y vuelve a intentarlo.", ], } satisfies Record; diff --git a/gui/src/i18n/getting-started-copy.ts b/gui/src/i18n/getting-started-copy.ts index 36974c6b038..c97964e977e 100644 --- a/gui/src/i18n/getting-started-copy.ts +++ b/gui/src/i18n/getting-started-copy.ts @@ -3,19 +3,19 @@ * order of `locales`; spread into the catalogs through shellV2Copy() so this surface lands as one * reviewable table without touching the eleven locale files. */ -type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; -const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; -type Row = readonly [string, string, string, string, string, string, string, string, string, string, string]; +type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt" | "es"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt", "es"]; +type Row = readonly [string, string, string, string, string, string, string, string, string, string, string, string]; const rows = { - "gettingStarted.hide": ["Hide", "숨기기", "Ausblenden", "Masquer", "隐藏", "隱藏", "Скрыть", "非表示", "Gizle", "Ẩn", "Ocultar"], - "gettingStarted.hideLabel": ["Hide Getting started", "시작하기 숨기기", "Erste Schritte ausblenden", "Masquer Premiers pas", "隐藏开始使用", "隱藏開始使用", "Скрыть «Начало работы»", "「はじめに」を非表示", "Başlarken’i gizle", "Ẩn Bắt đầu", "Ocultar Primeiros passos"], - "gettingStarted.hideHint": ["You can show it again from {place}.", "{place}에서 다시 보이게 할 수 있어요.", "Unter {place} kannst du es wieder einblenden.", "Vous pouvez le réafficher depuis {place}.", "可在{place}中重新显示。", "可在{place}中重新顯示。", "Вернуть можно в разделе {place}.", "{place} から再表示できます。", "{place} bölümünden yeniden gösterebilirsin.", "Bạn có thể hiện lại trong {place}.", "Você pode mostrar de novo em {place}."], - "gettingStarted.hiddenNote": ["Getting started is hidden. You can show it again from {place}.", "시작하기를 숨겼어요. {place}에서 다시 보이게 할 수 있어요.", "Erste Schritte ist ausgeblendet. Unter {place} kannst du es wieder einblenden.", "Premiers pas est masqué. Vous pouvez le réafficher depuis {place}.", "已隐藏“开始使用”。可在{place}中重新显示。", "已隱藏「開始使用」。可在{place}中重新顯示。", "Блок «Начало работы» скрыт. Вернуть его можно в разделе {place}.", "「はじめに」を非表示にしました。{place} からいつでも再表示できます。", "Başlarken gizlendi. {place} bölümünden yeniden gösterebilirsin.", "Đã ẩn Bắt đầu. Bạn có thể hiện lại trong {place}.", "Primeiros passos está oculto. Você pode mostrá-lo de novo em {place}."], - "gettingStarted.undo": ["Undo", "되돌리기", "Rückgängig", "Annuler", "撤销", "復原", "Отменить", "元に戻す", "Geri al", "Hoàn tác", "Desfazer"], - "gettingStarted.hiddenOnHome": ["Getting started is hidden on Home.", "홈에서 시작하기를 숨겨 두었어요.", "Erste Schritte ist auf der Startseite ausgeblendet.", "Premiers pas est masqué sur l’accueil.", "“开始使用”已在首页隐藏。", "「開始使用」已在首頁隱藏。", "Блок «Начало работы» скрыт на главной.", "「はじめに」はホームで非表示になっています。", "Başlarken ana sayfada gizli.", "Bắt đầu đang bị ẩn trên Trang chủ.", "Primeiros passos está oculto no Início."], - "gettingStarted.showOnHome": ["Show on Home", "홈에 다시 표시", "Auf der Startseite anzeigen", "Afficher sur l’accueil", "在首页显示", "在首頁顯示", "Показать на главной", "ホームに表示", "Ana sayfada göster", "Hiện trên Trang chủ", "Mostrar no Início"], - "gettingStarted.backOnHome": ["Getting started is back on Home.", "시작하기가 홈에 다시 나와요.", "Erste Schritte ist wieder auf der Startseite.", "Premiers pas est de retour sur l’accueil.", "“开始使用”已回到首页。", "「開始使用」已回到首頁。", "Блок «Начало работы» снова на главной.", "「はじめに」をホームに戻しました。", "Başlarken yeniden ana sayfada.", "Bắt đầu đã trở lại Trang chủ.", "Primeiros passos voltou ao Início."], + "gettingStarted.hide": ["Hide", "숨기기", "Ausblenden", "Masquer", "隐藏", "隱藏", "Скрыть", "非表示", "Gizle", "Ẩn", "Ocultar", "Ocultar"], + "gettingStarted.hideLabel": ["Hide Getting started", "시작하기 숨기기", "Erste Schritte ausblenden", "Masquer Premiers pas", "隐藏开始使用", "隱藏開始使用", "Скрыть «Начало работы»", "「はじめに」を非表示", "Başlarken’i gizle", "Ẩn Bắt đầu", "Ocultar Primeiros passos", "Ocultar Primeros pasos"], + "gettingStarted.hideHint": ["You can show it again from {place}.", "{place}에서 다시 보이게 할 수 있어요.", "Unter {place} kannst du es wieder einblenden.", "Vous pouvez le réafficher depuis {place}.", "可在{place}中重新显示。", "可在{place}中重新顯示。", "Вернуть можно в разделе {place}.", "{place} から再表示できます。", "{place} bölümünden yeniden gösterebilirsin.", "Bạn có thể hiện lại trong {place}.", "Você pode mostrar de novo em {place}.", "Puedes volver a mostrarlo desde {place}."], + "gettingStarted.hiddenNote": ["Getting started is hidden. You can show it again from {place}.", "시작하기를 숨겼어요. {place}에서 다시 보이게 할 수 있어요.", "Erste Schritte ist ausgeblendet. Unter {place} kannst du es wieder einblenden.", "Premiers pas est masqué. Vous pouvez le réafficher depuis {place}.", "已隐藏“开始使用”。可在{place}中重新显示。", "已隱藏「開始使用」。可在{place}中重新顯示。", "Блок «Начало работы» скрыт. Вернуть его можно в разделе {place}.", "「はじめに」を非表示にしました。{place} からいつでも再表示できます。", "Başlarken gizlendi. {place} bölümünden yeniden gösterebilirsin.", "Đã ẩn Bắt đầu. Bạn có thể hiện lại trong {place}.", "Primeiros passos está oculto. Você pode mostrá-lo de novo em {place}.", "Primeros pasos está oculto. Puedes volver a mostrarlo desde {place}."], + "gettingStarted.undo": ["Undo", "되돌리기", "Rückgängig", "Annuler", "撤销", "復原", "Отменить", "元に戻す", "Geri al", "Hoàn tác", "Desfazer", "Deshacer"], + "gettingStarted.hiddenOnHome": ["Getting started is hidden on Home.", "홈에서 시작하기를 숨겨 두었어요.", "Erste Schritte ist auf der Startseite ausgeblendet.", "Premiers pas est masqué sur l’accueil.", "“开始使用”已在首页隐藏。", "「開始使用」已在首頁隱藏。", "Блок «Начало работы» скрыт на главной.", "「はじめに」はホームで非表示になっています。", "Başlarken ana sayfada gizli.", "Bắt đầu đang bị ẩn trên Trang chủ.", "Primeiros passos está oculto no Início.", "Primeros pasos está oculto en Inicio."], + "gettingStarted.showOnHome": ["Show on Home", "홈에 다시 표시", "Auf der Startseite anzeigen", "Afficher sur l’accueil", "在首页显示", "在首頁顯示", "Показать на главной", "ホームに表示", "Ana sayfada göster", "Hiện trên Trang chủ", "Mostrar no Início", "Mostrar en Inicio"], + "gettingStarted.backOnHome": ["Getting started is back on Home.", "시작하기가 홈에 다시 나와요.", "Erste Schritte ist wieder auf der Startseite.", "Premiers pas est de retour sur l’accueil.", "“开始使用”已回到首页。", "「開始使用」已回到首頁。", "Блок «Начало работы» снова на главной.", "「はじめに」をホームに戻しました。", "Başlarken yeniden ana sayfada.", "Bắt đầu đã trở lại Trang chủ.", "Primeiros passos voltou ao Início.", "Primeros pasos volvió a Inicio."], } satisfies Record; export type GettingStartedKey = keyof typeof rows; diff --git a/gui/src/i18n/lab-translations.ts b/gui/src/i18n/lab-translations.ts index 8b4405f74fe..7aa408f5e7f 100644 --- a/gui/src/i18n/lab-translations.ts +++ b/gui/src/i18n/lab-translations.ts @@ -1,6 +1,6 @@ import type { TKey } from "./en"; -export type LabLocale = "en" | "de" | "fr" | "ko" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; +export type LabLocale = "en" | "de" | "fr" | "ko" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt" | "es"; export type LabCatalogKey = Exclude, `lab.production.${string}`>; export type LabSupplementKey = | "subjectKindUnknown" @@ -564,7 +564,58 @@ const pt: Record = { "lab.layer.task_effectiveness": "Eficácia nas tarefas", }; +const es: Record = { + "lab.title": "Laboratorio de compatibilidad", + "lab.subtitle": "Matriz de veredicto de compatibilidad de solo lectura a partir de pruebas de proyección de laboratorio.", + "lab.loadFailed": "No se pudo cargar los datos de laboratorio de compatibilidad", + "lab.projectionUnavailable": "La proyección de laboratorio no está disponible. Ejecutar la conformidad o sondas vivas primero.", + "lab.projectionIncompatible": "El esquema de proyección de laboratorio es incompatible. Reconstruir la proyección.", + "lab.statusTitle": "Estado de proyección", + "lab.matrixTitle": "Matriz de compatibilidad", + "lab.verdictsTitle": "Registros de veredicto", + "lab.filter.layer": "Capa de evidencia", + "lab.filter.verdict": "Veredicto", + "lab.filter.subject": "Identificación del sujeto", + "lab.filter.all": "Todos", + "lab.col.subject": "Sujeto", + "lab.col.layer": "Capa", + "lab.col.suite": "Suite", + "lab.col.verdict": "Veredicto", + "lab.col.asOf": "Datos al", + "lab.col.protocol": "Conformidad del protocolo", + "lab.col.live": "Compatibilidad de ruta en vivo", + "lab.col.task": "Eficacia de la tarea", + "lab.empty": "Todavía no hay veredictos de compatibilidad en la proyección.", + "lab.subjectKind": "Tipo", + "lab.observationCount": "Observaciones", + "lab.eventCount": "Eventos", + "lab.verdictCount": "Veredictos", + "lab.subjectCount": "Sujetos", + "lab.builtAt": "Generado el", + "lab.loading": "Cargando evidencia de compatibilidad…", + "lab.loadMore": "Cargar más", + "lab.detailTitle": "Detalle del veredicto", + "lab.detailClose": "Cerrar", + "lab.detailSubject": "Sujeto", + "lab.detailObservations": "Observaciones", + "lab.detailEvents": "Eventos de evidencia", + "lab.detailArtifacts": "Metadatos de artefactos", + "lab.detailLoadFailed": "No se pudo cargar el detalle del veredicto", + "lab.refresh": "Actualizar", + "lab.verdict.UNKNOWN": "Desconocido", + "lab.verdict.CLAIMED": "Declarado", + "lab.verdict.PROBED": "Sondeado", + "lab.verdict.VERIFIED": "Verificado", + "lab.verdict.DEGRADED": "Degradado", + "lab.verdict.BLOCKED": "Bloqueado", + "lab.verdict.UNSUPPORTED": "No compatible", + "lab.layer.protocol_conformance": "Conformidad del protocolo", + "lab.layer.live_route_compatibility": "Compatibilidad de ruta en vivo", + "lab.layer.task_effectiveness": "Eficacia de la tarea", +}; + export const LAB_CATALOG_OVERRIDES: Record> = { + es, en, de, fr, @@ -591,6 +642,18 @@ const supplements: Record> = { "community.activeRecords": "Active records", "community.revokedRecords": "Revoked records", }, + es: { + subjectKindUnknown: "Desconocido", + "artifact.present": "Presente", + "artifact.corrupt": "Corrupto", + "artifact.purged_unavailable": "Purgado / no disponible", + selectVerdict: "Ver veredicto para {subject}", + "community.title": "Pruebas comunitarias", + "community.notLocalVerdict": "Contexto de solo lectura no confiable. No incluido en este veredicto local.", + "community.bundles": "Paquetes", + "community.activeRecords": "Registros activos", + "community.revokedRecords": "Registros revocados", + }, de: { subjectKindUnknown: "Unbekannt", "artifact.present": "Vorhanden", diff --git a/gui/src/i18n/log-guard-labels.ts b/gui/src/i18n/log-guard-labels.ts index c32a5662efb..becc48183e2 100644 --- a/gui/src/i18n/log-guard-labels.ts +++ b/gui/src/i18n/log-guard-labels.ts @@ -55,6 +55,33 @@ const LABELS: Record> = { "error.database_error": "Could not update the Codex logs database.", "error.config_write_failed": "The database changed, but OpenCodex could not save the protection setting. Fix config storage, then run Repair.", }, + es: { + compact: "Compactar", + compactComplete: "Compactación completada (espacio lógico / recuperado en disco)", + pagesUnit: "páginas", + compactPartial: "Compactación parcial (espacio lógico / recuperado en disco)", + confirmCompact: "Confirmar la compactación", + cancel: "Cancelar", + inspectionOnly: "Solo inspección", + externalSqliteHome: "Almacenamiento SQLite externo", + inspectionUnavailable: "La inspección de los registros de diagnóstico no está disponible.", + metricsSkippedLarge: "Se omitieron las métricas de filas: la base de datos supera {threshold} y analizarla bloquearía el proxy.", + protection: "Protección", + compat: "Compatibilidad", + quiet: "Silencio", + disable: "Desactivar la protección", + repair: "Reparar protección", + applying: "Aplicando protección…", + "error.generic": "No se pudo cambiar la protección de registro Codex.", + "error.codex_running": "Cierra Codex antes de cambiar la protección de los registros.", + "error.process_enumeration_failed": "No se pudo verificar que Codex está detenido. La protección no ha cambiado.", + "error.busy": "La base de datos de registros de Codex está ocupada. Cierra Codex y reintenta.", + "error.unsupported_schema": "Este esquema de registros Codex no es compatible con la protección.", + "error.trigger_collision": "Ya se usa un nombre de disparador reservado de Log Guard. No se cambió la protección.", + "error.unsafe_path": "La ruta de la base de datos de registros Codex falló la comprobación de seguridad.", + "error.database_error": "No se pudo actualizar la base de datos de registros Codex.", + "error.config_write_failed": "La base de datos cambió, pero OpenCodex no pudo guardar la configuración de protección. Arreglar el almacenamiento de configuración y, a continuación, ejecutar Reparar.", + }, de: { compact: 'Komprimieren', compactComplete: "Komprimierung abgeschlossen (logisch / auf Datentraeger freigegeben)", diff --git a/gui/src/i18n/log-guard-operation-labels.ts b/gui/src/i18n/log-guard-operation-labels.ts index 173fee49002..85a078af4da 100644 --- a/gui/src/i18n/log-guard-operation-labels.ts +++ b/gui/src/i18n/log-guard-operation-labels.ts @@ -25,6 +25,18 @@ const LABELS: Record> = { "error.auto_vacuum_not_incremental": "This Codex logs database is not configured for incremental vacuum, so space cannot be reclaimed without a full rebuild.", "error.integrity_check_failed": "The Codex logs database failed its integrity check. No space was reclaimed.", }, + es: { + applying: "Aplicando el cambio de Log Guard…", + "error.generic": "No se pudo actualizar el almacenamiento de registro Codex.", + "error.codex_running": "Salga de Codex antes de cambiar el almacenamiento de registros Codex.", + "error.process_enumeration_failed": "No se pudo verificar que Codex está detenido. La operación Log Guard no se inició.", + "error.busy": "La base de datos de registros Codex está ocupada. Salga de Codex y vuelva a intentarlo.", + "error.unsupported_schema": "Este esquema de registros Codex no es compatible con esta operación.", + "error.unsafe_path": "La ruta de la base de datos de registros Codex falló la comprobación de seguridad.", + "error.database_error": "No se pudo actualizar la base de datos de registros Codex.", + "error.auto_vacuum_not_incremental": "Esta base de datos de registros de Codex no usa VACUUM incremental, por lo que no puede recuperar espacio sin reconstruirla por completo.", + "error.integrity_check_failed": "La base de datos de registros Codex falló su comprobación de integridad. No se recuperó ningún espacio.", + }, de: { applying: "Log-Guard-Änderung wird angewendet…", "error.generic": "Der Codex-Protokollspeicher konnte nicht aktualisiert werden.", diff --git a/gui/src/i18n/log-guard-state-labels.ts b/gui/src/i18n/log-guard-state-labels.ts index 71c789cbb1c..ffebd5f3bd9 100644 --- a/gui/src/i18n/log-guard-state-labels.ts +++ b/gui/src/i18n/log-guard-state-labels.ts @@ -16,6 +16,11 @@ const LABELS: Record = { protection: { off: "Off", active: "Active", drifted: "Needs repair", unsupported: "Unsupported", unknown: "Unknown" }, mode: { off: "Off", compat: "Compatibility", quiet: "Quiet", collision: "Unknown" }, }, + es: { + schema: { compatible: "Compatible", missing: "No se encontró la base de datos", unreadable: "Base de datos no disponible", unsupported: "No compatible" }, + protection: { off: "Desactivado", active: "Activo", drifted: "Necesita reparación", unsupported: "No compatible", unknown: "Desconocido" }, + mode: { off: "Desactivado", compat: "Compatibilidad", quiet: "Silencio", collision: "Desconocido" }, + }, de: { schema: { compatible: "Kompatibel", missing: "Datenbank nicht gefunden", unreadable: "Datenbank nicht lesbar", unsupported: "Nicht unterstützt" }, protection: { off: "Aus", active: "Aktiv", drifted: "Reparatur erforderlich", unsupported: "Nicht unterstützt", unknown: "Unbekannt" }, diff --git a/gui/src/i18n/models-overall-copy.ts b/gui/src/i18n/models-overall-copy.ts index eeba71b627d..1a290c31aa0 100644 --- a/gui/src/i18n/models-overall-copy.ts +++ b/gui/src/i18n/models-overall-copy.ts @@ -1,19 +1,19 @@ -type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; -const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; -type Row = readonly [string, string, string, string, string, string, string, string, string, string, string]; +type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt" | "es"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt", "es"]; +type Row = readonly [string, string, string, string, string, string, string, string, string, string, string, string]; /** Models page "Overall" tab copy, one row per key in `locales` order. */ const rows = { - "models.tab.overall": ["Overall", "전체", "Alle", "Tous", "全部", "全部", "Все", "すべて", "Tümü", "Tất cả", "Todos"], - "modelsOverall.lede": ["Every model from every provider in one list. Search, then switch a model on or off.", "모든 공급자의 모델을 한 목록에서 봅니다. 검색한 뒤 모델을 켜거나 끄세요.", "Alle Modelle aller Anbieter in einer Liste. Suche ein Modell und schalte es ein oder aus.", "Tous les modèles de tous les fournisseurs dans une seule liste. Recherchez, puis activez ou désactivez un modèle.", "所有供应商的模型都在一个列表里。搜索后即可开启或关闭模型。", "所有供應商的模型都在同一個清單中。搜尋後即可開啟或關閉模型。", "Все модели всех провайдеров в одном списке. Найдите модель и включите или выключите её.", "すべてのプロバイダーのモデルを 1 つのリストで表示します。検索して、モデルをオン・オフできます。", "Tüm sağlayıcıların modelleri tek listede. Arayın, ardından bir modeli açın veya kapatın.", "Mọi mô hình của mọi nhà cung cấp trong một danh sách. Tìm kiếm rồi bật hoặc tắt mô hình.", "Todos os modelos de todos os provedores em uma lista. Pesquise e ative ou desative um modelo."], - "modelsOverall.title": ["All models", "전체 모델", "Alle Modelle", "Tous les modèles", "全部模型", "全部模型", "Все модели", "すべてのモデル", "Tüm modeller", "Tất cả mô hình", "Todos os modelos"], - "modelsOverall.search": ["Search all models", "모든 모델 검색", "Alle Modelle durchsuchen", "Rechercher dans tous les modèles", "搜索全部模型", "搜尋全部模型", "Поиск по всем моделям", "すべてのモデルを検索", "Tüm modellerde ara", "Tìm trong tất cả mô hình", "Pesquisar todos os modelos"], - "modelsOverall.filterLabel": ["Show", "표시", "Anzeigen", "Afficher", "显示", "顯示", "Показать", "表示", "Göster", "Hiển thị", "Mostrar"], - "modelsOverall.filter.all": ["All", "전체", "Alle", "Tous", "全部", "全部", "Все", "すべて", "Tümü", "Tất cả", "Todos"], - "modelsOverall.filter.on": ["On", "켜짐", "An", "Activés", "已开启", "已開啟", "Вкл.", "オン", "Açık", "Bật", "Ativados"], - "modelsOverall.filter.off": ["Off", "꺼짐", "Aus", "Désactivés", "已关闭", "已關閉", "Выкл.", "オフ", "Kapalı", "Tắt", "Desativados"], - "modelsOverall.noMatch": ["No models match.", "일치하는 모델이 없습니다.", "Keine passenden Modelle.", "Aucun modèle ne correspond.", "没有匹配的模型。", "沒有符合的模型。", "Подходящих моделей нет.", "一致するモデルはありません。", "Eşleşen model yok.", "Không có mô hình phù hợp.", "Nenhum modelo corresponde."], - "modelsOverall.empty": ["No models yet. Add a provider to list its models here.", "아직 모델이 없습니다. 공급자를 추가하면 여기에 모델이 표시됩니다.", "Noch keine Modelle. Füge einen Anbieter hinzu, um seine Modelle hier zu sehen.", "Aucun modèle pour l’instant. Ajoutez un fournisseur pour voir ses modèles ici.", "还没有模型。添加供应商后,它的模型会显示在这里。", "還沒有模型。新增供應商後,它的模型會顯示在這裡。", "Моделей пока нет. Добавьте провайдера, и его модели появятся здесь.", "まだモデルがありません。プロバイダーを追加すると、ここにモデルが表示されます。", "Henüz model yok. Modellerini burada görmek için bir sağlayıcı ekleyin.", "Chưa có mô hình. Thêm nhà cung cấp để xem mô hình tại đây.", "Ainda não há modelos. Adicione um provedor para ver os modelos dele aqui."], + "models.tab.overall": ["Overall", "전체", "Alle", "Tous", "全部", "全部", "Все", "すべて", "Tümü", "Tất cả", "Todos", "General"], + "modelsOverall.lede": ["Every model from every provider in one list. Search, then switch a model on or off.", "모든 공급자의 모델을 한 목록에서 봅니다. 검색한 뒤 모델을 켜거나 끄세요.", "Alle Modelle aller Anbieter in einer Liste. Suche ein Modell und schalte es ein oder aus.", "Tous les modèles de tous les fournisseurs dans une seule liste. Recherchez, puis activez ou désactivez un modèle.", "所有供应商的模型都在一个列表里。搜索后即可开启或关闭模型。", "所有供應商的模型都在同一個清單中。搜尋後即可開啟或關閉模型。", "Все модели всех провайдеров в одном списке. Найдите модель и включите или выключите её.", "すべてのプロバイダーのモデルを 1 つのリストで表示します。検索して、モデルをオン・オフできます。", "Tüm sağlayıcıların modelleri tek listede. Arayın, ardından bir modeli açın veya kapatın.", "Mọi mô hình của mọi nhà cung cấp trong một danh sách. Tìm kiếm rồi bật hoặc tắt mô hình.", "Todos os modelos de todos os provedores em uma lista. Pesquise e ative ou desative um modelo.", "Todos los modelos de todos los proveedores en una sola lista. Busca y luego activa o desactiva un modelo."], + "modelsOverall.title": ["All models", "전체 모델", "Alle Modelle", "Tous les modèles", "全部模型", "全部模型", "Все модели", "すべてのモデル", "Tüm modeller", "Tất cả mô hình", "Todos os modelos", "Todos los modelos"], + "modelsOverall.search": ["Search all models", "모든 모델 검색", "Alle Modelle durchsuchen", "Rechercher dans tous les modèles", "搜索全部模型", "搜尋全部模型", "Поиск по всем моделям", "すべてのモデルを検索", "Tüm modellerde ara", "Tìm trong tất cả mô hình", "Pesquisar todos os modelos", "Buscar en todos los modelos"], + "modelsOverall.filterLabel": ["Show", "표시", "Anzeigen", "Afficher", "显示", "顯示", "Показать", "表示", "Göster", "Hiển thị", "Mostrar", "Mostrar"], + "modelsOverall.filter.all": ["All", "전체", "Alle", "Tous", "全部", "全部", "Все", "すべて", "Tümü", "Tất cả", "Todos", "Todos"], + "modelsOverall.filter.on": ["On", "켜짐", "An", "Activés", "已开启", "已開啟", "Вкл.", "オン", "Açık", "Bật", "Ativados", "Activados"], + "modelsOverall.filter.off": ["Off", "꺼짐", "Aus", "Désactivés", "已关闭", "已關閉", "Выкл.", "オフ", "Kapalı", "Tắt", "Desativados", "Desactivados"], + "modelsOverall.noMatch": ["No models match.", "일치하는 모델이 없습니다.", "Keine passenden Modelle.", "Aucun modèle ne correspond.", "没有匹配的模型。", "沒有符合的模型。", "Подходящих моделей нет.", "一致するモデルはありません。", "Eşleşen model yok.", "Không có mô hình phù hợp.", "Nenhum modelo corresponde.", "Ningún modelo coincide."], + "modelsOverall.empty": ["No models yet. Add a provider to list its models here.", "아직 모델이 없습니다. 공급자를 추가하면 여기에 모델이 표시됩니다.", "Noch keine Modelle. Füge einen Anbieter hinzu, um seine Modelle hier zu sehen.", "Aucun modèle pour l’instant. Ajoutez un fournisseur pour voir ses modèles ici.", "还没有模型。添加供应商后,它的模型会显示在这里。", "還沒有模型。新增供應商後,它的模型會顯示在這裡。", "Моделей пока нет. Добавьте провайдера, и его модели появятся здесь.", "まだモデルがありません。プロバイダーを追加すると、ここにモデルが表示されます。", "Henüz model yok. Modellerini burada görmek için bir sağlayıcı ekleyin.", "Chưa có mô hình. Thêm nhà cung cấp để xem mô hình tại đây.", "Ainda não há modelos. Adicione um provedor para ver os modelos dele aqui.", "Todavía no hay modelos. Añade un proveedor para ver sus modelos aquí."], } as const satisfies Record; export type ModelsOverallCopyKey = keyof typeof rows; diff --git a/gui/src/i18n/native-main-translations.ts b/gui/src/i18n/native-main-translations.ts index 3797cfb4114..c12a8b7d898 100644 --- a/gui/src/i18n/native-main-translations.ts +++ b/gui/src/i18n/native-main-translations.ts @@ -56,6 +56,60 @@ export const NATIVE_MAIN_EN = { export type NativeMainTKey = keyof typeof NATIVE_MAIN_EN; export const NATIVE_MAIN_TRANSLATIONS = { en: NATIVE_MAIN_EN, + es: { + "nativeMain.title": "Inicio de sesión nativo principal", + "nativeMain.manage": "Administrar el inicio de sesión principal", + "nativeMain.close": "Cerrar el administrador del inicio de sesión principal", + "nativeMain.separate": "Estos controles cambian el inicio de sesión de Codex nativo, no la cuenta seleccionada para la próxima solicitud en modo Pool.", + "nativeMain.home": "CODEX_HOME efectivo", + "nativeMain.current": "Perfil activo registrado", + "nativeMain.unregistered": "Sin registrar", + "nativeMain.physicalHint": "Este directorio pertenece al servidor de OpenCodex, que puede estar en otro equipo. El backend verifica el inicio de sesión real antes de cualquier cambio.", + "nativeMain.busyOther": "Hay otra operación de inicio de sesión nativo en curso. Primero complétala o cancélala.", + "nativeMain.working": "Procesando…", + "nativeMain.changed": "Cambió el directorio, el perfil activo o el estado de recuperación. Revisa el estado actualizado y vuelve a confirmar.", + "nativeMain.error": "No se pudo confirmar el resultado. La ausencia de una respuesta no significa que se haya restaurado el inicio de sesión original.", + "nativeMain.doctorHint": "Ejecuta {cmd} en el servidor para obtener más información.", + "nativeMain.saved": "El inicio de sesión actual se guardó como perfil. El inicio de sesión real no cambió.", + "nativeMain.lastResult": "Último resultado confirmado", + "nativeMain.restart": "Cambio de inicio de sesión completado. El servidor requiere reiniciar Codex nativo.", + "nativeMain.done": "Operación completada. El servidor no solicitó reiniciar Codex nativo.", + "nativeMain.refreshFailed": "No se pudo actualizar toda la información de las cuentas. Un cambio completado no se ha deshecho. Actualiza el estado antes de otra operación.", + "nativeMain.refresh": "Actualizar estado", + "nativeMain.unsupported": "Este almacén de credenciales no es compatible. La administración de perfiles nativos requiere el almacén de credenciales en archivos.", + "nativeMain.recoveryHint": "Una transacción interrumpida requiere recuperación. Recuperar completa la conciliación; restaurar revierte la transacción pendiente. Ninguna acción se ejecuta hasta que la confirmes.", + "nativeMain.recover": "Recuperar el cambio interrumpido", + "nativeMain.rollback": "Restaurar la transacción pendiente", + "nativeMain.empty": "Todavía no hay perfiles nativos registrados. Primero guarda el inicio de sesión actual.", + "nativeMain.active": "Activo", + "nativeMain.switchTo": "Cambiar el inicio de sesión nativo a {label}", + "nativeMain.switch": "Cambiar", + "nativeMain.restore": "Volver al perfil mostrado anteriormente: {label}", + "nativeMain.restoreHint": "Este acceso directo selecciona el perfil mostrado antes del último cambio; no utiliza un historial de transacciones verificado por el servidor. Solo se conserva en esta página.", + "nativeMain.label": "Nombre del perfil", + "nativeMain.save": "Guardar el inicio de sesión actual como perfil", + "nativeMain.saveHint": "Si el inicio de sesión activo ya está registrado, guardarlo actualiza su nombre. No añade otro inicio de sesión.", + "nativeMain.confirmHint": "Esto solo cambia el inicio de sesión nativo en el directorio indicado abajo. Primero cierra Codex nativo en ese equipo. Este panel no modifica la estrategia ni la pertenencia a Pool, las claves de proveedores ni los datos de tareas e historial.", + "nativeMain.stepClose": "Cierra Codex nativo en el equipo servidor para el CODEX_HOME indicado. Mantenlo cerrado hasta comprobar el resultado.", + "nativeMain.stepConfirm": "Marca la casilla de abajo para confirmar que Codex está cerrado y luego confirma el cambio.", + "nativeMain.stepResult": "Espera el resultado y la actualización del perfil activo; después sigue las instrucciones para volver a abrir Codex.", + "nativeMain.reopenHint": "Comprueba el perfil activo actualizado y vuelve a abrir Codex nativo en el equipo servidor con el CODEX_HOME indicado. Sigue cualquier requisito de reinicio que aparezca aquí.", + "nativeMain.retryHint": "Actualiza el estado y revisa el perfil activo. Para reintentar un cambio de inicio de sesión, vuelve a seleccionar la acción y confirma que Codex está cerrado. No se reintenta nada automáticamente.", + "nativeMain.errorCodexBusy": "Codex nativo sigue ejecutándose en el equipo servidor. Ciérralo para el CODEX_HOME indicado antes de reintentar.", + "nativeMain.errorProcessCheck": "El servidor no pudo verificar si Codex nativo está en ejecución. Comprueba que Codex esté cerrado en ese equipo y revisa los diagnósticos del servidor antes de reintentar.", + "nativeMain.errorRequests": "Todavía hay solicitudes de la cuenta principal en ejecución o finalizándose. Espera a que terminen antes de reintentar.", + "nativeMain.errorBusy": "Hay otra operación de inicio de sesión nativo en curso. Espera a que termine antes de volver a intentarlo.", + "nativeMain.errorAuth": "No se pudo leer el inicio de sesión nativo actual o verificarlo con su perfil guardado. Revisa los diagnósticos del servidor antes de otro cambio.", + "nativeMain.errorKeyStore": "No se pudo abrir el perfil guardado o el almacén de claves del sistema operativo. Revisa los diagnósticos del almacén y del perfil en el servidor antes de otro cambio.", + "nativeMain.errorStorage": "El servidor no puede acceder de forma segura al directorio de inicio de sesión o al almacenamiento de perfiles. Revisa los diagnósticos del servidor antes de otro cambio.", + "nativeMain.errorProfile": "El estado del perfil guardado no permite esta acción. Actualiza y revisa la lista de perfiles; consulta los diagnósticos si el problema continúa.", + "nativeMain.errorRecovery": "El almacenamiento de perfiles o una transacción interrumpida requiere atención. Actualiza el estado y revisa los diagnósticos del servidor. Usa los controles de recuperación solo cuando el panel los ofrezca.", + "nativeMain.errorRolledBack": "El servidor indica que el cambio falló y que se restauró el inicio de sesión original. Revisa el perfil activo actualizado antes de otro intento.", + "nativeMain.stopped": "He detenido Codex nativo que usa este CODEX_HOME y comprendo que puede ser necesario reiniciarlo.", + "nativeMain.cancel": "Cancelar", + "nativeMain.confirm": "Confirmar el cambio del inicio de sesión nativo", + "nativeMain.unavailable": "Los cambios de perfil no están disponibles. Comprueba el código de diagnóstico antes de continuar." +}, "ko": { "nativeMain.title": "실제 Codex 메인 로그인", "nativeMain.manage": "메인 로그인 관리", @@ -596,4 +650,4 @@ export const NATIVE_MAIN_TRANSLATIONS = { "nativeMain.confirm": "Confirmar alteração do login nativo", "nativeMain.unavailable": "As alterações de perfil estão indisponíveis. Verifique o código de diagnóstico antes de continuar." }, -} satisfies Record<"en" | "de" | "fr" | "ko" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt", Record>; +} satisfies Record<"en" | "de" | "fr" | "ko" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt" | "es", Record>; diff --git a/gui/src/i18n/remote-link-child-copy.ts b/gui/src/i18n/remote-link-child-copy.ts index 35ce793d48c..051480e4ee4 100644 --- a/gui/src/i18n/remote-link-child-copy.ts +++ b/gui/src/i18n/remote-link-child-copy.ts @@ -3,17 +3,17 @@ * in the order of `locales`, kept apart from the per-locale files like remote-link-diagnostics-copy.ts. * The commands themselves are technical text and are rendered raw, in . */ -type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; -const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; -type Row = readonly [string, string, string, string, string, string, string, string, string, string, string]; +type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt" | "es"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt", "es"]; +type Row = readonly [string, string, string, string, string, string, string, string, string, string, string, string]; const rows = { - title: ["Disconnect this computer","이 컴퓨터 연결 끊기","Diesen Computer trennen","Déconnecter cet ordinateur","断开这台电脑","中斷這台電腦","Отключить этот компьютер","このコンピューターの接続を解除","Bu bilgisayarın bağlantısını kes","Ngắt kết nối máy này","Desconectar este computador"], - body: ["This computer is a Child of {home}. The dashboard cannot disconnect a Child; run these commands in a terminal on this computer.","이 컴퓨터는 {home}의 Child예요. 대시보드에서는 Child 연결을 끊을 수 없으니, 이 컴퓨터의 터미널에서 아래 명령을 실행하세요.","Dieser Computer ist ein Child von {home}. Das Dashboard kann ein Child nicht trennen; führe diese Befehle in einem Terminal auf diesem Computer aus.","Cet ordinateur est un Child de {home}. Le tableau de bord ne peut pas déconnecter un Child ; exécutez ces commandes dans un terminal sur cet ordinateur.","这台电脑是 {home} 的 Child。仪表板无法断开 Child;请在这台电脑的终端中运行以下命令。","這台電腦是 {home} 的 Child。儀表板無法中斷 Child;請在這台電腦的終端機中執行以下指令。","Этот компьютер — Child для {home}. Панель управления не может отключить Child; выполните эти команды в терминале на этом компьютере.","このコンピューターは {home} の Child です。ダッシュボードからは Child の接続を解除できません。このコンピューターのターミナルで次のコマンドを実行してください。","Bu bilgisayar {home} için bir Child. Pano bir Child'ın bağlantısını kesemez; bu komutları bu bilgisayardaki bir terminalde çalıştırın.","Máy này là Child của {home}. Bảng điều khiển không thể ngắt kết nối Child; hãy chạy các lệnh sau trong terminal trên máy này.","Este computador é um Child de {home}. O painel não consegue desconectar um Child; execute estes comandos em um terminal neste computador."], - bodyUnnamed: ["This computer is a Remote Link Child. The dashboard cannot disconnect a Child; run these commands in a terminal on this computer.","이 컴퓨터는 Remote Link Child예요. 대시보드에서는 Child 연결을 끊을 수 없으니, 이 컴퓨터의 터미널에서 아래 명령을 실행하세요.","Dieser Computer ist ein Remote-Link-Child. Das Dashboard kann ein Child nicht trennen; führe diese Befehle in einem Terminal auf diesem Computer aus.","Cet ordinateur est un Child Remote Link. Le tableau de bord ne peut pas déconnecter un Child ; exécutez ces commandes dans un terminal sur cet ordinateur.","这台电脑是 Remote Link Child。仪表板无法断开 Child;请在这台电脑的终端中运行以下命令。","這台電腦是 Remote Link Child。儀表板無法中斷 Child;請在這台電腦的終端機中執行以下指令。","Этот компьютер — Child Remote Link. Панель управления не может отключить Child; выполните эти команды в терминале на этом компьютере.","このコンピューターは Remote Link の Child です。ダッシュボードからは Child の接続を解除できません。このコンピューターのターミナルで次のコマンドを実行してください。","Bu bilgisayar bir Remote Link Child. Pano bir Child'ın bağlantısını kesemez; bu komutları bu bilgisayardaki bir terminalde çalıştırın.","Máy này là Child của Remote Link. Bảng điều khiển không thể ngắt kết nối Child; hãy chạy các lệnh sau trong terminal trên máy này.","Este computador é um Child do Remote Link. O painel não consegue desconectar um Child; execute estes comandos em um terminal neste computador."], - stepDisconnect: ["End this link (refused if this computer has moved to another link)","이 링크 끊기 (이 컴퓨터가 다른 링크로 옮겨졌다면 거부돼요)","Diesen Link beenden (wird abgelehnt, wenn dieser Computer zu einem anderen Link gewechselt ist)","Mettre fin à ce lien (refusé si cet ordinateur est passé à un autre lien)","结束此链接(如果这台电脑已换到其他链接,会被拒绝)","結束此連結(如果這台電腦已換到其他連結,會被拒絕)","Завершить эту связь (будет отклонено, если компьютер уже перешёл на другую связь)","このリンクを終了(このコンピューターが別のリンクに移っている場合は拒否されます)","Bu bağlantıyı sonlandır (bilgisayar başka bir bağlantıya geçtiyse reddedilir)","Kết thúc liên kết này (bị từ chối nếu máy đã chuyển sang liên kết khác)","Encerrar este link (recusado se o computador tiver mudado para outro link)"], - stepRestart: ["Restart OpenCodex as a standalone runtime","OpenCodex를 독립 실행형으로 다시 시작","OpenCodex als eigenständige Laufzeit neu starten","Redémarrer OpenCodex en mode autonome","以独立运行时重新启动 OpenCodex","以獨立執行環境重新啟動 OpenCodex","Перезапустить OpenCodex как автономную среду","OpenCodex をスタンドアロンとして再起動","OpenCodex'i bağımsız çalışma ortamı olarak yeniden başlat","Khởi động lại OpenCodex ở chế độ độc lập","Reiniciar o OpenCodex como runtime independente"], - homeAlternative: ["You can also remove this Child from the Remote Link page on the Home.","Home의 Remote Link 페이지에서 이 Child를 제거할 수도 있어요.","Du kannst dieses Child auch auf der Remote-Link-Seite des Home entfernen.","Vous pouvez aussi retirer ce Child depuis la page Remote Link du Home.","也可以在 Home 的 Remote Link 页面中移除此 Child。","也可以在 Home 的 Remote Link 頁面中移除此 Child。","Этот Child также можно удалить на странице Remote Link на Home.","Home の Remote Link ページからこの Child を削除することもできます。","Bu Child'ı Home'daki Remote Link sayfasından da kaldırabilirsiniz.","Bạn cũng có thể gỡ Child này trên trang Remote Link của Home.","Você também pode remover este Child na página Remote Link do Home."], + title: ["Disconnect this computer","이 컴퓨터 연결 끊기","Diesen Computer trennen","Déconnecter cet ordinateur","断开这台电脑","中斷這台電腦","Отключить этот компьютер","このコンピューターの接続を解除","Bu bilgisayarın bağlantısını kes","Ngắt kết nối máy này","Desconectar este computador", "Desconectar este equipo"], + body: ["This computer is a Child of {home}. The dashboard cannot disconnect a Child; run these commands in a terminal on this computer.","이 컴퓨터는 {home}의 Child예요. 대시보드에서는 Child 연결을 끊을 수 없으니, 이 컴퓨터의 터미널에서 아래 명령을 실행하세요.","Dieser Computer ist ein Child von {home}. Das Dashboard kann ein Child nicht trennen; führe diese Befehle in einem Terminal auf diesem Computer aus.","Cet ordinateur est un Child de {home}. Le tableau de bord ne peut pas déconnecter un Child ; exécutez ces commandes dans un terminal sur cet ordinateur.","这台电脑是 {home} 的 Child。仪表板无法断开 Child;请在这台电脑的终端中运行以下命令。","這台電腦是 {home} 的 Child。儀表板無法中斷 Child;請在這台電腦的終端機中執行以下指令。","Этот компьютер — Child для {home}. Панель управления не может отключить Child; выполните эти команды в терминале на этом компьютере.","このコンピューターは {home} の Child です。ダッシュボードからは Child の接続を解除できません。このコンピューターのターミナルで次のコマンドを実行してください。","Bu bilgisayar {home} için bir Child. Pano bir Child'ın bağlantısını kesemez; bu komutları bu bilgisayardaki bir terminalde çalıştırın.","Máy này là Child của {home}. Bảng điều khiển không thể ngắt kết nối Child; hãy chạy các lệnh sau trong terminal trên máy này.","Este computador é um Child de {home}. O painel não consegue desconectar um Child; execute estes comandos em um terminal neste computador.", "Este equipo es un Child de {home}. El panel no puede desconectar un Child; ejecuta estos comandos en una terminal de este equipo."], + bodyUnnamed: ["This computer is a Remote Link Child. The dashboard cannot disconnect a Child; run these commands in a terminal on this computer.","이 컴퓨터는 Remote Link Child예요. 대시보드에서는 Child 연결을 끊을 수 없으니, 이 컴퓨터의 터미널에서 아래 명령을 실행하세요.","Dieser Computer ist ein Remote-Link-Child. Das Dashboard kann ein Child nicht trennen; führe diese Befehle in einem Terminal auf diesem Computer aus.","Cet ordinateur est un Child Remote Link. Le tableau de bord ne peut pas déconnecter un Child ; exécutez ces commandes dans un terminal sur cet ordinateur.","这台电脑是 Remote Link Child。仪表板无法断开 Child;请在这台电脑的终端中运行以下命令。","這台電腦是 Remote Link Child。儀表板無法中斷 Child;請在這台電腦的終端機中執行以下指令。","Этот компьютер — Child Remote Link. Панель управления не может отключить Child; выполните эти команды в терминале на этом компьютере.","このコンピューターは Remote Link の Child です。ダッシュボードからは Child の接続を解除できません。このコンピューターのターミナルで次のコマンドを実行してください。","Bu bilgisayar bir Remote Link Child. Pano bir Child'ın bağlantısını kesemez; bu komutları bu bilgisayardaki bir terminalde çalıştırın.","Máy này là Child của Remote Link. Bảng điều khiển không thể ngắt kết nối Child; hãy chạy các lệnh sau trong terminal trên máy này.","Este computador é um Child do Remote Link. O painel não consegue desconectar um Child; execute estes comandos em um terminal neste computador.", "Este equipo es un Child de Remote Link. El panel no puede desconectar un Child; ejecuta estos comandos en una terminal de este equipo."], + stepDisconnect: ["End this link (refused if this computer has moved to another link)","이 링크 끊기 (이 컴퓨터가 다른 링크로 옮겨졌다면 거부돼요)","Diesen Link beenden (wird abgelehnt, wenn dieser Computer zu einem anderen Link gewechselt ist)","Mettre fin à ce lien (refusé si cet ordinateur est passé à un autre lien)","结束此链接(如果这台电脑已换到其他链接,会被拒绝)","結束此連結(如果這台電腦已換到其他連結,會被拒絕)","Завершить эту связь (будет отклонено, если компьютер уже перешёл на другую связь)","このリンクを終了(このコンピューターが別のリンクに移っている場合は拒否されます)","Bu bağlantıyı sonlandır (bilgisayar başka bir bağlantıya geçtiyse reddedilir)","Kết thúc liên kết này (bị từ chối nếu máy đã chuyển sang liên kết khác)","Encerrar este link (recusado se o computador tiver mudado para outro link)", "Terminar este enlace (se rechaza si este equipo se movió a otro enlace)"], + stepRestart: ["Restart OpenCodex as a standalone runtime","OpenCodex를 독립 실행형으로 다시 시작","OpenCodex als eigenständige Laufzeit neu starten","Redémarrer OpenCodex en mode autonome","以独立运行时重新启动 OpenCodex","以獨立執行環境重新啟動 OpenCodex","Перезапустить OpenCodex как автономную среду","OpenCodex をスタンドアロンとして再起動","OpenCodex'i bağımsız çalışma ortamı olarak yeniden başlat","Khởi động lại OpenCodex ở chế độ độc lập","Reiniciar o OpenCodex como runtime independente", "Reiniciar OpenCodex como entorno de ejecución independiente"], + homeAlternative: ["You can also remove this Child from the Remote Link page on the Home.","Home의 Remote Link 페이지에서 이 Child를 제거할 수도 있어요.","Du kannst dieses Child auch auf der Remote-Link-Seite des Home entfernen.","Vous pouvez aussi retirer ce Child depuis la page Remote Link du Home.","也可以在 Home 的 Remote Link 页面中移除此 Child。","也可以在 Home 的 Remote Link 頁面中移除此 Child。","Этот Child также можно удалить на странице Remote Link на Home.","Home の Remote Link ページからこの Child を削除することもできます。","Bu Child'ı Home'daki Remote Link sayfasından da kaldırabilirsiniz.","Bạn cũng có thể gỡ Child này trên trang Remote Link của Home.","Você também pode remover este Child na página Remote Link do Home.", "También puedes quitar este Child desde la página Remote Link del Home."], } satisfies Record; export type RemoteLinkChildCopyKey = `remoteLinkChild.${keyof typeof rows}`; diff --git a/gui/src/i18n/remote-link-diagnostics-copy.ts b/gui/src/i18n/remote-link-diagnostics-copy.ts index b9046170578..da7120b0e9f 100644 --- a/gui/src/i18n/remote-link-diagnostics-copy.ts +++ b/gui/src/i18n/remote-link-diagnostics-copy.ts @@ -3,30 +3,30 @@ * order of `locales`, kept apart from the per-locale files like codex-cli-update-copy.ts. Event, * outcome and state words are machine codes and are shown raw, in . */ -type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; -const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; -type Row = readonly [string, string, string, string, string, string, string, string, string, string, string]; +type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt" | "es"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt", "es"]; +type Row = readonly [string, string, string, string, string, string, string, string, string, string, string, string]; const rows = { - title: ["Diagnostics","진단","Diagnose","Diagnostic","诊断","診斷","Диагностика","診断","Tanılama","Chẩn đoán","Diagnóstico"], - hint: ["Recent tunnel and relay events recorded on this computer. Only fixed categories, generated IDs, numbers and times are kept.","이 컴퓨터에 기록된 최근 터널·릴레이 이벤트예요. 정해진 분류, 생성된 ID, 숫자와 시간만 남겨요.","Letzte Tunnel- und Relay-Ereignisse, die auf diesem Computer aufgezeichnet wurden. Gespeichert werden nur feste Kategorien, erzeugte IDs, Zahlen und Zeiten.","Événements récents de tunnel et de relais enregistrés sur cet ordinateur. Seuls des catégories fixes, des identifiants générés, des nombres et des horodatages sont conservés.","此电脑上记录的最近隧道和中继事件。只保留固定类别、生成的 ID、数字和时间。","此電腦上記錄的最近通道和中繼事件。只保留固定類別、產生的 ID、數字和時間。","Недавние события туннеля и ретрансляции, записанные на этом компьютере. Хранятся только фиксированные категории, сгенерированные ID, числа и время.","このコンピューターで記録された最近のトンネルとリレーのイベントです。固定の分類、生成された ID、数値と時刻だけを残します。","Bu bilgisayarda kaydedilen son tünel ve aktarma olayları. Yalnızca sabit kategoriler, üretilmiş kimlikler, sayılar ve zamanlar tutulur.","Các sự kiện đường hầm và chuyển tiếp gần đây được ghi trên máy này. Chỉ giữ các loại cố định, ID được tạo, số và thời gian.","Eventos recentes de túnel e retransmissão registrados neste computador. Só são mantidos categorias fixas, IDs gerados, números e horários."], - show: ["Show diagnostics","진단 보기","Diagnose anzeigen","Afficher le diagnostic","显示诊断","顯示診斷","Показать диагностику","診断を表示","Tanılamayı göster","Hiện chẩn đoán","Mostrar diagnóstico"], - hide: ["Hide diagnostics","진단 숨기기","Diagnose ausblenden","Masquer le diagnostic","隐藏诊断","隱藏診斷","Скрыть диагностику","診断を隠す","Tanılamayı gizle","Ẩn chẩn đoán","Ocultar diagnóstico"], - loading: ["Loading diagnostics…","진단을 불러오는 중…","Diagnose wird geladen…","Chargement du diagnostic…","正在加载诊断…","正在載入診斷…","Загрузка диагностики…","診断を読み込み中…","Tanılama yükleniyor…","Đang tải chẩn đoán…","Carregando diagnóstico…"], - error: ["Diagnostics could not be read. Try again.","진단을 읽지 못했어요. 다시 시도하세요.","Die Diagnose konnte nicht gelesen werden. Versuche es erneut.","Le diagnostic n’a pas pu être lu. Réessayez.","无法读取诊断。请重试。","無法讀取診斷。請重試。","Не удалось прочитать диагностику. Повторите попытку.","診断を読み取れませんでした。もう一度お試しください。","Tanılama okunamadı. Yeniden deneyin.","Không đọc được chẩn đoán. Hãy thử lại.","Não foi possível ler o diagnóstico. Tente novamente."], - empty: ["No diagnostics recorded yet.","아직 기록된 진단이 없어요.","Noch keine Diagnose aufgezeichnet.","Aucun diagnostic enregistré pour l’instant.","尚未记录任何诊断。","尚未記錄任何診斷。","Диагностика ещё не записывалась.","まだ診断は記録されていません。","Henüz tanılama kaydedilmedi.","Chưa có chẩn đoán nào được ghi.","Nenhum diagnóstico registrado ainda."], - colTime: ["Time","시간","Zeit","Heure","时间","時間","Время","時刻","Zaman","Thời gian","Horário"], - colEvent: ["Event","이벤트","Ereignis","Événement","事件","事件","Событие","イベント","Olay","Sự kiện","Evento"], - colOutcome: ["Outcome","결과","Ergebnis","Résultat","结果","結果","Результат","結果","Sonuç","Kết quả","Resultado"], - colState: ["State","상태","Zustand","État","状态","狀態","Состояние","状態","Durum","Trạng thái","Estado"], - colAttempt: ["Attempt","시도","Versuch","Tentative","尝试","嘗試","Попытка","試行","Deneme","Lần thử","Tentativa"], - colPort: ["Port","포트","Port","Port","端口","連接埠","Порт","ポート","Bağlantı noktası","Cổng","Porta"], - suppressed: ["+{count} suppressed","+{count}건 생략","+{count} unterdrückt","+{count} supprimés","+{count} 条已合并","+{count} 筆已合併","+{count} подавлено","+{count} 件省略","+{count} bastırıldı","+{count} bị lược","+{count} suprimidos"], - showing: ["Showing the newest {shown} of {total} records.","전체 {total}건 중 최신 {shown}건을 보여줘요.","Die neuesten {shown} von {total} Einträgen werden angezeigt.","Affichage des {shown} enregistrements les plus récents sur {total}.","显示 {total} 条记录中最新的 {shown} 条。","顯示 {total} 筆記錄中最新的 {shown} 筆。","Показаны последние {shown} из {total} записей.","{total} 件中、最新の {shown} 件を表示しています。","{total} kaydın en yeni {shown} tanesi gösteriliyor.","Đang hiện {shown} bản ghi mới nhất trong {total}.","Mostrando os {shown} registros mais recentes de {total}."], - skipped: ["Skipped unreadable or unrecognized lines: {count}.","읽을 수 없거나 알 수 없는 줄 {count}개를 건너뛰었어요.","Übersprungene unlesbare oder unbekannte Zeilen: {count}.","Lignes illisibles ou non reconnues ignorées : {count}.","已跳过 {count} 行无法读取或无法识别的内容。","已略過 {count} 行無法讀取或無法辨識的內容。","Пропущено нечитаемых или нераспознанных строк: {count}.","読み取れない、または認識できない行を {count} 行スキップしました。","Okunamayan veya tanınmayan {count} satır atlandı.","Đã bỏ qua {count} dòng không đọc được hoặc không nhận ra.","Linhas ilegíveis ou não reconhecidas ignoradas: {count}."], - truncated: ["A diagnostics file is larger than 256 KiB; only its newest 256 KiB were read.","진단 파일이 256 KiB보다 커서 최신 256 KiB만 읽었어요.","Eine Diagnosedatei ist größer als 256 KiB; nur die neuesten 256 KiB wurden gelesen.","Un fichier de diagnostic dépasse 256 Kio ; seuls ses 256 Kio les plus récents ont été lus.","有诊断文件超过 256 KiB,只读取了最新的 256 KiB。","有診斷檔案超過 256 KiB,只讀取了最新的 256 KiB。","Файл диагностики больше 256 КиБ; прочитаны только последние 256 КиБ.","診断ファイルが 256 KiB を超えているため、最新の 256 KiB だけを読み取りました。","Bir tanılama dosyası 256 KiB'tan büyük; yalnızca en yeni 256 KiB okundu.","Một tệp chẩn đoán lớn hơn 256 KiB; chỉ 256 KiB mới nhất được đọc.","Um arquivo de diagnóstico tem mais de 256 KiB; só os 256 KiB mais recentes foram lidos."], - refused: ["A diagnostics file was not read because it is not a regular file.","일반 파일이 아니어서 읽지 않은 진단 파일이 있어요.","Eine Diagnosedatei wurde nicht gelesen, weil sie keine reguläre Datei ist.","Un fichier de diagnostic n’a pas été lu, car ce n’est pas un fichier ordinaire.","有诊断文件不是普通文件,因此未读取。","有診斷檔案不是一般檔案,因此未讀取。","Файл диагностики не прочитан: это не обычный файл.","通常のファイルではないため、読み取らなかった診断ファイルがあります。","Bir tanılama dosyası normal bir dosya olmadığı için okunmadı.","Một tệp chẩn đoán không được đọc vì nó không phải tệp thông thường.","Um arquivo de diagnóstico não foi lido porque não é um arquivo comum."], - unreadable: ["A diagnostics file exists but could not be read.","진단 파일이 있지만 읽지 못했어요.","Eine Diagnosedatei existiert, konnte aber nicht gelesen werden.","Un fichier de diagnostic existe mais n’a pas pu être lu.","诊断文件存在,但无法读取。","診斷檔案存在,但無法讀取。","Файл диагностики существует, но его не удалось прочитать.","診断ファイルはありますが、読み取れませんでした。","Bir tanılama dosyası var ama okunamadı.","Có tệp chẩn đoán nhưng không đọc được.","Existe um arquivo de diagnóstico, mas não foi possível lê-lo."], + title: ["Diagnostics","진단","Diagnose","Diagnostic","诊断","診斷","Диагностика","診断","Tanılama","Chẩn đoán","Diagnóstico", "Diagnóstico"], + hint: ["Recent tunnel and relay events recorded on this computer. Only fixed categories, generated IDs, numbers and times are kept.","이 컴퓨터에 기록된 최근 터널·릴레이 이벤트예요. 정해진 분류, 생성된 ID, 숫자와 시간만 남겨요.","Letzte Tunnel- und Relay-Ereignisse, die auf diesem Computer aufgezeichnet wurden. Gespeichert werden nur feste Kategorien, erzeugte IDs, Zahlen und Zeiten.","Événements récents de tunnel et de relais enregistrés sur cet ordinateur. Seuls des catégories fixes, des identifiants générés, des nombres et des horodatages sont conservés.","此电脑上记录的最近隧道和中继事件。只保留固定类别、生成的 ID、数字和时间。","此電腦上記錄的最近通道和中繼事件。只保留固定類別、產生的 ID、數字和時間。","Недавние события туннеля и ретрансляции, записанные на этом компьютере. Хранятся только фиксированные категории, сгенерированные ID, числа и время.","このコンピューターで記録された最近のトンネルとリレーのイベントです。固定の分類、生成された ID、数値と時刻だけを残します。","Bu bilgisayarda kaydedilen son tünel ve aktarma olayları. Yalnızca sabit kategoriler, üretilmiş kimlikler, sayılar ve zamanlar tutulur.","Các sự kiện đường hầm và chuyển tiếp gần đây được ghi trên máy này. Chỉ giữ các loại cố định, ID được tạo, số và thời gian.","Eventos recentes de túnel e retransmissão registrados neste computador. Só são mantidos categorias fixas, IDs gerados, números e horários.", "Eventos recientes de túnel y relay registrados en este equipo. Solo se guardan categorías fijas, IDs generados, números y horas."], + show: ["Show diagnostics","진단 보기","Diagnose anzeigen","Afficher le diagnostic","显示诊断","顯示診斷","Показать диагностику","診断を表示","Tanılamayı göster","Hiện chẩn đoán","Mostrar diagnóstico", "Mostrar diagnóstico"], + hide: ["Hide diagnostics","진단 숨기기","Diagnose ausblenden","Masquer le diagnostic","隐藏诊断","隱藏診斷","Скрыть диагностику","診断を隠す","Tanılamayı gizle","Ẩn chẩn đoán","Ocultar diagnóstico", "Ocultar diagnóstico"], + loading: ["Loading diagnostics…","진단을 불러오는 중…","Diagnose wird geladen…","Chargement du diagnostic…","正在加载诊断…","正在載入診斷…","Загрузка диагностики…","診断を読み込み中…","Tanılama yükleniyor…","Đang tải chẩn đoán…","Carregando diagnóstico…", "Cargando el diagnóstico…"], + error: ["Diagnostics could not be read. Try again.","진단을 읽지 못했어요. 다시 시도하세요.","Die Diagnose konnte nicht gelesen werden. Versuche es erneut.","Le diagnostic n’a pas pu être lu. Réessayez.","无法读取诊断。请重试。","無法讀取診斷。請重試。","Не удалось прочитать диагностику. Повторите попытку.","診断を読み取れませんでした。もう一度お試しください。","Tanılama okunamadı. Yeniden deneyin.","Không đọc được chẩn đoán. Hãy thử lại.","Não foi possível ler o diagnóstico. Tente novamente.", "No se pudo leer el diagnóstico. Vuelve a intentarlo."], + empty: ["No diagnostics recorded yet.","아직 기록된 진단이 없어요.","Noch keine Diagnose aufgezeichnet.","Aucun diagnostic enregistré pour l’instant.","尚未记录任何诊断。","尚未記錄任何診斷。","Диагностика ещё не записывалась.","まだ診断は記録されていません。","Henüz tanılama kaydedilmedi.","Chưa có chẩn đoán nào được ghi.","Nenhum diagnóstico registrado ainda.", "Aún no se han registrado datos de diagnóstico."], + colTime: ["Time","시간","Zeit","Heure","时间","時間","Время","時刻","Zaman","Thời gian","Horário", "Hora"], + colEvent: ["Event","이벤트","Ereignis","Événement","事件","事件","Событие","イベント","Olay","Sự kiện","Evento", "Evento"], + colOutcome: ["Outcome","결과","Ergebnis","Résultat","结果","結果","Результат","結果","Sonuç","Kết quả","Resultado", "Resultado"], + colState: ["State","상태","Zustand","État","状态","狀態","Состояние","状態","Durum","Trạng thái","Estado", "Estado"], + colAttempt: ["Attempt","시도","Versuch","Tentative","尝试","嘗試","Попытка","試行","Deneme","Lần thử","Tentativa", "Intento"], + colPort: ["Port","포트","Port","Port","端口","連接埠","Порт","ポート","Bağlantı noktası","Cổng","Porta", "Puerto"], + suppressed: ["+{count} suppressed","+{count}건 생략","+{count} unterdrückt","+{count} supprimés","+{count} 条已合并","+{count} 筆已合併","+{count} подавлено","+{count} 件省略","+{count} bastırıldı","+{count} bị lược","+{count} suprimidos", "+{count} omitidos"], + showing: ["Showing the newest {shown} of {total} records.","전체 {total}건 중 최신 {shown}건을 보여줘요.","Die neuesten {shown} von {total} Einträgen werden angezeigt.","Affichage des {shown} enregistrements les plus récents sur {total}.","显示 {total} 条记录中最新的 {shown} 条。","顯示 {total} 筆記錄中最新的 {shown} 筆。","Показаны последние {shown} из {total} записей.","{total} 件中、最新の {shown} 件を表示しています。","{total} kaydın en yeni {shown} tanesi gösteriliyor.","Đang hiện {shown} bản ghi mới nhất trong {total}.","Mostrando os {shown} registros mais recentes de {total}.", "Se muestran los {shown} registros más recientes de {total}."], + skipped: ["Skipped unreadable or unrecognized lines: {count}.","읽을 수 없거나 알 수 없는 줄 {count}개를 건너뛰었어요.","Übersprungene unlesbare oder unbekannte Zeilen: {count}.","Lignes illisibles ou non reconnues ignorées : {count}.","已跳过 {count} 行无法读取或无法识别的内容。","已略過 {count} 行無法讀取或無法辨識的內容。","Пропущено нечитаемых или нераспознанных строк: {count}.","読み取れない、または認識できない行を {count} 行スキップしました。","Okunamayan veya tanınmayan {count} satır atlandı.","Đã bỏ qua {count} dòng không đọc được hoặc không nhận ra.","Linhas ilegíveis ou não reconhecidas ignoradas: {count}.", "Líneas ilegibles o no reconocidas omitidas: {count}."], + truncated: ["A diagnostics file is larger than 256 KiB; only its newest 256 KiB were read.","진단 파일이 256 KiB보다 커서 최신 256 KiB만 읽었어요.","Eine Diagnosedatei ist größer als 256 KiB; nur die neuesten 256 KiB wurden gelesen.","Un fichier de diagnostic dépasse 256 Kio ; seuls ses 256 Kio les plus récents ont été lus.","有诊断文件超过 256 KiB,只读取了最新的 256 KiB。","有診斷檔案超過 256 KiB,只讀取了最新的 256 KiB。","Файл диагностики больше 256 КиБ; прочитаны только последние 256 КиБ.","診断ファイルが 256 KiB を超えているため、最新の 256 KiB だけを読み取りました。","Bir tanılama dosyası 256 KiB'tan büyük; yalnızca en yeni 256 KiB okundu.","Một tệp chẩn đoán lớn hơn 256 KiB; chỉ 256 KiB mới nhất được đọc.","Um arquivo de diagnóstico tem mais de 256 KiB; só os 256 KiB mais recentes foram lidos.", "Un archivo de diagnóstico supera los 256 KiB. Solo se han leído los 256 KiB más recientes."], + refused: ["A diagnostics file was not read because it is not a regular file.","일반 파일이 아니어서 읽지 않은 진단 파일이 있어요.","Eine Diagnosedatei wurde nicht gelesen, weil sie keine reguläre Datei ist.","Un fichier de diagnostic n’a pas été lu, car ce n’est pas un fichier ordinaire.","有诊断文件不是普通文件,因此未读取。","有診斷檔案不是一般檔案,因此未讀取。","Файл диагностики не прочитан: это не обычный файл.","通常のファイルではないため、読み取らなかった診断ファイルがあります。","Bir tanılama dosyası normal bir dosya olmadığı için okunmadı.","Một tệp chẩn đoán không được đọc vì nó không phải tệp thông thường.","Um arquivo de diagnóstico não foi lido porque não é um arquivo comum.", "No se leyó un archivo de diagnóstico porque no es un archivo normal."], + unreadable: ["A diagnostics file exists but could not be read.","진단 파일이 있지만 읽지 못했어요.","Eine Diagnosedatei existiert, konnte aber nicht gelesen werden.","Un fichier de diagnostic existe mais n’a pas pu être lu.","诊断文件存在,但无法读取。","診斷檔案存在,但無法讀取。","Файл диагностики существует, но его не удалось прочитать.","診断ファイルはありますが、読み取れませんでした。","Bir tanılama dosyası var ama okunamadı.","Có tệp chẩn đoán nhưng không đọc được.","Existe um arquivo de diagnóstico, mas não foi possível lê-lo.", "Hay un archivo de diagnóstico que no se pudo leer."], } satisfies Record; export type RemoteLinkDiagnosticsCopyKey = `remoteLinkDiagnostics.${keyof typeof rows}`; diff --git a/gui/src/i18n/routing-compatibility-labels.ts b/gui/src/i18n/routing-compatibility-labels.ts index 42b8d75a8ad..851eeb024f8 100644 --- a/gui/src/i18n/routing-compatibility-labels.ts +++ b/gui/src/i18n/routing-compatibility-labels.ts @@ -18,6 +18,11 @@ export const ROUTING_COMPATIBILITY_FIELD_LABELS: Record locale.code === stored); + if (saved) return saved.code; } catch { /* ignore */ } const nav = typeof navigator !== "undefined" && navigator?.language ? navigator.language.toLowerCase() : "en"; if (nav.startsWith("de")) return "de"; @@ -47,6 +49,7 @@ export function detectInitial(): Locale { if (nav.startsWith("tr")) return "tr"; if (nav.startsWith("vi")) return "vi"; if (nav.startsWith("pt")) return "pt"; + if (/^es(?:-|$)/.test(nav)) return "es"; return "en"; } diff --git a/gui/src/i18n/shell-v2-copy.ts b/gui/src/i18n/shell-v2-copy.ts index 4c03250a74a..2bc23a650ed 100644 --- a/gui/src/i18n/shell-v2-copy.ts +++ b/gui/src/i18n/shell-v2-copy.ts @@ -4,109 +4,106 @@ import { gettingStartedCopy, type GettingStartedKey } from "./getting-started-co * Copy for the v2 shell: the three-tier sidebar, Home, the Set up hub and the Advanced hub. * One row per key, columns in the order of `locales`. Kept apart from the per-locale files * the same way desktop-compatibility-copy.ts is, so the new surface lands as one reviewable - * table instead of eleven scattered edits. Plain words first; the original term, where one + * table instead of scattered locale edits. Plain words first; the original term, where one * exists, is shown beside it by the page so docs and CLI names still connect. */ -type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; -const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; -type Row = readonly [string, string, string, string, string, string, string, string, string, string, string]; +type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt" | "es"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt", "es"]; +type Row = readonly [string, string, string, string, string, string, string, string, string, string, string, string]; const rows = { // ---- sidebar ---------------------------------------------------------------- - tierDaily: ["Everyday", "매일", "Alltag", "Au quotidien", "日常", "日常", "Каждый день", "毎日", "Her gün", "Hằng ngày", "Dia a dia"], - tierSetup: ["Set up", "처음 설정", "Einrichtung", "Configuration", "初次设置", "初次設定", "Настройка", "初期設定", "Kurulum", "Thiết lập", "Configuração"], - tierAdvanced: ["Fine-tuning", "세부 설정", "Feinabstimmung", "Réglages fins", "细节设置", "細節設定", "Тонкая настройка", "詳細設定", "İnce ayar", "Tinh chỉnh", "Ajustes finos"], - navSearch: ["Search menu", "메뉴 검색", "Menü durchsuchen", "Rechercher dans le menu", "搜索菜单", "搜尋選單", "Поиск по меню", "メニューを検索", "Menüde ara", "Tìm trong menu", "Buscar no menu"], - navSearchPlaceholder: ["Search menu", "메뉴 검색", "Menü durchsuchen", "Rechercher…", "搜索菜单", "搜尋選單", "Поиск по меню", "メニューを検索", "Menüde ara", "Tìm trong menu", "Buscar no menu"], - navSearchEmpty: ["No menu matches", "맞는 메뉴가 없어요", "Kein Menüpunkt passt", "Aucun menu ne correspond", "没有匹配的菜单", "沒有符合的選單", "Ничего не найдено", "一致するメニューはありません", "Eşleşen menü yok", "Không có mục phù hợp", "Nenhum item corresponde"], - navHome: ["Home", "홈", "Start", "Accueil", "首页", "首頁", "Главная", "ホーム", "Ana sayfa", "Trang chủ", "Início"], - navAccounts: ["Accounts & limits", "계정·한도", "Konten & Limits", "Comptes et limites", "账号与额度", "帳號與額度", "Аккаунты и лимиты", "アカウントと上限", "Hesaplar ve limitler", "Tài khoản & hạn mức", "Contas e limites"], - navSetup: ["Set up", "설정하기", "Einrichten", "Configurer", "设置", "設定", "Настроить", "セットアップ", "Kur", "Thiết lập", "Configurar"], - navAdvanced: ["Advanced", "고급 설정", "Erweitert", "Avancé", "高级设置", "進階設定", "Расширенные", "詳細", "Gelişmiş", "Nâng cao", "Avançado"], - pageChecklist: ["Checklist", "체크리스트", "Checkliste", "Liste de contrôle", "清单", "清單", "Чек-лист", "チェックリスト", "Kontrol listesi", "Danh sách", "Checklist"], - pageAllSettings: ["All settings", "전체 설정", "Alle Einstellungen", "Tous les réglages", "全部设置", "全部設定", "Все настройки", "すべての設定", "Tüm ayarlar", "Mọi cài đặt", "Todos os ajustes"], - pageProxyDetails: ["Proxy details", "프록시 세부", "Proxy-Details", "Détails du proxy", "代理详情", "代理詳情", "Детали прокси", "プロキシ詳細", "Proxy ayrıntıları", "Chi tiết proxy", "Detalhes do proxy"], - + tierDaily: ["Everyday", "매일", "Alltag", "Au quotidien", "日常", "日常", "Каждый день", "毎日", "Her gün", "Hằng ngày", "Dia a dia", "Uso diario"], + tierSetup: ["Set up", "처음 설정", "Einrichtung", "Configuration", "初次设置", "初次設定", "Настройка", "初期設定", "Kurulum", "Thiết lập", "Configuração", "Configuración"], + tierAdvanced: ["Fine-tuning", "세부 설정", "Feinabstimmung", "Réglages fins", "细节设置", "細節設定", "Тонкая настройка", "詳細設定", "İnce ayar", "Tinh chỉnh", "Ajustes finos", "Ajustes avanzados"], + navSearch: ["Search menu", "메뉴 검색", "Menü durchsuchen", "Rechercher dans le menu", "搜索菜单", "搜尋選單", "Поиск по меню", "メニューを検索", "Menüde ara", "Tìm trong menu", "Buscar no menu", "Buscar en el menú"], + navSearchPlaceholder: ["Search menu", "메뉴 검색", "Menü durchsuchen", "Rechercher…", "搜索菜单", "搜尋選單", "Поиск по меню", "メニューを検索", "Menüde ara", "Tìm trong menu", "Buscar no menu", "Buscar en el menú"], + navSearchEmpty: ["No menu matches", "맞는 메뉴가 없어요", "Kein Menüpunkt passt", "Aucun menu ne correspond", "没有匹配的菜单", "沒有符合的選單", "Ничего не найдено", "一致するメニューはありません", "Eşleşen menü yok", "Không có mục phù hợp", "Nenhum item corresponde", "No hay coincidencias en el menú"], + navHome: ["Home", "홈", "Start", "Accueil", "首页", "首頁", "Главная", "ホーム", "Ana sayfa", "Trang chủ", "Início", "Inicio"], + navAccounts: ["Accounts & limits", "계정·한도", "Konten & Limits", "Comptes et limites", "账号与额度", "帳號與額度", "Аккаунты и лимиты", "アカウントと上限", "Hesaplar ve limitler", "Tài khoản & hạn mức", "Contas e limites", "Cuentas y límites"], + navSetup: ["Set up", "설정하기", "Einrichten", "Configurer", "设置", "設定", "Настроить", "セットアップ", "Kur", "Thiết lập", "Configurar", "Configuración"], + navAdvanced: ["Advanced", "고급 설정", "Erweitert", "Avancé", "高级设置", "進階設定", "Расширенные", "詳細", "Gelişmiş", "Nâng cao", "Avançado", "Avanzado"], + pageChecklist: ["Checklist", "체크리스트", "Checkliste", "Liste de contrôle", "清单", "清單", "Чек-лист", "チェックリスト", "Kontrol listesi", "Danh sách", "Checklist", "Lista de pasos"], + pageAllSettings: ["All settings", "전체 설정", "Alle Einstellungen", "Tous les réglages", "全部设置", "全部設定", "Все настройки", "すべての設定", "Tüm ayarlar", "Mọi cài đặt", "Todos os ajustes", "Toda la configuración"], + pageProxyDetails: ["Proxy details", "프록시 세부", "Proxy-Details", "Détails du proxy", "代理详情", "代理詳情", "Детали прокси", "プロキシ詳細", "Proxy ayrıntıları", "Chi tiết proxy", "Detalhes do proxy", "Detalles del proxy"], // ---- home ------------------------------------------------------------------- - homeOk: ["Everything is running", "모든 게 정상이에요", "Alles läuft", "Tout fonctionne", "一切正常", "一切正常", "Всё работает", "すべて正常です", "Her şey çalışıyor", "Mọi thứ đang chạy", "Tudo funcionando"], - homeErrorsUnavailable: ["Recent errors unavailable", "최근 오류를 확인할 수 없어요", "Letzte Fehler nicht verfügbar", "Erreurs récentes indisponibles", "无法获取最近的错误", "無法取得最近的錯誤", "Последние ошибки недоступны", "最近のエラーを取得できません", "Son hatalar kullanılamıyor", "Không thể tải lỗi gần đây", "Erros recentes indisponíveis"], - homeDown: ["The proxy is not answering", "프록시가 응답하지 않아요", "Der Proxy antwortet nicht", "Le proxy ne répond pas", "代理没有响应", "代理沒有回應", "Прокси не отвечает", "プロキシが応答していません", "Proxy yanıt vermiyor", "Proxy không phản hồi", "O proxy não está respondendo"], - homeErrorsToday: ["{count} requests failed in the last 24 hours", "최근 24시간 동안 요청 {count}개가 실패했어요", "{count} Anfragen in den letzten 24 Stunden fehlgeschlagen", "{count} requêtes ont échoué ces dernières 24 h", "过去 24 小时有 {count} 个请求失败", "過去 24 小時有 {count} 個請求失敗", "За 24 часа не выполнено запросов: {count}", "過去24時間に {count} 件のリクエストが失敗しました", "Son 24 saatte {count} istek başarısız oldu", "{count} yêu cầu lỗi trong 24 giờ qua", "{count} solicitações falharam nas últimas 24 horas"], - tileVersion: ["Version", "버전", "Version", "Version installée", "版本", "版本", "Версия", "バージョン", "Sürüm", "Phiên bản", "Versão"], - tileUptime: ["Running for", "켜진 시간", "Läuft seit", "Actif depuis", "已运行", "已執行", "Работает", "稼働時間", "Çalışma süresi", "Đã chạy", "Em execução há"], - leverHint: ["Pull halfway: {restart}. Pull all the way down: {stop}.", "반쯤 당기면 {restart}, 끝까지 당기면 {stop}", "Halb ziehen: {restart}. Ganz nach unten ziehen: {stop}.", "Tirez à mi-course : {restart}. Tirez jusqu’en bas : {stop}.", "拉到一半:{restart};拉到底:{stop}", "拉到一半:{restart};拉到底:{stop}", "Потяните наполовину: {restart}. До упора вниз: {stop}.", "半分引く:{restart}。下まで引く:{stop}", "Yarıya kadar çek: {restart}. Sonuna kadar çek: {stop}.", "Kéo nửa chừng: {restart}. Kéo hết xuống: {stop}.", "Puxe até a metade: {restart}. Puxe até o fim: {stop}."], - leverHover: ["Pull: reload · stop", "당겨서 새로고침·정지", "Ziehen: neu laden · stoppen", "Tirer : recharger · arrêter", "下拉:刷新 · 停止", "下拉:重新整理 · 停止", "Потяните: обновить · стоп", "引く:更新・停止", "Çek: yenile · durdur", "Kéo: tải lại · dừng", "Puxe: recarregar · parar"], - leverCancel: ["Let go to cancel", "놓으면 취소", "Loslassen bricht ab", "Relâchez pour annuler", "松开即取消", "放開即取消", "Отпустите — отмена", "離すとキャンセル", "Bırakınca iptal", "Thả để hủy", "Solte para cancelar"], - leverRelease: ["Let go: {action}", "놓으면 {action}", "Loslassen: {action}", "Relâchez : {action}", "松开:{action}", "放開:{action}", "Отпустите: {action}", "離すと{action}", "Bırakınca: {action}", "Thả: {action}", "Solte: {action}"], - leverReload: ["reload models", "모델 새로고침", "Modelle neu laden", "recharger les modèles", "刷新模型", "重新整理模型", "обновить модели", "モデルを更新", "modelleri yenile", "tải lại mô hình", "recarregar modelos"], - leverStop: ["stop the proxy", "프록시 정지", "Proxy stoppen", "arrêter le proxy", "停止代理", "停止代理", "остановить прокси", "プロキシを停止", "proxy’yi durdur", "dừng proxy", "parar o proxy"], - uiClassic: ["Classic dashboard", "구버전 UI", "Klassisches Dashboard", "Tableau de bord classique", "经典版仪表盘", "經典版儀表板", "Классическая панель", "クラシック ダッシュボード", "Klasik pano", "Bảng điều khiển cổ điển", "Painel clássico"], - uiClassicHint: ["Switch to the previous dashboard design. Its sidebar has a way back.", "이전 디자인의 대시보드로 바꿔요. 그쪽 사이드바에서 다시 돌아올 수 있어요.", "Zum bisherigen Dashboard-Design wechseln. In seiner Seitenleiste geht es zurück.", "Passer à l’ancienne présentation du tableau de bord. Sa barre latérale permet de revenir.", "切换到之前设计的仪表盘,可从其侧栏切换回来。", "切換到先前設計的儀表板,可從其側欄切換回來。", "Перейти к прежнему виду панели. Вернуться можно из её боковой панели.", "以前のデザインのダッシュボードに切り替えます。そのサイドバーから戻れます。", "Önceki pano tasarımına geç. Kenar çubuğundan geri dönebilirsin.", "Chuyển sang giao diện bảng điều khiển trước đây. Có thể quay lại từ thanh bên của nó.", "Mudar para o design anterior do painel. A barra lateral dele traz você de volta."], - uiCurrent: ["New dashboard", "새 UI로 전환", "Neues Dashboard", "Nouveau tableau de bord", "新版仪表盘", "新版儀表板", "Новая панель", "新しいダッシュボード", "Yeni pano", "Bảng điều khiển mới", "Novo painel"], - uiCurrentHint: ["Switch back to the current dashboard design.", "지금 디자인의 대시보드로 돌아가요.", "Zum aktuellen Dashboard-Design zurückwechseln.", "Revenir à la présentation actuelle du tableau de bord.", "切换回当前设计的仪表盘。", "切換回目前設計的儀表板。", "Вернуться к текущему виду панели.", "現在のデザインのダッシュボードに戻ります。", "Güncel pano tasarımına geri dön.", "Quay lại giao diện bảng điều khiển hiện tại.", "Voltar ao design atual do painel."], - uptimeValue: ["{h}h {m}m", "{h}시간 {m}분", "{h} Std. {m} Min.", "{h} h {m} min", "{h} 小时 {m} 分", "{h} 小時 {m} 分", "{h} ч {m} мин", "{h}時間{m}分", "{h} sa {m} dk", "{h} giờ {m} phút", "{h} h {m} min"], - tileRequests: ["Requests · 7 days", "요청 · 7일", "Anfragen · 7 Tage", "Requêtes · 7 jours", "请求 · 7 天", "請求 · 7 天", "Запросы · 7 дней", "リクエスト · 7日", "İstekler · 7 gün", "Yêu cầu · 7 ngày", "Solicitações · 7 dias"], - tileTokens: ["Tokens · 7 days", "토큰 · 7일", "Tokens · 7 Tage", "Jetons · 7 jours", "Token · 7 天", "Token · 7 天", "Токены · 7 дней", "トークン · 7日", "Token · 7 gün", "Token · 7 ngày", "Tokens · 7 dias"], - tileProviders: ["Providers", "프로바이더", "Anbieter", "Fournisseurs", "提供商", "供應商", "Провайдеры", "プロバイダー", "Sağlayıcılar", "Nhà cung cấp", "Provedores"], - openLogs: ["Open request log", "요청 기록 보기", "Anfrageprotokoll öffnen", "Ouvrir le journal", "打开请求记录", "開啟請求記錄", "Открыть журнал", "リクエスト履歴を開く", "İstek günlüğünü aç", "Mở nhật ký yêu cầu", "Abrir registro"], - checkUpdate: ["Check for updates", "업데이트 확인", "Nach Updates suchen", "Rechercher des mises à jour", "检查更新", "檢查更新", "Проверить обновления", "アップデートを確認", "Güncellemeleri denetle", "Kiểm tra cập nhật", "Verificar atualizações"], - checklistTitle: ["Getting started", "시작하기", "Erste Schritte", "Premiers pas", "开始使用", "開始使用", "Начало работы", "はじめに", "Başlarken", "Bắt đầu", "Primeiros passos"], - checklistProgress: ["{done} of {total} done", "{total}단계 중 {done}단계 완료", "{done} von {total} erledigt", "{done} sur {total} terminées", "已完成 {done}/{total}", "已完成 {done}/{total}", "Готово {done} из {total}", "{total}件中 {done}件完了", "{total} adımdan {done} tamam", "Xong {done}/{total}", "{done} de {total} concluídas"], - checklistAllDone: ["All set. opencodex is ready to use.", "준비 끝! 이제 opencodex를 쓰면 돼요.", "Fertig. opencodex ist einsatzbereit.", "Tout est prêt. opencodex est prêt à l’emploi.", "全部完成,opencodex 可以使用了。", "全部完成,opencodex 可以使用了。", "Готово. opencodex можно использовать.", "準備完了。opencodex を使えます。", "Hazır. opencodex kullanıma hazır.", "Xong. opencodex đã sẵn sàng.", "Tudo pronto. O opencodex está pronto para uso."], - stepProvider: ["Add a provider", "프로바이더 추가하기", "Anbieter hinzufügen", "Ajouter un fournisseur", "添加提供商", "新增供應商", "Добавить провайдера", "プロバイダーを追加", "Sağlayıcı ekle", "Thêm nhà cung cấp", "Adicionar provedor"], - stepProviderHint: ["Sign in or paste an API key so opencodex has models to offer.", "로그인하거나 API 키를 넣어서 쓸 수 있는 모델을 만들어요.", "Anmelden oder API-Schlüssel einfügen, damit opencodex Modelle anbieten kann.", "Connectez-vous ou collez une clé API pour qu’opencodex ait des modèles à proposer.", "登录或粘贴 API 密钥,让 opencodex 有模型可用。", "登入或貼上 API 金鑰,讓 opencodex 有模型可用。", "Войдите или вставьте API-ключ, чтобы у opencodex появились модели.", "サインインするか API キーを貼り付けて、使えるモデルを用意します。", "opencodex’in sunacak modeli olması için oturum açın veya API anahtarı yapıştırın.", "Đăng nhập hoặc dán khóa API để opencodex có mô hình để dùng.", "Entre ou cole uma chave de API para o opencodex ter modelos."], - stepFirstRequest: ["Connect your app and send a request", "앱을 연결하고 첫 요청 보내기", "App verbinden und eine Anfrage senden", "Connecter votre app et envoyer une requête", "连接应用并发送第一个请求", "連接應用程式並送出第一個請求", "Подключить приложение и отправить запрос", "アプリを接続して最初のリクエストを送る", "Uygulamanı bağla ve istek gönder", "Kết nối ứng dụng và gửi yêu cầu", "Conectar seu app e enviar uma solicitação"], - stepFirstRequestHint: ["Point Codex, Claude Code or another tool at opencodex, then ask it anything.", "Codex나 Claude Code 같은 도구를 opencodex에 연결하고 아무거나 물어보세요.", "Codex, Claude Code oder ein anderes Tool auf opencodex richten und etwas fragen.", "Branchez Codex, Claude Code ou un autre outil sur opencodex, puis posez une question.", "把 Codex、Claude Code 等工具连到 opencodex,然后随便问一句。", "把 Codex、Claude Code 等工具連到 opencodex,然後隨便問一句。", "Направьте Codex, Claude Code или другой инструмент на opencodex и задайте вопрос.", "Codex や Claude Code などを opencodex につなぎ、何か質問してみましょう。", "Codex, Claude Code veya başka bir aracı opencodex’e yönlendirip bir şey sorun.", "Trỏ Codex, Claude Code hoặc công cụ khác tới opencodex rồi hỏi bất cứ điều gì.", "Aponte o Codex, o Claude Code ou outra ferramenta para o opencodex e pergunte algo."], - stepAutostart: ["Start automatically", "자동 시작 켜기", "Automatisch starten", "Démarrer automatiquement", "开机自动启动", "開機自動啟動", "Запускать автоматически", "自動で起動", "Otomatik başlat", "Tự khởi động", "Iniciar automaticamente"], - stepAutostartHint: ["Keep opencodex running after a restart so your tools never lose it.", "컴퓨터를 다시 켜도 opencodex가 알아서 켜지게 해요.", "opencodex nach einem Neustart weiterlaufen lassen, damit Tools es nie verlieren.", "Gardez opencodex actif après un redémarrage pour que vos outils ne le perdent jamais.", "重启后 opencodex 仍会运行,工具不会断开。", "重新開機後 opencodex 仍會執行,工具不會斷線。", "opencodex продолжит работать после перезагрузки.", "再起動後も opencodex が動き続けるようにします。", "opencodex yeniden başlatmadan sonra da çalışsın.", "Giữ opencodex chạy sau khi khởi động lại.", "Mantenha o opencodex rodando após reiniciar."], - stepAutostartDesktop: ["Turn on Start at Login", "로그인 시 시작 켜기", "Start beim Anmelden einschalten", "Activer le démarrage à la connexion", "开启登录时启动", "開啟登入時啟動", "Включить запуск при входе", "ログイン時の起動をオンにする", "Oturum açılışında başlatmayı aç", "Bật khởi động khi đăng nhập", "Ativar Iniciar no login"], - stepAutostartDesktopHint: ["In the OpenCodex app menu, make sure Start at Login is checked. The app then opens when you log in and keeps the proxy running.", "OpenCodex 앱 메뉴에서 '로그인 시 시작'이 켜져 있는지 확인하세요. 로그인할 때 앱이 열리고 프록시도 계속 동작해요.", "Prüfe im Menü der OpenCodex-App, dass „Beim Anmelden starten“ aktiviert ist. Dann öffnet sich die App beim Anmelden und der Proxy läuft weiter.", "Dans le menu de l’app OpenCodex, vérifiez que le démarrage à la connexion est coché. L’app s’ouvre alors à la connexion et le proxy reste actif.", "请在 OpenCodex 应用菜单中确认已勾选“登录时启动”。这样登录时应用会自动打开,代理保持运行。", "請在 OpenCodex 應用程式選單中確認已勾選「登入時啟動」。這樣登入時應用程式會自動開啟,代理持續執行。", "Убедитесь, что в меню приложения OpenCodex отмечен запуск при входе. Тогда приложение откроется при входе, а прокси продолжит работать.", "OpenCodex アプリのメニューで「ログイン時の起動」がオンになっているか確認してください。ログイン時にアプリが開き、プロキシが動き続けます。", "OpenCodex uygulama menüsünde oturum açılışında başlatmanın işaretli olduğundan emin olun. Uygulama oturum açınca açılır ve proxy çalışmaya devam eder.", "Trong menu ứng dụng OpenCodex, hãy bảo đảm đã bật khởi động khi đăng nhập. Ứng dụng sẽ tự mở khi đăng nhập và proxy tiếp tục chạy.", "No menu do app OpenCodex, confirme que Iniciar no login está marcado. Assim o app abre ao entrar e o proxy continua rodando."], - stepOpen: ["Open", "열기", "Öffnen", "Ouvrir", "打开", "開啟", "Открыть", "開く", "Aç", "Mở", "Abrir"], - recentErrors: ["Recent errors", "최근 오류", "Letzte Fehler", "Erreurs récentes", "最近的错误", "最近的錯誤", "Недавние ошибки", "最近のエラー", "Son hatalar", "Lỗi gần đây", "Erros recentes"], - noErrors: ["No failed requests in the last 24 hours.", "최근 24시간 동안 실패한 요청이 없어요.", "Keine fehlgeschlagenen Anfragen in den letzten 24 Stunden.", "Aucune requête en échec ces dernières 24 h.", "过去 24 小时没有失败的请求。", "過去 24 小時沒有失敗的請求。", "За 24 часа ошибок нет.", "過去24時間に失敗したリクエストはありません。", "Son 24 saatte başarısız istek yok.", "Không có yêu cầu lỗi trong 24 giờ qua.", "Nenhuma falha nas últimas 24 horas."], - viewAll: ["View all", "모두 보기", "Alle anzeigen", "Tout voir", "查看全部", "查看全部", "Показать все", "すべて表示", "Tümünü gör", "Xem tất cả", "Ver tudo"], - + homeOk: ["Everything is running", "모든 게 정상이에요", "Alles läuft", "Tout fonctionne", "一切正常", "一切正常", "Всё работает", "すべて正常です", "Her şey çalışıyor", "Mọi thứ đang chạy", "Tudo funcionando", "Todo funciona"], + homeErrorsUnavailable: ["Recent errors unavailable", "최근 오류를 확인할 수 없어요", "Letzte Fehler nicht verfügbar", "Erreurs récentes indisponibles", "无法获取最近的错误", "無法取得最近的錯誤", "Последние ошибки недоступны", "最近のエラーを取得できません", "Son hatalar kullanılamıyor", "Không thể tải lỗi gần đây", "Erros recentes indisponíveis", "Errores recientes no disponibles"], + homeDown: ["The proxy is not answering", "프록시가 응답하지 않아요", "Der Proxy antwortet nicht", "Le proxy ne répond pas", "代理没有响应", "代理沒有回應", "Прокси не отвечает", "プロキシが応答していません", "Proxy yanıt vermiyor", "Proxy không phản hồi", "O proxy não está respondendo", "El proxy no responde"], + homeErrorsToday: ["{count} requests failed in the last 24 hours", "최근 24시간 동안 요청 {count}개가 실패했어요", "{count} Anfragen in den letzten 24 Stunden fehlgeschlagen", "{count} requêtes ont échoué ces dernières 24 h", "过去 24 小时有 {count} 个请求失败", "過去 24 小時有 {count} 個請求失敗", "За 24 часа не выполнено запросов: {count}", "過去24時間に {count} 件のリクエストが失敗しました", "Son 24 saatte {count} istek başarısız oldu", "{count} yêu cầu lỗi trong 24 giờ qua", "{count} solicitações falharam nas últimas 24 horas", "Fallaron {count} solicitudes en las últimas 24 horas"], + tileVersion: ["Version", "버전", "Version", "Version installée", "版本", "版本", "Версия", "バージョン", "Sürüm", "Phiên bản", "Versão", "Versión"], + tileUptime: ["Running for", "켜진 시간", "Läuft seit", "Actif depuis", "已运行", "已執行", "Работает", "稼働時間", "Çalışma süresi", "Đã chạy", "Em execução há", "Tiempo en ejecución"], + leverHint: ["Pull halfway: {restart}. Pull all the way down: {stop}.", "반쯤 당기면 {restart}, 끝까지 당기면 {stop}", "Halb ziehen: {restart}. Ganz nach unten ziehen: {stop}.", "Tirez à mi-course : {restart}. Tirez jusqu’en bas : {stop}.", "拉到一半:{restart};拉到底:{stop}", "拉到一半:{restart};拉到底:{stop}", "Потяните наполовину: {restart}. До упора вниз: {stop}.", "半分引く:{restart}。下まで引く:{stop}", "Yarıya kadar çek: {restart}. Sonuna kadar çek: {stop}.", "Kéo nửa chừng: {restart}. Kéo hết xuống: {stop}.", "Puxe até a metade: {restart}. Puxe até o fim: {stop}.", "Tira hasta la mitad para {restart}. Tira hasta abajo para {stop}."], + leverHover: ["Pull: reload · stop", "당겨서 새로고침·정지", "Ziehen: neu laden · stoppen", "Tirer : recharger · arrêter", "下拉:刷新 · 停止", "下拉:重新整理 · 停止", "Потяните: обновить · стоп", "引く:更新・停止", "Çek: yenile · durdur", "Kéo: tải lại · dừng", "Puxe: recarregar · parar", "Tira para recargar o detener"], + leverCancel: ["Let go to cancel", "놓으면 취소", "Loslassen bricht ab", "Relâchez pour annuler", "松开即取消", "放開即取消", "Отпустите — отмена", "離すとキャンセル", "Bırakınca iptal", "Thả để hủy", "Solte para cancelar", "Suelta para cancelar"], + leverRelease: ["Let go: {action}", "놓으면 {action}", "Loslassen: {action}", "Relâchez : {action}", "松开:{action}", "放開:{action}", "Отпустите: {action}", "離すと{action}", "Bırakınca: {action}", "Thả: {action}", "Solte: {action}", "Suelta para {action}"], + leverReload: ["reload models", "모델 새로고침", "Modelle neu laden", "recharger les modèles", "刷新模型", "重新整理模型", "обновить модели", "モデルを更新", "modelleri yenile", "tải lại mô hình", "recarregar modelos", "recargar los modelos"], + leverStop: ["stop the proxy", "프록시 정지", "Proxy stoppen", "arrêter le proxy", "停止代理", "停止代理", "остановить прокси", "プロキシを停止", "proxy’yi durdur", "dừng proxy", "parar o proxy", "detener el proxy"], + uiClassic: ["Classic dashboard", "구버전 UI", "Klassisches Dashboard", "Tableau de bord classique", "经典版仪表盘", "經典版儀表板", "Классическая панель", "クラシック ダッシュボード", "Klasik pano", "Bảng điều khiển cổ điển", "Painel clássico", "Panel clásico"], + uiClassicHint: ["Switch to the previous dashboard design. Its sidebar has a way back.", "이전 디자인의 대시보드로 바꿔요. 그쪽 사이드바에서 다시 돌아올 수 있어요.", "Zum bisherigen Dashboard-Design wechseln. In seiner Seitenleiste geht es zurück.", "Passer à l’ancienne présentation du tableau de bord. Sa barre latérale permet de revenir.", "切换到之前设计的仪表盘,可从其侧栏切换回来。", "切換到先前設計的儀表板,可從其側欄切換回來。", "Перейти к прежнему виду панели. Вернуться можно из её боковой панели.", "以前のデザインのダッシュボードに切り替えます。そのサイドバーから戻れます。", "Önceki pano tasarımına geç. Kenar çubuğundan geri dönebilirsin.", "Chuyển sang giao diện bảng điều khiển trước đây. Có thể quay lại từ thanh bên của nó.", "Mudar para o design anterior do painel. A barra lateral dele traz você de volta.", "Cambia al diseño anterior del panel. Desde su barra lateral puedes volver."], + uiCurrent: ["New dashboard", "새 UI로 전환", "Neues Dashboard", "Nouveau tableau de bord", "新版仪表盘", "新版儀表板", "Новая панель", "新しいダッシュボード", "Yeni pano", "Bảng điều khiển mới", "Novo painel", "Panel nuevo"], + uiCurrentHint: ["Switch back to the current dashboard design.", "지금 디자인의 대시보드로 돌아가요.", "Zum aktuellen Dashboard-Design zurückwechseln.", "Revenir à la présentation actuelle du tableau de bord.", "切换回当前设计的仪表盘。", "切換回目前設計的儀表板。", "Вернуться к текущему виду панели.", "現在のデザインのダッシュボードに戻ります。", "Güncel pano tasarımına geri dön.", "Quay lại giao diện bảng điều khiển hiện tại.", "Voltar ao design atual do painel.", "Vuelve al diseño actual del panel."], + uptimeValue: ["{h}h {m}m", "{h}시간 {m}분", "{h} Std. {m} Min.", "{h} h {m} min", "{h} 小时 {m} 分", "{h} 小時 {m} 分", "{h} ч {m} мин", "{h}時間{m}分", "{h} sa {m} dk", "{h} giờ {m} phút", "{h} h {m} min", "{h} h {m} min"], + tileRequests: ["Requests · 7 days", "요청 · 7일", "Anfragen · 7 Tage", "Requêtes · 7 jours", "请求 · 7 天", "請求 · 7 天", "Запросы · 7 дней", "リクエスト · 7日", "İstekler · 7 gün", "Yêu cầu · 7 ngày", "Solicitações · 7 dias", "Solicitudes · 7 días"], + tileTokens: ["Tokens · 7 days", "토큰 · 7일", "Tokens · 7 Tage", "Jetons · 7 jours", "Token · 7 天", "Token · 7 天", "Токены · 7 дней", "トークン · 7日", "Token · 7 gün", "Token · 7 ngày", "Tokens · 7 dias", "Tokens · 7 días"], + tileProviders: ["Providers", "프로바이더", "Anbieter", "Fournisseurs", "提供商", "供應商", "Провайдеры", "プロバイダー", "Sağlayıcılar", "Nhà cung cấp", "Provedores", "Proveedores"], + openLogs: ["Open request log", "요청 기록 보기", "Anfrageprotokoll öffnen", "Ouvrir le journal", "打开请求记录", "開啟請求記錄", "Открыть журнал", "リクエスト履歴を開く", "İstek günlüğünü aç", "Mở nhật ký yêu cầu", "Abrir registro", "Abrir registro de solicitudes"], + checkUpdate: ["Check for updates", "업데이트 확인", "Nach Updates suchen", "Rechercher des mises à jour", "检查更新", "檢查更新", "Проверить обновления", "アップデートを確認", "Güncellemeleri denetle", "Kiểm tra cập nhật", "Verificar atualizações", "Buscar actualizaciones"], + checklistTitle: ["Getting started", "시작하기", "Erste Schritte", "Premiers pas", "开始使用", "開始使用", "Начало работы", "はじめに", "Başlarken", "Bắt đầu", "Primeiros passos", "Primeros pasos"], + checklistProgress: ["{done} of {total} done", "{total}단계 중 {done}단계 완료", "{done} von {total} erledigt", "{done} sur {total} terminées", "已完成 {done}/{total}", "已完成 {done}/{total}", "Готово {done} из {total}", "{total}件中 {done}件完了", "{total} adımdan {done} tamam", "Xong {done}/{total}", "{done} de {total} concluídas", "{done} de {total} completados"], + checklistAllDone: ["All set. opencodex is ready to use.", "준비 끝! 이제 opencodex를 쓰면 돼요.", "Fertig. opencodex ist einsatzbereit.", "Tout est prêt. opencodex est prêt à l’emploi.", "全部完成,opencodex 可以使用了。", "全部完成,opencodex 可以使用了。", "Готово. opencodex можно использовать.", "準備完了。opencodex を使えます。", "Hazır. opencodex kullanıma hazır.", "Xong. opencodex đã sẵn sàng.", "Tudo pronto. O opencodex está pronto para uso.", "Todo listo. OpenCodex está preparado para usarse."], + stepProvider: ["Add a provider", "프로바이더 추가하기", "Anbieter hinzufügen", "Ajouter un fournisseur", "添加提供商", "新增供應商", "Добавить провайдера", "プロバイダーを追加", "Sağlayıcı ekle", "Thêm nhà cung cấp", "Adicionar provedor", "Añade un proveedor"], + stepProviderHint: ["Sign in or paste an API key so opencodex has models to offer.", "로그인하거나 API 키를 넣어서 쓸 수 있는 모델을 만들어요.", "Anmelden oder API-Schlüssel einfügen, damit opencodex Modelle anbieten kann.", "Connectez-vous ou collez une clé API pour qu’opencodex ait des modèles à proposer.", "登录或粘贴 API 密钥,让 opencodex 有模型可用。", "登入或貼上 API 金鑰,讓 opencodex 有模型可用。", "Войдите или вставьте API-ключ, чтобы у opencodex появились модели.", "サインインするか API キーを貼り付けて、使えるモデルを用意します。", "opencodex’in sunacak modeli olması için oturum açın veya API anahtarı yapıştırın.", "Đăng nhập hoặc dán khóa API để opencodex có mô hình để dùng.", "Entre ou cole uma chave de API para o opencodex ter modelos.", "Inicia sesión o pega una clave API para que OpenCodex pueda ofrecer modelos."], + stepFirstRequest: ["Connect your app and send a request", "앱을 연결하고 첫 요청 보내기", "App verbinden und eine Anfrage senden", "Connecter votre app et envoyer une requête", "连接应用并发送第一个请求", "連接應用程式並送出第一個請求", "Подключить приложение и отправить запрос", "アプリを接続して最初のリクエストを送る", "Uygulamanı bağla ve istek gönder", "Kết nối ứng dụng và gửi yêu cầu", "Conectar seu app e enviar uma solicitação", "Conecta tu aplicación y envía una solicitud"], + stepFirstRequestHint: ["Point Codex, Claude Code or another tool at opencodex, then ask it anything.", "Codex나 Claude Code 같은 도구를 opencodex에 연결하고 아무거나 물어보세요.", "Codex, Claude Code oder ein anderes Tool auf opencodex richten und etwas fragen.", "Branchez Codex, Claude Code ou un autre outil sur opencodex, puis posez une question.", "把 Codex、Claude Code 等工具连到 opencodex,然后随便问一句。", "把 Codex、Claude Code 等工具連到 opencodex,然後隨便問一句。", "Направьте Codex, Claude Code или другой инструмент на opencodex и задайте вопрос.", "Codex や Claude Code などを opencodex につなぎ、何か質問してみましょう。", "Codex, Claude Code veya başka bir aracı opencodex’e yönlendirip bir şey sorun.", "Trỏ Codex, Claude Code hoặc công cụ khác tới opencodex rồi hỏi bất cứ điều gì.", "Aponte o Codex, o Claude Code ou outra ferramenta para o opencodex e pergunte algo.", "Conecta Codex, Claude Code u otra herramienta a OpenCodex y pídele algo."], + stepAutostart: ["Start automatically", "자동 시작 켜기", "Automatisch starten", "Démarrer automatiquement", "开机自动启动", "開機自動啟動", "Запускать автоматически", "自動で起動", "Otomatik başlat", "Tự khởi động", "Iniciar automaticamente", "Inicia automáticamente"], + stepAutostartHint: ["Keep opencodex running after a restart so your tools never lose it.", "컴퓨터를 다시 켜도 opencodex가 알아서 켜지게 해요.", "opencodex nach einem Neustart weiterlaufen lassen, damit Tools es nie verlieren.", "Gardez opencodex actif après un redémarrage pour que vos outils ne le perdent jamais.", "重启后 opencodex 仍会运行,工具不会断开。", "重新開機後 opencodex 仍會執行,工具不會斷線。", "opencodex продолжит работать после перезагрузки.", "再起動後も opencodex が動き続けるようにします。", "opencodex yeniden başlatmadan sonra da çalışsın.", "Giữ opencodex chạy sau khi khởi động lại.", "Mantenha o opencodex rodando após reiniciar.", "Mantén OpenCodex en ejecución tras reiniciar el equipo para que tus herramientas sigan conectadas."], + stepAutostartDesktop: ["Turn on Start at Login", "로그인 시 시작 켜기", "Start beim Anmelden einschalten", "Activer le démarrage à la connexion", "开启登录时启动", "開啟登入時啟動", "Включить запуск при входе", "ログイン時の起動をオンにする", "Oturum açılışında başlatmayı aç", "Bật khởi động khi đăng nhập", "Ativar Iniciar no login", "Activa el inicio al iniciar sesión"], + stepAutostartDesktopHint: ["In the OpenCodex app menu, make sure Start at Login is checked. The app then opens when you log in and keeps the proxy running.", "OpenCodex 앱 메뉴에서 '로그인 시 시작'이 켜져 있는지 확인하세요. 로그인할 때 앱이 열리고 프록시도 계속 동작해요.", "Prüfe im Menü der OpenCodex-App, dass „Beim Anmelden starten“ aktiviert ist. Dann öffnet sich die App beim Anmelden und der Proxy läuft weiter.", "Dans le menu de l’app OpenCodex, vérifiez que le démarrage à la connexion est coché. L’app s’ouvre alors à la connexion et le proxy reste actif.", "请在 OpenCodex 应用菜单中确认已勾选“登录时启动”。这样登录时应用会自动打开,代理保持运行。", "請在 OpenCodex 應用程式選單中確認已勾選「登入時啟動」。這樣登入時應用程式會自動開啟,代理持續執行。", "Убедитесь, что в меню приложения OpenCodex отмечен запуск при входе. Тогда приложение откроется при входе, а прокси продолжит работать.", "OpenCodex アプリのメニューで「ログイン時の起動」がオンになっているか確認してください。ログイン時にアプリが開き、プロキシが動き続けます。", "OpenCodex uygulama menüsünde oturum açılışında başlatmanın işaretli olduğundan emin olun. Uygulama oturum açınca açılır ve proxy çalışmaya devam eder.", "Trong menu ứng dụng OpenCodex, hãy bảo đảm đã bật khởi động khi đăng nhập. Ứng dụng sẽ tự mở khi đăng nhập và proxy tiếp tục chạy.", "No menu do app OpenCodex, confirme que Iniciar no login está marcado. Assim o app abre ao entrar e o proxy continua rodando.", "Asegúrate de que la opción para iniciar al iniciar sesión esté marcada en el menú de OpenCodex. Así la aplicación se abre cuando inicias sesión y mantiene el proxy en ejecución."], + stepOpen: ["Open", "열기", "Öffnen", "Ouvrir", "打开", "開啟", "Открыть", "開く", "Aç", "Mở", "Abrir", "Abrir"], + recentErrors: ["Recent errors", "최근 오류", "Letzte Fehler", "Erreurs récentes", "最近的错误", "最近的錯誤", "Недавние ошибки", "最近のエラー", "Son hatalar", "Lỗi gần đây", "Erros recentes", "Errores recientes"], + noErrors: ["No failed requests in the last 24 hours.", "최근 24시간 동안 실패한 요청이 없어요.", "Keine fehlgeschlagenen Anfragen in den letzten 24 Stunden.", "Aucune requête en échec ces dernières 24 h.", "过去 24 小时没有失败的请求。", "過去 24 小時沒有失敗的請求。", "За 24 часа ошибок нет.", "過去24時間に失敗したリクエストはありません。", "Son 24 saatte başarısız istek yok.", "Không có yêu cầu lỗi trong 24 giờ qua.", "Nenhuma falha nas últimas 24 horas.", "No falló ninguna solicitud en las últimas 24 horas."], + viewAll: ["View all", "모두 보기", "Alle anzeigen", "Tout voir", "查看全部", "查看全部", "Показать все", "すべて表示", "Tümünü gör", "Xem tất cả", "Ver tudo", "Ver todos"], // ---- set up hub --------------------------------------------------------------- - setupTitle: ["Set up opencodex", "opencodex 설정하기", "opencodex einrichten", "Configurer opencodex", "设置 opencodex", "設定 opencodex", "Настройка opencodex", "opencodex のセットアップ", "opencodex’i kur", "Thiết lập opencodex", "Configurar o opencodex"], - setupIntro: ["Things you do once when you install opencodex or connect a new tool. Done steps are checked; you can come back any time.", "설치하거나 새 도구를 연결할 때 한 번 하는 일이에요. 끝난 단계는 체크되고, 언제든 다시 와도 돼요.", "Dinge, die du einmal bei der Installation oder beim Verbinden eines neuen Tools erledigst. Erledigte Schritte sind abgehakt.", "Ce que vous faites une fois à l’installation ou pour connecter un nouvel outil. Les étapes terminées sont cochées.", "安装或连接新工具时只需做一次的事情。完成的步骤会打勾,可以随时回来。", "安裝或連接新工具時只需做一次的事。完成的步驟會打勾,可以隨時回來。", "То, что делается один раз при установке или подключении нового инструмента. Готовые шаги отмечены.", "インストール時や新しいツールをつなぐときに一度だけ行う作業です。完了した手順にはチェックが付きます。", "Kurulumda veya yeni bir araç bağlarken bir kez yaptığınız işler. Biten adımlar işaretlenir.", "Những việc làm một lần khi cài đặt hoặc kết nối công cụ mới. Bước đã xong được đánh dấu.", "O que você faz uma vez ao instalar ou conectar uma nova ferramenta. Etapas concluídas ficam marcadas."], - setupApps: ["Connect apps", "앱 연결", "Apps verbinden", "Connecter des apps", "连接应用", "連接應用程式", "Подключить приложения", "アプリを接続", "Uygulamaları bağla", "Kết nối ứng dụng", "Conectar apps"], - setupAppsHint: ["Codex, Claude Code, Claude Desktop, Grok, Cursor and 20+ other tools.", "Codex, Claude Code, Claude Desktop, Grok, Cursor 외 20여 개 도구.", "Codex, Claude Code, Claude Desktop, Grok, Cursor und über 20 weitere Tools.", "Codex, Claude Code, Claude Desktop, Grok, Cursor et plus de 20 autres outils.", "Codex、Claude Code、Claude Desktop、Grok、Cursor 等 20 多个工具。", "Codex、Claude Code、Claude Desktop、Grok、Cursor 等 20 多個工具。", "Codex, Claude Code, Claude Desktop, Grok, Cursor и ещё 20+ инструментов.", "Codex、Claude Code、Claude Desktop、Grok、Cursor ほか 20 以上のツール。", "Codex, Claude Code, Claude Desktop, Grok, Cursor ve 20’den fazla araç.", "Codex, Claude Code, Claude Desktop, Grok, Cursor và hơn 20 công cụ khác.", "Codex, Claude Code, Claude Desktop, Grok, Cursor e mais de 20 ferramentas."], - setupApiKeys: ["API keys for other apps", "다른 앱용 API 키", "API-Schlüssel für andere Apps", "Clés API pour d’autres apps", "给其他应用的 API 密钥", "給其他應用程式的 API 金鑰", "API-ключи для других приложений", "ほかのアプリ用 API キー", "Diğer uygulamalar için API anahtarları", "Khóa API cho ứng dụng khác", "Chaves de API para outros apps"], - setupApiKeysHint: ["Give any OpenAI-compatible app a key and a ready-made config.", "OpenAI 호환 앱에 키와 바로 쓰는 설정을 만들어 줘요.", "Jeder OpenAI-kompatiblen App einen Schlüssel und eine fertige Konfiguration geben.", "Donnez une clé et une config prête à toute app compatible OpenAI.", "为任何兼容 OpenAI 的应用生成密钥和现成配置。", "為任何相容 OpenAI 的應用程式產生金鑰和現成設定。", "Ключ и готовая конфигурация для любого OpenAI-совместимого приложения.", "OpenAI 互換アプリにキーとそのまま使える設定を発行します。", "OpenAI uyumlu her uygulamaya anahtar ve hazır yapılandırma verin.", "Cấp khóa và cấu hình sẵn cho mọi ứng dụng tương thích OpenAI.", "Gere uma chave e uma configuração pronta para qualquer app compatível com OpenAI."], - setupRemote: ["Use from other computers", "다른 컴퓨터에서 쓰기", "Von anderen Computern nutzen", "Utiliser depuis d’autres ordinateurs", "在其他电脑上使用", "在其他電腦上使用", "Использовать с других компьютеров", "ほかのコンピューターから使う", "Diğer bilgisayarlardan kullan", "Dùng từ máy tính khác", "Usar em outros computadores"], - setupRemoteHint: ["Link computers so they share one opencodex.", "여러 컴퓨터가 opencodex 하나를 같이 쓰게 연결해요.", "Computer verbinden, damit sie ein opencodex teilen.", "Reliez des ordinateurs pour partager un seul opencodex.", "连接多台电脑,共用一个 opencodex。", "連接多台電腦,共用一個 opencodex。", "Свяжите компьютеры, чтобы они делили один opencodex.", "複数のコンピューターで1つの opencodex を共有します。", "Bilgisayarları tek bir opencodex’i paylaşacak şekilde bağlayın.", "Liên kết máy tính để dùng chung một opencodex.", "Conecte computadores para compartilhar um único opencodex."], - badgeDone: ["Done", "완료", "Erledigt", "Terminé", "已完成", "已完成", "Готово", "完了", "Tamam", "Xong", "Concluído"], - badgeTodo: ["To do", "할 일", "Offen", "À faire", "待完成", "待完成", "Сделать", "未完了", "Yapılacak", "Cần làm", "Pendente"], - badgeOptional: ["Optional", "선택", "Optional", "Facultatif", "可选", "選用", "Необязательно", "任意", "İsteğe bağlı", "Tùy chọn", "Opcional"], - + setupTitle: ["Set up opencodex", "opencodex 설정하기", "opencodex einrichten", "Configurer opencodex", "设置 opencodex", "設定 opencodex", "Настройка opencodex", "opencodex のセットアップ", "opencodex’i kur", "Thiết lập opencodex", "Configurar o opencodex", "Configura OpenCodex"], + setupIntro: ["Things you do once when you install opencodex or connect a new tool. Done steps are checked; you can come back any time.", "설치하거나 새 도구를 연결할 때 한 번 하는 일이에요. 끝난 단계는 체크되고, 언제든 다시 와도 돼요.", "Dinge, die du einmal bei der Installation oder beim Verbinden eines neuen Tools erledigst. Erledigte Schritte sind abgehakt.", "Ce que vous faites une fois à l’installation ou pour connecter un nouvel outil. Les étapes terminées sont cochées.", "安装或连接新工具时只需做一次的事情。完成的步骤会打勾,可以随时回来。", "安裝或連接新工具時只需做一次的事。完成的步驟會打勾,可以隨時回來。", "То, что делается один раз при установке или подключении нового инструмента. Готовые шаги отмечены.", "インストール時や新しいツールをつなぐときに一度だけ行う作業です。完了した手順にはチェックが付きます。", "Kurulumda veya yeni bir araç bağlarken bir kez yaptığınız işler. Biten adımlar işaretlenir.", "Những việc làm một lần khi cài đặt hoặc kết nối công cụ mới. Bước đã xong được đánh dấu.", "O que você faz uma vez ao instalar ou conectar uma nova ferramenta. Etapas concluídas ficam marcadas.", "Pasos que haces una vez al instalar OpenCodex o conectar una herramienta. Los pasos completados quedan marcados; puedes volver en cualquier momento."], + setupApps: ["Connect apps", "앱 연결", "Apps verbinden", "Connecter des apps", "连接应用", "連接應用程式", "Подключить приложения", "アプリを接続", "Uygulamaları bağla", "Kết nối ứng dụng", "Conectar apps", "Conectar aplicaciones"], + setupAppsHint: ["Codex, Claude Code, Claude Desktop, Grok, Cursor and 20+ other tools.", "Codex, Claude Code, Claude Desktop, Grok, Cursor 외 20여 개 도구.", "Codex, Claude Code, Claude Desktop, Grok, Cursor und über 20 weitere Tools.", "Codex, Claude Code, Claude Desktop, Grok, Cursor et plus de 20 autres outils.", "Codex、Claude Code、Claude Desktop、Grok、Cursor 等 20 多个工具。", "Codex、Claude Code、Claude Desktop、Grok、Cursor 等 20 多個工具。", "Codex, Claude Code, Claude Desktop, Grok, Cursor и ещё 20+ инструментов.", "Codex、Claude Code、Claude Desktop、Grok、Cursor ほか 20 以上のツール。", "Codex, Claude Code, Claude Desktop, Grok, Cursor ve 20’den fazla araç.", "Codex, Claude Code, Claude Desktop, Grok, Cursor và hơn 20 công cụ khác.", "Codex, Claude Code, Claude Desktop, Grok, Cursor e mais de 20 ferramentas.", "Codex, Claude Code, Claude Desktop, Grok, Cursor y más de 20 herramientas."], + setupApiKeys: ["API keys for other apps", "다른 앱용 API 키", "API-Schlüssel für andere Apps", "Clés API pour d’autres apps", "给其他应用的 API 密钥", "給其他應用程式的 API 金鑰", "API-ключи для других приложений", "ほかのアプリ用 API キー", "Diğer uygulamalar için API anahtarları", "Khóa API cho ứng dụng khác", "Chaves de API para outros apps", "Claves API para otras aplicaciones"], + setupApiKeysHint: ["Give any OpenAI-compatible app a key and a ready-made config.", "OpenAI 호환 앱에 키와 바로 쓰는 설정을 만들어 줘요.", "Jeder OpenAI-kompatiblen App einen Schlüssel und eine fertige Konfiguration geben.", "Donnez une clé et une config prête à toute app compatible OpenAI.", "为任何兼容 OpenAI 的应用生成密钥和现成配置。", "為任何相容 OpenAI 的應用程式產生金鑰和現成設定。", "Ключ и готовая конфигурация для любого OpenAI-совместимого приложения.", "OpenAI 互換アプリにキーとそのまま使える設定を発行します。", "OpenAI uyumlu her uygulamaya anahtar ve hazır yapılandırma verin.", "Cấp khóa và cấu hình sẵn cho mọi ứng dụng tương thích OpenAI.", "Gere uma chave e uma configuração pronta para qualquer app compatível com OpenAI.", "Da una clave y una configuración lista para usar a cualquier aplicación compatible con OpenAI."], + setupRemote: ["Use from other computers", "다른 컴퓨터에서 쓰기", "Von anderen Computern nutzen", "Utiliser depuis d’autres ordinateurs", "在其他电脑上使用", "在其他電腦上使用", "Использовать с других компьютеров", "ほかのコンピューターから使う", "Diğer bilgisayarlardan kullan", "Dùng từ máy tính khác", "Usar em outros computadores", "Usar desde otros equipos"], + setupRemoteHint: ["Link computers so they share one opencodex.", "여러 컴퓨터가 opencodex 하나를 같이 쓰게 연결해요.", "Computer verbinden, damit sie ein opencodex teilen.", "Reliez des ordinateurs pour partager un seul opencodex.", "连接多台电脑,共用一个 opencodex。", "連接多台電腦,共用一個 opencodex。", "Свяжите компьютеры, чтобы они делили один opencodex.", "複数のコンピューターで1つの opencodex を共有します。", "Bilgisayarları tek bir opencodex’i paylaşacak şekilde bağlayın.", "Liên kết máy tính để dùng chung một opencodex.", "Conecte computadores para compartilhar um único opencodex.", "Enlaza equipos para compartir una instancia de OpenCodex."], + badgeDone: ["Done", "완료", "Erledigt", "Terminé", "已完成", "已完成", "Готово", "完了", "Tamam", "Xong", "Concluído", "Hecho"], + badgeTodo: ["To do", "할 일", "Offen", "À faire", "待完成", "待完成", "Сделать", "未完了", "Yapılacak", "Cần làm", "Pendente", "Pendiente"], + badgeOptional: ["Optional", "선택", "Optional", "Facultatif", "可选", "選用", "Необязательно", "任意", "İsteğe bağlı", "Tùy chọn", "Opcional", "Opcional"], // ---- advanced hub --------------------------------------------------------------- - advancedTitle: ["Advanced settings", "고급 설정", "Erweiterte Einstellungen", "Réglages avancés", "高级设置", "進階設定", "Расширенные настройки", "詳細設定", "Gelişmiş ayarlar", "Cài đặt nâng cao", "Configurações avançadas"], - advancedIntro: ["Settings most people never need to change. Each card says what it does and when you might want it.", "대부분은 바꿀 일이 없는 설정이에요. 카드마다 무엇을 하는지, 언제 바꾸면 좋은지 적어 뒀어요.", "Einstellungen, die die meisten nie ändern müssen. Jede Karte sagt, was sie tut und wann sie nützt.", "Des réglages que la plupart ne touchent jamais. Chaque carte explique ce qu’elle fait et quand l’utiliser.", "大多数人不需要改动的设置。每张卡片说明它的作用以及何时需要。", "大多數人不需要改動的設定。每張卡片說明它的作用以及何時需要。", "Настройки, которые обычно не нужно менять. На каждой карточке — что она делает и когда пригодится.", "多くの人は変更する必要のない設定です。各カードに内容と使いどころを書いています。", "Çoğu kişinin hiç değiştirmesi gerekmeyen ayarlar. Her kart ne yaptığını ve ne zaman işe yarayacağını söyler.", "Thiết lập hầu hết mọi người không cần đổi. Mỗi thẻ cho biết chức năng và khi nào nên dùng.", "Configurações que a maioria nunca precisa mudar. Cada cartão diz o que faz e quando usar."], - advancedSearch: ["Search settings…", "설정 검색…", "Einstellungen suchen…", "Rechercher un réglage…", "搜索设置…", "搜尋設定…", "Поиск настроек…", "設定を検索…", "Ayarlarda ara…", "Tìm cài đặt…", "Buscar configurações…"], - advancedEmpty: ["No setting matches that search.", "검색과 맞는 설정이 없어요.", "Keine Einstellung passt zur Suche.", "Aucun réglage ne correspond.", "没有匹配的设置。", "沒有符合的設定。", "Ничего не найдено.", "一致する設定はありません。", "Aramayla eşleşen ayar yok.", "Không có cài đặt phù hợp.", "Nenhuma configuração encontrada."], - advancedWhen: ["When to change", "언제 바꾸나요", "Wann ändern", "Quand le modifier", "何时修改", "何時修改", "Когда менять", "変更するとき", "Ne zaman değiştirilir", "Khi nào nên đổi", "Quando mudar"], - proxyUptime: ["Up {time}", "켜진 지 {time}", "Läuft seit {time}", "Actif depuis {time}", "已运行 {time}", "已執行 {time}", "Работает {time}", "稼働 {time}", "{time} çalışıyor", "Đã chạy {time}", "Ativo há {time}"], - themeCycle: ["Theme: {mode}. Click for {next}", "테마: {mode} · 누르면 {next}", "Design: {mode}. Klicken für {next}", "Thème : {mode}. Cliquer pour {next}", "主题:{mode},点击切换为{next}", "主題:{mode},點擊切換為{next}", "Тема: {mode}. Нажмите для: {next}", "テーマ:{mode}(クリックで{next})", "Tema: {mode}. {next} için tıklayın", "Giao diện: {mode}. Nhấn để chuyển sang {next}", "Tema: {mode}. Clique para {next}"], - advSubagents: ["Helper agents", "도우미 에이전트", "Hilfsagenten", "Agents auxiliaires", "辅助智能体", "輔助代理", "Вспомогательные агенты", "補助エージェント", "Yardımcı ajanlar", "Tác tử phụ", "Agentes auxiliares"], - advSubagentsWhen: ["You want Codex to hand side tasks to a cheaper or faster model.", "Codex가 곁가지 일을 더 싸거나 빠른 모델에 맡기게 하고 싶을 때.", "Codex soll Nebenaufgaben an ein günstigeres oder schnelleres Modell abgeben.", "Vous voulez que Codex confie des tâches annexes à un modèle moins cher ou plus rapide.", "希望 Codex 把旁支任务交给更便宜或更快的模型时。", "希望 Codex 把旁支任務交給更便宜或更快的模型時。", "Нужно, чтобы Codex отдавал побочные задачи более дешёвой или быстрой модели.", "Codex に脇のタスクを安い・速いモデルへ任せたいとき。", "Codex’in yan görevleri daha ucuz veya hızlı bir modele vermesini istediğinizde.", "Muốn Codex giao việc phụ cho mô hình rẻ hoặc nhanh hơn.", "Quando quer que o Codex passe tarefas paralelas a um modelo mais barato ou rápido."], - advAdvisor: ["Expert advisor", "전문가 상담", "Experten-Berater", "Conseiller expert", "专家顾问", "專家顧問", "Эксперт-советник", "エキスパート相談", "Uzman danışman", "Cố vấn chuyên gia", "Consultor especialista"], - advAdvisorWhen: ["You want a stronger model consulted on hard steps.", "어려운 단계에서 더 강한 모델에게 물어보게 하고 싶을 때.", "Bei schwierigen Schritten soll ein stärkeres Modell befragt werden.", "Vous voulez consulter un modèle plus fort sur les étapes difficiles.", "希望在困难步骤咨询更强的模型时。", "希望在困難步驟諮詢更強的模型時。", "Нужно советоваться с более сильной моделью на сложных шагах.", "難しい場面でより強いモデルに相談させたいとき。", "Zor adımlarda daha güçlü bir modele danışılmasını istediğinizde.", "Muốn hỏi mô hình mạnh hơn ở bước khó.", "Quando quer consultar um modelo mais forte em etapas difíceis."], - advProxy: ["Proxy details", "프록시 세부 설정", "Proxy-Details", "Détails du proxy", "代理详细设置", "代理詳細設定", "Детали прокси", "プロキシの詳細設定", "Proxy ayrıntıları", "Chi tiết proxy", "Detalhes do proxy"], - advProxyWhen: ["Web search and image helpers, long-chat summaries, memory, updates and more.", "웹 검색·이미지 도우미, 긴 대화 요약, 메모리, 업데이트 등.", "Websuche- und Bildhelfer, Zusammenfassungen langer Chats, Speicher, Updates und mehr.", "Aides recherche web et image, résumés des longues discussions, mémoire, mises à jour…", "网页搜索与图片助手、长对话摘要、记忆、更新等。", "網頁搜尋與圖片助手、長對話摘要、記憶、更新等。", "Помощники для поиска и изображений, сводки длинных чатов, память, обновления и другое.", "Web 検索・画像ヘルパー、長い会話の要約、メモリ、アップデートなど。", "Web arama ve görsel yardımcıları, uzun sohbet özetleri, bellek, güncellemeler ve daha fazlası.", "Trợ lý tìm kiếm web và hình ảnh, tóm tắt hội thoại dài, bộ nhớ, cập nhật…", "Ajudantes de busca e imagem, resumos de conversas longas, memória, atualizações e mais."], - advRouting: ["Automatic model choice", "자동 모델 선택", "Automatische Modellwahl", "Choix automatique du modèle", "自动选择模型", "自動選擇模型", "Автовыбор модели", "モデルの自動選択", "Otomatik model seçimi", "Tự chọn mô hình", "Escolha automática de modelo"], - advRoutingWhen: ["You want requests sent to whichever model fits best, with test results to back it.", "요청마다 가장 잘 맞는 모델을 시험 결과를 근거로 고르게 하고 싶을 때.", "Anfragen sollen an das jeweils passendste Modell gehen, gestützt auf Testergebnisse.", "Vous voulez envoyer chaque requête au modèle le mieux adapté, preuves à l’appui.", "希望根据测试结果把请求发给最合适的模型时。", "希望依測試結果把請求送給最合適的模型時。", "Нужно отправлять запросы самой подходящей модели по результатам тестов.", "テスト結果をもとに最適なモデルへ振り分けたいとき。", "İstekleri test sonuçlarına göre en uygun modele göndermek istediğinizde.", "Muốn gửi yêu cầu tới mô hình phù hợp nhất dựa trên kết quả kiểm thử.", "Quando quer enviar cada pedido ao modelo mais adequado, com base em testes."], - advPrompt: ["Codex prompt sections", "Codex 프롬프트 구성", "Codex-Prompt-Abschnitte", "Sections du prompt Codex", "Codex 提示词分段", "Codex 提示詞分段", "Разделы промпта Codex", "Codex プロンプト構成", "Codex istem bölümleri", "Các phần prompt Codex", "Seções do prompt do Codex"], - advPromptWhen: ["You want to add or turn off instructions Codex sends with every task.", "Codex가 매번 보내는 지시문을 추가하거나 끄고 싶을 때.", "Anweisungen hinzufügen oder abschalten, die Codex bei jeder Aufgabe sendet.", "Ajouter ou couper des instructions que Codex envoie à chaque tâche.", "想添加或关闭 Codex 每次都会发送的指令时。", "想新增或關閉 Codex 每次都會送出的指令時。", "Нужно добавить или отключить инструкции, которые Codex отправляет с каждой задачей.", "Codex が毎回送る指示を追加・オフにしたいとき。", "Codex’in her görevle gönderdiği talimatları eklemek veya kapatmak istediğinizde.", "Muốn thêm hoặc tắt chỉ dẫn Codex gửi kèm mỗi tác vụ.", "Quando quer adicionar ou desligar instruções que o Codex envia em cada tarefa."], - advClaude: ["Claude Code details", "Claude Code 세부 설정", "Claude-Code-Details", "Détails de Claude Code", "Claude Code 详细设置", "Claude Code 詳細設定", "Детали Claude Code", "Claude Code の詳細", "Claude Code ayrıntıları", "Chi tiết Claude Code", "Detalhes do Claude Code"], - advClaudeWhen: ["You want to pick default models per tier or swap models by rule.", "등급별 기본 모델을 정하거나 규칙대로 모델을 바꾸고 싶을 때.", "Standardmodelle pro Stufe wählen oder Modelle per Regel tauschen.", "Choisir les modèles par défaut par niveau ou remplacer des modèles par règle.", "想按档位设定默认模型或按规则替换模型时。", "想依等級設定預設模型或按規則替換模型時。", "Нужно выбрать модели по уровням или подменять модели по правилам.", "ティアごとの既定モデルを選ぶ・ルールで置き換えたいとき。", "Katmana göre varsayılan model seçmek veya kurala göre değiştirmek istediğinizde.", "Muốn chọn mô hình mặc định theo cấp hoặc đổi mô hình theo quy tắc.", "Quando quer escolher modelos padrão por nível ou trocar modelos por regra."], - advProviders: ["Provider details", "프로바이더 세부 설정", "Anbieter-Details", "Détails des fournisseurs", "提供商详细设置", "供應商詳細設定", "Детали провайдеров", "プロバイダーの詳細", "Sağlayıcı ayrıntıları", "Chi tiết nhà cung cấp", "Detalhes dos provedores"], - advProvidersWhen: ["You hit rate limits or need to change an endpoint, key rotation or API format.", "속도 제한에 걸리거나 주소·키 순환·API 형식을 바꿔야 할 때.", "Bei Ratenlimits oder um Endpunkt, Schlüsselrotation oder API-Format zu ändern.", "En cas de limite de débit ou pour changer l’URL, la rotation de clés ou le format d’API.", "遇到速率限制,或需要改地址、密钥轮换、API 格式时。", "遇到速率限制,或需要改位址、金鑰輪換、API 格式時。", "При лимитах скорости или чтобы сменить адрес, ротацию ключей или формат API.", "レート制限にかかったとき、またはエンドポイント・キーの切替・API 形式を変えるとき。", "Hız sınırına takıldığınızda veya uç nokta, anahtar dönüşümü ya da API biçimini değiştirmeniz gerektiğinde.", "Khi gặp giới hạn tốc độ hoặc cần đổi địa chỉ, xoay vòng khóa, định dạng API.", "Quando atinge limites de taxa ou precisa mudar endereço, rotação de chaves ou formato da API."], - advStorage: ["Disk space", "저장 공간", "Speicherplatz", "Espace disque", "磁盘空间", "磁碟空間", "Место на диске", "ディスク容量", "Disk alanı", "Dung lượng đĩa", "Espaço em disco"], - advStorageWhen: ["Codex data is taking too much space and you want it cleaned up automatically.", "Codex 데이터가 공간을 너무 차지해서 자동으로 정리하고 싶을 때.", "Codex-Daten belegen zu viel Platz und sollen automatisch aufgeräumt werden.", "Les données de Codex prennent trop de place et vous voulez un nettoyage automatique.", "Codex 数据占用空间太多,想自动清理时。", "Codex 資料佔用空間太多,想自動清理時。", "Данные Codex занимают много места и нужна автоочистка.", "Codex のデータが容量を圧迫していて自動で整理したいとき。", "Codex verileri çok yer kaplıyor ve otomatik temizlemek istiyorsanız.", "Dữ liệu Codex chiếm nhiều chỗ và muốn tự dọn dẹp.", "Quando os dados do Codex ocupam espaço demais e quer limpeza automática."], - advDiagnostics: ["Diagnostics", "진단 로그", "Diagnose", "Diagnostic", "诊断日志", "診斷日誌", "Диагностика", "診断ログ", "Tanılama", "Chẩn đoán", "Diagnóstico"], - advDiagnosticsWhen: ["Something misbehaves and you need detailed logs to report it.", "뭔가 이상하고 신고하려면 자세한 로그가 필요할 때.", "Etwas läuft falsch und du brauchst detaillierte Protokolle für eine Meldung.", "Quelque chose cloche et il vous faut des journaux détaillés pour le signaler.", "出现异常、需要详细日志来报告问题时。", "出現異常、需要詳細日誌回報問題時。", "Что-то работает не так и для отчёта нужны подробные логи.", "不具合があり、報告のために詳しいログが必要なとき。", "Bir şey ters gidiyor ve bildirmek için ayrıntılı günlük gerekiyorsa.", "Có lỗi và cần nhật ký chi tiết để báo cáo.", "Algo está errado e você precisa de registros detalhados para relatar."], - advDesktopCompat: ["Codex Desktop fix (experimental)", "Codex 데스크톱 호환 (실험)", "Codex-Desktop-Korrektur (experimentell)", "Correctif Codex Desktop (expérimental)", "Codex 桌面修复(实验)", "Codex 桌面修正(實驗)", "Исправление Codex Desktop (эксперимент)", "Codex デスクトップ修正(試験的)", "Codex Desktop düzeltmesi (deneysel)", "Sửa Codex Desktop (thử nghiệm)", "Correção do Codex Desktop (experimental)"], - advDesktopCompatWhen: ["Windows only: the Codex app stops letting you type after a usage limit.", "Windows 전용: 사용량 한도 뒤에 Codex 앱 입력이 막힐 때.", "Nur Windows: Die Codex-App lässt nach einem Nutzungslimit keine Eingabe mehr zu.", "Windows uniquement : l’app Codex bloque la saisie après une limite d’usage.", "仅 Windows:用量上限后 Codex 应用无法输入时。", "僅 Windows:用量上限後 Codex 應用程式無法輸入時。", "Только Windows: после лимита приложение Codex не даёт вводить текст.", "Windows のみ:使用上限のあと Codex アプリに入力できなくなるとき。", "Yalnızca Windows: Kullanım sınırından sonra Codex uygulaması yazmaya izin vermiyorsa.", "Chỉ Windows: ứng dụng Codex không cho nhập sau khi hết hạn mức.", "Apenas Windows: o app do Codex deixa de aceitar digitação após um limite de uso."], + advancedTitle: ["Advanced settings", "고급 설정", "Erweiterte Einstellungen", "Réglages avancés", "高级设置", "進階設定", "Расширенные настройки", "詳細設定", "Gelişmiş ayarlar", "Cài đặt nâng cao", "Configurações avançadas", "Configuración avanzada"], + advancedIntro: ["Settings most people never need to change. Each card says what it does and when you might want it.", "대부분은 바꿀 일이 없는 설정이에요. 카드마다 무엇을 하는지, 언제 바꾸면 좋은지 적어 뒀어요.", "Einstellungen, die die meisten nie ändern müssen. Jede Karte sagt, was sie tut und wann sie nützt.", "Des réglages que la plupart ne touchent jamais. Chaque carte explique ce qu’elle fait et quand l’utiliser.", "大多数人不需要改动的设置。每张卡片说明它的作用以及何时需要。", "大多數人不需要改動的設定。每張卡片說明它的作用以及何時需要。", "Настройки, которые обычно не нужно менять. На каждой карточке — что она делает и когда пригодится.", "多くの人は変更する必要のない設定です。各カードに内容と使いどころを書いています。", "Çoğu kişinin hiç değiştirmesi gerekmeyen ayarlar. Her kart ne yaptığını ve ne zaman işe yarayacağını söyler.", "Thiết lập hầu hết mọi người không cần đổi. Mỗi thẻ cho biết chức năng và khi nào nên dùng.", "Configurações que a maioria nunca precisa mudar. Cada cartão diz o que faz e quando usar.", "Ajustes que rara vez necesitas cambiar. Cada tarjeta explica qué hace y cuándo conviene ajustarla."], + advancedSearch: ["Search settings…", "설정 검색…", "Einstellungen suchen…", "Rechercher un réglage…", "搜索设置…", "搜尋設定…", "Поиск настроек…", "設定を検索…", "Ayarlarda ara…", "Tìm cài đặt…", "Buscar configurações…", "Buscar configuración…"], + advancedEmpty: ["No setting matches that search.", "검색과 맞는 설정이 없어요.", "Keine Einstellung passt zur Suche.", "Aucun réglage ne correspond.", "没有匹配的设置。", "沒有符合的設定。", "Ничего не найдено.", "一致する設定はありません。", "Aramayla eşleşen ayar yok.", "Không có cài đặt phù hợp.", "Nenhuma configuração encontrada.", "Ningún ajuste coincide con la búsqueda."], + advancedWhen: ["When to change", "언제 바꾸나요", "Wann ändern", "Quand le modifier", "何时修改", "何時修改", "Когда менять", "変更するとき", "Ne zaman değiştirilir", "Khi nào nên đổi", "Quando mudar", "Cuándo cambiarlo"], + proxyUptime: ["Up {time}", "켜진 지 {time}", "Läuft seit {time}", "Actif depuis {time}", "已运行 {time}", "已執行 {time}", "Работает {time}", "稼働 {time}", "{time} çalışıyor", "Đã chạy {time}", "Ativo há {time}", "Activo desde hace {time}"], + themeCycle: ["Theme: {mode}. Click for {next}", "테마: {mode} · 누르면 {next}", "Design: {mode}. Klicken für {next}", "Thème : {mode}. Cliquer pour {next}", "主题:{mode},点击切换为{next}", "主題:{mode},點擊切換為{next}", "Тема: {mode}. Нажмите для: {next}", "テーマ:{mode}(クリックで{next})", "Tema: {mode}. {next} için tıklayın", "Giao diện: {mode}. Nhấn để chuyển sang {next}", "Tema: {mode}. Clique para {next}", "Tema: {mode}. Haz clic para cambiar a {next}."], + advSubagents: ["Helper agents", "도우미 에이전트", "Hilfsagenten", "Agents auxiliaires", "辅助智能体", "輔助代理", "Вспомогательные агенты", "補助エージェント", "Yardımcı ajanlar", "Tác tử phụ", "Agentes auxiliares", "Subagentes"], + advSubagentsWhen: ["You want Codex to hand side tasks to a cheaper or faster model.", "Codex가 곁가지 일을 더 싸거나 빠른 모델에 맡기게 하고 싶을 때.", "Codex soll Nebenaufgaben an ein günstigeres oder schnelleres Modell abgeben.", "Vous voulez que Codex confie des tâches annexes à un modèle moins cher ou plus rapide.", "希望 Codex 把旁支任务交给更便宜或更快的模型时。", "希望 Codex 把旁支任務交給更便宜或更快的模型時。", "Нужно, чтобы Codex отдавал побочные задачи более дешёвой или быстрой модели.", "Codex に脇のタスクを安い・速いモデルへ任せたいとき。", "Codex’in yan görevleri daha ucuz veya hızlı bir modele vermesini istediğinizde.", "Muốn Codex giao việc phụ cho mô hình rẻ hoặc nhanh hơn.", "Quando quer que o Codex passe tarefas paralelas a um modelo mais barato ou rápido.", "Quieres que Codex delegue tareas secundarias a un modelo más económico o rápido."], + advAdvisor: ["Expert advisor", "전문가 상담", "Experten-Berater", "Conseiller expert", "专家顾问", "專家顧問", "Эксперт-советник", "エキスパート相談", "Uzman danışman", "Cố vấn chuyên gia", "Consultor especialista", "Asesor experto"], + advAdvisorWhen: ["You want a stronger model consulted on hard steps.", "어려운 단계에서 더 강한 모델에게 물어보게 하고 싶을 때.", "Bei schwierigen Schritten soll ein stärkeres Modell befragt werden.", "Vous voulez consulter un modèle plus fort sur les étapes difficiles.", "希望在困难步骤咨询更强的模型时。", "希望在困難步驟諮詢更強的模型時。", "Нужно советоваться с более сильной моделью на сложных шагах.", "難しい場面でより強いモデルに相談させたいとき。", "Zor adımlarda daha güçlü bir modele danışılmasını istediğinizde.", "Muốn hỏi mô hình mạnh hơn ở bước khó.", "Quando quer consultar um modelo mais forte em etapas difíceis.", "Quieres consultar un modelo más capaz en pasos difíciles."], + advProxy: ["Proxy details", "프록시 세부 설정", "Proxy-Details", "Détails du proxy", "代理详细设置", "代理詳細設定", "Детали прокси", "プロキシの詳細設定", "Proxy ayrıntıları", "Chi tiết proxy", "Detalhes do proxy", "Detalles del proxy"], + advProxyWhen: ["Web search and image helpers, long-chat summaries, memory, updates and more.", "웹 검색·이미지 도우미, 긴 대화 요약, 메모리, 업데이트 등.", "Websuche- und Bildhelfer, Zusammenfassungen langer Chats, Speicher, Updates und mehr.", "Aides recherche web et image, résumés des longues discussions, mémoire, mises à jour…", "网页搜索与图片助手、长对话摘要、记忆、更新等。", "網頁搜尋與圖片助手、長對話摘要、記憶、更新等。", "Помощники для поиска и изображений, сводки длинных чатов, память, обновления и другое.", "Web 検索・画像ヘルパー、長い会話の要約、メモリ、アップデートなど。", "Web arama ve görsel yardımcıları, uzun sohbet özetleri, bellek, güncellemeler ve daha fazlası.", "Trợ lý tìm kiếm web và hình ảnh, tóm tắt hội thoại dài, bộ nhớ, cập nhật…", "Ajudantes de busca e imagem, resumos de conversas longas, memória, atualizações e mais.", "Búsqueda web, asistentes de imagen, resúmenes de conversaciones largas, memoria, actualizaciones y más."], + advRouting: ["Automatic model choice", "자동 모델 선택", "Automatische Modellwahl", "Choix automatique du modèle", "自动选择模型", "自動選擇模型", "Автовыбор модели", "モデルの自動選択", "Otomatik model seçimi", "Tự chọn mô hình", "Escolha automática de modelo", "Selección automática de modelos"], + advRoutingWhen: ["You want requests sent to whichever model fits best, with test results to back it.", "요청마다 가장 잘 맞는 모델을 시험 결과를 근거로 고르게 하고 싶을 때.", "Anfragen sollen an das jeweils passendste Modell gehen, gestützt auf Testergebnisse.", "Vous voulez envoyer chaque requête au modèle le mieux adapté, preuves à l’appui.", "希望根据测试结果把请求发给最合适的模型时。", "希望依測試結果把請求送給最合適的模型時。", "Нужно отправлять запросы самой подходящей модели по результатам тестов.", "テスト結果をもとに最適なモデルへ振り分けたいとき。", "İstekleri test sonuçlarına göre en uygun modele göndermek istediğinizde.", "Muốn gửi yêu cầu tới mô hình phù hợp nhất dựa trên kết quả kiểm thử.", "Quando quer enviar cada pedido ao modelo mais adequado, com base em testes.", "Quieres enviar las solicitudes al modelo más adecuado, con resultados de pruebas como respaldo."], + advPrompt: ["Codex prompt sections", "Codex 프롬프트 구성", "Codex-Prompt-Abschnitte", "Sections du prompt Codex", "Codex 提示词分段", "Codex 提示詞分段", "Разделы промпта Codex", "Codex プロンプト構成", "Codex istem bölümleri", "Các phần prompt Codex", "Seções do prompt do Codex", "Secciones del prompt de Codex"], + advPromptWhen: ["You want to add or turn off instructions Codex sends with every task.", "Codex가 매번 보내는 지시문을 추가하거나 끄고 싶을 때.", "Anweisungen hinzufügen oder abschalten, die Codex bei jeder Aufgabe sendet.", "Ajouter ou couper des instructions que Codex envoie à chaque tâche.", "想添加或关闭 Codex 每次都会发送的指令时。", "想新增或關閉 Codex 每次都會送出的指令時。", "Нужно добавить или отключить инструкции, которые Codex отправляет с каждой задачей.", "Codex が毎回送る指示を追加・オフにしたいとき。", "Codex’in her görevle gönderdiği talimatları eklemek veya kapatmak istediğinizde.", "Muốn thêm hoặc tắt chỉ dẫn Codex gửi kèm mỗi tác vụ.", "Quando quer adicionar ou desligar instruções que o Codex envia em cada tarefa.", "Quieres añadir o desactivar instrucciones que Codex envía con cada tarea."], + advClaude: ["Claude Code details", "Claude Code 세부 설정", "Claude-Code-Details", "Détails de Claude Code", "Claude Code 详细设置", "Claude Code 詳細設定", "Детали Claude Code", "Claude Code の詳細", "Claude Code ayrıntıları", "Chi tiết Claude Code", "Detalhes do Claude Code", "Detalles de Claude Code"], + advClaudeWhen: ["You want to pick default models per tier or swap models by rule.", "등급별 기본 모델을 정하거나 규칙대로 모델을 바꾸고 싶을 때.", "Standardmodelle pro Stufe wählen oder Modelle per Regel tauschen.", "Choisir les modèles par défaut par niveau ou remplacer des modèles par règle.", "想按档位设定默认模型或按规则替换模型时。", "想依等級設定預設模型或按規則替換模型時。", "Нужно выбрать модели по уровням или подменять модели по правилам.", "ティアごとの既定モデルを選ぶ・ルールで置き換えたいとき。", "Katmana göre varsayılan model seçmek veya kurala göre değiştirmek istediğinizde.", "Muốn chọn mô hình mặc định theo cấp hoặc đổi mô hình theo quy tắc.", "Quando quer escolher modelos padrão por nível ou trocar modelos por regra.", "Quieres elegir modelos predeterminados por nivel o sustituirlos mediante reglas."], + advProviders: ["Provider details", "프로바이더 세부 설정", "Anbieter-Details", "Détails des fournisseurs", "提供商详细设置", "供應商詳細設定", "Детали провайдеров", "プロバイダーの詳細", "Sağlayıcı ayrıntıları", "Chi tiết nhà cung cấp", "Detalhes dos provedores", "Detalles del proveedor"], + advProvidersWhen: ["You hit rate limits or need to change an endpoint, key rotation or API format.", "속도 제한에 걸리거나 주소·키 순환·API 형식을 바꿔야 할 때.", "Bei Ratenlimits oder um Endpunkt, Schlüsselrotation oder API-Format zu ändern.", "En cas de limite de débit ou pour changer l’URL, la rotation de clés ou le format d’API.", "遇到速率限制,或需要改地址、密钥轮换、API 格式时。", "遇到速率限制,或需要改位址、金鑰輪換、API 格式時。", "При лимитах скорости или чтобы сменить адрес, ротацию ключей или формат API.", "レート制限にかかったとき、またはエンドポイント・キーの切替・API 形式を変えるとき。", "Hız sınırına takıldığınızda veya uç nokta, anahtar dönüşümü ya da API biçimini değiştirmeniz gerektiğinde.", "Khi gặp giới hạn tốc độ hoặc cần đổi địa chỉ, xoay vòng khóa, định dạng API.", "Quando atinge limites de taxa ou precisa mudar endereço, rotação de chaves ou formato da API.", "Alcanzaste límites de solicitudes o necesitas cambiar un endpoint, la rotación de claves o el formato de la API."], + advStorage: ["Disk space", "저장 공간", "Speicherplatz", "Espace disque", "磁盘空间", "磁碟空間", "Место на диске", "ディスク容量", "Disk alanı", "Dung lượng đĩa", "Espaço em disco", "Espacio en disco"], + advStorageWhen: ["Codex data is taking too much space and you want it cleaned up automatically.", "Codex 데이터가 공간을 너무 차지해서 자동으로 정리하고 싶을 때.", "Codex-Daten belegen zu viel Platz und sollen automatisch aufgeräumt werden.", "Les données de Codex prennent trop de place et vous voulez un nettoyage automatique.", "Codex 数据占用空间太多,想自动清理时。", "Codex 資料佔用空間太多,想自動清理時。", "Данные Codex занимают много места и нужна автоочистка.", "Codex のデータが容量を圧迫していて自動で整理したいとき。", "Codex verileri çok yer kaplıyor ve otomatik temizlemek istiyorsanız.", "Dữ liệu Codex chiếm nhiều chỗ và muốn tự dọn dẹp.", "Quando os dados do Codex ocupam espaço demais e quer limpeza automática.", "Los datos de Codex ocupan demasiado espacio y quieres limpiarlos automáticamente."], + advDiagnostics: ["Diagnostics", "진단 로그", "Diagnose", "Diagnostic", "诊断日志", "診斷日誌", "Диагностика", "診断ログ", "Tanılama", "Chẩn đoán", "Diagnóstico", "Diagnóstico"], + advDiagnosticsWhen: ["Something misbehaves and you need detailed logs to report it.", "뭔가 이상하고 신고하려면 자세한 로그가 필요할 때.", "Etwas läuft falsch und du brauchst detaillierte Protokolle für eine Meldung.", "Quelque chose cloche et il vous faut des journaux détaillés pour le signaler.", "出现异常、需要详细日志来报告问题时。", "出現異常、需要詳細日誌回報問題時。", "Что-то работает не так и для отчёта нужны подробные логи.", "不具合があり、報告のために詳しいログが必要なとき。", "Bir şey ters gidiyor ve bildirmek için ayrıntılı günlük gerekiyorsa.", "Có lỗi và cần nhật ký chi tiết để báo cáo.", "Algo está errado e você precisa de registros detalhados para relatar.", "Algo falla y necesitas registros detallados para informarlo."], + advDesktopCompat: ["Codex Desktop fix (experimental)", "Codex 데스크톱 호환 (실험)", "Codex-Desktop-Korrektur (experimentell)", "Correctif Codex Desktop (expérimental)", "Codex 桌面修复(实验)", "Codex 桌面修正(實驗)", "Исправление Codex Desktop (эксперимент)", "Codex デスクトップ修正(試験的)", "Codex Desktop düzeltmesi (deneysel)", "Sửa Codex Desktop (thử nghiệm)", "Correção do Codex Desktop (experimental)", "Corrección para Codex Desktop (experimental)"], + advDesktopCompatWhen: ["Windows only: the Codex app stops letting you type after a usage limit.", "Windows 전용: 사용량 한도 뒤에 Codex 앱 입력이 막힐 때.", "Nur Windows: Die Codex-App lässt nach einem Nutzungslimit keine Eingabe mehr zu.", "Windows uniquement : l’app Codex bloque la saisie après une limite d’usage.", "仅 Windows:用量上限后 Codex 应用无法输入时。", "僅 Windows:用量上限後 Codex 應用程式無法輸入時。", "Только Windows: после лимита приложение Codex не даёт вводить текст.", "Windows のみ:使用上限のあと Codex アプリに入力できなくなるとき。", "Yalnızca Windows: Kullanım sınırından sonra Codex uygulaması yazmaya izin vermiyorsa.", "Chỉ Windows: ứng dụng Codex không cho nhập sau khi hết hạn mức.", "Apenas Windows: o app do Codex deixa de aceitar digitação após um limite de uso.", "Solo Windows: Codex deja de permitirte escribir después de alcanzar un límite de uso."], } satisfies Record; export type ShellV2Key = `shellV2.${keyof typeof rows}`; diff --git a/gui/src/i18n/v2-pages/accounts-copy.ts b/gui/src/i18n/v2-pages/accounts-copy.ts index 3e725d0ea9b..bacecd55d10 100644 --- a/gui/src/i18n/v2-pages/accounts-copy.ts +++ b/gui/src/i18n/v2-pages/accounts-copy.ts @@ -1,11 +1,11 @@ import { copyTable, type Row } from "./copy-table"; /* - * Copy for the v2 Accounts & limits (Codex Set, Providers) page. Columns: en, ko, de, fr, zh, zh-TW, ru, ja, tr, vi, pt. + * Copy for the v2 Accounts & limits (Codex Set, Providers) page. Columns: en, ko, de, fr, zh, zh-TW, ru, ja, tr, vi, pt, es. * Keys render as `accountsV2.`. */ const rows = { - servingNow: ["Serving now", "지금 사용 중", "Gerade im Einsatz", "En service", "当前使用", "目前使用", "Используется сейчас", "現在使用中", "Şu an kullanılan", "Đang phục vụ", "Em uso agora"], + servingNow: ["Serving now", "지금 사용 중", "Gerade im Einsatz", "En service", "当前使用", "目前使用", "Используется сейчас", "現在使用中", "Şu an kullanılan", "Đang phục vụ", "Em uso agora", "Atendiendo solicitudes"], servingPool: [ "New sessions start on this account. The pool switches by your rotation strategy.", "새 세션은 이 계정으로 시작하고, 풀은 로테이션 전략에 따라 계정을 바꿉니다.", @@ -18,6 +18,7 @@ const rows = { "Yeni oturumlar bu hesapla başlar. Havuz, döndürme stratejinize göre geçiş yapar.", "Phiên mới bắt đầu trên tài khoản này. Nhóm tài khoản chuyển đổi theo chiến lược xoay vòng của bạn.", "Novas sessões começam nesta conta. O pool alterna conforme sua estratégia de rotação.", + "Las sesiones nuevas empiezan en esta cuenta. El grupo alterna según la estrategia de rotación que elijas.", ], servingDirect: [ "Direct mode: every request uses the main login.", @@ -31,6 +32,7 @@ const rows = { "Doğrudan mod: her istek ana oturumu kullanır.", "Chế độ trực tiếp: mọi yêu cầu đều dùng đăng nhập chính.", "Modo direto: toda solicitação usa o login principal.", + "Modo directo: todas las solicitudes usan la sesión principal.", ], servingNone: [ "No account can take requests right now.", @@ -44,8 +46,9 @@ const rows = { "Şu anda istek alabilecek bir hesap yok.", "Hiện không có tài khoản nào nhận được yêu cầu.", "Nenhuma conta pode receber solicitações agora.", + "En este momento ninguna cuenta puede atender solicitudes.", ], - left: ["{pct}% left", "{pct}% 남음", "{pct} % übrig", "{pct} % restant", "剩余 {pct}%", "剩餘 {pct}%", "осталось {pct}%", "残り {pct}%", "%{pct} kaldı", "còn {pct}%", "{pct}% restante"], + left: ["{pct}% left", "{pct}% 남음", "{pct} % übrig", "{pct} % restant", "剩余 {pct}%", "剩餘 {pct}%", "осталось {pct}%", "残り {pct}%", "%{pct} kaldı", "còn {pct}%", "{pct}% restante", "Queda {pct} %"], quotaUnknown: [ "Quota not read yet", "아직 할당량을 읽지 못했습니다", @@ -58,8 +61,9 @@ const rows = { "Kota henüz okunmadı", "Chưa đọc được hạn mức", "Cota ainda não lida", + "Aún no se consultó la cuota", ], - accounts: ["Accounts", "계정", "Konten", "Comptes", "账号", "帳號", "Аккаунты", "アカウント", "Hesaplar", "Tài khoản", "Contas"], + accounts: ["Accounts", "계정", "Konten", "Comptes", "账号", "帳號", "Аккаунты", "アカウント", "Hesaplar", "Tài khoản", "Contas", "Cuentas"], emptyPoolHint: [ "In pool mode, add another ChatGPT account so requests can move to it when one reaches its limit.", "풀 모드에서는 다른 ChatGPT 계정을 추가해 두면, 한 계정이 한도에 닿았을 때 요청이 그 계정으로 넘어갈 수 있어요.", @@ -72,15 +76,16 @@ const rows = { "Havuz modunda başka bir ChatGPT hesabı ekleyin; bir hesap limitine ulaştığında istekler ona geçebilir.", "Ở chế độ nhóm, hãy thêm một tài khoản ChatGPT khác để yêu cầu có thể chuyển sang khi một tài khoản chạm hạn mức.", "No modo pool, adicione outra conta do ChatGPT para que as solicitações possam passar para ela quando uma atingir o limite.", + "En modo de grupo, añade otra cuenta de ChatGPT para que las solicitudes pasen a ella si una cuenta alcanza su límite.", ], - about: ["About: {name}", "{name} 설명", "Erklärung: {name}", "Explication : {name}", "说明:{name}", "說明:{name}", "Пояснение: {name}", "{name} の説明", "Açıklama: {name}", "Giải thích: {name}", "Explicação: {name}"], - howItWorks: ["How it works", "작동 방식", "So funktioniert es", "Fonctionnement", "工作方式", "運作方式", "Как это работает", "仕組み", "Nasıl çalışır", "Cách hoạt động", "Como funciona"], - accountSettings: ["Account settings", "계정 설정", "Kontoeinstellungen", "Réglages du compte", "账号设置", "帳號設定", "Настройки аккаунта", "アカウント設定", "Hesap ayarları", "Cài đặt tài khoản", "Configurações da conta"], - mainLogin: ["Main login", "메인 로그인", "Hauptanmeldung", "Connexion principale", "主登录", "主登入", "Основной вход", "メインログイン", "Ana oturum", "Đăng nhập chính", "Login principal"], - tabsLabel: ["Codex settings", "Codex 설정", "Codex-Einstellungen", "Réglages Codex", "Codex 设置", "Codex 設定", "Настройки Codex", "Codex 設定", "Codex ayarları", "Cài đặt Codex", "Configurações do Codex"], - status: ["Status", "상태", "Status", "État", "状态", "狀態", "Состояние", "状態", "Durum", "Trạng thái", "Estado"], - actions: ["Actions", "작업", "Aktionen", "Actions disponibles", "操作", "操作", "Действия", "操作", "İşlemler", "Thao tác", "Ações"], - providersList: ["Providers", "프로바이더", "Anbieter", "Fournisseurs", "提供方", "提供者", "Провайдеры", "プロバイダー", "Sağlayıcılar", "Nhà cung cấp", "Provedores"], + about: ["About: {name}", "{name} 설명", "Erklärung: {name}", "Explication : {name}", "说明:{name}", "說明:{name}", "Пояснение: {name}", "{name} の説明", "Açıklama: {name}", "Giải thích: {name}", "Explicação: {name}", "Acerca de {name}"], + howItWorks: ["How it works", "작동 방식", "So funktioniert es", "Fonctionnement", "工作方式", "運作方式", "Как это работает", "仕組み", "Nasıl çalışır", "Cách hoạt động", "Como funciona", "Cómo funciona"], + accountSettings: ["Account settings", "계정 설정", "Kontoeinstellungen", "Réglages du compte", "账号设置", "帳號設定", "Настройки аккаунта", "アカウント設定", "Hesap ayarları", "Cài đặt tài khoản", "Configurações da conta", "Configuración de cuentas"], + mainLogin: ["Main login", "메인 로그인", "Hauptanmeldung", "Connexion principale", "主登录", "主登入", "Основной вход", "メインログイン", "Ana oturum", "Đăng nhập chính", "Login principal", "Inicio de sesión principal"], + tabsLabel: ["Codex settings", "Codex 설정", "Codex-Einstellungen", "Réglages Codex", "Codex 设置", "Codex 設定", "Настройки Codex", "Codex 設定", "Codex ayarları", "Cài đặt Codex", "Configurações do Codex", "Configuración de Codex"], + status: ["Status", "상태", "Status", "État", "状态", "狀態", "Состояние", "状態", "Durum", "Trạng thái", "Estado", "Estado"], + actions: ["Actions", "작업", "Aktionen", "Actions disponibles", "操作", "操作", "Действия", "操作", "İşlemler", "Thao tác", "Ações", "Acciones"], + providersList: ["Providers", "프로바이더", "Anbieter", "Fournisseurs", "提供方", "提供者", "Провайдеры", "プロバイダー", "Sağlayıcılar", "Nhà cung cấp", "Provedores", "Proveedores"], } satisfies Record; export const accountsV2Copy = copyTable("accountsV2", rows); diff --git a/gui/src/i18n/v2-pages/connect-copy.ts b/gui/src/i18n/v2-pages/connect-copy.ts index 06716935bed..c2a933e2df5 100644 --- a/gui/src/i18n/v2-pages/connect-copy.ts +++ b/gui/src/i18n/v2-pages/connect-copy.ts @@ -1,11 +1,11 @@ import { copyTable, type Row } from "./copy-table"; /* - * Copy for the v2 Connect (integrations, Claude, API keys) and the Set up hub pages. Columns: en, ko, de, fr, zh, zh-TW, ru, ja, tr, vi, pt. + * Copy for the v2 Connect (integrations, Claude, API keys) and the Set up hub pages. Columns: en, ko, de, fr, zh, zh-TW, ru, ja, tr, vi, pt, es. * Keys render as `connectV2.`. */ const rows = { - moreAbout: ["More about {label}", "{label} 자세히", "Mehr zu {label}", "En savoir plus sur {label}", "关于{label}的更多信息", "關於{label}的更多資訊", "Подробнее: {label}", "{label}の詳細", "{label} hakkında daha fazla", "Tìm hiểu thêm về {label}", "Mais sobre {label}"], + moreAbout: ["More about {label}", "{label} 자세히", "Mehr zu {label}", "En savoir plus sur {label}", "关于{label}的更多信息", "關於{label}的更多資訊", "Подробнее: {label}", "{label}の詳細", "{label} hakkında daha fazla", "Tìm hiểu thêm về {label}", "Mais sobre {label}", "Más sobre {label}"], subtitle: [ "Turn an app on and its requests go through opencodex. Before changing an app's settings, opencodex keeps a backup of them.", "앱을 켜면 그 앱의 요청이 opencodex를 거쳐 가요. 앱 설정을 바꾸기 전에는 백업을 남겨 둬요.", @@ -18,11 +18,12 @@ const rows = { "Bir uygulamayı açtığınızda istekleri opencodex üzerinden geçer. opencodex, bir uygulamanın ayarlarını değiştirmeden önce yedeğini alır.", "Bật một ứng dụng và các yêu cầu của nó sẽ đi qua opencodex. Trước khi thay đổi cài đặt của ứng dụng, opencodex giữ lại một bản sao lưu.", "Ative um app e as solicitações dele passam pelo opencodex. Antes de alterar as configurações de um app, o opencodex guarda um backup delas.", + "Activa una aplicación para que sus solicitudes pasen por OpenCodex. OpenCodex guarda una copia antes de cambiar la configuración de la aplicación.", ], - elsewhereTitle: ["Not on this computer ({count})", "이 컴퓨터에 없는 앱 ({count})", "Nicht auf diesem Computer ({count})", "Absentes de cet ordinateur ({count})", "此电脑上未安装({count})", "此電腦上未安裝({count})", "Не установлены на этом компьютере ({count})", "このパソコンにないアプリ({count})", "Bu bilgisayarda yok ({count})", "Chưa có trên máy này ({count})", "Não estão neste computador ({count})"], - elsewhereHint: ["Install one and it moves up to your apps.", "설치하면 위의 내 앱 목록으로 올라가요.", "Installiere eine, dann erscheint sie oben bei deinen Apps.", "Installez-en une et elle remonte parmi vos applications.", "安装后会移到上方的应用列表中。", "安裝後會移到上方的應用程式清單中。", "Установите приложение, и оно появится выше в списке.", "インストールすると上のアプリ一覧に移ります。", "Birini kurduğunuzda yukarıdaki uygulamalarınıza taşınır.", "Cài đặt một ứng dụng và nó sẽ chuyển lên danh sách phía trên.", "Instale um e ele sobe para os seus apps."], - setupEssentials: ["The essentials", "꼭 할 일", "Das Wichtigste", "L’essentiel", "必做事项", "必做事項", "Самое важное", "まずやること", "Temel adımlar", "Việc cần làm", "O essencial"], - setupOptional: ["When you need them", "필요할 때", "Bei Bedarf", "Selon vos besoins", "需要时再设置", "需要時再設定", "По необходимости", "必要なときに", "İhtiyaç duyduğunuzda", "Khi bạn cần", "Quando precisar"], + elsewhereTitle: ["Not on this computer ({count})", "이 컴퓨터에 없는 앱 ({count})", "Nicht auf diesem Computer ({count})", "Absentes de cet ordinateur ({count})", "此电脑上未安装({count})", "此電腦上未安裝({count})", "Не установлены на этом компьютере ({count})", "このパソコンにないアプリ({count})", "Bu bilgisayarda yok ({count})", "Chưa có trên máy này ({count})", "Não estão neste computador ({count})", "No instaladas en este equipo ({count})"], + elsewhereHint: ["Install one and it moves up to your apps.", "설치하면 위의 내 앱 목록으로 올라가요.", "Installiere eine, dann erscheint sie oben bei deinen Apps.", "Installez-en une et elle remonte parmi vos applications.", "安装后会移到上方的应用列表中。", "安裝後會移到上方的應用程式清單中。", "Установите приложение, и оно появится выше в списке.", "インストールすると上のアプリ一覧に移ります。", "Birini kurduğunuzda yukarıdaki uygulamalarınıza taşınır.", "Cài đặt một ứng dụng và nó sẽ chuyển lên danh sách phía trên.", "Instale um e ele sobe para os seus apps.", "Instala una aplicación y aparecerá arriba en tus aplicaciones."], + setupEssentials: ["The essentials", "꼭 할 일", "Das Wichtigste", "L’essentiel", "必做事项", "必做事項", "Самое важное", "まずやること", "Temel adımlar", "Việc cần làm", "O essencial", "Lo esencial"], + setupOptional: ["When you need them", "필요할 때", "Bei Bedarf", "Selon vos besoins", "需要时再设置", "需要時再設定", "По необходимости", "必要なときに", "İhtiyaç duyduğunuzda", "Khi bạn cần", "Quando precisar", "Cuando los necesites"], } satisfies Record; export const connectV2Copy = copyTable("connectV2", rows); diff --git a/gui/src/i18n/v2-pages/copy-table.ts b/gui/src/i18n/v2-pages/copy-table.ts index ad9296639c8..56cceae6b94 100644 --- a/gui/src/i18n/v2-pages/copy-table.ts +++ b/gui/src/i18n/v2-pages/copy-table.ts @@ -1,10 +1,10 @@ /* * Shared shape of the v2 page copy tables: one row per key, one column per locale, so a - * page's new strings land as one reviewable table instead of eleven scattered edits. + * page's new strings land as one reviewable table instead of scattered locale edits. */ -export type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; -const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt"]; -export type Row = readonly [string, string, string, string, string, string, string, string, string, string, string]; +export type Locale = "en" | "ko" | "de" | "fr" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt" | "es"; +const locales: readonly Locale[] = ["en", "ko", "de", "fr", "zh", "zh-TW", "ru", "ja", "tr", "vi", "pt", "es"]; +export type Row = readonly [string, string, string, string, string, string, string, string, string, string, string, string]; /** Turns a table into a per-locale dictionary whose keys carry `prefix`. */ export function copyTable

    >(prefix: P, rows: R) { diff --git a/gui/src/i18n/v2-pages/logs-copy.ts b/gui/src/i18n/v2-pages/logs-copy.ts index 3831d3cbf0d..76c1f4b2e0e 100644 --- a/gui/src/i18n/v2-pages/logs-copy.ts +++ b/gui/src/i18n/v2-pages/logs-copy.ts @@ -1,16 +1,16 @@ import { copyTable, type Row } from "./copy-table"; /* - * Copy for the v2 Logs & Debug, Storage page. Columns: en, ko, de, fr, zh, zh-TW, ru, ja, tr, vi, pt. + * Copy for the v2 Logs & Debug, Storage page. Columns: en, ko, de, fr, zh, zh-TW, ru, ja, tr, vi, pt, es. * Keys render as `logsV2.`. */ const rows = { - client: ["Client", "클라이언트", "Client", "Application cliente", "客户端", "用戶端", "Клиент", "クライアント", "İstemci", "Ứng dụng", "Cliente"], - clientUnknown: ["Unknown", "알 수 없음", "Unbekannt", "Inconnu", "未知", "未知", "Неизвестно", "不明", "Bilinmiyor", "Không xác định", "Desconhecido"], - clientOther: ["Other", "기타", "Andere", "Autre", "其他", "其他", "Другое", "その他", "Diğer", "Khác", "Outro"], - requests: ["Requests", "요청", "Anfragen", "Requêtes", "请求", "請求", "Запросы", "リクエスト", "İstekler", "Yêu cầu", "Requisições"], - live: ["Live", "실시간", "Live", "En direct", "实时", "即時", "В эфире", "ライブ", "Canlı", "Trực tiếp", "Ao vivo"], - paused: ["Paused", "일시 정지됨", "Pausiert", "En pause", "已暂停", "已暫停", "Пауза", "一時停止中", "Duraklatıldı", "Đã tạm dừng", "Pausado"], + client: ["Client", "클라이언트", "Client", "Application cliente", "客户端", "用戶端", "Клиент", "クライアント", "İstemci", "Ứng dụng", "Cliente", "Cliente"], + clientUnknown: ["Unknown", "알 수 없음", "Unbekannt", "Inconnu", "未知", "未知", "Неизвестно", "不明", "Bilinmiyor", "Không xác định", "Desconhecido", "Desconocido"], + clientOther: ["Other", "기타", "Andere", "Autre", "其他", "其他", "Другое", "その他", "Diğer", "Khác", "Outro", "Otros"], + requests: ["Requests", "요청", "Anfragen", "Requêtes", "请求", "請求", "Запросы", "リクエスト", "İstekler", "Yêu cầu", "Requisições", "Solicitudes"], + live: ["Live", "실시간", "Live", "En direct", "实时", "即時", "В эфире", "ライブ", "Canlı", "Trực tiếp", "Ao vivo", "En vivo"], + paused: ["Paused", "일시 정지됨", "Pausiert", "En pause", "已暂停", "已暫停", "Пауза", "一時停止中", "Duraklatıldı", "Đã tạm dừng", "Pausado", "Detenido"], liveHint: [ "New requests appear every 2 seconds", "2초마다 새 요청을 불러옵니다", @@ -23,9 +23,10 @@ const rows = { "Yeni istekler 2 saniyede bir görünür", "Yêu cầu mới hiện sau mỗi 2 giây", "Novas requisições aparecem a cada 2 segundos", + "Las solicitudes nuevas aparecen cada 2 segundos", ], - filters: ["Filters", "필터", "Filter", "Filtres", "筛选", "篩選", "Фильтры", "フィルター", "Filtreler", "Bộ lọc", "Filtros"], - columns: ["Columns", "열", "Spalten", "Colonnes", "列", "欄位", "Столбцы", "列", "Sütunlar", "Cột", "Colunas"], + filters: ["Filters", "필터", "Filter", "Filtres", "筛选", "篩選", "Фильтры", "フィルター", "Filtreler", "Bộ lọc", "Filtros", "Filtros"], + columns: ["Columns", "열", "Spalten", "Colonnes", "列", "欄位", "Столбцы", "列", "Sütunlar", "Cột", "Colunas", "Columnas"], columnsMenu: [ "Show or hide columns", "표시할 열 고르기", @@ -38,6 +39,7 @@ const rows = { "Sütunları göster veya gizle", "Hiện hoặc ẩn cột", "Mostrar ou ocultar colunas", + "Mostrar u ocultar columnas", ], removeFilter: [ "Remove filter: {name}", @@ -51,6 +53,7 @@ const rows = { "Filtreyi kaldır: {name}", "Bỏ bộ lọc: {name}", "Remover filtro: {name}", + "Quitar filtro: {name}", ], countLine: [ "{shown} of {total} requests", @@ -64,12 +67,13 @@ const rows = { "{total} istekten {shown} tanesi", "{shown} / {total} yêu cầu", "{shown} de {total} requisições", + "{shown} de {total} solicitudes", ], - failedCount: ["{count} failed", "실패 {count}건", "{count} fehlgeschlagen", "{count} en échec", "{count} 个失败", "{count} 個失敗", "Ошибок: {count}", "失敗 {count} 件", "{count} başarısız", "{count} lỗi", "{count} com falha"], - debugLogging: ["Debug logging", "디버그 로깅", "Debug-Protokollierung", "Journalisation de débogage", "调试日志", "除錯日誌", "Отладочный журнал", "デバッグログ", "Hata ayıklama günlüğü", "Ghi log gỡ lỗi", "Registro de depuração"], - debugTail: ["Live tail", "실시간 로그", "Live-Protokoll", "Flux en direct", "实时日志", "即時日誌", "Журнал в реальном времени", "ライブログ", "Canlı akış", "Log trực tiếp", "Log ao vivo"], - debugLines: ["{count} lines", "{count}줄", "{count} Zeilen", "{count} lignes", "{count} 行", "{count} 行", "Строк: {count}", "{count} 行", "{count} satır", "{count} dòng", "{count} linhas"], - debugStream: ["Stream", "스트림", "Stream", "Flux", "数据流", "資料流", "Поток", "ストリーム", "Akış", "Luồng", "Fluxo"], + failedCount: ["{count} failed", "실패 {count}건", "{count} fehlgeschlagen", "{count} en échec", "{count} 个失败", "{count} 個失敗", "Ошибок: {count}", "失敗 {count} 件", "{count} başarısız", "{count} lỗi", "{count} com falha", "Fallidos: {count}"], + debugLogging: ["Debug logging", "디버그 로깅", "Debug-Protokollierung", "Journalisation de débogage", "调试日志", "除錯日誌", "Отладочный журнал", "デバッグログ", "Hata ayıklama günlüğü", "Ghi log gỡ lỗi", "Registro de depuração", "Registro de depuración"], + debugTail: ["Live tail", "실시간 로그", "Live-Protokoll", "Flux en direct", "实时日志", "即時日誌", "Журнал в реальном времени", "ライブログ", "Canlı akış", "Log trực tiếp", "Log ao vivo", "Últimas líneas en vivo"], + debugLines: ["{count} lines", "{count}줄", "{count} Zeilen", "{count} lignes", "{count} 行", "{count} 行", "Строк: {count}", "{count} 行", "{count} satır", "{count} dòng", "{count} linhas", "{count} líneas"], + debugStream: ["Stream", "스트림", "Stream", "Flux", "数据流", "資料流", "Поток", "ストリーム", "Akış", "Luồng", "Fluxo", "Flujo"], } satisfies Record; export const logsV2Copy = copyTable("logsV2", rows); diff --git a/gui/src/i18n/v2-pages/models-copy.ts b/gui/src/i18n/v2-pages/models-copy.ts index 2c966267a32..0cd44455196 100644 --- a/gui/src/i18n/v2-pages/models-copy.ts +++ b/gui/src/i18n/v2-pages/models-copy.ts @@ -1,19 +1,18 @@ import { copyTable, type Row } from "./copy-table"; /* - * Copy for the v2 Models page. Columns: en, ko, de, fr, zh, zh-TW, ru, ja, tr, vi, pt. + * Copy for the v2 Models page. Columns: en, ko, de, fr, zh, zh-TW, ru, ja, tr, vi, pt, es. * Keys render as `modelsV2.`. */ const rows = { // ---- page head: one plain line per tab; the long description sits behind "About" ------ - ledeCatalog: ["Choose which models show up in the Codex model picker.", "Codex 모델 선택기에 보일 모델을 켜고 꺼요.", "Legen Sie fest, welche Modelle in der Codex-Modellauswahl erscheinen.", "Choisissez les modèles proposés dans le sélecteur de Codex.", "选择 Codex 模型选择器中显示哪些模型。", "選擇 Codex 模型選擇器中顯示哪些模型。", "Выберите, какие модели видны в списке моделей Codex.", "Codex のモデル選択に表示するモデルを選びます。", "Codex model seçicisinde hangi modellerin görüneceğini seçin.", "Chọn các mô hình hiển thị trong bộ chọn mô hình của Codex.", "Escolha quais modelos aparecem no seletor de modelos do Codex."], - ledeCombos: ["Bundle several models under one id that answers in order.", "여러 모델을 하나의 id로 묶어 차례대로 응답하게 해요.", "Bündeln Sie mehrere Modelle unter einer ID, die der Reihe nach antworten.", "Regroupez plusieurs modèles sous un seul id qui répondent dans l'ordre.", "把多个模型合并到一个 id 下,按顺序响应。", "把多個模型合併到一個 id 下,依序回應。", "Объедините несколько моделей под одним id — они отвечают по очереди.", "複数のモデルを 1 つの id にまとめ、順番に応答させます。", "Birden çok modeli sırayla yanıt veren tek bir id altında toplayın.", "Gộp nhiều mô hình dưới một id và trả lời lần lượt.", "Agrupe vários modelos sob um único id que responde em ordem."], - about: ["About this page", "이 화면 설명", "Über diese Seite", "À propos de cette page", "关于此页面", "關於此頁面", "Об этой странице", "このページについて", "Bu sayfa hakkında", "Về trang này", "Sobre esta página"], - + ledeCatalog: ["Choose which models show up in the Codex model picker.", "Codex 모델 선택기에 보일 모델을 켜고 꺼요.", "Legen Sie fest, welche Modelle in der Codex-Modellauswahl erscheinen.", "Choisissez les modèles proposés dans le sélecteur de Codex.", "选择 Codex 模型选择器中显示哪些模型。", "選擇 Codex 模型選擇器中顯示哪些模型。", "Выберите, какие модели видны в списке моделей Codex.", "Codex のモデル選択に表示するモデルを選びます。", "Codex model seçicisinde hangi modellerin görüneceğini seçin.", "Chọn các mô hình hiển thị trong bộ chọn mô hình của Codex.", "Escolha quais modelos aparecem no seletor de modelos do Codex.", "Elige qué modelos aparecen en el selector de Codex."], + ledeCombos: ["Bundle several models under one id that answers in order.", "여러 모델을 하나의 id로 묶어 차례대로 응답하게 해요.", "Bündeln Sie mehrere Modelle unter einer ID, die der Reihe nach antworten.", "Regroupez plusieurs modèles sous un seul id qui répondent dans l'ordre.", "把多个模型合并到一个 id 下,按顺序响应。", "把多個模型合併到一個 id 下,依序回應。", "Объедините несколько моделей под одним id — они отвечают по очереди.", "複数のモデルを 1 つの id にまとめ、順番に応答させます。", "Birden çok modeli sırayla yanıt veren tek bir id altında toplayın.", "Gộp nhiều mô hình dưới một id và trả lời lần lượt.", "Agrupe vários modelos sob um único id que responde em ordem.", "Agrupa varios modelos bajo un mismo ID y pruébalos en orden al responder."], + about: ["About this page", "이 화면 설명", "Über diese Seite", "À propos de cette page", "关于此页面", "關於此頁面", "Об этой странице", "このページについて", "Bu sayfa hakkında", "Về trang này", "Sobre esta página", "Acerca de esta página"], // ---- provider card ----------------------------------------------------------------------- - providerTools: ["Provider settings", "프로바이더 설정", "Anbietereinstellungen", "Réglages du fournisseur", "提供商设置", "提供者設定", "Настройки провайдера", "プロバイダー設定", "Sağlayıcı ayarları", "Cài đặt nhà cung cấp", "Configurações do provedor"], - bulkLabel: ["Turn every model on or off", "모든 모델 켜기·끄기", "Alle Modelle ein- oder ausschalten", "Activer ou désactiver tous les modèles", "全部开启或关闭", "全部開啟或關閉", "Включить или выключить все модели", "すべてのモデルをオン・オフ", "Tüm modelleri aç veya kapat", "Bật hoặc tắt mọi mô hình", "Ativar ou desativar todos os modelos"], - modelActions: ["Model actions", "모델 작업", "Modellaktionen", "Actions du modèle", "模型操作", "模型操作", "Действия с моделью", "モデルの操作", "Model işlemleri", "Thao tác mô hình", "Ações do modelo"], + providerTools: ["Provider settings", "프로바이더 설정", "Anbietereinstellungen", "Réglages du fournisseur", "提供商设置", "提供者設定", "Настройки провайдера", "プロバイダー設定", "Sağlayıcı ayarları", "Cài đặt nhà cung cấp", "Configurações do provedor", "Configuración del proveedor"], + bulkLabel: ["Turn every model on or off", "모든 모델 켜기·끄기", "Alle Modelle ein- oder ausschalten", "Activer ou désactiver tous les modèles", "全部开启或关闭", "全部開啟或關閉", "Включить или выключить все модели", "すべてのモデルをオン・オフ", "Tüm modelleri aç veya kapat", "Bật hoặc tắt mọi mô hình", "Ativar ou desativar todos os modelos", "Activar o desactivar todos los modelos"], + modelActions: ["Model actions", "모델 작업", "Modellaktionen", "Actions du modèle", "模型操作", "模型操作", "Действия с моделью", "モデルの操作", "Model işlemleri", "Thao tác mô hình", "Ações do modelo", "Acciones de modelos"], } satisfies Record; export const modelsV2Copy = copyTable("modelsV2", rows); diff --git a/gui/src/i18n/v2-pages/proxy-copy.ts b/gui/src/i18n/v2-pages/proxy-copy.ts index 936872197fc..c03296f1e1e 100644 --- a/gui/src/i18n/v2-pages/proxy-copy.ts +++ b/gui/src/i18n/v2-pages/proxy-copy.ts @@ -1,87 +1,83 @@ import { copyTable, type Row } from "./copy-table"; /* - * Copy for the v2 Proxy details, Advisor and the All settings hub pages. Columns: en, ko, de, fr, zh, zh-TW, ru, ja, tr, vi, pt. + * Copy for the v2 Proxy details, Advisor and the All settings hub pages. Columns: en, ko, de, fr, zh, zh-TW, ru, ja, tr, vi, pt, es. * Keys render as `proxyV2.`. */ const rows = { // ---- Proxy details: page head and in-page index --------------------------------------------- - pageLede: ["Expert settings for the proxy, grouped by what they change.", "프록시의 전문가 설정을 바꾸는 대상별로 모았어요.", "Expertenoptionen des Proxys, nach Wirkung gruppiert.", "Réglages avancés du proxy, regroupés selon ce qu'ils modifient.", "代理的高级设置,按作用分组。", "代理的進階設定,依作用分組。", "Экспертные настройки прокси, сгруппированные по назначению.", "プロキシの上級者向け設定を、変える対象ごとにまとめています。", "Proxy için uzman ayarları, neyi değiştirdiklerine göre gruplandı.", "Cài đặt chuyên sâu của proxy, nhóm theo phần chúng thay đổi.", "Configurações avançadas do proxy, agrupadas pelo que alteram."], - indexLabel: ["On this page", "이 페이지에서", "Auf dieser Seite", "Sur cette page", "本页内容", "本頁內容", "На этой странице", "このページの項目", "Bu sayfada", "Trên trang này", "Nesta página"], - details: ["Details", "자세히", "Details", "Détails", "详情", "詳情", "Подробнее", "詳細", "Ayrıntılar", "Chi tiết", "Detalhes"], - detailsFor: ["More about {name}", "{name} 자세히", "Mehr zu {name}", "En savoir plus : {name}", "关于{name}的详情", "關於{name}的詳情", "Подробнее: {name}", "{name}の詳細", "{name} hakkında daha fazla", "Thêm về {name}", "Mais sobre {name}"], - + pageLede: ["Expert settings for the proxy, grouped by what they change.", "프록시의 전문가 설정을 바꾸는 대상별로 모았어요.", "Expertenoptionen des Proxys, nach Wirkung gruppiert.", "Réglages avancés du proxy, regroupés selon ce qu'ils modifient.", "代理的高级设置,按作用分组。", "代理的進階設定,依作用分組。", "Экспертные настройки прокси, сгруппированные по назначению.", "プロキシの上級者向け設定を、変える対象ごとにまとめています。", "Proxy için uzman ayarları, neyi değiştirdiklerine göre gruplandı.", "Cài đặt chuyên sâu của proxy, nhóm theo phần chúng thay đổi.", "Configurações avançadas do proxy, agrupadas pelo que alteram.", "Configuración avanzada del proxy, agrupada por función."], + indexLabel: ["On this page", "이 페이지에서", "Auf dieser Seite", "Sur cette page", "本页内容", "本頁內容", "На этой странице", "このページの項目", "Bu sayfada", "Trên trang này", "Nesta página", "En esta página"], + details: ["Details", "자세히", "Details", "Détails", "详情", "詳情", "Подробнее", "詳細", "Ayrıntılar", "Chi tiết", "Detalhes", "Detalles"], + detailsFor: ["More about {name}", "{name} 자세히", "Mehr zu {name}", "En savoir plus : {name}", "关于{name}的详情", "關於{name}的詳情", "Подробнее: {name}", "{name}の詳細", "{name} hakkında daha fazla", "Thêm về {name}", "Mais sobre {name}", "Más sobre {name}"], // ---- Proxy details: section titles and one-line ledes ---------------------------------------- - secSubagents: ["Subagents", "서브에이전트", "Subagenten", "Sous-agents", "子代理", "子代理", "Субагенты", "サブエージェント", "Alt ajanlar", "Tác tử phụ", "Subagentes"], - secSubagentsLede: ["How Codex hands work to helper agents, and how hard they may think.", "Codex가 보조 에이전트에 일을 넘기는 방식과 추론 강도를 정해요.", "Wie Codex Arbeit an Hilfsagenten abgibt und wie intensiv sie denken dürfen.", "Comment Codex confie le travail à des agents d'appoint, et jusqu'où ils peuvent réfléchir.", "Codex 如何把工作交给辅助代理,以及它们的推理强度。", "Codex 如何把工作交給輔助代理,以及它們的推理強度。", "Как Codex передаёт работу вспомогательным агентам и насколько глубоко они думают.", "Codex が補助エージェントに作業を渡す方法と、推論の強さを決めます。", "Codex'in işi yardımcı ajanlara nasıl devrettiği ve ne kadar düşünebilecekleri.", "Cách Codex giao việc cho tác tử hỗ trợ và mức suy luận của chúng.", "Como o Codex passa trabalho para agentes auxiliares e quanto eles podem raciocinar."], - secCodex: ["Codex app", "Codex 앱", "Codex-App", "Application Codex", "Codex 应用", "Codex 應用程式", "Приложение Codex", "Codex アプリ", "Codex uygulaması", "Ứng dụng Codex", "App Codex"], - secCodexLede: ["How Codex starts, signs in and keeps its model list in step with the proxy.", "Codex 시작, 로그인, 모델 목록을 프록시와 어떻게 맞출지 정해요.", "Wie Codex startet, sich anmeldet und seine Modellliste mit dem Proxy abgleicht.", "Démarrage de Codex, connexion et synchronisation de sa liste de modèles avec le proxy.", "Codex 如何启动、登录,并让模型列表与代理保持一致。", "Codex 如何啟動、登入,並讓模型清單與代理保持一致。", "Как Codex запускается, входит в систему и сверяет список моделей с прокси.", "Codex の起動、サインイン、モデル一覧をプロキシとそろえる方法を決めます。", "Codex'in nasıl başladığı, oturum açtığı ve model listesini proxy ile eşitlediği.", "Cách Codex khởi động, đăng nhập và đồng bộ danh sách mô hình với proxy.", "Como o Codex inicia, entra e mantém a lista de modelos alinhada ao proxy."], - secSidecars: ["Helper models", "보조 모델", "Hilfsmodelle", "Modèles d'appoint", "辅助模型", "輔助模型", "Вспомогательные модели", "補助モデル", "Yardımcı modeller", "Mô hình hỗ trợ", "Modelos auxiliares"], - secSidecarsLede: ["Models that do web search, read images or take background calls for routed models.", "라우팅 모델 대신 웹 검색, 이미지 읽기, 백그라운드 호출을 맡는 모델이에요.", "Modelle, die für geroutete Modelle suchen, Bilder lesen oder Hintergrundaufrufe übernehmen.", "Des modèles qui cherchent sur le web, lisent les images ou prennent les appels de fond des modèles routés.", "为路由模型执行网页搜索、读取图片或接管后台调用的模型。", "為路由模型執行網頁搜尋、讀取圖片或接管背景呼叫的模型。", "Модели, которые ищут в интернете, читают изображения или берут фоновые вызовы за маршрутизируемые модели.", "ルーティングされたモデルの代わりに、ウェブ検索、画像の読み取り、バックグラウンド呼び出しを担うモデルです。", "Yönlendirilen modeller için web araması yapan, görselleri okuyan veya arka plan çağrılarını üstlenen modeller.", "Các mô hình tìm kiếm web, đọc ảnh hoặc nhận lời gọi nền thay cho mô hình được định tuyến.", "Modelos que pesquisam na web, leem imagens ou assumem chamadas em segundo plano pelos modelos roteados."], - secCompaction: ["Compaction and reasoning", "압축과 추론", "Komprimierung und Reasoning", "Compaction et raisonnement", "压缩与推理", "壓縮與推理", "Сжатие и рассуждения", "圧縮と推論", "Sıkıştırma ve akıl yürütme", "Nén và suy luận", "Compactação e raciocínio"], - secCompactionLede: ["Which model summarizes long chats, and what reasoning is kept between turns.", "긴 대화를 요약할 모델과 턴 사이에 남길 추론을 정해요.", "Welches Modell lange Chats zusammenfasst und welches Reasoning zwischen Zügen erhalten bleibt.", "Le modèle qui résume les longues conversations et le raisonnement conservé d'un tour à l'autre.", "由哪个模型总结长对话,以及轮次之间保留哪些推理。", "由哪個模型摘要長對話,以及回合之間保留哪些推理。", "Какая модель сжимает длинные диалоги и какие рассуждения сохраняются между ходами.", "長い会話を要約するモデルと、ターン間に残す推論を決めます。", "Uzun sohbetleri hangi modelin özetleyeceği ve turlar arasında hangi akıl yürütmenin tutulacağı.", "Mô hình nào tóm tắt cuộc trò chuyện dài và suy luận nào được giữ giữa các lượt.", "Qual modelo resume conversas longas e qual raciocínio é mantido entre turnos."], - secMemory: ["Memory", "메모리", "Speicher", "Mémoire", "内存与记忆", "記憶體與記憶", "Память", "メモリ", "Bellek", "Bộ nhớ", "Memória"], - secMemoryLede: ["Models for Codex's background memory, and how much memory the proxy itself uses.", "Codex 백그라운드 메모리에 쓸 모델과 프록시 자체의 메모리 사용량이에요.", "Modelle für das Hintergrundgedächtnis von Codex und der Speicherverbrauch des Proxys selbst.", "Les modèles de la mémoire d'arrière-plan de Codex, et la mémoire utilisée par le proxy lui-même.", "Codex 后台记忆使用的模型,以及代理自身的内存占用。", "Codex 背景記憶使用的模型,以及代理本身的記憶體用量。", "Модели для фоновой памяти Codex и сколько памяти занимает сам прокси.", "Codex のバックグラウンドメモリに使うモデルと、プロキシ自体のメモリ使用量です。", "Codex'in arka plan belleği için modeller ve proxy'nin kendi bellek kullanımı.", "Mô hình cho bộ nhớ nền của Codex và lượng bộ nhớ proxy đang dùng.", "Modelos da memória em segundo plano do Codex e quanta memória o próprio proxy usa."], - secFallback: ["Fallback", "폴백", "Fallback", "Repli", "回退", "備援", "Резервный переход", "フォールバック", "Yedeğe geçiş", "Dự phòng", "Fallback"], - secFallbackLede: ["What happens when a model or provider fails.", "모델이나 프로바이더가 실패했을 때의 동작이에요.", "Was passiert, wenn ein Modell oder Anbieter ausfällt.", "Ce qui se passe quand un modèle ou un fournisseur échoue.", "模型或提供商失败时的处理方式。", "模型或供應商失敗時的處理方式。", "Что происходит, когда модель или провайдер дают сбой.", "モデルやプロバイダーが失敗したときの動作です。", "Bir model veya sağlayıcı başarısız olduğunda ne olacağı.", "Điều gì xảy ra khi mô hình hoặc nhà cung cấp gặp lỗi.", "O que acontece quando um modelo ou provedor falha."], - secTelemetry: ["Telemetry", "텔레메트리", "Telemetrie", "Télémétrie", "遥测", "遙測", "Телеметрия", "テレメトリ", "Telemetri", "Telemetri", "Telemetria"], - secTelemetryLede: ["Anonymous daily usage totals shared with the project dashboard.", "프로젝트 대시보드에 공유되는 익명 일일 사용 합계예요.", "Anonyme tägliche Nutzungszahlen, die mit dem Projekt-Dashboard geteilt werden.", "Totaux quotidiens anonymes partagés avec le tableau de bord du projet.", "与项目仪表盘共享的匿名每日使用汇总。", "與專案儀表板共享的匿名每日使用彙總。", "Анонимные дневные сводки использования для дашборда проекта.", "プロジェクトのダッシュボードに共有される匿名の1日ごとの利用集計です。", "Proje panosuyla paylaşılan anonim günlük kullanım toplamları.", "Tổng hợp sử dụng hằng ngày ẩn danh chia sẻ với bảng điều khiển dự án.", "Totais diários anônimos de uso compartilhados com o painel do projeto."], - + secSubagents: ["Subagents", "서브에이전트", "Subagenten", "Sous-agents", "子代理", "子代理", "Субагенты", "サブエージェント", "Alt ajanlar", "Tác tử phụ", "Subagentes", "Subagentes"], + secSubagentsLede: ["How Codex hands work to helper agents, and how hard they may think.", "Codex가 보조 에이전트에 일을 넘기는 방식과 추론 강도를 정해요.", "Wie Codex Arbeit an Hilfsagenten abgibt und wie intensiv sie denken dürfen.", "Comment Codex confie le travail à des agents d'appoint, et jusqu'où ils peuvent réfléchir.", "Codex 如何把工作交给辅助代理,以及它们的推理强度。", "Codex 如何把工作交給輔助代理,以及它們的推理強度。", "Как Codex передаёт работу вспомогательным агентам и насколько глубоко они думают.", "Codex が補助エージェントに作業を渡す方法と、推論の強さを決めます。", "Codex'in işi yardımcı ajanlara nasıl devrettiği ve ne kadar düşünebilecekleri.", "Cách Codex giao việc cho tác tử hỗ trợ và mức suy luận của chúng.", "Como o Codex passa trabalho para agentes auxiliares e quanto eles podem raciocinar.", "Cómo Codex delega trabajo a subagentes y cuánto razonamiento pueden usar."], + secCodex: ["Codex app", "Codex 앱", "Codex-App", "Application Codex", "Codex 应用", "Codex 應用程式", "Приложение Codex", "Codex アプリ", "Codex uygulaması", "Ứng dụng Codex", "App Codex", "Aplicación de Codex"], + secCodexLede: ["How Codex starts, signs in and keeps its model list in step with the proxy.", "Codex 시작, 로그인, 모델 목록을 프록시와 어떻게 맞출지 정해요.", "Wie Codex startet, sich anmeldet und seine Modellliste mit dem Proxy abgleicht.", "Démarrage de Codex, connexion et synchronisation de sa liste de modèles avec le proxy.", "Codex 如何启动、登录,并让模型列表与代理保持一致。", "Codex 如何啟動、登入,並讓模型清單與代理保持一致。", "Как Codex запускается, входит в систему и сверяет список моделей с прокси.", "Codex の起動、サインイン、モデル一覧をプロキシとそろえる方法を決めます。", "Codex'in nasıl başladığı, oturum açtığı ve model listesini proxy ile eşitlediği.", "Cách Codex khởi động, đăng nhập và đồng bộ danh sách mô hình với proxy.", "Como o Codex inicia, entra e mantém a lista de modelos alinhada ao proxy.", "Cómo Codex se inicia, inicia sesión y mantiene su lista de modelos sincronizada con el proxy."], + secSidecars: ["Helper models", "보조 모델", "Hilfsmodelle", "Modèles d'appoint", "辅助模型", "輔助模型", "Вспомогательные модели", "補助モデル", "Yardımcı modeller", "Mô hình hỗ trợ", "Modelos auxiliares", "Modelos auxiliares"], + secSidecarsLede: ["Models that do web search, read images or take background calls for routed models.", "라우팅 모델 대신 웹 검색, 이미지 읽기, 백그라운드 호출을 맡는 모델이에요.", "Modelle, die für geroutete Modelle suchen, Bilder lesen oder Hintergrundaufrufe übernehmen.", "Des modèles qui cherchent sur le web, lisent les images ou prennent les appels de fond des modèles routés.", "为路由模型执行网页搜索、读取图片或接管后台调用的模型。", "為路由模型執行網頁搜尋、讀取圖片或接管背景呼叫的模型。", "Модели, которые ищут в интернете, читают изображения или берут фоновые вызовы за маршрутизируемые модели.", "ルーティングされたモデルの代わりに、ウェブ検索、画像の読み取り、バックグラウンド呼び出しを担うモデルです。", "Yönlendirilen modeller için web araması yapan, görselleri okuyan veya arka plan çağrılarını üstlenen modeller.", "Các mô hình tìm kiếm web, đọc ảnh hoặc nhận lời gọi nền thay cho mô hình được định tuyến.", "Modelos que pesquisam na web, leem imagens ou assumem chamadas em segundo plano pelos modelos roteados.", "Modelos que realizan búsquedas web, leen imágenes o atienden llamadas en segundo plano para modelos enrutados."], + secCompaction: ["Compaction and reasoning", "압축과 추론", "Komprimierung und Reasoning", "Compaction et raisonnement", "压缩与推理", "壓縮與推理", "Сжатие и рассуждения", "圧縮と推論", "Sıkıştırma ve akıl yürütme", "Nén và suy luận", "Compactação e raciocínio", "Compactación y razonamiento"], + secCompactionLede: ["Which model summarizes long chats, and what reasoning is kept between turns.", "긴 대화를 요약할 모델과 턴 사이에 남길 추론을 정해요.", "Welches Modell lange Chats zusammenfasst und welches Reasoning zwischen Zügen erhalten bleibt.", "Le modèle qui résume les longues conversations et le raisonnement conservé d'un tour à l'autre.", "由哪个模型总结长对话,以及轮次之间保留哪些推理。", "由哪個模型摘要長對話,以及回合之間保留哪些推理。", "Какая модель сжимает длинные диалоги и какие рассуждения сохраняются между ходами.", "長い会話を要約するモデルと、ターン間に残す推論を決めます。", "Uzun sohbetleri hangi modelin özetleyeceği ve turlar arasında hangi akıl yürütmenin tutulacağı.", "Mô hình nào tóm tắt cuộc trò chuyện dài và suy luận nào được giữ giữa các lượt.", "Qual modelo resume conversas longas e qual raciocínio é mantido entre turnos.", "Qué modelo resume conversaciones largas y qué razonamiento se conserva entre turnos."], + secMemory: ["Memory", "메모리", "Speicher", "Mémoire", "内存与记忆", "記憶體與記憶", "Память", "メモリ", "Bellek", "Bộ nhớ", "Memória", "Memoria"], + secMemoryLede: ["Models for Codex's background memory, and how much memory the proxy itself uses.", "Codex 백그라운드 메모리에 쓸 모델과 프록시 자체의 메모리 사용량이에요.", "Modelle für das Hintergrundgedächtnis von Codex und der Speicherverbrauch des Proxys selbst.", "Les modèles de la mémoire d'arrière-plan de Codex, et la mémoire utilisée par le proxy lui-même.", "Codex 后台记忆使用的模型,以及代理自身的内存占用。", "Codex 背景記憶使用的模型,以及代理本身的記憶體用量。", "Модели для фоновой памяти Codex и сколько памяти занимает сам прокси.", "Codex のバックグラウンドメモリに使うモデルと、プロキシ自体のメモリ使用量です。", "Codex'in arka plan belleği için modeller ve proxy'nin kendi bellek kullanımı.", "Mô hình cho bộ nhớ nền của Codex và lượng bộ nhớ proxy đang dùng.", "Modelos da memória em segundo plano do Codex e quanta memória o próprio proxy usa.", "Modelos que gestionan la memoria de Codex en segundo plano y cuánta memoria usa el propio proxy."], + secFallback: ["Fallback", "폴백", "Fallback", "Repli", "回退", "備援", "Резервный переход", "フォールバック", "Yedeğe geçiş", "Dự phòng", "Fallback", "Alternativas"], + secFallbackLede: ["What happens when a model or provider fails.", "모델이나 프로바이더가 실패했을 때의 동작이에요.", "Was passiert, wenn ein Modell oder Anbieter ausfällt.", "Ce qui se passe quand un modèle ou un fournisseur échoue.", "模型或提供商失败时的处理方式。", "模型或供應商失敗時的處理方式。", "Что происходит, когда модель или провайдер дают сбой.", "モデルやプロバイダーが失敗したときの動作です。", "Bir model veya sağlayıcı başarısız olduğunda ne olacağı.", "Điều gì xảy ra khi mô hình hoặc nhà cung cấp gặp lỗi.", "O que acontece quando um modelo ou provedor falha.", "Qué ocurre cuando falla un modelo o proveedor."], + secTelemetry: ["Telemetry", "텔레메트리", "Telemetrie", "Télémétrie", "遥测", "遙測", "Телеметрия", "テレメトリ", "Telemetri", "Telemetri", "Telemetria", "Telemetría"], + secTelemetryLede: ["Anonymous daily usage totals shared with the project dashboard.", "프로젝트 대시보드에 공유되는 익명 일일 사용 합계예요.", "Anonyme tägliche Nutzungszahlen, die mit dem Projekt-Dashboard geteilt werden.", "Totaux quotidiens anonymes partagés avec le tableau de bord du projet.", "与项目仪表盘共享的匿名每日使用汇总。", "與專案儀表板共享的匿名每日使用彙總。", "Анонимные дневные сводки использования для дашборда проекта.", "プロジェクトのダッシュボードに共有される匿名の1日ごとの利用集計です。", "Proje panosuyla paylaşılan anonim günlük kullanım toplamları.", "Tổng hợp sử dụng hằng ngày ẩn danh chia sẻ với bảng điều khiển dự án.", "Totais diários anônimos de uso compartilhados com o painel do projeto.", "Totales diarios anónimos de uso que se comparten con el panel del proyecto."], // ---- Proxy details: one-line row hints (the long text stays behind "Details") --------------- - maModeHint: ["Which subagent engine Codex uses: v1, base or v2.", "Codex가 쓸 서브에이전트 방식을 골라요: v1, base, v2.", "Welche Subagenten-Engine Codex nutzt: v1, base oder v2.", "Le moteur de sous-agents utilisé par Codex : v1, base ou v2.", "Codex 使用的子代理引擎:v1、base 或 v2。", "Codex 使用的子代理引擎:v1、base 或 v2。", "Какой движок субагентов использует Codex: v1, base или v2.", "Codex が使うサブエージェント方式を選びます:v1、base、v2。", "Codex'in kullandığı alt ajan motoru: v1, base veya v2.", "Bộ máy tác tử phụ mà Codex dùng: v1, base hoặc v2.", "Qual mecanismo de subagentes o Codex usa: v1, base ou v2."], - effortCapHint: ["Lowers max-effort requests in ultra mode. It never raises them.", "ultra 모드의 max 요청을 낮춰요. 높이지는 않아요.", "Senkt Max-Effort-Anfragen im Ultra-Modus. Hebt sie nie an.", "Abaisse les requêtes à effort maximal en mode ultra, sans jamais les relever.", "降低 ultra 模式下的 max 强度请求,绝不提高。", "降低 ultra 模式下的 max 強度請求,絕不提高。", "Снижает запросы с максимальным усилием в режиме ultra, но не повышает.", "ultra モードの max 要求を下げます。上げることはありません。", "Ultra modundaki maksimum efor isteklerini düşürür, asla yükseltmez.", "Hạ các yêu cầu mức tối đa ở chế độ ultra, không bao giờ nâng lên.", "Reduz pedidos de esforço máximo no modo ultra, sem nunca aumentá-los."], - subagentEffortCapHint: ["The same limit, only for spawned child agents.", "같은 제한을 생성된 자식 에이전트에만 적용해요.", "Dieselbe Grenze, nur für erzeugte Kind-Agenten.", "La même limite, seulement pour les agents enfants lancés.", "同样的限制,仅用于派生的子代理。", "同樣的限制,僅用於衍生的子代理。", "То же ограничение, только для порождённых дочерних агентов.", "同じ制限を、起動された子エージェントにだけ適用します。", "Aynı sınır, yalnızca başlatılan alt ajanlar için.", "Cùng giới hạn đó, chỉ cho các tác tử con được tạo ra.", "O mesmo limite, só para agentes filhos criados."], - injectionHint: ["The default model subagent work is handed to.", "서브에이전트 작업을 넘길 기본 모델이에요.", "Das Standardmodell, an das Subagenten-Arbeit geht.", "Le modèle par défaut qui reçoit le travail des sous-agents.", "子代理工作默认交给的模型。", "子代理工作預設交給的模型。", "Модель по умолчанию, которой передаётся работа субагентов.", "サブエージェントの作業を渡す既定のモデルです。", "Alt ajan işinin devredildiği varsayılan model.", "Mô hình mặc định nhận việc của tác tử phụ.", "O modelo padrão que recebe o trabalho dos subagentes."], - autoStartShort: ["Start the proxy whenever Codex launches.", "Codex를 켜면 프록시도 함께 켜요.", "Den Proxy bei jedem Codex-Start mitstarten.", "Démarrer le proxy à chaque lancement de Codex.", "每次启动 Codex 时一并启动代理。", "每次啟動 Codex 時一併啟動代理。", "Запускать прокси при каждом запуске Codex.", "Codex を起動するとプロキシも一緒に起動します。", "Codex her açıldığında proxy'yi de başlat.", "Khởi động proxy mỗi khi mở Codex.", "Iniciar o proxy sempre que o Codex abrir."], - authlessShort: ["Skip the separate Desktop sign-in. Off by default.", "Desktop 로그인을 따로 하지 않아요. 기본값은 꺼짐이에요.", "Die separate Desktop-Anmeldung überspringen. Standardmäßig aus.", "Ignorer la connexion Desktop séparée. Désactivé par défaut.", "跳过单独的桌面端登录。默认关闭。", "略過單獨的桌面版登入。預設關閉。", "Пропускать отдельный вход в Desktop. По умолчанию выключено.", "Desktop の個別サインインを省きます。既定はオフです。", "Ayrı Desktop oturum açmayı atla. Varsayılan olarak kapalı.", "Bỏ qua bước đăng nhập Desktop riêng. Mặc định tắt.", "Pular o login separado do Desktop. Desativado por padrão."], - clientCompactionShort: ["Store compaction summaries as portable plain text. Off by default.", "압축 요약을 옮길 수 있는 평문으로 저장해요. 기본값은 꺼짐이에요.", "Komprimierungs-Zusammenfassungen als portablen Klartext speichern. Standardmäßig aus.", "Enregistrer les résumés de compaction en texte brut portable. Désactivé par défaut.", "以可移植的纯文本保存压缩摘要。默认关闭。", "以可攜的純文字儲存壓縮摘要。預設關閉。", "Хранить сводки сжатия переносимым текстом. По умолчанию выключено.", "圧縮の要約を持ち運べるプレーンテキストで保存します。既定はオフです。", "Sıkıştırma özetlerini taşınabilir düz metin olarak sakla. Varsayılan olarak kapalı.", "Lưu bản tóm tắt nén dưới dạng văn bản thuần di chuyển được. Mặc định tắt.", "Guardar resumos de compactação como texto simples portátil. Desativado por padrão."], - shadowShort: ["Send Codex App background calls, like titles and commit messages, to another model.", "Codex 앱의 백그라운드 호출(제목, 커밋 메시지 등)을 다른 모델로 보내요.", "Hintergrundaufrufe der Codex-App, etwa Titel und Commit-Nachrichten, an ein anderes Modell senden.", "Envoyer les appels de fond de l'app Codex, comme les titres et messages de commit, à un autre modèle.", "把 Codex 应用的后台调用(如标题、提交信息)发送到另一个模型。", "把 Codex 應用程式的背景呼叫(如標題、提交訊息)傳送到另一個模型。", "Отправлять фоновые вызовы приложения Codex (заголовки, сообщения коммитов) другой модели.", "Codex アプリのバックグラウンド呼び出し(タイトル、コミットメッセージなど)を別のモデルに送ります。", "Codex uygulamasının başlık ve commit mesajı gibi arka plan çağrılarını başka bir modele gönder.", "Gửi các lời gọi nền của ứng dụng Codex, như tiêu đề và thông điệp commit, sang mô hình khác.", "Enviar chamadas em segundo plano do app Codex, como títulos e mensagens de commit, para outro modelo."], - telemetryToggleLabel: ["Share anonymous usage statistics", "익명 사용 통계 공유", "Anonyme Nutzungsstatistiken teilen", "Partager des statistiques d'utilisation anonymes", "共享匿名使用统计", "共享匿名使用統計", "Делиться анонимной статистикой использования", "匿名の利用統計を共有する", "Anonim kullanım istatistiklerini paylaş", "Chia sẻ thống kê sử dụng ẩn danh", "Compartilhar estatísticas anônimas de uso"], - telemetryToggleHint: ["Sends one daily aggregate of version, platform, coarse model family, token totals and error counts. On by default.", "버전, 플랫폼, 모델 계열, 토큰 합계, 오류 건수의 일일 집계만 하루 한 번 보내요. 기본값은 켜짐이에요.", "Sendet einmal täglich aggregierte Angaben zu Version, Plattform, grober Modellfamilie, Token-Summen und Fehlerzahlen. Standardmäßig an.", "Envoie une synthèse quotidienne (version, plateforme, famille de modèles, totaux de jetons et nombres d'erreurs). Activé par défaut.", "每天发送一次版本、平台、模型系列、令牌总数与错误计数的汇总。默认开启。", "每天傳送一次版本、平台、模型系列、Token 總數與錯誤計數的彙總。預設開啟。", "Раз в день отправляет сводку: версия, платформа, семейство моделей, сумма токенов и число ошибок. По умолчанию включено.", "バージョン、OS、モデル系統、トークン合計、エラー件数の日次集計を1日1回送信します。既定はオンです。", "Sürüm, platform, model ailesi, jeton toplamları ve hata sayılarının günlük özetini günde bir kez gönderir. Varsayılan olarak açıktır.", "Gửi một bản tổng hợp mỗi ngày gồm phiên bản, nền tảng, dòng mô hình, tổng token và số lỗi. Mặc định bật.", "Envia um resumo diário com versão, plataforma, família de modelos, totais de tokens e contagem de erros. Ativado por padrão."], - telemetryDetails: ["Reports use a per-day hash of a random local install ID. Disabling telemetry deletes that ID immediately. Prompts, responses, API keys, account emails, custom URLs and file paths are never collected.", "보고서는 무작위 로컬 설치 ID의 일일 해시를 사용하며, 끄면 해당 ID를 즉시 삭제해요. 프롬프트, 응답, API 키, 계정 이메일, 사용자 지정 URL, 파일 경로는 절대 수집하지 않아요.", "Berichte nutzen einen täglichen Hash einer zufälligen lokalen Installations-ID. Beim Deaktivieren wird diese ID sofort gelöscht. Prompts, Antworten, API-Schlüssel, E-Mail-Adressen, eigene URLs und Dateipfade werden nie erfasst.", "Les rapports utilisent un hachage quotidien d'un identifiant local aléatoire, supprimé dès la désactivation. Prompts, réponses, clés API, e-mails, URL personnalisées et chemins de fichiers ne sont jamais collectés.", "报告使用随机本地安装 ID 的每日哈希;关闭遥测会立即删除该 ID。绝不收集提示词、回复、API 密钥、账户邮箱、自定义 URL 或文件路径。", "報告使用隨機本機安裝 ID 的每日雜湊;關閉遙測會立即刪除該 ID。絕不收集提示詞、回覆、API 金鑰、帳號信箱、自訂 URL 或檔案路徑。", "Отчёты используют суточный хеш случайного локального ID установки; при отключении этот ID сразу удаляется. Промпты, ответы, API-ключи, адреса почты, свои URL и пути к файлам никогда не собираются.", "レポートにはランダムなローカルインストールIDの日次ハッシュを使い、オフにするとそのIDは即座に削除されます。プロンプト、応答、APIキー、メールアドレス、カスタムURL、ファイルパスは一切収集されません。", "Raporlar rastgele yerel kurulum kimliğinin günlük karmasını kullanır; kapatıldığında bu kimlik hemen silinir. İstemler, yanıtlar, API anahtarları, e-postalar, özel URL'ler ve dosya yolları asla toplanmaz.", "Báo cáo dùng mã băm theo ngày của ID cài đặt ngẫu nhiên cục bộ; tắt telemetri sẽ xóa ID đó ngay lập tức. Prompt, phản hồi, khóa API, email tài khoản, URL tùy chỉnh và đường dẫn tệp không bao giờ được thu thập.", "Os relatórios usam um hash diário de um ID de instalação local aleatório; desativar a telemetria apaga esse ID imediatamente. Prompts, respostas, chaves de API, e-mails, URLs personalizadas e caminhos de arquivos nunca são coletados."], - telemetryWhatIsSent: ["Preview the JSON", "JSON 미리보기", "JSON-Vorschau", "Aperçu du JSON", "预览 JSON", "預覽 JSON", "Предпросмотр JSON", "JSONをプレビュー", "JSON önizlemesi", "Xem trước JSON", "Pré-visualizar o JSON"], - telemetryPreviewHint: ["Exact JSON payload prepared from the latest completed UTC day:", "가장 최근 완료된 UTC 일자 기준으로 준비된 실제 JSON 페이로드:", "Exakte JSON-Nutzlast aus dem letzten abgeschlossenen UTC-Tag:", "Charge JSON exacte préparée à partir du dernier jour UTC complet :", "根据最近一个完整 UTC 日生成的完整 JSON 载荷:", "根據最近一個完整 UTC 日產生的完整 JSON 負載:", "Точный JSON-пакет, собранный за последние завершённые сутки UTC:", "直近の完了したUTC日に基づいて生成された実際のJSONペイロード:", "Tamamlanan son UTC gününden hazırlanan tam JSON yükü:", "Payload JSON chính xác được tạo từ ngày UTC hoàn tất gần nhất:", "Payload JSON exato preparado a partir do último dia UTC concluído:"], - telemetryPreviewIneligible: ["This day would not be sent", "이 날짜는 전송되지 않아요", "Dieser Tag würde nicht gesendet", "Ce jour ne serait pas envoyé", "该日不会发送", "該日不會傳送", "Этот день не будет отправлен", "この日は送信されません", "Bu gün gönderilmez", "Ngày này sẽ không được gửi", "Este dia não seria enviado"], - telemetryEnvOverride: ["Disabled by environment variable {envVar}. Unset it in the proxy environment to change this setting here.", "환경 변수 {envVar}로 인해 비활성화되었어요. 여기서 바꾸려면 프록시 환경에서 해당 변수를 해제하세요.", "Durch die Umgebungsvariable {envVar} deaktiviert. Entfernen Sie sie aus der Proxy-Umgebung, um die Einstellung hier zu ändern.", "Désactivé par la variable d'environnement {envVar}. Retirez-la de l'environnement du proxy pour modifier ce réglage ici.", "已被环境变量 {envVar} 禁用。若要在此更改,请在代理环境中取消设置该变量。", "已被環境變數 {envVar} 停用。若要在此變更,請在代理環境中取消設定該變數。", "Отключено переменной окружения {envVar}. Уберите её из окружения прокси, чтобы менять настройку здесь.", "環境変数 {envVar} により無効化されています。ここで変更するにはプロキシ環境から解除してください。", "{envVar} ortam değişkeni tarafından devre dışı bırakıldı. Buradan değiştirmek için proxy ortamında kaldırın.", "Đã tắt bởi biến môi trường {envVar}. Hãy bỏ biến này khỏi môi trường proxy để thay đổi tại đây.", "Desativado pela variável de ambiente {envVar}. Remova-a do ambiente do proxy para alterar esta opção aqui."], - telemetryReadOnlyHint: ["Managed on the Home proxy for this Remote Link.", "이 원격 링크의 Home 프록시에서 관리돼요.", "Wird auf dem Home-Proxy dieses Remote Links verwaltet.", "Géré sur le proxy Home de ce lien distant.", "由该远程连接的 Home 代理管理。", "由該遠端連線的 Home 代理管理。", "Управляется на прокси Home этой удалённой связки.", "このリモートリンクの Home プロキシで管理されています。", "Bu Uzak Bağlantının Home proxy'sinde yönetilir.", "Được quản lý trên proxy Home của Liên kết từ xa này.", "Gerenciado no proxy Home deste Remote Link."], - telemetryLoadFailed: ["Could not load telemetry status.", "텔레메트리 상태를 불러오지 못했어요.", "Telemetriestatus konnte nicht geladen werden.", "Impossible de charger l'état de la télémétrie.", "无法加载遥测状态。", "無法載入遙測狀態。", "Не удалось загрузить состояние телеметрии.", "テレメトリの状態を読み込めませんでした。", "Telemetri durumu yüklenemedi.", "Không thể tải trạng thái telemetri.", "Não foi possível carregar o status da telemetria."], - telemetrySaveFailed: ["Could not save telemetry preference.", "텔레메트리 설정을 저장하지 못했어요.", "Telemetrie-Einstellung konnte nicht gespeichert werden.", "Impossible d'enregistrer la préférence de télémétrie.", "无法保存遥测偏好设置。", "無法儲存遙測偏好設定。", "Не удалось сохранить настройку телеметрии.", "テレメトリ設定を保存できませんでした。", "Telemetri tercihi kaydedilemedi.", "Không thể lưu tùy chọn telemetri.", "Não foi possível salvar a preferência de telemetria."], - telemetrySaveUnconfirmed: ["Could not confirm the telemetry setting yet; checking again shortly.", "텔레메트리 설정을 아직 확인하지 못했어요. 곧 다시 확인해요.", "Die Telemetrie-Einstellung konnte noch nicht bestätigt werden; sie wird gleich erneut geprüft.", "Impossible de confirmer le réglage de télémétrie pour l'instant ; nouvelle vérification sous peu.", "暂时无法确认遥测设置,稍后会再次检查。", "暫時無法確認遙測設定,稍後會再次檢查。", "Пока не удалось подтвердить настройку телеметрии; скоро проверим ещё раз.", "テレメトリ設定をまだ確認できません。まもなく再確認します。", "Telemetri ayarı henüz doğrulanamadı; kısa süre içinde yeniden denetlenecek.", "Chưa xác nhận được cài đặt telemetri; sẽ kiểm tra lại trong giây lát.", "Ainda não foi possível confirmar a configuração de telemetria; verificaremos novamente em breve."], - telemetrySaveNeedsHumanSession: ["This session was restored from a remembered device, so it can't record a telemetry choice. Open the dashboard on the proxy's computer, or run ocx telemetry enable or ocx telemetry disable in a terminal.", "이 세션은 기억된 기기에서 복원되어 텔레메트리 선택을 저장할 수 없어요. 프록시가 실행 중인 컴퓨터에서 대시보드를 열거나, 터미널에서 ocx telemetry enable 또는 ocx telemetry disable을 실행하세요.", "Diese Sitzung wurde von einem gespeicherten Gerät wiederhergestellt und kann keine Telemetrie-Entscheidung speichern. Öffnen Sie das Dashboard auf dem Rechner des Proxys oder führen Sie ocx telemetry enable bzw. ocx telemetry disable im Terminal aus.", "Cette session a été restaurée depuis un appareil mémorisé et ne peut pas enregistrer de choix de télémétrie. Ouvrez le tableau de bord sur l'ordinateur du proxy, ou lancez ocx telemetry enable ou ocx telemetry disable dans un terminal.", "此会话由已记住的设备恢复,无法保存遥测选择。请在运行代理的电脑上打开仪表盘,或在终端运行 ocx telemetry enable 或 ocx telemetry disable。", "此工作階段由已記住的裝置還原,無法儲存遙測選擇。請在執行代理的電腦上開啟儀表板,或在終端機執行 ocx telemetry enable 或 ocx telemetry disable。", "Этот сеанс восстановлен с запомненного устройства, поэтому не может сохранить выбор телеметрии. Откройте дашборд на компьютере с прокси или выполните ocx telemetry enable либо ocx telemetry disable в терминале.", "このセッションは記憶済みのデバイスから復元されたため、テレメトリの選択を保存できません。プロキシが動いているコンピューターでダッシュボードを開くか、ターミナルで ocx telemetry enable または ocx telemetry disable を実行してください。", "Bu oturum hatırlanan bir cihazdan geri yüklendiği için telemetri tercihini kaydedemez. Panoyu proxy'nin çalıştığı bilgisayarda açın veya bir terminalde ocx telemetry enable ya da ocx telemetry disable çalıştırın.", "Phiên này được khôi phục từ một thiết bị đã ghi nhớ nên không thể lưu lựa chọn telemetri. Hãy mở bảng điều khiển trên máy đang chạy proxy, hoặc chạy ocx telemetry enable hay ocx telemetry disable trong terminal.", "Esta sessão foi restaurada de um dispositivo lembrado e não pode salvar a escolha de telemetria. Abra o painel no computador do proxy ou execute ocx telemetry enable ou ocx telemetry disable em um terminal."], - telemetryConsentTitle: ["Help improve opencodex with anonymous usage stats", "익명 사용 통계로 opencodex 개선에 함께해 주세요", "opencodex mit anonymen Nutzungsstatistiken verbessern", "Aider à améliorer opencodex avec des statistiques anonymes", "通过匿名使用统计帮助改进 opencodex", "透過匿名使用統計協助改進 opencodex", "Помогите улучшать opencodex анонимной статистикой", "匿名の利用統計で opencodex の改善に協力する", "Anonim kullanım istatistikleriyle opencodex'i geliştirmeye yardımcı olun", "Giúp cải thiện opencodex bằng thống kê sử dụng ẩn danh", "Ajude a melhorar o opencodex com estatísticas anônimas de uso"], - telemetryConsentBody: ["opencodex can send one anonymous daily summary to telemetry.opencodex.me; only project-wide totals are published at opencodex.me/dashboard. You can turn it off here, later in Proxy details, with ocx telemetry disable, or with OCX_TELEMETRY=0 or DO_NOT_TRACK=1 in the proxy's environment.", "opencodex는 하루 한 번 익명 요약을 telemetry.opencodex.me로 보낼 수 있어요. 공개되는 것은 opencodex.me/dashboard의 프로젝트 전체 합계뿐이에요. 여기서, 나중에 프록시 상세 설정에서, ocx telemetry disable 명령으로, 또는 프록시 환경의 OCX_TELEMETRY=0이나 DO_NOT_TRACK=1로 끌 수 있어요.", "opencodex kann einmal täglich eine anonyme Zusammenfassung an telemetry.opencodex.me senden; veröffentlicht werden nur projektweite Summen unter opencodex.me/dashboard. Sie können dies hier, später in den Proxy-Details, mit ocx telemetry disable oder mit OCX_TELEMETRY=0 bzw. DO_NOT_TRACK=1 in der Umgebung des Proxys abschalten.", "opencodex peut envoyer un résumé quotidien anonyme à telemetry.opencodex.me ; seuls les totaux du projet sont publiés sur opencodex.me/dashboard. Vous pouvez le désactiver ici, plus tard dans les détails du proxy, avec ocx telemetry disable, ou avec OCX_TELEMETRY=0 ou DO_NOT_TRACK=1 dans l'environnement du proxy.", "opencodex 可每天向 telemetry.opencodex.me 发送一次匿名汇总;opencodex.me/dashboard 只公开项目整体总数。您可以在此处、稍后在代理详情中、使用 ocx telemetry disable,或在代理环境中设置 OCX_TELEMETRY=0 或 DO_NOT_TRACK=1 来关闭。", "opencodex 可每天向 telemetry.opencodex.me 傳送一次匿名彙總;opencodex.me/dashboard 只公開專案整體總數。您可以在此處、稍後在代理詳情中、使用 ocx telemetry disable,或在代理環境中設定 OCX_TELEMETRY=0 或 DO_NOT_TRACK=1 來關閉。", "opencodex может раз в день отправлять анонимную сводку на telemetry.opencodex.me; на opencodex.me/dashboard публикуются только общие итоги проекта. Отключить можно здесь, позже в настройках прокси, командой ocx telemetry disable или переменной OCX_TELEMETRY=0 либо DO_NOT_TRACK=1 в окружении прокси.", "opencodex は1日1回、匿名の集計を telemetry.opencodex.me に送信できます。opencodex.me/dashboard で公開されるのはプロジェクト全体の合計だけです。ここで、あとでプロキシ詳細で、ocx telemetry disable で、またはプロキシの環境で OCX_TELEMETRY=0 か DO_NOT_TRACK=1 を設定してオフにできます。", "opencodex günde bir kez anonim bir özeti telemetry.opencodex.me adresine gönderebilir; opencodex.me/dashboard'da yalnızca proje geneli toplamlar yayımlanır. Bunu burada, daha sonra Proxy ayrıntılarında, ocx telemetry disable ile ya da proxy ortamında OCX_TELEMETRY=0 veya DO_NOT_TRACK=1 ile kapatabilirsiniz.", "opencodex có thể gửi bản tóm tắt ẩn danh mỗi ngày một lần tới telemetry.opencodex.me; chỉ tổng số toàn dự án được công bố tại opencodex.me/dashboard. Bạn có thể tắt tại đây, sau này trong Chi tiết proxy, bằng ocx telemetry disable, hoặc bằng OCX_TELEMETRY=0 hay DO_NOT_TRACK=1 trong môi trường của proxy.", "O opencodex pode enviar um resumo diário anônimo para telemetry.opencodex.me; apenas os totais do projeto são publicados em opencodex.me/dashboard. Você pode desativar aqui, depois nos detalhes do proxy, com ocx telemetry disable, ou com OCX_TELEMETRY=0 ou DO_NOT_TRACK=1 no ambiente do proxy."], - telemetrySentTitle: ["What is sent", "보내는 항목", "Gesendet wird", "Envoyé", "发送的数据", "傳送的資料", "Отправляется", "送信されるもの", "Gönderilenler", "Được gửi", "Enviado"], - telemetrySentItems: ["A per-day install hash that changes every day, version, release channel, OS/CPU, install channel, first-report flag, active minutes, provider kind, coarse model family, request outcomes, token totals, and closed error codes.", "매일 바뀌는 일별 설치 해시, 버전, 릴리스 채널, OS/CPU, 설치 채널, 첫 보고 여부, 활성 시간(분), 프로바이더 종류, 모델 계열, 요청 결과, 토큰 합계, 고정된 오류 코드.", "Ein täglich wechselnder Installations-Hash, Version, Release-Kanal, OS/CPU, Installationskanal, Erstmeldungs-Flag, aktive Minuten, Anbieterart, grobe Modellfamilie, Anfrageergebnisse, Token-Summen und feste Fehlercodes.", "Un hachage d'installation qui change chaque jour, version, canal de publication, OS/CPU, canal d'installation, indicateur de premier envoi, minutes actives, type de fournisseur, famille de modèles, résultats des requêtes, totaux de jetons et codes d'erreur fermés.", "每天更换的安装哈希、版本、发布渠道、系统与架构、安装渠道、首次上报标记、活跃分钟数、提供商类型、粗粒度模型系列、请求结果、令牌总数及固定错误码。", "每天更換的安裝雜湊、版本、發布管道、系統與架構、安裝管道、首次回報標記、活躍分鐘數、供應商類型、粗粒度模型系列、請求結果、Token 總數及固定錯誤碼。", "Хеш установки, меняющийся каждый день, версия, канал выпуска, ОС и архитектура, канал установки, признак первого отчёта, активные минуты, тип провайдера, семейство моделей, исходы запросов, суммы токенов и закрытые коды ошибок.", "毎日変わるインストールハッシュ、バージョン、リリースチャネル、OS/CPU、インストール経路、初回送信フラグ、アクティブ分数、プロバイダー種別、大まかなモデル系統、リクエスト結果、トークン合計、固定エラーコード。", "Her gün değişen bir kurulum karması, sürüm, sürüm kanalı, İS/CPU, kurulum kanalı, ilk rapor işareti, etkin dakikalar, sağlayıcı türü, kaba model ailesi, istek sonuçları, jeton toplamları ve kapalı hata kodları.", "Mã băm cài đặt thay đổi mỗi ngày, phiên bản, kênh phát hành, OS/CPU, kênh cài đặt, cờ báo cáo đầu tiên, số phút hoạt động, loại nhà cung cấp, dòng mô hình, kết quả yêu cầu, tổng token và mã lỗi cố định.", "Um hash de instalação que muda todo dia, versão, canal de lançamento, SO/CPU, canal de instalação, indicador de primeiro envio, minutos ativos, tipo de provedor, família de modelos, resultados de requisições, totais de tokens e códigos fechados de erro."], - telemetryNeverTitle: ["Never sent", "절대 보내지 않는 항목", "Niemals gesendet", "Jamais envoyé", "绝不发送", "絕不傳送", "Никогда не отправляется", "送信されないもの", "Asla gönderilmeyenler", "Không bao giờ gửi", "Nunca enviado"], - telemetryNeverItems: ["Prompts, model outputs, request/response bodies, API keys, OAuth tokens, account IDs or emails, custom base URLs, hostnames, file paths, or raw error messages.", "프롬프트, 모델 출력, 요청/응답 본문, API 키, OAuth 토큰, 계정 ID나 이메일, 사용자 지정 URL, 호스트 이름, 파일 경로, 원본 오류 메시지.", "Prompts, Modellausgaben, Anfrage-/Antwortinhalte, API-Schlüssel, OAuth-Tokens, Konto-IDs oder E-Mail-Adressen, eigene Basis-URLs, Hostnamen, Dateipfade oder rohe Fehlermeldungen.", "Prompts, sorties de modèles, corps de requêtes/réponses, clés API, jetons OAuth, identifiants de compte ou e-mails, URL de base personnalisées, noms d'hôte, chemins de fichiers ou messages d'erreur bruts.", "提示词、模型输出、请求或响应正文、API 密钥、OAuth 令牌、账户 ID 或邮箱、自定义基础 URL、主机名、文件路径或原始错误信息。", "提示詞、模型輸出、請求或回應正文、API 金鑰、OAuth 權杖、帳號 ID 或信箱、自訂基礎 URL、主機名稱、檔案路徑或原始錯誤訊息。", "Промпты, ответы моделей, тела запросов и ответов, API-ключи, OAuth-токены, ID аккаунтов и адреса почты, свои базовые URL, имена хостов, пути к файлам и тексты ошибок.", "プロンプト、モデル出力、リクエスト/レスポンス本文、APIキー、OAuthトークン、アカウントIDやメールアドレス、カスタムURL、ホスト名、ファイルパス、生のエラーメッセージ。", "İstemler, model çıktıları, istek/yanıt gövdeleri, API anahtarları, OAuth belirteçleri, hesap kimlikleri veya e-postaları, özel temel URL'ler, ana bilgisayar adları, dosya yolları veya ham hata iletileri.", "Prompt, đầu ra mô hình, nội dung yêu cầu/phản hồi, khóa API, token OAuth, ID hoặc email tài khoản, URL cơ sở tùy chỉnh, tên máy chủ, đường dẫn tệp hoặc thông báo lỗi thô.", "Prompts, saídas de modelos, corpos de requisição/resposta, chaves de API, tokens OAuth, IDs ou e-mails de contas, URLs base personalizadas, nomes de host, caminhos de arquivos ou mensagens brutas de erro."], - telemetryPolicyLink: ["Read the full privacy policy", "전체 개인정보 처리방침 보기", "Vollständige Datenschutzerklärung lesen", "Lire la politique de confidentialité complète", "阅读完整隐私政策", "閱讀完整隱私權政策", "Полная политика конфиденциальности", "プライバシーポリシー全文を読む", "Gizlilik politikasının tamamını okuyun", "Đọc toàn bộ chính sách quyền riêng tư", "Ler a política de privacidade completa"], - telemetryConsentCheckbox: ["Share anonymous daily usage statistics", "익명 일일 사용 통계 공유하기", "Anonyme tägliche Nutzungsstatistiken teilen", "Partager les statistiques quotidiennes anonymes", "共享匿名每日使用统计", "共享匿名每日使用統計", "Делиться анонимной ежедневной статистикой", "匿名の1日ごとの利用統計を共有する", "Anonim günlük kullanım istatistiklerini paylaş", "Chia sẻ thống kê sử dụng ẩn danh hằng ngày", "Compartilhar estatísticas diárias anônimas de uso"], - telemetryConsentContinue: ["Continue", "계속", "Weiter", "Continuer", "继续", "繼續", "Продолжить", "続行", "Devam", "Tiếp tục", "Continuar"], - + maModeHint: ["Which subagent engine Codex uses: v1, base or v2.", "Codex가 쓸 서브에이전트 방식을 골라요: v1, base, v2.", "Welche Subagenten-Engine Codex nutzt: v1, base oder v2.", "Le moteur de sous-agents utilisé par Codex : v1, base ou v2.", "Codex 使用的子代理引擎:v1、base 或 v2。", "Codex 使用的子代理引擎:v1、base 或 v2。", "Какой движок субагентов использует Codex: v1, base или v2.", "Codex が使うサブエージェント方式を選びます:v1、base、v2。", "Codex'in kullandığı alt ajan motoru: v1, base veya v2.", "Bộ máy tác tử phụ mà Codex dùng: v1, base hoặc v2.", "Qual mecanismo de subagentes o Codex usa: v1, base ou v2.", "Motor de subagentes que usa Codex: v1, base o v2."], + effortCapHint: ["Lowers max-effort requests in ultra mode. It never raises them.", "ultra 모드의 max 요청을 낮춰요. 높이지는 않아요.", "Senkt Max-Effort-Anfragen im Ultra-Modus. Hebt sie nie an.", "Abaisse les requêtes à effort maximal en mode ultra, sans jamais les relever.", "降低 ultra 模式下的 max 强度请求,绝不提高。", "降低 ultra 模式下的 max 強度請求,絕不提高。", "Снижает запросы с максимальным усилием в режиме ultra, но не повышает.", "ultra モードの max 要求を下げます。上げることはありません。", "Ultra modundaki maksimum efor isteklerini düşürür, asla yükseltmez.", "Hạ các yêu cầu mức tối đa ở chế độ ultra, không bao giờ nâng lên.", "Reduz pedidos de esforço máximo no modo ultra, sem nunca aumentá-los.", "Reduce las solicitudes de esfuerzo máximo en modo ultra. No lo aumenta."], + subagentEffortCapHint: ["The same limit, only for spawned child agents.", "같은 제한을 생성된 자식 에이전트에만 적용해요.", "Dieselbe Grenze, nur für erzeugte Kind-Agenten.", "La même limite, seulement pour les agents enfants lancés.", "同样的限制,仅用于派生的子代理。", "同樣的限制,僅用於衍生的子代理。", "То же ограничение, только для порождённых дочерних агентов.", "同じ制限を、起動された子エージェントにだけ適用します。", "Aynı sınır, yalnızca başlatılan alt ajanlar için.", "Cùng giới hạn đó, chỉ cho các tác tử con được tạo ra.", "O mesmo limite, só para agentes filhos criados.", "El mismo límite, aplicado solo a los subagentes iniciados."], + injectionHint: ["The default model subagent work is handed to.", "서브에이전트 작업을 넘길 기본 모델이에요.", "Das Standardmodell, an das Subagenten-Arbeit geht.", "Le modèle par défaut qui reçoit le travail des sous-agents.", "子代理工作默认交给的模型。", "子代理工作預設交給的模型。", "Модель по умолчанию, которой передаётся работа субагентов.", "サブエージェントの作業を渡す既定のモデルです。", "Alt ajan işinin devredildiği varsayılan model.", "Mô hình mặc định nhận việc của tác tử phụ.", "O modelo padrão que recebe o trabalho dos subagentes.", "Modelo predeterminado al que se delega el trabajo de subagentes."], + autoStartShort: ["Start the proxy whenever Codex launches.", "Codex를 켜면 프록시도 함께 켜요.", "Den Proxy bei jedem Codex-Start mitstarten.", "Démarrer le proxy à chaque lancement de Codex.", "每次启动 Codex 时一并启动代理。", "每次啟動 Codex 時一併啟動代理。", "Запускать прокси при каждом запуске Codex.", "Codex を起動するとプロキシも一緒に起動します。", "Codex her açıldığında proxy'yi de başlat.", "Khởi động proxy mỗi khi mở Codex.", "Iniciar o proxy sempre que o Codex abrir.", "Inicia el proxy cada vez que se abre Codex."], + authlessShort: ["Skip the separate Desktop sign-in. Off by default.", "Desktop 로그인을 따로 하지 않아요. 기본값은 꺼짐이에요.", "Die separate Desktop-Anmeldung überspringen. Standardmäßig aus.", "Ignorer la connexion Desktop séparée. Désactivé par défaut.", "跳过单独的桌面端登录。默认关闭。", "略過單獨的桌面版登入。預設關閉。", "Пропускать отдельный вход в Desktop. По умолчанию выключено.", "Desktop の個別サインインを省きます。既定はオフです。", "Ayrı Desktop oturum açmayı atla. Varsayılan olarak kapalı.", "Bỏ qua bước đăng nhập Desktop riêng. Mặc định tắt.", "Pular o login separado do Desktop. Desativado por padrão.", "Omite el inicio de sesión separado de Desktop. Desactivado de forma predeterminada."], + clientCompactionShort: ["Store compaction summaries as portable plain text. Off by default.", "압축 요약을 옮길 수 있는 평문으로 저장해요. 기본값은 꺼짐이에요.", "Komprimierungs-Zusammenfassungen als portablen Klartext speichern. Standardmäßig aus.", "Enregistrer les résumés de compaction en texte brut portable. Désactivé par défaut.", "以可移植的纯文本保存压缩摘要。默认关闭。", "以可攜的純文字儲存壓縮摘要。預設關閉。", "Хранить сводки сжатия переносимым текстом. По умолчанию выключено.", "圧縮の要約を持ち運べるプレーンテキストで保存します。既定はオフです。", "Sıkıştırma özetlerini taşınabilir düz metin olarak sakla. Varsayılan olarak kapalı.", "Lưu bản tóm tắt nén dưới dạng văn bản thuần di chuyển được. Mặc định tắt.", "Guardar resumos de compactação como texto simples portátil. Desativado por padrão.", "Almacena los resúmenes de compactación como texto claro portable. Desactivado de forma predeterminada."], + shadowShort: ["Send Codex App background calls, like titles and commit messages, to another model.", "Codex 앱의 백그라운드 호출(제목, 커밋 메시지 등)을 다른 모델로 보내요.", "Hintergrundaufrufe der Codex-App, etwa Titel und Commit-Nachrichten, an ein anderes Modell senden.", "Envoyer les appels de fond de l'app Codex, comme les titres et messages de commit, à un autre modèle.", "把 Codex 应用的后台调用(如标题、提交信息)发送到另一个模型。", "把 Codex 應用程式的背景呼叫(如標題、提交訊息)傳送到另一個模型。", "Отправлять фоновые вызовы приложения Codex (заголовки, сообщения коммитов) другой модели.", "Codex アプリのバックグラウンド呼び出し(タイトル、コミットメッセージなど)を別のモデルに送ります。", "Codex uygulamasının başlık ve commit mesajı gibi arka plan çağrılarını başka bir modele gönder.", "Gửi các lời gọi nền của ứng dụng Codex, như tiêu đề và thông điệp commit, sang mô hình khác.", "Enviar chamadas em segundo plano do app Codex, como títulos e mensagens de commit, para outro modelo.", "Envía las llamadas en segundo plano de Codex App, como títulos y mensajes de commit, a otro modelo."], + telemetryToggleLabel: ["Share anonymous usage statistics", "익명 사용 통계 공유", "Anonyme Nutzungsstatistiken teilen", "Partager des statistiques d'utilisation anonymes", "共享匿名使用统计", "共享匿名使用統計", "Делиться анонимной статистикой использования", "匿名の利用統計を共有する", "Anonim kullanım istatistiklerini paylaş", "Chia sẻ thống kê sử dụng ẩn danh", "Compartilhar estatísticas anônimas de uso", "Compartir estadísticas anónimas de uso"], + telemetryToggleHint: ["Sends one daily aggregate of version, platform, coarse model family, token totals and error counts. On by default.", "버전, 플랫폼, 모델 계열, 토큰 합계, 오류 건수의 일일 집계만 하루 한 번 보내요. 기본값은 켜짐이에요.", "Sendet einmal täglich aggregierte Angaben zu Version, Plattform, grober Modellfamilie, Token-Summen und Fehlerzahlen. Standardmäßig an.", "Envoie une synthèse quotidienne (version, plateforme, famille de modèles, totaux de jetons et nombres d'erreurs). Activé par défaut.", "每天发送一次版本、平台、模型系列、令牌总数与错误计数的汇总。默认开启。", "每天傳送一次版本、平台、模型系列、Token 總數與錯誤計數的彙總。預設開啟。", "Раз в день отправляет сводку: версия, платформа, семейство моделей, сумма токенов и число ошибок. По умолчанию включено.", "バージョン、OS、モデル系統、トークン合計、エラー件数の日次集計を1日1回送信します。既定はオンです。", "Sürüm, platform, model ailesi, jeton toplamları ve hata sayılarının günlük özetini günde bir kez gönderir. Varsayılan olarak açıktır.", "Gửi một bản tổng hợp mỗi ngày gồm phiên bản, nền tảng, dòng mô hình, tổng token và số lỗi. Mặc định bật.", "Envia um resumo diário com versão, plataforma, família de modelos, totais de tokens e contagem de erros. Ativado por padrão.", "Envía un resumen diario de la versión, plataforma, familia general de modelos y totales de tokens y errores. Activado de forma predeterminada."], + telemetryDetails: ["Reports use a per-day hash of a random local install ID. Disabling telemetry deletes that ID immediately. Prompts, responses, API keys, account emails, custom URLs and file paths are never collected.", "보고서는 무작위 로컬 설치 ID의 일일 해시를 사용하며, 끄면 해당 ID를 즉시 삭제해요. 프롬프트, 응답, API 키, 계정 이메일, 사용자 지정 URL, 파일 경로는 절대 수집하지 않아요.", "Berichte nutzen einen täglichen Hash einer zufälligen lokalen Installations-ID. Beim Deaktivieren wird diese ID sofort gelöscht. Prompts, Antworten, API-Schlüssel, E-Mail-Adressen, eigene URLs und Dateipfade werden nie erfasst.", "Les rapports utilisent un hachage quotidien d'un identifiant local aléatoire, supprimé dès la désactivation. Prompts, réponses, clés API, e-mails, URL personnalisées et chemins de fichiers ne sont jamais collectés.", "报告使用随机本地安装 ID 的每日哈希;关闭遥测会立即删除该 ID。绝不收集提示词、回复、API 密钥、账户邮箱、自定义 URL 或文件路径。", "報告使用隨機本機安裝 ID 的每日雜湊;關閉遙測會立即刪除該 ID。絕不收集提示詞、回覆、API 金鑰、帳號信箱、自訂 URL 或檔案路徑。", "Отчёты используют суточный хеш случайного локального ID установки; при отключении этот ID сразу удаляется. Промпты, ответы, API-ключи, адреса почты, свои URL и пути к файлам никогда не собираются.", "レポートにはランダムなローカルインストールIDの日次ハッシュを使い、オフにするとそのIDは即座に削除されます。プロンプト、応答、APIキー、メールアドレス、カスタムURL、ファイルパスは一切収集されません。", "Raporlar rastgele yerel kurulum kimliğinin günlük karmasını kullanır; kapatıldığında bu kimlik hemen silinir. İstemler, yanıtlar, API anahtarları, e-postalar, özel URL'ler ve dosya yolları asla toplanmaz.", "Báo cáo dùng mã băm theo ngày của ID cài đặt ngẫu nhiên cục bộ; tắt telemetri sẽ xóa ID đó ngay lập tức. Prompt, phản hồi, khóa API, email tài khoản, URL tùy chỉnh và đường dẫn tệp không bao giờ được thu thập.", "Os relatórios usam um hash diário de um ID de instalação local aleatório; desativar a telemetria apaga esse ID imediatamente. Prompts, respostas, chaves de API, e-mails, URLs personalizadas e caminhos de arquivos nunca são coletados.", "Los informes usan un hash diario de un ID de instalación local aleatorio. Al desactivar la telemetría se elimina ese ID de inmediato. Nunca se recopilan prompts, respuestas, claves API, correos de cuentas, URLs personalizadas ni rutas de archivos."], + telemetryWhatIsSent: ["Preview the JSON", "JSON 미리보기", "JSON-Vorschau", "Aperçu du JSON", "预览 JSON", "預覽 JSON", "Предпросмотр JSON", "JSONをプレビュー", "JSON önizlemesi", "Xem trước JSON", "Pré-visualizar o JSON", "Vista previa del JSON"], + telemetryPreviewHint: ["Exact JSON payload prepared from the latest completed UTC day:", "가장 최근 완료된 UTC 일자 기준으로 준비된 실제 JSON 페이로드:", "Exakte JSON-Nutzlast aus dem letzten abgeschlossenen UTC-Tag:", "Charge JSON exacte préparée à partir du dernier jour UTC complet :", "根据最近一个完整 UTC 日生成的完整 JSON 载荷:", "根據最近一個完整 UTC 日產生的完整 JSON 負載:", "Точный JSON-пакет, собранный за последние завершённые сутки UTC:", "直近の完了したUTC日に基づいて生成された実際のJSONペイロード:", "Tamamlanan son UTC gününden hazırlanan tam JSON yükü:", "Payload JSON chính xác được tạo từ ngày UTC hoàn tất gần nhất:", "Payload JSON exato preparado a partir do último dia UTC concluído:", "Contenido JSON exacto preparado para el último día completo en UTC:"], + telemetryPreviewIneligible: ["This day would not be sent", "이 날짜는 전송되지 않아요", "Dieser Tag würde nicht gesendet", "Ce jour ne serait pas envoyé", "该日不会发送", "該日不會傳送", "Этот день не будет отправлен", "この日は送信されません", "Bu gün gönderilmez", "Ngày này sẽ không được gửi", "Este dia não seria enviado", "No se enviaría este día"], + telemetryEnvOverride: ["Disabled by environment variable {envVar}. Unset it in the proxy environment to change this setting here.", "환경 변수 {envVar}로 인해 비활성화되었어요. 여기서 바꾸려면 프록시 환경에서 해당 변수를 해제하세요.", "Durch die Umgebungsvariable {envVar} deaktiviert. Entfernen Sie sie aus der Proxy-Umgebung, um die Einstellung hier zu ändern.", "Désactivé par la variable d'environnement {envVar}. Retirez-la de l'environnement du proxy pour modifier ce réglage ici.", "已被环境变量 {envVar} 禁用。若要在此更改,请在代理环境中取消设置该变量。", "已被環境變數 {envVar} 停用。若要在此變更,請在代理環境中取消設定該變數。", "Отключено переменной окружения {envVar}. Уберите её из окружения прокси, чтобы менять настройку здесь.", "環境変数 {envVar} により無効化されています。ここで変更するにはプロキシ環境から解除してください。", "{envVar} ortam değişkeni tarafından devre dışı bırakıldı. Buradan değiştirmek için proxy ortamında kaldırın.", "Đã tắt bởi biến môi trường {envVar}. Hãy bỏ biến này khỏi môi trường proxy để thay đổi tại đây.", "Desativado pela variável de ambiente {envVar}. Remova-a do ambiente do proxy para alterar esta opção aqui.", "Desactivada por la variable de entorno {envVar}. Elimínala del entorno del proxy para cambiar esta opción aquí."], + telemetryReadOnlyHint: ["Managed on the Home proxy for this Remote Link.", "이 원격 링크의 Home 프록시에서 관리돼요.", "Wird auf dem Home-Proxy dieses Remote Links verwaltet.", "Géré sur le proxy Home de ce lien distant.", "由该远程连接的 Home 代理管理。", "由該遠端連線的 Home 代理管理。", "Управляется на прокси Home этой удалённой связки.", "このリモートリンクの Home プロキシで管理されています。", "Bu Uzak Bağlantının Home proxy'sinde yönetilir.", "Được quản lý trên proxy Home của Liên kết từ xa này.", "Gerenciado no proxy Home deste Remote Link.", "Para este Remote Link se gestiona en el proxy de Home."], + telemetryLoadFailed: ["Could not load telemetry status.", "텔레메트리 상태를 불러오지 못했어요.", "Telemetriestatus konnte nicht geladen werden.", "Impossible de charger l'état de la télémétrie.", "无法加载遥测状态。", "無法載入遙測狀態。", "Не удалось загрузить состояние телеметрии.", "テレメトリの状態を読み込めませんでした。", "Telemetri durumu yüklenemedi.", "Không thể tải trạng thái telemetri.", "Não foi possível carregar o status da telemetria.", "No se pudo cargar el estado de la telemetría."], + telemetrySaveFailed: ["Could not save telemetry preference.", "텔레메트리 설정을 저장하지 못했어요.", "Telemetrie-Einstellung konnte nicht gespeichert werden.", "Impossible d'enregistrer la préférence de télémétrie.", "无法保存遥测偏好设置。", "無法儲存遙測偏好設定。", "Не удалось сохранить настройку телеметрии.", "テレメトリ設定を保存できませんでした。", "Telemetri tercihi kaydedilemedi.", "Không thể lưu tùy chọn telemetri.", "Não foi possível salvar a preferência de telemetria.", "No se pudo guardar la preferencia de telemetría."], + telemetrySaveUnconfirmed: ["Could not confirm the telemetry setting yet; checking again shortly.", "텔레메트리 설정을 아직 확인하지 못했어요. 곧 다시 확인해요.", "Die Telemetrie-Einstellung konnte noch nicht bestätigt werden; sie wird gleich erneut geprüft.", "Impossible de confirmer le réglage de télémétrie pour l'instant ; nouvelle vérification sous peu.", "暂时无法确认遥测设置,稍后会再次检查。", "暫時無法確認遙測設定,稍後會再次檢查。", "Пока не удалось подтвердить настройку телеметрии; скоро проверим ещё раз.", "テレメトリ設定をまだ確認できません。まもなく再確認します。", "Telemetri ayarı henüz doğrulanamadı; kısa süre içinde yeniden denetlenecek.", "Chưa xác nhận được cài đặt telemetri; sẽ kiểm tra lại trong giây lát.", "Ainda não foi possível confirmar a configuração de telemetria; verificaremos novamente em breve.", "Aún no se pudo confirmar la configuración de telemetría. Se volverá a consultar en breve."], + telemetrySaveNeedsHumanSession: ["This session was restored from a remembered device, so it can't record a telemetry choice. Open the dashboard on the proxy's computer, or run ocx telemetry enable or ocx telemetry disable in a terminal.", "이 세션은 기억된 기기에서 복원되어 텔레메트리 선택을 저장할 수 없어요. 프록시가 실행 중인 컴퓨터에서 대시보드를 열거나, 터미널에서 ocx telemetry enable 또는 ocx telemetry disable을 실행하세요.", "Diese Sitzung wurde von einem gespeicherten Gerät wiederhergestellt und kann keine Telemetrie-Entscheidung speichern. Öffnen Sie das Dashboard auf dem Rechner des Proxys oder führen Sie ocx telemetry enable bzw. ocx telemetry disable im Terminal aus.", "Cette session a été restaurée depuis un appareil mémorisé et ne peut pas enregistrer de choix de télémétrie. Ouvrez le tableau de bord sur l'ordinateur du proxy, ou lancez ocx telemetry enable ou ocx telemetry disable dans un terminal.", "此会话由已记住的设备恢复,无法保存遥测选择。请在运行代理的电脑上打开仪表盘,或在终端运行 ocx telemetry enable 或 ocx telemetry disable。", "此工作階段由已記住的裝置還原,無法儲存遙測選擇。請在執行代理的電腦上開啟儀表板,或在終端機執行 ocx telemetry enable 或 ocx telemetry disable。", "Этот сеанс восстановлен с запомненного устройства, поэтому не может сохранить выбор телеметрии. Откройте дашборд на компьютере с прокси или выполните ocx telemetry enable либо ocx telemetry disable в терминале.", "このセッションは記憶済みのデバイスから復元されたため、テレメトリの選択を保存できません。プロキシが動いているコンピューターでダッシュボードを開くか、ターミナルで ocx telemetry enable または ocx telemetry disable を実行してください。", "Bu oturum hatırlanan bir cihazdan geri yüklendiği için telemetri tercihini kaydedemez. Panoyu proxy'nin çalıştığı bilgisayarda açın veya bir terminalde ocx telemetry enable ya da ocx telemetry disable çalıştırın.", "Phiên này được khôi phục từ một thiết bị đã ghi nhớ nên không thể lưu lựa chọn telemetri. Hãy mở bảng điều khiển trên máy đang chạy proxy, hoặc chạy ocx telemetry enable hay ocx telemetry disable trong terminal.", "Esta sessão foi restaurada de um dispositivo lembrado e não pode salvar a escolha de telemetria. Abra o painel no computador do proxy ou execute ocx telemetry enable ou ocx telemetry disable em um terminal.", "La sesión se restauró desde un dispositivo recordado y no puede registrar una elección de telemetría. Abre el panel en el equipo del proxy o ejecuta ocx telemetry enable u ocx telemetry disable en una terminal."], + telemetryConsentTitle: ["Help improve opencodex with anonymous usage stats", "익명 사용 통계로 opencodex 개선에 함께해 주세요", "opencodex mit anonymen Nutzungsstatistiken verbessern", "Aider à améliorer opencodex avec des statistiques anonymes", "通过匿名使用统计帮助改进 opencodex", "透過匿名使用統計協助改進 opencodex", "Помогите улучшать opencodex анонимной статистикой", "匿名の利用統計で opencodex の改善に協力する", "Anonim kullanım istatistikleriyle opencodex'i geliştirmeye yardımcı olun", "Giúp cải thiện opencodex bằng thống kê sử dụng ẩn danh", "Ajude a melhorar o opencodex com estatísticas anônimas de uso", "Ayuda a mejorar OpenCodex con estadísticas anónimas"], + telemetryConsentBody: ["opencodex can send one anonymous daily summary to telemetry.opencodex.me; only project-wide totals are published at opencodex.me/dashboard. You can turn it off here, later in Proxy details, with ocx telemetry disable, or with OCX_TELEMETRY=0 or DO_NOT_TRACK=1 in the proxy's environment.", "opencodex는 하루 한 번 익명 요약을 telemetry.opencodex.me로 보낼 수 있어요. 공개되는 것은 opencodex.me/dashboard의 프로젝트 전체 합계뿐이에요. 여기서, 나중에 프록시 상세 설정에서, ocx telemetry disable 명령으로, 또는 프록시 환경의 OCX_TELEMETRY=0이나 DO_NOT_TRACK=1로 끌 수 있어요.", "opencodex kann einmal täglich eine anonyme Zusammenfassung an telemetry.opencodex.me senden; veröffentlicht werden nur projektweite Summen unter opencodex.me/dashboard. Sie können dies hier, später in den Proxy-Details, mit ocx telemetry disable oder mit OCX_TELEMETRY=0 bzw. DO_NOT_TRACK=1 in der Umgebung des Proxys abschalten.", "opencodex peut envoyer un résumé quotidien anonyme à telemetry.opencodex.me ; seuls les totaux du projet sont publiés sur opencodex.me/dashboard. Vous pouvez le désactiver ici, plus tard dans les détails du proxy, avec ocx telemetry disable, ou avec OCX_TELEMETRY=0 ou DO_NOT_TRACK=1 dans l'environnement du proxy.", "opencodex 可每天向 telemetry.opencodex.me 发送一次匿名汇总;opencodex.me/dashboard 只公开项目整体总数。您可以在此处、稍后在代理详情中、使用 ocx telemetry disable,或在代理环境中设置 OCX_TELEMETRY=0 或 DO_NOT_TRACK=1 来关闭。", "opencodex 可每天向 telemetry.opencodex.me 傳送一次匿名彙總;opencodex.me/dashboard 只公開專案整體總數。您可以在此處、稍後在代理詳情中、使用 ocx telemetry disable,或在代理環境中設定 OCX_TELEMETRY=0 或 DO_NOT_TRACK=1 來關閉。", "opencodex может раз в день отправлять анонимную сводку на telemetry.opencodex.me; на opencodex.me/dashboard публикуются только общие итоги проекта. Отключить можно здесь, позже в настройках прокси, командой ocx telemetry disable или переменной OCX_TELEMETRY=0 либо DO_NOT_TRACK=1 в окружении прокси.", "opencodex は1日1回、匿名の集計を telemetry.opencodex.me に送信できます。opencodex.me/dashboard で公開されるのはプロジェクト全体の合計だけです。ここで、あとでプロキシ詳細で、ocx telemetry disable で、またはプロキシの環境で OCX_TELEMETRY=0 か DO_NOT_TRACK=1 を設定してオフにできます。", "opencodex günde bir kez anonim bir özeti telemetry.opencodex.me adresine gönderebilir; opencodex.me/dashboard'da yalnızca proje geneli toplamlar yayımlanır. Bunu burada, daha sonra Proxy ayrıntılarında, ocx telemetry disable ile ya da proxy ortamında OCX_TELEMETRY=0 veya DO_NOT_TRACK=1 ile kapatabilirsiniz.", "opencodex có thể gửi bản tóm tắt ẩn danh mỗi ngày một lần tới telemetry.opencodex.me; chỉ tổng số toàn dự án được công bố tại opencodex.me/dashboard. Bạn có thể tắt tại đây, sau này trong Chi tiết proxy, bằng ocx telemetry disable, hoặc bằng OCX_TELEMETRY=0 hay DO_NOT_TRACK=1 trong môi trường của proxy.", "O opencodex pode enviar um resumo diário anônimo para telemetry.opencodex.me; apenas os totais do projeto são publicados em opencodex.me/dashboard. Você pode desativar aqui, depois nos detalhes do proxy, com ocx telemetry disable, ou com OCX_TELEMETRY=0 ou DO_NOT_TRACK=1 no ambiente do proxy.", "OpenCodex puede enviar un resumen diario anónimo a telemetry.opencodex.me. En opencodex.me/dashboard solo se publican los totales del proyecto. Puedes desactivarlo aquí, más adelante en Detalles del proxy, con ocx telemetry disable o con OCX_TELEMETRY=0 o DO_NOT_TRACK=1 en el entorno del proxy."], + telemetrySentTitle: ["What is sent", "보내는 항목", "Gesendet wird", "Envoyé", "发送的数据", "傳送的資料", "Отправляется", "送信されるもの", "Gönderilenler", "Được gửi", "Enviado", "Qué se envía"], + telemetrySentItems: ["A per-day install hash that changes every day, version, release channel, OS/CPU, install channel, first-report flag, active minutes, provider kind, coarse model family, request outcomes, token totals, and closed error codes.", "매일 바뀌는 일별 설치 해시, 버전, 릴리스 채널, OS/CPU, 설치 채널, 첫 보고 여부, 활성 시간(분), 프로바이더 종류, 모델 계열, 요청 결과, 토큰 합계, 고정된 오류 코드.", "Ein täglich wechselnder Installations-Hash, Version, Release-Kanal, OS/CPU, Installationskanal, Erstmeldungs-Flag, aktive Minuten, Anbieterart, grobe Modellfamilie, Anfrageergebnisse, Token-Summen und feste Fehlercodes.", "Un hachage d'installation qui change chaque jour, version, canal de publication, OS/CPU, canal d'installation, indicateur de premier envoi, minutes actives, type de fournisseur, famille de modèles, résultats des requêtes, totaux de jetons et codes d'erreur fermés.", "每天更换的安装哈希、版本、发布渠道、系统与架构、安装渠道、首次上报标记、活跃分钟数、提供商类型、粗粒度模型系列、请求结果、令牌总数及固定错误码。", "每天更換的安裝雜湊、版本、發布管道、系統與架構、安裝管道、首次回報標記、活躍分鐘數、供應商類型、粗粒度模型系列、請求結果、Token 總數及固定錯誤碼。", "Хеш установки, меняющийся каждый день, версия, канал выпуска, ОС и архитектура, канал установки, признак первого отчёта, активные минуты, тип провайдера, семейство моделей, исходы запросов, суммы токенов и закрытые коды ошибок.", "毎日変わるインストールハッシュ、バージョン、リリースチャネル、OS/CPU、インストール経路、初回送信フラグ、アクティブ分数、プロバイダー種別、大まかなモデル系統、リクエスト結果、トークン合計、固定エラーコード。", "Her gün değişen bir kurulum karması, sürüm, sürüm kanalı, İS/CPU, kurulum kanalı, ilk rapor işareti, etkin dakikalar, sağlayıcı türü, kaba model ailesi, istek sonuçları, jeton toplamları ve kapalı hata kodları.", "Mã băm cài đặt thay đổi mỗi ngày, phiên bản, kênh phát hành, OS/CPU, kênh cài đặt, cờ báo cáo đầu tiên, số phút hoạt động, loại nhà cung cấp, dòng mô hình, kết quả yêu cầu, tổng token và mã lỗi cố định.", "Um hash de instalação que muda todo dia, versão, canal de lançamento, SO/CPU, canal de instalação, indicador de primeiro envio, minutos ativos, tipo de provedor, família de modelos, resultados de requisições, totais de tokens e códigos fechados de erro.", "Un hash de la instalación que cambia cada día, versión, canal de publicación, sistema operativo y CPU, canal de instalación, indicador del primer informe, minutos de actividad, tipo de proveedor, familia general del modelo, resultados de las solicitudes, totales de tokens y códigos de error de un conjunto cerrado."], + telemetryNeverTitle: ["Never sent", "절대 보내지 않는 항목", "Niemals gesendet", "Jamais envoyé", "绝不发送", "絕不傳送", "Никогда не отправляется", "送信されないもの", "Asla gönderilmeyenler", "Không bao giờ gửi", "Nunca enviado", "Nunca se envía"], + telemetryNeverItems: ["Prompts, model outputs, request/response bodies, API keys, OAuth tokens, account IDs or emails, custom base URLs, hostnames, file paths, or raw error messages.", "프롬프트, 모델 출력, 요청/응답 본문, API 키, OAuth 토큰, 계정 ID나 이메일, 사용자 지정 URL, 호스트 이름, 파일 경로, 원본 오류 메시지.", "Prompts, Modellausgaben, Anfrage-/Antwortinhalte, API-Schlüssel, OAuth-Tokens, Konto-IDs oder E-Mail-Adressen, eigene Basis-URLs, Hostnamen, Dateipfade oder rohe Fehlermeldungen.", "Prompts, sorties de modèles, corps de requêtes/réponses, clés API, jetons OAuth, identifiants de compte ou e-mails, URL de base personnalisées, noms d'hôte, chemins de fichiers ou messages d'erreur bruts.", "提示词、模型输出、请求或响应正文、API 密钥、OAuth 令牌、账户 ID 或邮箱、自定义基础 URL、主机名、文件路径或原始错误信息。", "提示詞、模型輸出、請求或回應正文、API 金鑰、OAuth 權杖、帳號 ID 或信箱、自訂基礎 URL、主機名稱、檔案路徑或原始錯誤訊息。", "Промпты, ответы моделей, тела запросов и ответов, API-ключи, OAuth-токены, ID аккаунтов и адреса почты, свои базовые URL, имена хостов, пути к файлам и тексты ошибок.", "プロンプト、モデル出力、リクエスト/レスポンス本文、APIキー、OAuthトークン、アカウントIDやメールアドレス、カスタムURL、ホスト名、ファイルパス、生のエラーメッセージ。", "İstemler, model çıktıları, istek/yanıt gövdeleri, API anahtarları, OAuth belirteçleri, hesap kimlikleri veya e-postaları, özel temel URL'ler, ana bilgisayar adları, dosya yolları veya ham hata iletileri.", "Prompt, đầu ra mô hình, nội dung yêu cầu/phản hồi, khóa API, token OAuth, ID hoặc email tài khoản, URL cơ sở tùy chỉnh, tên máy chủ, đường dẫn tệp hoặc thông báo lỗi thô.", "Prompts, saídas de modelos, corpos de requisição/resposta, chaves de API, tokens OAuth, IDs ou e-mails de contas, URLs base personalizadas, nomes de host, caminhos de arquivos ou mensagens brutas de erro.", "Prompts, salidas del modelo, cuerpos de solicitudes o respuestas, claves API, tokens OAuth, IDs o correos de cuentas, URLs base personalizadas, nombres de host, rutas de archivos ni mensajes de error sin procesar."], + telemetryPolicyLink: ["Read the full privacy policy", "전체 개인정보 처리방침 보기", "Vollständige Datenschutzerklärung lesen", "Lire la politique de confidentialité complète", "阅读完整隐私政策", "閱讀完整隱私權政策", "Полная политика конфиденциальности", "プライバシーポリシー全文を読む", "Gizlilik politikasının tamamını okuyun", "Đọc toàn bộ chính sách quyền riêng tư", "Ler a política de privacidade completa", "Leer la política de privacidad completa"], + telemetryConsentCheckbox: ["Share anonymous daily usage statistics", "익명 일일 사용 통계 공유하기", "Anonyme tägliche Nutzungsstatistiken teilen", "Partager les statistiques quotidiennes anonymes", "共享匿名每日使用统计", "共享匿名每日使用統計", "Делиться анонимной ежедневной статистикой", "匿名の1日ごとの利用統計を共有する", "Anonim günlük kullanım istatistiklerini paylaş", "Chia sẻ thống kê sử dụng ẩn danh hằng ngày", "Compartilhar estatísticas diárias anônimas de uso", "Compartir estadísticas diarias anónimas de uso"], + telemetryConsentContinue: ["Continue", "계속", "Weiter", "Continuer", "继续", "繼續", "Продолжить", "続行", "Devam", "Tiếp tục", "Continuar", "Continuar"], // ---- Advisor ------------------------------------------------------------------------------------ - advisorLede: ["A second model that reviews the worker's progress and sends advice back.", "Worker의 작업을 검토하고 조언을 돌려주는 두 번째 모델이에요.", "Ein zweites Modell, das den Fortschritt des Workers prüft und Rat zurückgibt.", "Un second modèle qui examine l'avancement du worker et lui renvoie des conseils.", "第二个模型,审查 Worker 的进展并返回建议。", "第二個模型,審查 Worker 的進展並回傳建議。", "Вторая модель, которая проверяет ход работы и возвращает советы.", "Worker の作業を確認して助言を返す、2 つ目のモデルです。", "Worker'ın ilerlemesini inceleyip tavsiye döndüren ikinci bir model.", "Mô hình thứ hai xem xét tiến độ của worker và gửi lại lời khuyên.", "Um segundo modelo que revisa o progresso do worker e devolve conselhos."], - advisorSettings: ["Advisor settings", "어드바이저 설정", "Berater-Einstellungen", "Réglages du conseiller", "顾问设置", "顧問設定", "Настройки советника", "アドバイザー設定", "Danışman ayarları", "Cài đặt cố vấn", "Configurações do conselheiro"], - enabledHint: ["Consultations run only while this is on.", "켜져 있을 때만 상담해요.", "Beratungen laufen nur, solange dies an ist.", "Les consultations n'ont lieu que lorsque cette option est active.", "仅在开启时进行咨询。", "僅在開啟時進行諮詢。", "Консультации идут, только пока это включено.", "オンのときだけ相談します。", "Danışmalar yalnızca bu açıkken çalışır.", "Chỉ tham vấn khi tùy chọn này bật.", "As consultas só acontecem enquanto isto estiver ativado."], - effortHint: ["How hard the advisor thinks before it answers.", "어드바이저가 답하기 전에 얼마나 깊이 생각할지예요.", "Wie gründlich der Berater vor der Antwort nachdenkt.", "Le niveau de réflexion du conseiller avant de répondre.", "顾问回答前的思考深度。", "顧問回答前的思考深度。", "Насколько глубоко советник думает перед ответом.", "アドバイザーが答える前にどれだけ深く考えるかです。", "Danışmanın yanıt vermeden önce ne kadar düşüneceği.", "Mức độ cố vấn suy nghĩ trước khi trả lời.", "Quanto o conselheiro pensa antes de responder."], - policyHint: ["When the advisor is consulted.", "언제 상담할지 정해요.", "Wann der Berater gefragt wird.", "Quand le conseiller est consulté.", "何时咨询顾问。", "何時諮詢顧問。", "Когда обращаться к советнику.", "いつアドバイザーに相談するかです。", "Danışmana ne zaman başvurulacağı.", "Khi nào tham vấn cố vấn.", "Quando o conselheiro é consultado."], - taskLimitHint: ["The most automatic consultations one task can use.", "작업 하나에서 쓸 수 있는 자동 상담 최대 횟수예요.", "Höchstzahl automatischer Beratungen pro Aufgabe.", "Le nombre maximal de consultations automatiques par tâche.", "单个任务最多可用的自动咨询次数。", "單一任務最多可用的自動諮詢次數。", "Максимум автоматических консультаций на одну задачу.", "1 つの作業で使える自動相談の上限回数です。", "Bir görevin kullanabileceği en fazla otomatik danışma sayısı.", "Số lần tham vấn tự động tối đa cho một tác vụ.", "O máximo de consultas automáticas que uma tarefa pode usar."], - timeoutHint: ["How long to wait for advice before giving up.", "조언을 기다리다 포기하기까지의 시간이에요.", "Wie lange auf Rat gewartet wird, bevor abgebrochen wird.", "Durée d'attente des conseils avant abandon.", "放弃前等待建议的时长。", "放棄前等待建議的時間。", "Сколько ждать совета, прежде чем отказаться.", "助言をあきらめるまで待つ時間です。", "Vazgeçmeden önce tavsiye için ne kadar bekleneceği.", "Thời gian chờ lời khuyên trước khi bỏ qua.", "Quanto esperar pelo conselho antes de desistir."], - consentTitle: ["Context sharing", "컨텍스트 공유 동의", "Kontextfreigabe", "Partage du contexte", "上下文共享", "上下文共享", "Передача контекста", "コンテキスト共有", "Bağlam paylaşımı", "Chia sẻ ngữ cảnh", "Compartilhamento de contexto"], - consentNeeded: ["Required to run", "실행에 필요", "Zum Ausführen nötig", "Requis pour l'exécution", "运行所必需", "執行所必需", "Нужно для запуска", "実行に必要", "Çalışmak için gerekli", "Bắt buộc để chạy", "Necessário para executar"], - consentGiven: ["Agreed", "동의함", "Zugestimmt", "Accepté", "已同意", "已同意", "Согласие дано", "同意済み", "Onaylandı", "Đã đồng ý", "Aceito"], - unsaved: ["Unsaved changes", "저장하지 않은 변경 사항", "Ungespeicherte Änderungen", "Modifications non enregistrées", "有未保存的更改", "有未儲存的變更", "Есть несохранённые изменения", "未保存の変更があります", "Kaydedilmemiş değişiklikler", "Có thay đổi chưa lưu", "Alterações não salvas"], - activityLede: ["Consultations from the last 24 hours of this process.", "이 프로세스에서 최근 24시간 동안의 상담 기록이에요.", "Beratungen der letzten 24 Stunden dieses Prozesses.", "Consultations des dernières 24 heures de ce processus.", "此进程最近 24 小时的咨询记录。", "此程序最近 24 小時的諮詢紀錄。", "Консультации этого процесса за последние 24 часа.", "このプロセスの直近 24 時間の相談記録です。", "Bu işlemin son 24 saatteki danışmaları.", "Các lần tham vấn trong 24 giờ qua của tiến trình này.", "Consultas das últimas 24 horas deste processo."], - activityEmptyHint: ["Consultations appear here once the advisor runs.", "어드바이저가 실행되면 여기에 기록이 쌓여요.", "Beratungen erscheinen hier, sobald der Berater läuft.", "Les consultations apparaissent ici dès que le conseiller s'exécute.", "顾问运行后,咨询记录会显示在这里。", "顧問執行後,諮詢紀錄會顯示在這裡。", "Консультации появятся здесь, когда советник начнёт работать.", "アドバイザーが動くと、ここに記録がたまります。", "Danışman çalıştığında danışmalar burada görünür.", "Các lần tham vấn sẽ hiện ở đây khi cố vấn chạy.", "As consultas aparecem aqui quando o conselheiro rodar."], - + advisorLede: ["A second model that reviews the worker's progress and sends advice back.", "Worker의 작업을 검토하고 조언을 돌려주는 두 번째 모델이에요.", "Ein zweites Modell, das den Fortschritt des Workers prüft und Rat zurückgibt.", "Un second modèle qui examine l'avancement du worker et lui renvoie des conseils.", "第二个模型,审查 Worker 的进展并返回建议。", "第二個模型,審查 Worker 的進展並回傳建議。", "Вторая модель, которая проверяет ход работы и возвращает советы.", "Worker の作業を確認して助言を返す、2 つ目のモデルです。", "Worker'ın ilerlemesini inceleyip tavsiye döndüren ikinci bir model.", "Mô hình thứ hai xem xét tiến độ của worker và gửi lại lời khuyên.", "Um segundo modelo que revisa o progresso do worker e devolve conselhos.", "Un segundo modelo revisa el progreso del agente ejecutor y le envía recomendaciones."], + advisorSettings: ["Advisor settings", "어드바이저 설정", "Berater-Einstellungen", "Réglages du conseiller", "顾问设置", "顧問設定", "Настройки советника", "アドバイザー設定", "Danışman ayarları", "Cài đặt cố vấn", "Configurações do conselheiro", "Configuración del asesor"], + enabledHint: ["Consultations run only while this is on.", "켜져 있을 때만 상담해요.", "Beratungen laufen nur, solange dies an ist.", "Les consultations n'ont lieu que lorsque cette option est active.", "仅在开启时进行咨询。", "僅在開啟時進行諮詢。", "Консультации идут, только пока это включено.", "オンのときだけ相談します。", "Danışmalar yalnızca bu açıkken çalışır.", "Chỉ tham vấn khi tùy chọn này bật.", "As consultas só acontecem enquanto isto estiver ativado.", "Solo se hacen consultas mientras esta opción está activa."], + effortHint: ["How hard the advisor thinks before it answers.", "어드바이저가 답하기 전에 얼마나 깊이 생각할지예요.", "Wie gründlich der Berater vor der Antwort nachdenkt.", "Le niveau de réflexion du conseiller avant de répondre.", "顾问回答前的思考深度。", "顧問回答前的思考深度。", "Насколько глубоко советник думает перед ответом.", "アドバイザーが答える前にどれだけ深く考えるかです。", "Danışmanın yanıt vermeden önce ne kadar düşüneceği.", "Mức độ cố vấn suy nghĩ trước khi trả lời.", "Quanto o conselheiro pensa antes de responder.", "Cuánto razonamiento usa el asesor antes de responder."], + policyHint: ["When the advisor is consulted.", "언제 상담할지 정해요.", "Wann der Berater gefragt wird.", "Quand le conseiller est consulté.", "何时咨询顾问。", "何時諮詢顧問。", "Когда обращаться к советнику.", "いつアドバイザーに相談するかです。", "Danışmana ne zaman başvurulacağı.", "Khi nào tham vấn cố vấn.", "Quando o conselheiro é consultado.", "Cuándo se consulta al asesor."], + taskLimitHint: ["The most automatic consultations one task can use.", "작업 하나에서 쓸 수 있는 자동 상담 최대 횟수예요.", "Höchstzahl automatischer Beratungen pro Aufgabe.", "Le nombre maximal de consultations automatiques par tâche.", "单个任务最多可用的自动咨询次数。", "單一任務最多可用的自動諮詢次數。", "Максимум автоматических консультаций на одну задачу.", "1 つの作業で使える自動相談の上限回数です。", "Bir görevin kullanabileceği en fazla otomatik danışma sayısı.", "Số lần tham vấn tự động tối đa cho một tác vụ.", "O máximo de consultas automáticas que uma tarefa pode usar.", "Máximo de consultas automáticas que puede usar una tarea."], + timeoutHint: ["How long to wait for advice before giving up.", "조언을 기다리다 포기하기까지의 시간이에요.", "Wie lange auf Rat gewartet wird, bevor abgebrochen wird.", "Durée d'attente des conseils avant abandon.", "放弃前等待建议的时长。", "放棄前等待建議的時間。", "Сколько ждать совета, прежде чем отказаться.", "助言をあきらめるまで待つ時間です。", "Vazgeçmeden önce tavsiye için ne kadar bekleneceği.", "Thời gian chờ lời khuyên trước khi bỏ qua.", "Quanto esperar pelo conselho antes de desistir.", "Cuánto esperar una recomendación antes de cancelar la consulta."], + consentTitle: ["Context sharing", "컨텍스트 공유 동의", "Kontextfreigabe", "Partage du contexte", "上下文共享", "上下文共享", "Передача контекста", "コンテキスト共有", "Bağlam paylaşımı", "Chia sẻ ngữ cảnh", "Compartilhamento de contexto", "Compartir contexto"], + consentNeeded: ["Required to run", "실행에 필요", "Zum Ausführen nötig", "Requis pour l'exécution", "运行所必需", "執行所必需", "Нужно для запуска", "実行に必要", "Çalışmak için gerekli", "Bắt buộc để chạy", "Necessário para executar", "Necesario para funcionar"], + consentGiven: ["Agreed", "동의함", "Zugestimmt", "Accepté", "已同意", "已同意", "Согласие дано", "同意済み", "Onaylandı", "Đã đồng ý", "Aceito", "Aceptado"], + unsaved: ["Unsaved changes", "저장하지 않은 변경 사항", "Ungespeicherte Änderungen", "Modifications non enregistrées", "有未保存的更改", "有未儲存的變更", "Есть несохранённые изменения", "未保存の変更があります", "Kaydedilmemiş değişiklikler", "Có thay đổi chưa lưu", "Alterações não salvas", "Cambios no guardados"], + activityLede: ["Consultations from the last 24 hours of this process.", "이 프로세스에서 최근 24시간 동안의 상담 기록이에요.", "Beratungen der letzten 24 Stunden dieses Prozesses.", "Consultations des dernières 24 heures de ce processus.", "此进程最近 24 小时的咨询记录。", "此程序最近 24 小時的諮詢紀錄。", "Консультации этого процесса за последние 24 часа.", "このプロセスの直近 24 時間の相談記録です。", "Bu işlemin son 24 saatteki danışmaları.", "Các lần tham vấn trong 24 giờ qua của tiến trình này.", "Consultas das últimas 24 horas deste processo.", "Consultas de las últimas 24 horas de este proceso."], + activityEmptyHint: ["Consultations appear here once the advisor runs.", "어드바이저가 실행되면 여기에 기록이 쌓여요.", "Beratungen erscheinen hier, sobald der Berater läuft.", "Les consultations apparaissent ici dès que le conseiller s'exécute.", "顾问运行后,咨询记录会显示在这里。", "顧問執行後,諮詢紀錄會顯示在這裡。", "Консультации появятся здесь, когда советник начнёт работать.", "アドバイザーが動くと、ここに記録がたまります。", "Danışman çalıştığında danışmalar burada görünür.", "Các lần tham vấn sẽ hiện ở đây khi cố vấn chạy.", "As consultas aparecem aqui quando o conselheiro rodar.", "Las consultas aparecen aquí cuando se usa el asesor."], // ---- All settings hub --------------------------------------------------------------------------- // Descriptive line under a card title (product names such as Advisor or Claude Code stay literal). - advTermProxy: ["Sidecars · Compaction · Memory", "사이드카 · 압축 · 메모리", "Sidecars · Komprimierung · Speicher", "Modèles annexes · Compaction · Mémoire", "辅助模型 · 压缩 · 记忆", "輔助模型 · 壓縮 · 記憶", "Вспомогательные модели · Сжатие · Память", "サイドカー · 圧縮 · メモリ", "Yardımcı modeller · Sıkıştırma · Bellek", "Mô hình phụ trợ · Nén · Bộ nhớ", "Sidecars · Compactação · Memória"], - advTermRouting: ["Routing profiles · Compatibility", "라우팅 프로필 · 호환성", "Routing-Profile · Kompatibilität", "Profils de routage · Compatibilité", "路由配置 · 兼容性", "路由設定檔 · 相容性", "Профили маршрутизации · Совместимость", "ルーティングプロファイル · 互換性", "Yönlendirme profilleri · Uyumluluk", "Hồ sơ định tuyến · Tương thích", "Perfis de roteamento · Compatibilidade"], - advTermPrompt: ["Prompt layers", "프롬프트 레이어", "Prompt-Ebenen", "Couches de prompt", "提示词层", "提示詞層", "Слои промпта", "プロンプトレイヤー", "İstem katmanları", "Các lớp prompt", "Camadas de prompt"], - advTermProviders: ["Request pacing · Key rotation", "요청 속도 조절 · 키 순환", "Anfragetaktung · Schlüsselrotation", "Rythme des requêtes · Rotation des clés", "请求节流 · 密钥轮换", "請求節流 · 金鑰輪替", "Темп запросов · Ротация ключей", "リクエスト間隔 · キーのローテーション", "İstek hızı · Anahtar rotasyonu", "Điều tốc yêu cầu · Xoay vòng khóa", "Ritmo de requisições · Rotação de chaves"], - advTermStorage: ["Storage · Log Guard", "저장 공간 · Log Guard", "Speicherplatz · Log Guard", "Stockage · Log Guard", "存储 · Log Guard", "儲存空間 · Log Guard", "Хранилище · Log Guard", "ストレージ · Log Guard", "Depolama · Log Guard", "Lưu trữ · Log Guard", "Armazenamento · Log Guard"], - advTermDesktop: ["Desktop compatibility", "Desktop 호환성", "Desktop-Kompatibilität", "Compatibilité Desktop", "Desktop 兼容性", "Desktop 相容性", "Совместимость с Desktop", "Desktop 互換性", "Desktop uyumluluğu", "Tương thích Desktop", "Compatibilidade com o Desktop"], - hubCount: ["{count} shown", "{count}개 표시", "{count} angezeigt", "{count} affichés", "显示 {count} 项", "顯示 {count} 項", "Показано: {count}", "{count} 件を表示", "{count} gösteriliyor", "Đang hiện {count}", "{count} exibidos"], + advTermProxy: ["Sidecars · Compaction · Memory", "사이드카 · 압축 · 메모리", "Sidecars · Komprimierung · Speicher", "Modèles annexes · Compaction · Mémoire", "辅助模型 · 压缩 · 记忆", "輔助模型 · 壓縮 · 記憶", "Вспомогательные модели · Сжатие · Память", "サイドカー · 圧縮 · メモリ", "Yardımcı modeller · Sıkıştırma · Bellek", "Mô hình phụ trợ · Nén · Bộ nhớ", "Sidecars · Compactação · Memória", "Modelos auxiliares · Compactación · Memoria"], + advTermRouting: ["Routing profiles · Compatibility", "라우팅 프로필 · 호환성", "Routing-Profile · Kompatibilität", "Profils de routage · Compatibilité", "路由配置 · 兼容性", "路由設定檔 · 相容性", "Профили маршрутизации · Совместимость", "ルーティングプロファイル · 互換性", "Yönlendirme profilleri · Uyumluluk", "Hồ sơ định tuyến · Tương thích", "Perfis de roteamento · Compatibilidade", "Perfiles de routing · Compatibilidad"], + advTermPrompt: ["Prompt layers", "프롬프트 레이어", "Prompt-Ebenen", "Couches de prompt", "提示词层", "提示詞層", "Слои промпта", "プロンプトレイヤー", "İstem katmanları", "Các lớp prompt", "Camadas de prompt", "Capas rápidas"], + advTermProviders: ["Request pacing · Key rotation", "요청 속도 조절 · 키 순환", "Anfragetaktung · Schlüsselrotation", "Rythme des requêtes · Rotation des clés", "请求节流 · 密钥轮换", "請求節流 · 金鑰輪替", "Темп запросов · Ротация ключей", "リクエスト間隔 · キーのローテーション", "İstek hızı · Anahtar rotasyonu", "Điều tốc yêu cầu · Xoay vòng khóa", "Ritmo de requisições · Rotação de chaves", "Ritmo de solicitudes · Rotación de claves"], + advTermStorage: ["Storage · Log Guard", "저장 공간 · Log Guard", "Speicherplatz · Log Guard", "Stockage · Log Guard", "存储 · Log Guard", "儲存空間 · Log Guard", "Хранилище · Log Guard", "ストレージ · Log Guard", "Depolama · Log Guard", "Lưu trữ · Log Guard", "Armazenamento · Log Guard", "Almacenamiento · Log Guard"], + advTermDesktop: ["Desktop compatibility", "Desktop 호환성", "Desktop-Kompatibilität", "Compatibilité Desktop", "Desktop 兼容性", "Desktop 相容性", "Совместимость с Desktop", "Desktop 互換性", "Desktop uyumluluğu", "Tương thích Desktop", "Compatibilidade com o Desktop", "Compatibilidad con Desktop"], + hubCount: ["{count} shown", "{count}개 표시", "{count} angezeigt", "{count} affichés", "显示 {count} 项", "顯示 {count} 項", "Показано: {count}", "{count} 件を表示", "{count} gösteriliyor", "Đang hiện {count}", "{count} exibidos", "Se muestran {count}"], } satisfies Record; export const proxyV2Copy = copyTable("proxyV2", rows); diff --git a/gui/src/i18n/v2-pages/startup-copy.ts b/gui/src/i18n/v2-pages/startup-copy.ts index af8ff502cfe..dacb248a358 100644 --- a/gui/src/i18n/v2-pages/startup-copy.ts +++ b/gui/src/i18n/v2-pages/startup-copy.ts @@ -1,12 +1,12 @@ import { copyTable, type Row } from "./copy-table"; /* - * Copy for the v2 Startup protection, Remote Link and Remote Workspace pages. Columns: en, ko, de, fr, zh, zh-TW, ru, ja, tr, vi, pt. + * Copy for the v2 Startup protection, Remote Link and Remote Workspace pages. Columns: en, ko, de, fr, zh, zh-TW, ru, ja, tr, vi, pt, es. * Keys render as `startupV2.`. */ const rows = { // ---- Startup protection - about: ["About: {name}", "{name} 설명", "Info: {name}", "À propos : {name}", "说明:{name}", "說明:{name}", "Подробнее: {name}", "説明: {name}", "Hakkında: {name}", "Giới thiệu: {name}", "Sobre: {name}"], + about: ["About: {name}", "{name} 설명", "Info: {name}", "À propos : {name}", "说明:{name}", "說明:{name}", "Подробнее: {name}", "説明: {name}", "Hakkında: {name}", "Giới thiệu: {name}", "Sobre: {name}", "Acerca de {name}"], optionsTitle: [ "Keep Codex working after a restart", "재부팅 후에도 Codex가 동작하게 하기", @@ -19,6 +19,7 @@ const rows = { "Yeniden başlatmadan sonra Codex çalışmaya devam etsin", "Giữ Codex hoạt động sau khi khởi động lại", "Manter o Codex funcionando após reiniciar", + "Mantén Codex operativo después de reiniciar", ], optionsHint: [ "One healthy option is enough. The background service covers the most ways Codex starts.", @@ -32,10 +33,11 @@ const rows = { "Sağlıklı tek bir seçenek yeterli. Arka plan hizmeti, Codex'in en çok başlatılma yolunu kapsar.", "Chỉ cần một cách hoạt động tốt. Dịch vụ nền bao quát nhiều cách khởi động Codex nhất.", "Uma opção funcionando já basta. O serviço em segundo plano cobre a maioria das formas de iniciar o Codex.", + "Basta con una opción que funcione. El servicio en segundo plano cubre la mayoría de las formas de iniciar Codex.", ], - recommended: ["Recommended", "권장", "Empfohlen", "Recommandé", "推荐", "推薦", "Рекомендуется", "推奨", "Önerilen", "Khuyên dùng", "Recomendado"], - optional: ["Optional", "선택", "Optional", "Facultatif", "可选", "選用", "Необязательно", "任意", "İsteğe bağlı", "Tùy chọn", "Opcional"], - shimPlain: ["Start with Codex", "Codex와 함께 시작", "Mit Codex starten", "Démarrer avec Codex", "随 Codex 启动", "隨 Codex 啟動", "Запуск вместе с Codex", "Codex と一緒に起動", "Codex ile başlat", "Khởi động cùng Codex", "Iniciar com o Codex"], + recommended: ["Recommended", "권장", "Empfohlen", "Recommandé", "推荐", "推薦", "Рекомендуется", "推奨", "Önerilen", "Khuyên dùng", "Recomendado", "Recomendado"], + optional: ["Optional", "선택", "Optional", "Facultatif", "可选", "選用", "Необязательно", "任意", "İsteğe bağlı", "Tùy chọn", "Opcional", "Opcional"], + shimPlain: ["Start with Codex", "Codex와 함께 시작", "Mit Codex starten", "Démarrer avec Codex", "随 Codex 启动", "隨 Codex 啟動", "Запуск вместе с Codex", "Codex と一緒に起動", "Codex ile başlat", "Khởi động cùng Codex", "Iniciar com o Codex", "Iniciar con Codex"], recoveryMeta: [ "Commands to run yourself", "직접 실행하는 명령", @@ -48,10 +50,11 @@ const rows = { "Kendiniz çalıştıracağınız komutlar", "Lệnh để tự chạy", "Comandos para você executar", + "Comandos para ejecutar manualmente", ], // ---- Remote Link - off: ["Off", "꺼짐", "Aus", "Désactivé", "关闭", "關閉", "Выкл.", "オフ", "Kapalı", "Tắt", "Desligado"], - on: ["On", "켜짐", "An", "Activé", "开启", "開啟", "Вкл.", "オン", "Açık", "Bật", "Ligado"], + off: ["Off", "꺼짐", "Aus", "Désactivé", "关闭", "關閉", "Выкл.", "オフ", "Kapalı", "Tắt", "Desligado", "Desactivado"], + on: ["On", "켜짐", "An", "Activé", "开启", "開啟", "Вкл.", "オン", "Açık", "Bật", "Ligado", "Activado"], linkIntroTitle: [ "Use one computer's setup on your other computers", "한 컴퓨터의 설정을 다른 컴퓨터에서도 쓰기", @@ -64,6 +67,7 @@ const rows = { "Bir bilgisayarın kurulumunu diğer bilgisayarlarınızda kullanın", "Dùng thiết lập của một máy cho các máy khác", "Use a configuração de um computador nos outros", + "Usa la configuración de un equipo en tus otros equipos", ], linkIntroBody: [ "Remote Link connects OpenCodex computers over SSH. The Home shares its providers, and a Child uses them without any setup of its own.", @@ -77,12 +81,13 @@ const rows = { "Remote Link, OpenCodex bilgisayarlarını SSH üzerinden bağlar. Home sağlayıcılarını paylaşır, Child bunları kendi kurulumu olmadan kullanır.", "Remote Link kết nối các máy OpenCodex qua SSH. Máy Home chia sẻ nhà cung cấp, máy Child dùng lại mà không cần tự thiết lập.", "O Remote Link conecta computadores OpenCodex por SSH. O Home compartilha seus provedores e um Child os usa sem configuração própria.", + "Remote Link conecta equipos con OpenCodex por SSH. Home comparte sus proveedores y el Child los usa sin configuración propia.", ], - sshTunnel: ["SSH tunnel", "SSH 터널", "SSH-Tunnel", "Tunnel SSH", "SSH 隧道", "SSH 通道", "SSH-туннель", "SSH トンネル", "SSH tüneli", "Đường hầm SSH", "Túnel SSH"], - stepHost: ["Choose a host", "호스트 선택", "Host wählen", "Choisir un hôte", "选择主机", "選擇主機", "Выбор хоста", "ホストを選ぶ", "Ana bilgisayar seçin", "Chọn máy chủ", "Escolher o host"], - stepVerify: ["Check the host key", "호스트 키 확인", "Hostschlüssel prüfen", "Vérifier la clé d’hôte", "核对主机密钥", "核對主機金鑰", "Проверка ключа хоста", "ホストキーを確認", "Ana bilgisayar anahtarını doğrulayın", "Kiểm tra khóa máy chủ", "Conferir a chave do host"], - stepConnect: ["Connect", "연결", "Verbinden", "Connecter", "连接", "連線", "Подключение", "接続", "Bağlan", "Kết nối", "Conectar"], - steps: ["Steps", "단계", "Schritte", "Étapes", "步骤", "步驟", "Шаги", "手順", "Adımlar", "Các bước", "Etapas"], + sshTunnel: ["SSH tunnel", "SSH 터널", "SSH-Tunnel", "Tunnel SSH", "SSH 隧道", "SSH 通道", "SSH-туннель", "SSH トンネル", "SSH tüneli", "Đường hầm SSH", "Túnel SSH", "Túnel SSH"], + stepHost: ["Choose a host", "호스트 선택", "Host wählen", "Choisir un hôte", "选择主机", "選擇主機", "Выбор хоста", "ホストを選ぶ", "Ana bilgisayar seçin", "Chọn máy chủ", "Escolher o host", "Elige un host"], + stepVerify: ["Check the host key", "호스트 키 확인", "Hostschlüssel prüfen", "Vérifier la clé d’hôte", "核对主机密钥", "核對主機金鑰", "Проверка ключа хоста", "ホストキーを確認", "Ana bilgisayar anahtarını doğrulayın", "Kiểm tra khóa máy chủ", "Conferir a chave do host", "Comprueba la clave del host"], + stepConnect: ["Connect", "연결", "Verbinden", "Connecter", "连接", "連線", "Подключение", "接続", "Bağlan", "Kết nối", "Conectar", "Conectar"], + steps: ["Steps", "단계", "Schritte", "Étapes", "步骤", "步驟", "Шаги", "手順", "Adımlar", "Các bước", "Etapas", "Pasos"], } satisfies Record; export const startupV2Copy = copyTable("startupV2", rows); diff --git a/gui/src/i18n/v2-pages/subagents-copy.ts b/gui/src/i18n/v2-pages/subagents-copy.ts index cf3bf82d6b1..73df3532558 100644 --- a/gui/src/i18n/v2-pages/subagents-copy.ts +++ b/gui/src/i18n/v2-pages/subagents-copy.ts @@ -1,7 +1,7 @@ import { copyTable, type Row } from "./copy-table"; /* - * Copy for the v2 Subagents page. Columns: en, ko, de, fr, zh, zh-TW, ru, ja, tr, vi, pt. + * Copy for the v2 Subagents page. Columns: en, ko, de, fr, zh, zh-TW, ru, ja, tr, vi, pt, es. * Keys render as `subagentsV2.`. */ const rows = { @@ -17,51 +17,61 @@ const rows = { "Codex ve Claude Code'un iş devredeceği modelleri seçin.", "Chọn các mô hình mà Codex và Claude Code giao việc cho.", "Escolha os modelos para os quais o Codex e o Claude Code delegam trabalho.", + "Elige los modelos a los que Codex y Claude Code delegan trabajo.", ], nowTitle: [ "In effect now", "지금 적용 중", "Aktuell wirksam", "En vigueur", "当前生效", "目前生效", "Сейчас действует", "現在の設定", "Şu an geçerli", "Đang áp dụng", "Em vigor agora", + "Configuración vigente", ], nowOrder: [ "Codex picker, first choice", "Codex 추천 1순위", "Codex-Auswahl, erste Wahl", "Sélecteur Codex, premier choix", "Codex 推荐首选", "Codex 推薦首選", "Codex: первый вариант", "Codex 推奨の 1 位", "Codex seçicisi, ilk tercih", "Codex: lựa chọn đầu tiên", "Seletor do Codex, primeira opção", + "Primera opción del selector de Codex", ], nowOrderNone: [ "Not set, catalog order", "설정 안 함, 카탈로그 순서", "Nicht gesetzt, Katalogreihenfolge", "Non défini, ordre du catalogue", "未设置,按目录顺序", "未設定,依目錄順序", "Не задано, порядок каталога", "未設定(カタログ順)", "Ayarlanmadı, katalog sırası", "Chưa đặt, theo thứ tự danh mục", "Não definido, ordem do catálogo", + "Sin configurar, sigue el orden del catálogo", ], nowOrderCaption: [ "{n} of {max} picked", "{max}개 중 {n}개 선택", "{n} von {max} gewählt", "{n} sur {max} choisis", "已选 {n}/{max}", "已選 {n}/{max}", "Выбрано {n} из {max}", "{max} 件中 {n} 件を選択", "{max} içinden {n} seçildi", "Đã chọn {n}/{max}", "{n} de {max} escolhidos", + "{n} de {max} seleccionados", ], firstNoneCaption: [ "Codex picks on its own", "Codex가 알아서 고릅니다", "Codex wählt selbst", "Codex choisit seul", "由 Codex 自行选择", "由 Codex 自行選擇", "Codex выбирает сам", "Codex が自分で選びます", "Codex kendisi seçer", "Codex tự chọn", "O Codex escolhe sozinho", + "Codex elige por su cuenta", ], nowPin: [ "Claude Code pin", "Claude Code 모델 고정", "Claude-Code-Fixierung", "Modèle fixé Claude Code", "Claude Code 固定模型", "Claude Code 固定模型", "Закрепление Claude Code", "Claude Code の固定", "Claude Code sabitleme", "Ghim Claude Code", "Fixação do Claude Code", + "Modelo fijo de Claude Code", ], pinOffCaption: [ "Each agent keeps its own model", "에이전트마다 원래 모델을 씁니다", "Jeder Agent behält sein Modell", "Chaque agent garde son modèle", "各代理沿用自己的模型", "各代理沿用自己的模型", "Каждый агент со своей моделью", "各エージェントが自分のモデルを使います", "Her ajan kendi modelini kullanır", "Mỗi tác tử giữ mô hình riêng", "Cada agente mantém o próprio modelo", + "Cada agente conserva su modelo", ], pinOnCaption: [ "Every Claude Code subagent", "Claude Code의 모든 서브에이전트", "Jeder Claude-Code-Subagent", "Tous les sous-agents Claude Code", "所有 Claude Code 子代理", "所有 Claude Code 子代理", "Все субагенты Claude Code", "Claude Code のすべてのサブエージェント", "Tüm Claude Code alt ajanları", "Mọi tác tử phụ của Claude Code", "Todos os subagentes do Claude Code", + "Todos los subagentes de Claude Code", ], - off: ["Off", "꺼짐", "Aus", "Désactivé", "关闭", "關閉", "Выкл.", "オフ", "Kapalı", "Tắt", "Desligado"], - change: ["Change", "변경", "Ändern", "Modifier", "更改", "變更", "Изменить", "変更", "Değiştir", "Thay đổi", "Alterar"], + off: ["Off", "꺼짐", "Aus", "Désactivé", "关闭", "關閉", "Выкл.", "オフ", "Kapalı", "Tắt", "Desligado", "Desactivado"], + change: ["Change", "변경", "Ändern", "Modifier", "更改", "變更", "Изменить", "変更", "Değiştir", "Thay đổi", "Alterar", "Cambiar"], moreAbout: [ "More about {label}", "{label} 자세히 보기", "Mehr zu {label}", "En savoir plus : {label}", "关于{label}", "關於{label}", "Подробнее: {label}", "{label}の詳細", "{label} hakkında", "Thêm về {label}", "Mais sobre {label}", + "Más sobre {label}", ], forceLede: [ "When on, every Claude Code subagent runs on the one model you pick.", @@ -75,6 +85,7 @@ const rows = { "Açıkken tüm Claude Code alt ajanları seçtiğiniz tek modelle çalışır.", "Khi bật, mọi tác tử phụ của Claude Code chạy trên mô hình bạn chọn.", "Ligado, todos os subagentes do Claude Code usam o modelo escolhido.", + "Al activarlo, todos los subagentes de Claude Code usan el modelo que elijas.", ], budgetLede: [ "Per-task caps that stop a runaway task from flooding your providers.", @@ -88,16 +99,19 @@ const rows = { "Kontrolden çıkan bir görevin sağlayıcıları boğmasını önleyen görev başına sınırlar.", "Giới hạn cho mỗi tác vụ để một tác vụ mất kiểm soát không làm ngập nhà cung cấp.", "Limites por tarefa para que uma tarefa descontrolada não sobrecarregue os provedores.", + "Límites por tarea que evitan que una tarea fuera de control sature a tus proveedores.", ], unsaved: [ "Unsaved changes", "저장하지 않은 변경 사항", "Ungespeicherte Änderungen", "Modifications non enregistrées", "有未保存的更改", "有未儲存的變更", "Есть несохранённые изменения", "未保存の変更があります", "Kaydedilmemiş değişiklikler", "Có thay đổi chưa lưu", "Alterações não salvas", + "Cambios sin guardar", ], noChanges: [ "No unsaved changes", "변경 사항 없음", "Keine ungespeicherten Änderungen", "Aucune modification en attente", "没有未保存的更改", "沒有未儲存的變更", "Несохранённых изменений нет", "未保存の変更はありません", "Kaydedilmemiş değişiklik yok", "Không có thay đổi chưa lưu", "Nenhuma alteração pendente", + "No hay cambios sin guardar", ], featuredLede: [ "Codex offers these first, top to bottom. Changes save on their own.", @@ -111,10 +125,12 @@ const rows = { "Codex bunları yukarıdan aşağıya ilk sırada sunar. Değişiklikler kendiliğinden kaydedilir.", "Codex đề xuất các mô hình này trước, từ trên xuống. Thay đổi tự lưu.", "O Codex oferece estes primeiro, de cima para baixo. As alterações são salvas sozinhas.", + "Codex ofrece primero estos modelos, de arriba abajo. Los cambios se guardan automáticamente.", ], emptySlot: [ "Empty slot", "빈 자리", "Freier Platz", "Emplacement libre", "空位", "空位", "Свободное место", "空き枠", "Boş yer", "Ô trống", "Espaço livre", + "Espacio vacío", ], modelsLede: [ "Add up to {max} models to the picker order.", @@ -128,13 +144,15 @@ const rows = { "Seçici sırasına en fazla {max} model ekleyin.", "Thêm tối đa {max} mô hình vào thứ tự đề xuất.", "Adicione até {max} modelos à ordem do seletor.", + "Añade hasta {max} modelos al orden del selector.", ], - rank: ["No. {n}", "{n}순위", "Nr. {n}", "N° {n}", "第 {n} 位", "第 {n} 位", "№ {n}", "{n} 位", "{n}. sıra", "Hạng {n}", "N.º {n}"], - add: ["Add", "추가", "Hinzufügen", "Ajouter", "添加", "新增", "Добавить", "追加", "Ekle", "Thêm", "Adicionar"], - added: ["Added", "추가됨", "Hinzugefügt", "Ajouté", "已添加", "已新增", "Добавлено", "追加済み", "Eklendi", "Đã thêm", "Adicionado"], + rank: ["No. {n}", "{n}순위", "Nr. {n}", "N° {n}", "第 {n} 位", "第 {n} 位", "№ {n}", "{n} 位", "{n}. sıra", "Hạng {n}", "N.º {n}", "N.º {n}"], + add: ["Add", "추가", "Hinzufügen", "Ajouter", "添加", "新增", "Добавить", "追加", "Ekle", "Thêm", "Adicionar", "Añadir"], + added: ["Added", "추가됨", "Hinzugefügt", "Ajouté", "已添加", "已新增", "Добавлено", "追加済み", "Eklendi", "Đã thêm", "Adicionado", "Añadido"], delegationTitle: [ "Codex delegation", "Codex 위임", "Codex-Delegation", "Délégation Codex", "Codex 委派", "Codex 委派", "Делегирование Codex", "Codex の委任", "Codex devretme", "Ủy quyền của Codex", "Delegação do Codex", + "Delegación de Codex", ], delegationShort: [ "Codex calls this model first when it splits work.", @@ -148,6 +166,7 @@ const rows = { "Codex işi bölerken önce bu modeli çağırır.", "Codex gọi mô hình này đầu tiên khi chia việc.", "O Codex chama este modelo primeiro ao dividir o trabalho.", + "Codex llama primero a este modelo cuando divide el trabajo.", ], syncShort: [ "Also write it to Codex's config, so new tasks start with it.", @@ -161,6 +180,7 @@ const rows = { "Codex yapılandırmasına da yaz, yeni görevler bununla başlasın.", "Ghi cả vào cấu hình Codex để tác vụ mới cũng bắt đầu với mô hình này.", "Gravar também na config do Codex, para novas tarefas começarem com ele.", + "Guárdalo también en la configuración de Codex para que las tareas nuevas lo usen desde el inicio.", ], guidanceShort: [ "Send Codex a short note on how to split work.", @@ -174,6 +194,7 @@ const rows = { "Codex'e işin nasıl bölüneceğine dair kısa bir not gönder.", "Gửi Codex một ghi chú ngắn về cách chia việc.", "Enviar ao Codex uma nota curta sobre como dividir o trabalho.", + "Envía a Codex una indicación breve sobre cómo dividir el trabajo.", ], ultraShort: [ "Have every model delegate proactively.", @@ -187,6 +208,7 @@ const rows = { "Her model işi kendiliğinden devretsin.", "Để mọi mô hình chủ động giao việc.", "Fazer cada modelo delegar por iniciativa própria.", + "Haz que todos los modelos deleguen de forma proactiva.", ], surfaceShort: [ "Which multi-agent surface each model uses.", @@ -200,6 +222,7 @@ const rows = { "Her modelin hangi çoklu ajan yüzeyini kullandığı.", "Mỗi mô hình dùng bề mặt đa tác tử nào.", "Qual superfície multiagente cada modelo usa.", + "Interfaz multiagente que usa cada modelo.", ], advancedHint: [ "Surface, split-work note, proactive delegation", @@ -213,6 +236,7 @@ const rows = { "Yüzey, bölme notu, proaktif devretme", "Bề mặt, ghi chú chia việc, ủy quyền chủ động", "Superfície, nota de divisão, delegação proativa", + "Interfaz, indicaciones para dividir el trabajo y delegación proactiva", ], } satisfies Record; diff --git a/gui/src/i18n/v2-pages/telemetry-profile-copy.ts b/gui/src/i18n/v2-pages/telemetry-profile-copy.ts index a4689950e15..bf463d201b0 100644 --- a/gui/src/i18n/v2-pages/telemetry-profile-copy.ts +++ b/gui/src/i18n/v2-pages/telemetry-profile-copy.ts @@ -2,46 +2,46 @@ import { copyTable, type Row } from "./copy-table"; /* * Copy for the Home "Public profile & rank" card (the opt-in leaderboard profile). Columns: en, ko, - * de, fr, zh, zh-TW, ru, ja, tr, vi, pt. Keys render as `telemetryProfile.`. + * de, fr, zh, zh-TW, ru, ja, tr, vi, pt, es. Keys render as `telemetryProfile.`. */ const rows = { - title: ["Public profile & rank", "공개 프로필 & 순위", "Öffentliches Profil & Rang", "Profil public et classement", "公开资料与排名", "公開資料與排名", "Публичный профиль и рейтинг", "公開プロフィールと順位", "Herkese açık profil ve sıralama", "Hồ sơ công khai & xếp hạng", "Perfil público e ranking"], - lede: ["Join the opencodex.me leaderboard and see where your usage ranks. Off unless you connect it.", "opencodex.me 리더보드에 참여해 내 사용량 순위를 확인해요. 직접 연결하기 전에는 꺼져 있어요.", "Tritt der Rangliste auf opencodex.me bei und sieh, wo deine Nutzung steht. Aus, bis du verbindest.", "Rejoignez le classement d'opencodex.me et voyez où se situe votre usage. Désactivé tant que vous ne vous connectez pas.", "加入 opencodex.me 排行榜,查看你的用量排名。在你主动连接前保持关闭。", "加入 opencodex.me 排行榜,查看你的用量排名。在你主動連接前保持關閉。", "Присоединяйтесь к рейтингу opencodex.me и смотрите своё место по использованию. Выключено, пока вы не подключитесь.", "opencodex.me のリーダーボードに参加して、利用量の順位を確認できます。接続するまではオフです。", "opencodex.me sıralamasına katıl ve kullanımının nerede olduğunu gör. Bağlanana kadar kapalıdır.", "Tham gia bảng xếp hạng opencodex.me và xem mức sử dụng của bạn đứng thứ mấy. Tắt cho đến khi bạn kết nối.", "Entre no ranking do opencodex.me e veja onde seu uso se posiciona. Desligado até você conectar."], - publicWhat: ["Public: the handle, name and colour you choose, your rank, and daily request, token and model-family totals.", "공개: 직접 고른 핸들·이름·색상, 순위, 일일 요청·토큰·모델 계열 합계.", "Öffentlich: gewählter Handle, Name und Farbe, dein Rang sowie tägliche Summen für Anfragen, Tokens und Modellfamilien.", "Public : l'identifiant, le nom et la couleur choisis, votre rang et les totaux quotidiens de requêtes, jetons et familles de modèles.", "公开:你选择的用户名、名称和颜色,你的排名,以及每日请求、令牌和模型系列合计。", "公開:你選擇的帳號名稱、名稱與顏色,你的排名,以及每日請求、Token 與模型系列合計。", "Публично: выбранные ник, имя и цвет, ваше место и дневные суммы запросов, токенов и семейств моделей.", "公開されるもの: 選んだハンドル・名前・色、順位、日ごとのリクエスト・トークン・モデル系統の合計。", "Herkese açık: seçtiğin kullanıcı adı, isim ve renk, sıran ve günlük istek, jeton ve model ailesi toplamları.", "Công khai: tên định danh, tên và màu bạn chọn, thứ hạng, cùng tổng số yêu cầu, token và dòng mô hình mỗi ngày.", "Público: o identificador, o nome e a cor que você escolher, sua posição e os totais diários de requisições, tokens e famílias de modelos."], - neverWhat: ["Never shared: prompts, responses, keys, accounts, e-mail, devices or your anonymous telemetry ID.", "절대 공유하지 않음: 프롬프트, 응답, 키, 계정, 이메일, 기기, 익명 텔레메트리 ID.", "Nie geteilt: Prompts, Antworten, Schlüssel, Konten, E-Mail, Geräte oder deine anonyme Telemetrie-ID.", "Jamais partagé : prompts, réponses, clés, comptes, e-mail, appareils ni votre identifiant de télémétrie anonyme.", "绝不共享:提示词、回复、密钥、账户、邮箱、设备或你的匿名遥测 ID。", "絕不分享:提示詞、回覆、金鑰、帳號、電子郵件、裝置或你的匿名遙測 ID。", "Никогда не передаются: промпты, ответы, ключи, аккаунты, почта, устройства и ваш анонимный ID телеметрии.", "共有されないもの: プロンプト、応答、キー、アカウント、メール、デバイス、匿名テレメトリ ID。", "Asla paylaşılmaz: istemler, yanıtlar, anahtarlar, hesaplar, e-posta, cihazlar veya anonim telemetri kimliğin.", "Không bao giờ chia sẻ: prompt, phản hồi, khóa, tài khoản, email, thiết bị hay ID telemetri ẩn danh của bạn.", "Nunca compartilhado: prompts, respostas, chaves, contas, e-mail, dispositivos ou seu ID anônimo de telemetria."], - learnMore: ["How it works", "작동 방식", "So funktioniert es", "Fonctionnement", "工作方式", "運作方式", "Как это работает", "仕組み", "Nasıl çalışır", "Cách hoạt động", "Como funciona"], - connect: ["Connect", "연결", "Verbinden", "Connecter", "连接", "連接", "Подключить", "接続", "Bağlan", "Kết nối", "Conectar"], - connecting: ["Connecting…", "연결 중…", "Verbinde…", "Connexion…", "正在连接…", "正在連接…", "Подключение…", "接続中…", "Bağlanıyor…", "Đang kết nối…", "Conectando…"], - cancel: ["Cancel", "취소", "Abbrechen", "Annuler", "取消", "取消", "Отмена", "キャンセル", "İptal", "Hủy", "Cancelar"], - handleLabel: ["Handle", "핸들", "Handle", "Identifiant", "用户名", "帳號名稱", "Ник", "ハンドル", "Kullanıcı adı", "Tên định danh", "Identificador"], - handleHint: ["3–24 lowercase letters, digits or hyphens", "소문자·숫자·하이픈 3–24자", "3–24 Kleinbuchstaben, Ziffern oder Bindestriche", "3 à 24 minuscules, chiffres ou tirets", "3–24 个小写字母、数字或连字符", "3–24 個小寫字母、數字或連字號", "3–24 строчные латинские буквы, цифры или дефисы", "小文字・数字・ハイフンで 3〜24 文字", "3–24 küçük harf, rakam veya tire", "3–24 chữ thường, chữ số hoặc dấu gạch ngang", "3 a 24 letras minúsculas, dígitos ou hifens"], - nameLabel: ["Display name", "표시 이름", "Anzeigename", "Nom affiché", "显示名称", "顯示名稱", "Отображаемое имя", "表示名", "Görünen ad", "Tên hiển thị", "Nome de exibição"], - colourLabel: ["Colour", "색상", "Farbe", "Couleur", "颜色", "顏色", "Цвет", "色", "Renk", "Màu", "Cor"], - acknowledge: ["I understand this profile and its totals are public.", "이 프로필과 합계가 공개된다는 것을 이해했어요.", "Mir ist klar, dass dieses Profil und seine Summen öffentlich sind.", "Je comprends que ce profil et ses totaux sont publics.", "我了解此资料及其合计是公开的。", "我了解此資料及其合計是公開的。", "Я понимаю, что профиль и его суммы публичны.", "このプロフィールと合計が公開されることを理解しました。", "Bu profilin ve toplamlarının herkese açık olduğunu anlıyorum.", "Tôi hiểu hồ sơ này và các tổng số của nó là công khai.", "Entendo que este perfil e seus totais são públicos."], - errTaken: ["That handle is already taken.", "이미 사용 중인 핸들이에요.", "Dieser Handle ist bereits vergeben.", "Cet identifiant est déjà pris.", "该用户名已被占用。", "該帳號名稱已被使用。", "Этот ник уже занят.", "そのハンドルは既に使われています。", "Bu kullanıcı adı zaten alınmış.", "Tên định danh này đã có người dùng.", "Esse identificador já está em uso."], - errInvalid: ["Check the handle and display name.", "핸들과 표시 이름을 확인해 주세요.", "Prüfe Handle und Anzeigenamen.", "Vérifiez l'identifiant et le nom affiché.", "请检查用户名和显示名称。", "請檢查帳號名稱與顯示名稱。", "Проверьте ник и отображаемое имя.", "ハンドルと表示名を確認してください。", "Kullanıcı adını ve görünen adı kontrol et.", "Hãy kiểm tra tên định danh và tên hiển thị.", "Verifique o identificador e o nome de exibição."], - errRateLimited: ["Too many profiles were created from this network. Try again later.", "이 네트워크에서 프로필이 너무 많이 만들어졌어요. 나중에 다시 시도해 주세요.", "Von diesem Netzwerk wurden zu viele Profile erstellt. Versuche es später erneut.", "Trop de profils ont été créés depuis ce réseau. Réessayez plus tard.", "此网络创建的资料过多,请稍后再试。", "此網路建立的資料過多,請稍後再試。", "С этой сети создано слишком много профилей. Повторите позже.", "このネットワークから作成されたプロフィールが多すぎます。後でもう一度お試しください。", "Bu ağdan çok fazla profil oluşturuldu. Daha sonra tekrar dene.", "Đã có quá nhiều hồ sơ được tạo từ mạng này. Hãy thử lại sau.", "Muitos perfis foram criados a partir desta rede. Tente novamente mais tarde."], - errTelemetryOff: ["Turn anonymous telemetry on first.", "먼저 익명 텔레메트리를 켜 주세요.", "Schalte zuerst die anonyme Telemetrie ein.", "Activez d'abord la télémétrie anonyme.", "请先开启匿名遥测。", "請先開啟匿名遙測。", "Сначала включите анонимную телеметрию.", "まず匿名テレメトリをオンにしてください。", "Önce anonim telemetriyi aç.", "Hãy bật telemetri ẩn danh trước.", "Ative primeiro a telemetria anônima."], - errSession: ["Connecting needs a dashboard session you opened yourself, or the CLI: ocx telemetry profile connect.", "연결하려면 직접 연 대시보드 세션이나 CLI(ocx telemetry profile connect)가 필요해요.", "Zum Verbinden brauchst du eine selbst geöffnete Dashboard-Sitzung oder die CLI: ocx telemetry profile connect.", "La connexion exige une session de tableau de bord ouverte par vous, ou la CLI : ocx telemetry profile connect.", "连接需要你亲自打开的仪表板会话,或使用 CLI:ocx telemetry profile connect。", "連接需要你親自開啟的儀表板工作階段,或使用 CLI:ocx telemetry profile connect。", "Для подключения нужен открытый вами сеанс панели или CLI: ocx telemetry profile connect.", "接続には自分で開いたダッシュボードのセッション、または CLI (ocx telemetry profile connect) が必要です。", "Bağlanmak için kendi açtığın bir pano oturumu veya CLI gerekir: ocx telemetry profile connect.", "Để kết nối cần phiên bảng điều khiển do bạn tự mở, hoặc CLI: ocx telemetry profile connect.", "Para conectar é preciso uma sessão do painel aberta por você, ou a CLI: ocx telemetry profile connect."], - errUnavailable: ["The telemetry service could not be reached. Nothing was saved.", "텔레메트리 서비스에 연결하지 못했어요. 아무것도 저장되지 않았어요.", "Der Telemetriedienst war nicht erreichbar. Nichts wurde gespeichert.", "Le service de télémétrie est injoignable. Rien n'a été enregistré.", "无法连接遥测服务,未保存任何内容。", "無法連線至遙測服務,未儲存任何內容。", "Сервис телеметрии недоступен. Ничего не сохранено.", "テレメトリサービスに接続できませんでした。何も保存されていません。", "Telemetri hizmetine ulaşılamadı. Hiçbir şey kaydedilmedi.", "Không thể kết nối dịch vụ telemetri. Chưa có gì được lưu.", "Não foi possível acessar o serviço de telemetria. Nada foi salvo."], - day: ["Day", "일간", "Tag", "Jour", "日", "日", "День", "日", "Gün", "Ngày", "Dia"], - week: ["Week", "주간", "Woche", "Semaine", "周", "週", "Неделя", "週", "Hafta", "Tuần", "Semana"], - month: ["Month", "월간", "Monat", "Mois", "月", "月", "Месяц", "月", "Ay", "Tháng", "Mês"], - rankOf: ["#{rank} of {of}", "{of}명 중 {rank}위", "Platz {rank} von {of}", "{rank}e sur {of}", "第 {rank} 名 / 共 {of}", "第 {rank} 名 / 共 {of}", "№{rank} из {of}", "{of} 人中 {rank} 位", "{of} kişi içinde {rank}.", "Hạng {rank}/{of}", "#{rank} de {of}"], - notRanked: ["Not ranked yet", "아직 순위 없음", "Noch kein Rang", "Pas encore classé", "尚未排名", "尚未排名", "Пока без места", "まだ順位なし", "Henüz sıralamada değil", "Chưa có hạng", "Ainda sem posição"], - totals: ["{tokens} tokens · {requests} requests", "토큰 {tokens} · 요청 {requests}", "{tokens} Tokens · {requests} Anfragen", "{tokens} jetons · {requests} requêtes", "{tokens} 令牌 · {requests} 请求", "{tokens} Token · {requests} 請求", "{tokens} токенов · {requests} запросов", "{tokens} トークン · {requests} リクエスト", "{tokens} jeton · {requests} istek", "{tokens} token · {requests} yêu cầu", "{tokens} tokens · {requests} requisições"], - firstRank: ["Your first rank appears after your first full UTC day.", "첫 순위는 첫 번째 UTC 하루가 지난 뒤에 나타나요.", "Dein erster Rang erscheint nach deinem ersten vollen UTC-Tag.", "Votre premier rang apparaît après votre premier jour UTC complet.", "首个排名会在你的第一个完整 UTC 日之后出现。", "首個排名會在你的第一個完整 UTC 日之後出現。", "Первое место появится после первых полных суток UTC.", "最初の順位は最初の UTC 日が終わった後に表示されます。", "İlk sıran ilk tam UTC gününden sonra görünür.", "Thứ hạng đầu tiên sẽ xuất hiện sau ngày UTC đầy đủ đầu tiên.", "Sua primeira posição aparece após seu primeiro dia UTC completo."], - topModels: ["Top model families this month", "이번 달 주요 모델 계열", "Wichtigste Modellfamilien diesen Monat", "Principales familles de modèles ce mois-ci", "本月主要模型系列", "本月主要模型系列", "Основные семейства моделей за месяц", "今月の主なモデル系統", "Bu ayın başlıca model aileleri", "Các dòng mô hình hàng đầu tháng này", "Principais famílias de modelos neste mês"], - viewLeaderboard: ["View leaderboard", "리더보드 보기", "Rangliste ansehen", "Voir le classement", "查看排行榜", "查看排行榜", "Открыть рейтинг", "リーダーボードを見る", "Sıralamayı gör", "Xem bảng xếp hạng", "Ver ranking"], - disconnect: ["Disconnect", "연결 해제", "Trennen", "Déconnecter", "断开连接", "中斷連接", "Отключить", "接続を解除", "Bağlantıyı kes", "Ngắt kết nối", "Desconectar"], - disconnectConfirm: ["Delete your public profile and all its data?", "공개 프로필과 모든 데이터를 삭제할까요?", "Öffentliches Profil und alle Daten löschen?", "Supprimer votre profil public et toutes ses données ?", "删除你的公开资料及其全部数据?", "刪除你的公開資料及其全部資料?", "Удалить публичный профиль и все его данные?", "公開プロフィールとそのすべてのデータを削除しますか?", "Herkese açık profilin ve tüm verileri silinsin mi?", "Xóa hồ sơ công khai và toàn bộ dữ liệu của nó?", "Excluir seu perfil público e todos os dados dele?"], - disconnectYes: ["Delete profile", "프로필 삭제", "Profil löschen", "Supprimer le profil", "删除资料", "刪除資料", "Удалить профиль", "プロフィールを削除", "Profili sil", "Xóa hồ sơ", "Excluir perfil"], - deletionPending: ["Deletion is pending: the telemetry service could not be reached. Nothing more is sent, and the proxy keeps retrying.", "삭제 대기 중: 텔레메트리 서비스에 연결하지 못했어요. 더 이상 아무것도 보내지 않고 프록시가 계속 재시도해요.", "Löschung ausstehend: Der Telemetriedienst war nicht erreichbar. Es wird nichts mehr gesendet, der Proxy versucht es weiter.", "Suppression en attente : le service de télémétrie est injoignable. Plus rien n'est envoyé et le proxy réessaie.", "删除待处理:无法连接遥测服务。不会再发送任何内容,代理会持续重试。", "刪除待處理:無法連線至遙測服務。不會再傳送任何內容,代理會持續重試。", "Удаление ожидает: сервис телеметрии недоступен. Больше ничего не отправляется, прокси повторяет попытки.", "削除待ち: テレメトリサービスに接続できませんでした。これ以上何も送信されず、プロキシが再試行を続けます。", "Silme bekliyor: telemetri hizmetine ulaşılamadı. Artık hiçbir şey gönderilmez, vekil tekrar denemeye devam eder.", "Đang chờ xóa: không thể kết nối dịch vụ telemetri. Sẽ không gửi thêm gì và proxy tiếp tục thử lại.", "Exclusão pendente: não foi possível acessar o serviço de telemetria. Nada mais é enviado e o proxy continua tentando."], - retry: ["Retry", "다시 시도", "Erneut versuchen", "Réessayer", "重试", "重試", "Повторить", "再試行", "Tekrar dene", "Thử lại", "Tentar novamente"], - paused: ["Paused while anonymous telemetry is off.", "익명 텔레메트리가 꺼져 있는 동안 일시 중지돼요.", "Pausiert, solange die anonyme Telemetrie aus ist.", "En pause tant que la télémétrie anonyme est désactivée.", "匿名遥测关闭期间已暂停。", "匿名遙測關閉期間已暫停。", "Приостановлено, пока анонимная телеметрия выключена.", "匿名テレメトリがオフの間は一時停止しています。", "Anonim telemetri kapalıyken duraklatıldı.", "Tạm dừng khi telemetri ẩn danh đang tắt.", "Pausado enquanto a telemetria anônima está desligada."], - revoked: ["The telemetry service no longer knows this profile. Disconnect and connect again.", "텔레메트리 서비스가 이 프로필을 더 이상 알지 못해요. 연결을 해제한 뒤 다시 연결해 주세요.", "Der Telemetriedienst kennt dieses Profil nicht mehr. Trenne die Verbindung und verbinde erneut.", "Le service de télémétrie ne connaît plus ce profil. Déconnectez-vous puis reconnectez-vous.", "遥测服务已不再识别此资料。请断开后重新连接。", "遙測服務已不再識別此資料。請中斷後重新連接。", "Сервис телеметрии больше не знает этот профиль. Отключитесь и подключитесь снова.", "テレメトリサービスはこのプロフィールを認識しなくなりました。接続を解除してから再接続してください。", "Telemetri hizmeti artık bu profili tanımıyor. Bağlantıyı kesip yeniden bağlan.", "Dịch vụ telemetri không còn nhận ra hồ sơ này. Hãy ngắt kết nối rồi kết nối lại.", "O serviço de telemetria não reconhece mais este perfil. Desconecte e conecte novamente."], - rankUnavailable: ["Rank is unavailable right now.", "지금은 순위를 불러올 수 없어요.", "Der Rang ist gerade nicht verfügbar.", "Le rang est indisponible pour le moment.", "暂时无法获取排名。", "暫時無法取得排名。", "Рейтинг сейчас недоступен.", "現在、順位を取得できません。", "Sıralama şu anda kullanılamıyor.", "Hiện không lấy được thứ hạng.", "A posição está indisponível no momento."], - unreadable: ["The local profile file cannot be read, so nothing is sent. Disconnect removes it.", "로컬 프로필 파일을 읽을 수 없어 아무것도 보내지 않아요. 연결 해제하면 파일을 지워요.", "Die lokale Profildatei ist nicht lesbar, daher wird nichts gesendet. Trennen entfernt sie.", "Le fichier de profil local est illisible ; rien n'est envoyé. Déconnecter le supprime.", "无法读取本地资料文件,因此不会发送任何内容。断开连接会删除该文件。", "無法讀取本機資料檔案,因此不會傳送任何內容。中斷連接會刪除該檔案。", "Локальный файл профиля не читается, поэтому ничего не отправляется. Отключение удалит его.", "ローカルのプロフィールファイルを読めないため、何も送信されません。接続を解除すると削除されます。", "Yerel profil dosyası okunamıyor, bu yüzden hiçbir şey gönderilmiyor. Bağlantıyı kesmek dosyayı siler.", "Không đọc được tệp hồ sơ cục bộ nên không gửi gì cả. Ngắt kết nối sẽ xóa tệp.", "O arquivo de perfil local não pode ser lido, então nada é enviado. Desconectar o remove."], + title: ["Public profile & rank", "공개 프로필 & 순위", "Öffentliches Profil & Rang", "Profil public et classement", "公开资料与排名", "公開資料與排名", "Публичный профиль и рейтинг", "公開プロフィールと順位", "Herkese açık profil ve sıralama", "Hồ sơ công khai & xếp hạng", "Perfil público e ranking", "Perfil público y clasificación"], + lede: ["Join the opencodex.me leaderboard and see where your usage ranks. Off unless you connect it.", "opencodex.me 리더보드에 참여해 내 사용량 순위를 확인해요. 직접 연결하기 전에는 꺼져 있어요.", "Tritt der Rangliste auf opencodex.me bei und sieh, wo deine Nutzung steht. Aus, bis du verbindest.", "Rejoignez le classement d'opencodex.me et voyez où se situe votre usage. Désactivé tant que vous ne vous connectez pas.", "加入 opencodex.me 排行榜,查看你的用量排名。在你主动连接前保持关闭。", "加入 opencodex.me 排行榜,查看你的用量排名。在你主動連接前保持關閉。", "Присоединяйтесь к рейтингу opencodex.me и смотрите своё место по использованию. Выключено, пока вы не подключитесь.", "opencodex.me のリーダーボードに参加して、利用量の順位を確認できます。接続するまではオフです。", "opencodex.me sıralamasına katıl ve kullanımının nerede olduğunu gör. Bağlanana kadar kapalıdır.", "Tham gia bảng xếp hạng opencodex.me và xem mức sử dụng của bạn đứng thứ mấy. Tắt cho đến khi bạn kết nối.", "Entre no ranking do opencodex.me e veja onde seu uso se posiciona. Desligado até você conectar.", "Únete a la clasificación de opencodex.me y consulta tu posición según el uso. Está desactivado hasta que conectes un perfil."], + publicWhat: ["Public: the handle, name and colour you choose, your rank, and daily request, token and model-family totals.", "공개: 직접 고른 핸들·이름·색상, 순위, 일일 요청·토큰·모델 계열 합계.", "Öffentlich: gewählter Handle, Name und Farbe, dein Rang sowie tägliche Summen für Anfragen, Tokens und Modellfamilien.", "Public : l'identifiant, le nom et la couleur choisis, votre rang et les totaux quotidiens de requêtes, jetons et familles de modèles.", "公开:你选择的用户名、名称和颜色,你的排名,以及每日请求、令牌和模型系列合计。", "公開:你選擇的帳號名稱、名稱與顏色,你的排名,以及每日請求、Token 與模型系列合計。", "Публично: выбранные ник, имя и цвет, ваше место и дневные суммы запросов, токенов и семейств моделей.", "公開されるもの: 選んだハンドル・名前・色、順位、日ごとのリクエスト・トークン・モデル系統の合計。", "Herkese açık: seçtiğin kullanıcı adı, isim ve renk, sıran ve günlük istek, jeton ve model ailesi toplamları.", "Công khai: tên định danh, tên và màu bạn chọn, thứ hạng, cùng tổng số yêu cầu, token và dòng mô hình mỗi ngày.", "Público: o identificador, o nome e a cor que você escolher, sua posição e os totais diários de requisições, tokens e famílias de modelos.", "Público: el alias, el nombre y el color que elijas, tu posición y los totales diarios de solicitudes, tokens y familias de modelos."], + neverWhat: ["Never shared: prompts, responses, keys, accounts, e-mail, devices or your anonymous telemetry ID.", "절대 공유하지 않음: 프롬프트, 응답, 키, 계정, 이메일, 기기, 익명 텔레메트리 ID.", "Nie geteilt: Prompts, Antworten, Schlüssel, Konten, E-Mail, Geräte oder deine anonyme Telemetrie-ID.", "Jamais partagé : prompts, réponses, clés, comptes, e-mail, appareils ni votre identifiant de télémétrie anonyme.", "绝不共享:提示词、回复、密钥、账户、邮箱、设备或你的匿名遥测 ID。", "絕不分享:提示詞、回覆、金鑰、帳號、電子郵件、裝置或你的匿名遙測 ID。", "Никогда не передаются: промпты, ответы, ключи, аккаунты, почта, устройства и ваш анонимный ID телеметрии.", "共有されないもの: プロンプト、応答、キー、アカウント、メール、デバイス、匿名テレメトリ ID。", "Asla paylaşılmaz: istemler, yanıtlar, anahtarlar, hesaplar, e-posta, cihazlar veya anonim telemetri kimliğin.", "Không bao giờ chia sẻ: prompt, phản hồi, khóa, tài khoản, email, thiết bị hay ID telemetri ẩn danh của bạn.", "Nunca compartilhado: prompts, respostas, chaves, contas, e-mail, dispositivos ou seu ID anônimo de telemetria.", "Nunca se comparten: prompts, respuestas, claves, cuentas, correo electrónico, dispositivos ni tu ID de telemetría anónima."], + learnMore: ["How it works", "작동 방식", "So funktioniert es", "Fonctionnement", "工作方式", "運作方式", "Как это работает", "仕組み", "Nasıl çalışır", "Cách hoạt động", "Como funciona", "Cómo funciona"], + connect: ["Connect", "연결", "Verbinden", "Connecter", "连接", "連接", "Подключить", "接続", "Bağlan", "Kết nối", "Conectar", "Conectar"], + connecting: ["Connecting…", "연결 중…", "Verbinde…", "Connexion…", "正在连接…", "正在連接…", "Подключение…", "接続中…", "Bağlanıyor…", "Đang kết nối…", "Conectando…", "Conectando…"], + cancel: ["Cancel", "취소", "Abbrechen", "Annuler", "取消", "取消", "Отмена", "キャンセル", "İptal", "Hủy", "Cancelar", "Cancelar"], + handleLabel: ["Handle", "핸들", "Handle", "Identifiant", "用户名", "帳號名稱", "Ник", "ハンドル", "Kullanıcı adı", "Tên định danh", "Identificador", "Alias"], + handleHint: ["3–24 lowercase letters, digits or hyphens", "소문자·숫자·하이픈 3–24자", "3–24 Kleinbuchstaben, Ziffern oder Bindestriche", "3 à 24 minuscules, chiffres ou tirets", "3–24 个小写字母、数字或连字符", "3–24 個小寫字母、數字或連字號", "3–24 строчные латинские буквы, цифры или дефисы", "小文字・数字・ハイフンで 3〜24 文字", "3–24 küçük harf, rakam veya tire", "3–24 chữ thường, chữ số hoặc dấu gạch ngang", "3 a 24 letras minúsculas, dígitos ou hifens", "Entre 3 y 24 letras minúsculas, dígitos o guiones"], + nameLabel: ["Display name", "표시 이름", "Anzeigename", "Nom affiché", "显示名称", "顯示名稱", "Отображаемое имя", "表示名", "Görünen ad", "Tên hiển thị", "Nome de exibição", "Mostrar nombre"], + colourLabel: ["Colour", "색상", "Farbe", "Couleur", "颜色", "顏色", "Цвет", "色", "Renk", "Màu", "Cor", "Color"], + acknowledge: ["I understand this profile and its totals are public.", "이 프로필과 합계가 공개된다는 것을 이해했어요.", "Mir ist klar, dass dieses Profil und seine Summen öffentlich sind.", "Je comprends que ce profil et ses totaux sont publics.", "我了解此资料及其合计是公开的。", "我了解此資料及其合計是公開的。", "Я понимаю, что профиль и его суммы публичны.", "このプロフィールと合計が公開されることを理解しました。", "Bu profilin ve toplamlarının herkese açık olduğunu anlıyorum.", "Tôi hiểu hồ sơ này và các tổng số của nó là công khai.", "Entendo que este perfil e seus totais são públicos.", "Entiendo que este perfil y sus totales son públicos."], + errTaken: ["That handle is already taken.", "이미 사용 중인 핸들이에요.", "Dieser Handle ist bereits vergeben.", "Cet identifiant est déjà pris.", "该用户名已被占用。", "該帳號名稱已被使用。", "Этот ник уже занят.", "そのハンドルは既に使われています。", "Bu kullanıcı adı zaten alınmış.", "Tên định danh này đã có người dùng.", "Esse identificador já está em uso.", "Ese alias ya está en uso."], + errInvalid: ["Check the handle and display name.", "핸들과 표시 이름을 확인해 주세요.", "Prüfe Handle und Anzeigenamen.", "Vérifiez l'identifiant et le nom affiché.", "请检查用户名和显示名称。", "請檢查帳號名稱與顯示名稱。", "Проверьте ник и отображаемое имя.", "ハンドルと表示名を確認してください。", "Kullanıcı adını ve görünen adı kontrol et.", "Hãy kiểm tra tên định danh và tên hiển thị.", "Verifique o identificador e o nome de exibição.", "Comprueba el alias y el nombre visible."], + errRateLimited: ["Too many profiles were created from this network. Try again later.", "이 네트워크에서 프로필이 너무 많이 만들어졌어요. 나중에 다시 시도해 주세요.", "Von diesem Netzwerk wurden zu viele Profile erstellt. Versuche es später erneut.", "Trop de profils ont été créés depuis ce réseau. Réessayez plus tard.", "此网络创建的资料过多,请稍后再试。", "此網路建立的資料過多,請稍後再試。", "С этой сети создано слишком много профилей. Повторите позже.", "このネットワークから作成されたプロフィールが多すぎます。後でもう一度お試しください。", "Bu ağdan çok fazla profil oluşturuldu. Daha sonra tekrar dene.", "Đã có quá nhiều hồ sơ được tạo từ mạng này. Hãy thử lại sau.", "Muitos perfis foram criados a partir desta rede. Tente novamente mais tarde.", "Se crearon demasiados perfiles desde esta red. Vuelve a intentarlo más tarde."], + errTelemetryOff: ["Turn anonymous telemetry on first.", "먼저 익명 텔레메트리를 켜 주세요.", "Schalte zuerst die anonyme Telemetrie ein.", "Activez d'abord la télémétrie anonyme.", "请先开启匿名遥测。", "請先開啟匿名遙測。", "Сначала включите анонимную телеметрию.", "まず匿名テレメトリをオンにしてください。", "Önce anonim telemetriyi aç.", "Hãy bật telemetri ẩn danh trước.", "Ative primeiro a telemetria anônima.", "Activa primero la telemetría anónima."], + errSession: ["Connecting needs a dashboard session you opened yourself, or the CLI: ocx telemetry profile connect.", "연결하려면 직접 연 대시보드 세션이나 CLI(ocx telemetry profile connect)가 필요해요.", "Zum Verbinden brauchst du eine selbst geöffnete Dashboard-Sitzung oder die CLI: ocx telemetry profile connect.", "La connexion exige une session de tableau de bord ouverte par vous, ou la CLI : ocx telemetry profile connect.", "连接需要你亲自打开的仪表板会话,或使用 CLI:ocx telemetry profile connect。", "連接需要你親自開啟的儀表板工作階段,或使用 CLI:ocx telemetry profile connect。", "Для подключения нужен открытый вами сеанс панели или CLI: ocx telemetry profile connect.", "接続には自分で開いたダッシュボードのセッション、または CLI (ocx telemetry profile connect) が必要です。", "Bağlanmak için kendi açtığın bir pano oturumu veya CLI gerekir: ocx telemetry profile connect.", "Để kết nối cần phiên bảng điều khiển do bạn tự mở, hoặc CLI: ocx telemetry profile connect.", "Para conectar é preciso uma sessão do painel aberta por você, ou a CLI: ocx telemetry profile connect.", "Para conectar el perfil, abre una sesión del panel tú mismo o usa la CLI: ocx telemetry profile connect."], + errUnavailable: ["The telemetry service could not be reached. Nothing was saved.", "텔레메트리 서비스에 연결하지 못했어요. 아무것도 저장되지 않았어요.", "Der Telemetriedienst war nicht erreichbar. Nichts wurde gespeichert.", "Le service de télémétrie est injoignable. Rien n'a été enregistré.", "无法连接遥测服务,未保存任何内容。", "無法連線至遙測服務,未儲存任何內容。", "Сервис телеметрии недоступен. Ничего не сохранено.", "テレメトリサービスに接続できませんでした。何も保存されていません。", "Telemetri hizmetine ulaşılamadı. Hiçbir şey kaydedilmedi.", "Không thể kết nối dịch vụ telemetri. Chưa có gì được lưu.", "Não foi possível acessar o serviço de telemetria. Nada foi salvo.", "No se pudo contactar al servicio de telemetría. No se guardó nada."], + day: ["Day", "일간", "Tag", "Jour", "日", "日", "День", "日", "Gün", "Ngày", "Dia", "Día"], + week: ["Week", "주간", "Woche", "Semaine", "周", "週", "Неделя", "週", "Hafta", "Tuần", "Semana", "Semana"], + month: ["Month", "월간", "Monat", "Mois", "月", "月", "Месяц", "月", "Ay", "Tháng", "Mês", "Mes"], + rankOf: ["#{rank} of {of}", "{of}명 중 {rank}위", "Platz {rank} von {of}", "{rank}e sur {of}", "第 {rank} 名 / 共 {of}", "第 {rank} 名 / 共 {of}", "№{rank} из {of}", "{of} 人中 {rank} 位", "{of} kişi içinde {rank}.", "Hạng {rank}/{of}", "#{rank} de {of}", "Puesto {rank} de {of}"], + notRanked: ["Not ranked yet", "아직 순위 없음", "Noch kein Rang", "Pas encore classé", "尚未排名", "尚未排名", "Пока без места", "まだ順位なし", "Henüz sıralamada değil", "Chưa có hạng", "Ainda sem posição", "Aún sin posición"], + totals: ["{tokens} tokens · {requests} requests", "토큰 {tokens} · 요청 {requests}", "{tokens} Tokens · {requests} Anfragen", "{tokens} jetons · {requests} requêtes", "{tokens} 令牌 · {requests} 请求", "{tokens} Token · {requests} 請求", "{tokens} токенов · {requests} запросов", "{tokens} トークン · {requests} リクエスト", "{tokens} jeton · {requests} istek", "{tokens} token · {requests} yêu cầu", "{tokens} tokens · {requests} requisições", "{tokens} tokens · {requests} solicitudes"], + firstRank: ["Your first rank appears after your first full UTC day.", "첫 순위는 첫 번째 UTC 하루가 지난 뒤에 나타나요.", "Dein erster Rang erscheint nach deinem ersten vollen UTC-Tag.", "Votre premier rang apparaît après votre premier jour UTC complet.", "首个排名会在你的第一个完整 UTC 日之后出现。", "首個排名會在你的第一個完整 UTC 日之後出現。", "Первое место появится после первых полных суток UTC.", "最初の順位は最初の UTC 日が終わった後に表示されます。", "İlk sıran ilk tam UTC gününden sonra görünür.", "Thứ hạng đầu tiên sẽ xuất hiện sau ngày UTC đầy đủ đầu tiên.", "Sua primeira posição aparece após seu primeiro dia UTC completo.", "Tu primera posición aparece después de tu primer día completo en UTC."], + topModels: ["Top model families this month", "이번 달 주요 모델 계열", "Wichtigste Modellfamilien diesen Monat", "Principales familles de modèles ce mois-ci", "本月主要模型系列", "本月主要模型系列", "Основные семейства моделей за месяц", "今月の主なモデル系統", "Bu ayın başlıca model aileleri", "Các dòng mô hình hàng đầu tháng này", "Principais famílias de modelos neste mês", "Familias de modelos más usadas este mes"], + viewLeaderboard: ["View leaderboard", "리더보드 보기", "Rangliste ansehen", "Voir le classement", "查看排行榜", "查看排行榜", "Открыть рейтинг", "リーダーボードを見る", "Sıralamayı gör", "Xem bảng xếp hạng", "Ver ranking", "Ver clasificación"], + disconnect: ["Disconnect", "연결 해제", "Trennen", "Déconnecter", "断开连接", "中斷連接", "Отключить", "接続を解除", "Bağlantıyı kes", "Ngắt kết nối", "Desconectar", "Desconectar"], + disconnectConfirm: ["Delete your public profile and all its data?", "공개 프로필과 모든 데이터를 삭제할까요?", "Öffentliches Profil und alle Daten löschen?", "Supprimer votre profil public et toutes ses données ?", "删除你的公开资料及其全部数据?", "刪除你的公開資料及其全部資料?", "Удалить публичный профиль и все его данные?", "公開プロフィールとそのすべてのデータを削除しますか?", "Herkese açık profilin ve tüm verileri silinsin mi?", "Xóa hồ sơ công khai và toàn bộ dữ liệu của nó?", "Excluir seu perfil público e todos os dados dele?", "¿Eliminar tu perfil público y todos sus datos?"], + disconnectYes: ["Delete profile", "프로필 삭제", "Profil löschen", "Supprimer le profil", "删除资料", "刪除資料", "Удалить профиль", "プロフィールを削除", "Profili sil", "Xóa hồ sơ", "Excluir perfil", "Eliminar perfil"], + deletionPending: ["Deletion is pending: the telemetry service could not be reached. Nothing more is sent, and the proxy keeps retrying.", "삭제 대기 중: 텔레메트리 서비스에 연결하지 못했어요. 더 이상 아무것도 보내지 않고 프록시가 계속 재시도해요.", "Löschung ausstehend: Der Telemetriedienst war nicht erreichbar. Es wird nichts mehr gesendet, der Proxy versucht es weiter.", "Suppression en attente : le service de télémétrie est injoignable. Plus rien n'est envoyé et le proxy réessaie.", "删除待处理:无法连接遥测服务。不会再发送任何内容,代理会持续重试。", "刪除待處理:無法連線至遙測服務。不會再傳送任何內容,代理會持續重試。", "Удаление ожидает: сервис телеметрии недоступен. Больше ничего не отправляется, прокси повторяет попытки.", "削除待ち: テレメトリサービスに接続できませんでした。これ以上何も送信されず、プロキシが再試行を続けます。", "Silme bekliyor: telemetri hizmetine ulaşılamadı. Artık hiçbir şey gönderilmez, vekil tekrar denemeye devam eder.", "Đang chờ xóa: không thể kết nối dịch vụ telemetri. Sẽ không gửi thêm gì và proxy tiếp tục thử lại.", "Exclusão pendente: não foi possível acessar o serviço de telemetria. Nada mais é enviado e o proxy continua tentando.", "La eliminación está pendiente: no se pudo contactar al servicio de telemetría. No se envían más datos y el proxy sigue reintentando."], + retry: ["Retry", "다시 시도", "Erneut versuchen", "Réessayer", "重试", "重試", "Повторить", "再試行", "Tekrar dene", "Thử lại", "Tentar novamente", "Reintentar"], + paused: ["Paused while anonymous telemetry is off.", "익명 텔레메트리가 꺼져 있는 동안 일시 중지돼요.", "Pausiert, solange die anonyme Telemetrie aus ist.", "En pause tant que la télémétrie anonyme est désactivée.", "匿名遥测关闭期间已暂停。", "匿名遙測關閉期間已暫停。", "Приостановлено, пока анонимная телеметрия выключена.", "匿名テレメトリがオフの間は一時停止しています。", "Anonim telemetri kapalıyken duraklatıldı.", "Tạm dừng khi telemetri ẩn danh đang tắt.", "Pausado enquanto a telemetria anônima está desligada.", "En pausa mientras la telemetría anónima esté desactivada."], + revoked: ["The telemetry service no longer knows this profile. Disconnect and connect again.", "텔레메트리 서비스가 이 프로필을 더 이상 알지 못해요. 연결을 해제한 뒤 다시 연결해 주세요.", "Der Telemetriedienst kennt dieses Profil nicht mehr. Trenne die Verbindung und verbinde erneut.", "Le service de télémétrie ne connaît plus ce profil. Déconnectez-vous puis reconnectez-vous.", "遥测服务已不再识别此资料。请断开后重新连接。", "遙測服務已不再識別此資料。請中斷後重新連接。", "Сервис телеметрии больше не знает этот профиль. Отключитесь и подключитесь снова.", "テレメトリサービスはこのプロフィールを認識しなくなりました。接続を解除してから再接続してください。", "Telemetri hizmeti artık bu profili tanımıyor. Bağlantıyı kesip yeniden bağlan.", "Dịch vụ telemetri không còn nhận ra hồ sơ này. Hãy ngắt kết nối rồi kết nối lại.", "O serviço de telemetria não reconhece mais este perfil. Desconecte e conecte novamente.", "El servicio de telemetría ya no reconoce este perfil. Desconéctalo y vuelve a conectarlo."], + rankUnavailable: ["Rank is unavailable right now.", "지금은 순위를 불러올 수 없어요.", "Der Rang ist gerade nicht verfügbar.", "Le rang est indisponible pour le moment.", "暂时无法获取排名。", "暫時無法取得排名。", "Рейтинг сейчас недоступен.", "現在、順位を取得できません。", "Sıralama şu anda kullanılamıyor.", "Hiện không lấy được thứ hạng.", "A posição está indisponível no momento.", "La clasificación no está disponible en este momento."], + unreadable: ["The local profile file cannot be read, so nothing is sent. Disconnect removes it.", "로컬 프로필 파일을 읽을 수 없어 아무것도 보내지 않아요. 연결 해제하면 파일을 지워요.", "Die lokale Profildatei ist nicht lesbar, daher wird nichts gesendet. Trennen entfernt sie.", "Le fichier de profil local est illisible ; rien n'est envoyé. Déconnecter le supprime.", "无法读取本地资料文件,因此不会发送任何内容。断开连接会删除该文件。", "無法讀取本機資料檔案,因此不會傳送任何內容。中斷連接會刪除該檔案。", "Локальный файл профиля не читается, поэтому ничего не отправляется. Отключение удалит его.", "ローカルのプロフィールファイルを読めないため、何も送信されません。接続を解除すると削除されます。", "Yerel profil dosyası okunamıyor, bu yüzden hiçbir şey gönderilmiyor. Bağlantıyı kesmek dosyayı siler.", "Không đọc được tệp hồ sơ cục bộ nên không gửi gì cả. Ngắt kết nối sẽ xóa tệp.", "O arquivo de perfil local não pode ser lido, então nada é enviado. Desconectar o remove.", "No se puede leer el archivo local del perfil, así que no se envía nada. Al desconectar se elimina el archivo."], } satisfies Record; export const telemetryProfileCopy = copyTable("telemetryProfile", rows); diff --git a/gui/src/i18n/v2-pages/usage-copy.ts b/gui/src/i18n/v2-pages/usage-copy.ts index 0ff2dfea21a..196c27288ce 100644 --- a/gui/src/i18n/v2-pages/usage-copy.ts +++ b/gui/src/i18n/v2-pages/usage-copy.ts @@ -1,49 +1,49 @@ import { copyTable, type Row } from "./copy-table"; /* - * Copy for the v2 Usage page. Columns: en, ko, de, fr, zh, zh-TW, ru, ja, tr, vi, pt. + * Copy for the v2 Usage page. Columns: en, ko, de, fr, zh, zh-TW, ru, ja, tr, vi, pt, es. * Keys render as `usageV2.`. */ const rows = { - otherApps: ["Other Chat API apps", "기타 Chat API 앱", "Andere Chat-API-Apps", "Autres apps Chat API", "其他 Chat API 应用", "其他 Chat API 應用程式", "Другие приложения Chat API", "その他の Chat API アプリ", "Diğer Chat API uygulamaları", "Ứng dụng Chat API khác", "Outros apps Chat API"], - otherDetail: ["Chat API", "Chat API", "Chat API", "API de conversation", "Chat API", "Chat API", "Chat API", "Chat API", "Chat API", "Chat API", "Chat API"], - codexDetail: ["CLI · Desktop · IDE", "CLI · Desktop · IDE", "CLI · Desktop · IDE", "CLI · Application de bureau · IDE", "CLI · Desktop · IDE", "CLI · Desktop · IDE", "CLI · Desktop · IDE", "CLI · Desktop · IDE", "CLI · Desktop · IDE", "CLI · Desktop · IDE", "CLI · Desktop · IDE"], - codexUnclassified: ["{count} unclassified", "미분류 {count}건", "{count} nicht zugeordnet", "{count} non classées", "{count} 条未分类", "{count} 筆未分類", "Без классификации: {count}", "未分類 {count} 件", "{count} sınıflandırılmamış", "{count} chưa phân loại", "{count} não classificados"], - classificationHelp: ["App counts use recognized client signatures; other traffic remains unknown.", "앱 건수는 식별된 클라이언트 기준이며 나머지는 미분류로 남습니다.", "App-Zahlen erfassen erkannte Clients; anderer Verkehr bleibt unbekannt.", "Les nombres reposent sur les clients reconnus ; le reste demeure inconnu.", "应用计数基于可识别的客户端,其余流量保持未知。", "應用程式計數依已識別的客戶端統計,其餘流量保持未知。", "Числа основаны на распознанных клиентах; остальной трафик неизвестен.", "アプリの件数は識別済みクライアントに基づき、その他は不明のままです。", "Uygulama sayıları tanınan istemcilere dayanır; diğer trafik bilinmez kalır.", "Số lượng ứng dụng dựa trên ứng dụng đã nhận diện; lưu lượng khác vẫn chưa rõ.", "As contagens usam clientes identificados; o restante permanece desconhecido."], - clientUnverified: ["This app is not identified automatically yet; its traffic may appear as unknown.", "이 앱은 아직 자동으로 식별하지 못해 요청이 미분류로 표시될 수 있습니다.", "Diese App wird noch nicht automatisch erkannt; Anfragen können als unbekannt erscheinen.", "Cette application n’est pas encore reconnue automatiquement ; son trafic peut apparaître comme inconnu.", "此应用尚无法自动识别,其流量可能显示为未知。", "此應用程式尚無法自動識別,其流量可能顯示為未知。", "Приложение пока не распознаётся автоматически; его трафик может быть неизвестным.", "このアプリはまだ自動識別できないため、通信が不明として表示される場合があります。", "Bu uygulama henüz otomatik tanınmıyor; trafiği bilinmeyen olarak görünebilir.", "Ứng dụng này chưa được tự động nhận diện; lưu lượng có thể hiển thị là chưa rõ.", "Este aplicativo ainda não é identificado automaticamente; seu tráfego pode aparecer como desconhecido."], - remoteLink: ["Remote Link", "Remote Link", "Remote Link", "Remote Link", "Remote Link", "Remote Link", "Remote Link", "Remote Link", "Remote Link", "Remote Link", "Remote Link"], - unknownLinkedDevice: ["Unknown linked device {number}", "알 수 없는 연결 기기 {number}", "Unbekanntes verbundenes Gerät {number}", "Appareil lié inconnu {number}", "未知关联设备 {number}", "未知連結裝置 {number}", "Неизвестное связанное устройство {number}", "不明な連携デバイス {number}", "Bilinmeyen bağlı cihaz {number}", "Thiết bị liên kết không rõ {number}", "Dispositivo vinculado desconhecido {number}"], - unknownDeviceNumber: ["Unknown device {number}", "알 수 없는 기기 {number}", "Unbekanntes Gerät {number}", "Appareil inconnu {number}", "未知设备 {number}", "未知裝置 {number}", "Неизвестное устройство {number}", "不明なデバイス {number}", "Bilinmeyen cihaz {number}", "Thiết bị không rõ {number}", "Dispositivo desconhecido {number}"], - thisMac: ["This Mac", "이 Mac", "Dieser Mac", "Ce Mac", "此 Mac", "此 Mac", "Этот Mac", "この Mac", "Bu Mac", "Máy Mac này", "Este Mac"], - thisDevice: ["This device", "이 기기", "Dieses Gerät", "Cet appareil", "此设备", "此裝置", "Это устройство", "このデバイス", "Bu cihaz", "Thiết bị này", "Este dispositivo"], - homeDevice: ["Home device", "Home 기기", "Home-Gerät", "Appareil Home", "Home 设备", "Home 裝置", "Устройство Home", "Home デバイス", "Home cihazı", "Thiết bị Home", "Dispositivo Home"], - source: ["Usage source", "사용 출처", "Nutzungsquelle", "Source d’utilisation", "用量来源", "用量來源", "Источник использования", "使用元", "Kullanım kaynağı", "Nguồn sử dụng", "Origem de uso"], - searchSources: ["Search apps and devices", "앱과 기기 검색", "Apps und Geräte suchen", "Rechercher apps et appareils", "搜索应用和设备", "搜尋應用程式與裝置", "Поиск приложений и устройств", "アプリとデバイスを検索", "Uygulama ve cihaz ara", "Tìm ứng dụng và thiết bị", "Buscar apps e dispositivos"], - apps: ["Apps", "앱", "Apps", "Applications", "应用", "應用程式", "Приложения", "アプリ", "Uygulamalar", "Ứng dụng", "Aplicativos"], - app: ["App", "앱", "App", "Application", "应用", "應用程式", "Приложение", "アプリ", "Uygulama", "Ứng dụng", "Aplicativo"], - unclassified: ["Unclassified", "미분류", "Nicht zugeordnet", "Non classé", "未分类", "未分類", "Без классификации", "未分類", "Sınıflandırılmamış", "Chưa phân loại", "Não classificado"], - appsUnavailable: ["App breakdown is unavailable from this proxy.", "이 프록시에서는 앱별 내역을 제공하지 않습니다.", "Dieser Proxy stellt keine Aufschlüsselung nach Apps bereit.", "La répartition par application n’est pas disponible sur ce proxy.", "此代理不提供按应用细分的数据。", "此代理不提供依應用程式細分的資料。", "Этот прокси не предоставляет разбивку по приложениям.", "このプロキシはアプリ別の内訳を提供していません。", "Bu proxy uygulama dökümü sunmuyor.", "Proxy này không cung cấp bảng phân tích theo ứng dụng.", "Este proxy não fornece a discriminação por aplicativo."], - appsEmpty: ["No app usage in this report.", "이 보고서에 앱 사용량이 없습니다.", "Keine App-Nutzung in diesem Bericht.", "Aucune utilisation d’application dans ce rapport.", "此报告中没有应用用量。", "此報告中沒有應用程式用量。", "В этом отчёте нет использования приложений.", "このレポートにアプリの使用量はありません。", "Bu raporda uygulama kullanımı yok.", "Không có mức dùng ứng dụng trong báo cáo này.", "Não há uso de aplicativos neste relatório."], - devices: ["Devices", "기기", "Geräte", "Appareils", "设备", "裝置", "Устройства", "デバイス", "Cihazlar", "Thiết bị", "Dispositivos"], - allApps: ["All apps", "모든 앱", "Alle Apps", "Toutes les applications", "所有应用", "所有應用程式", "Все приложения", "すべてのアプリ", "Tüm uygulamalar", "Tất cả ứng dụng", "Todos os aplicativos"], - allDevices: ["All devices", "모든 기기", "Alle Geräte", "Tous les appareils", "所有设备", "所有裝置", "Все устройства", "すべてのデバイス", "Tüm cihazlar", "Tất cả thiết bị", "Todos os dispositivos"], - noKey: ["No key", "키 없음", "Kein Schlüssel", "Sans clé", "无密钥", "無金鑰", "Без ключа", "キーなし", "Anahtar yok", "Không có khóa", "Sem chave"], - unconfigured: ["Unconfigured keys", "설정되지 않은 키", "Nicht konfigurierte Schlüssel", "Clés non configurées", "未配置的密钥", "未設定的金鑰", "Ненастроенные ключи", "未設定のキー", "Yapılandırılmamış anahtarlar", "Khóa chưa cấu hình", "Chaves não configuradas"], - other: ["Other", "기타", "Andere", "Autre", "其他", "其他", "Другое", "その他", "Diğer", "Khác", "Outro"], - unknown: ["Unknown", "알 수 없음", "Unbekannt", "Inconnu", "未知", "未知", "Неизвестно", "不明", "Bilinmiyor", "Không rõ", "Desconhecido"], - last30: ["Last 30 days", "최근 30일", "Letzte 30 Tage", "30 derniers jours", "最近 30 天", "最近 30 天", "Последние 30 дней", "過去30日間", "Son 30 gün", "30 ngày qua", "Últimos 30 dias"], - noKeyHelp: ["No key includes older and environment traffic; it does not prove the originating device.", "키 없음에는 이전 기록과 환경 방식 요청이 포함되며 실제 기기를 식별하지 않습니다.", "Ohne Schlüssel umfasst ältere und Umgebungsanfragen und belegt kein bestimmtes Gerät.", "Sans clé comprend le trafic ancien et d’environnement, sans prouver l’appareil d’origine.", "无密钥包含旧记录和环境流量,不能证明来源设备。", "無金鑰包含舊紀錄和環境流量,無法證明來源裝置。", "Без ключа включает старый трафик и трафик окружения и не определяет устройство.", "キーなしには古い記録や環境経由の通信が含まれ、送信元を特定しません。", "Anahtarsız eski ve ortam trafiğini içerir; kaynak cihazı kanıtlamaz.", "Không có khóa gồm lưu lượng cũ và từ môi trường; không xác định thiết bị gửi.", "Sem chave inclui tráfego antigo e de ambiente; não comprova o dispositivo de origem."], - unconfiguredHelp: ["Unconfigured keys are absent from the current configuration; deletion is not established.", "설정되지 않은 키는 현재 설정에 없으며 삭제 여부는 알 수 없습니다.", "Nicht konfigurierte Schlüssel fehlen aktuell; eine Löschung ist nicht belegt.", "Les clés non configurées sont absentes actuellement ; leur suppression n’est pas établie.", "未配置的密钥不在当前配置中,不能证明已删除。", "未設定的金鑰不在目前設定中,不能證明已刪除。", "Ненастроенных ключей нет в текущей конфигурации; удаление не доказано.", "未設定のキーは現在の設定になく、削除されたとは限りません。", "Yapılandırılmamış anahtarlar mevcut yapılandırmada yoktur; silindikleri kesin değildir.", "Khóa chưa cấu hình không có trong cấu hình hiện tại; chưa thể kết luận đã bị xóa.", "Chaves não configuradas estão ausentes da configuração atual; isso não comprova exclusão."], - locked: ["This connection is restricted to its authenticated device key.", "이 연결은 인증된 기기 키로 제한됩니다.", "Diese Verbindung ist auf ihren authentifizierten Geräteschlüssel beschränkt.", "Cette connexion est limitée à sa clé d’appareil authentifiée.", "此连接仅限其已认证的设备密钥。", "此連線僅限其已驗證的裝置金鑰。", "Соединение ограничено ключом аутентифицированного устройства.", "この接続は認証済みデバイスのキーに制限されます。", "Bu bağlantı doğrulanmış cihaz anahtarıyla sınırlıdır.", "Kết nối này chỉ được dùng khóa thiết bị đã xác thực.", "Esta conexão está limitada à chave do dispositivo autenticado."], - unavailableKeys: ["Configured keys unavailable for selection: {count}. Their IDs cannot be used in this filter.", "선택할 수 없는 설정된 키: {count}개. 해당 ID는 이 필터에서 사용할 수 없습니다.", "Nicht auswählbare konfigurierte Schlüssel: {count}. Ihre IDs können in diesem Filter nicht verwendet werden.", "Clés configurées non sélectionnables : {count}. Leurs identifiants ne peuvent pas être utilisés dans ce filtre.", "无法选择的已配置密钥:{count} 个。其 ID 无法用于此筛选器。", "無法選取的已設定金鑰:{count} 個。其 ID 無法用於此篩選器。", "Недоступных для выбора настроенных ключей: {count}. Их идентификаторы нельзя использовать в этом фильтре.", "選択できない設定済みキー: {count} 件。これらの ID はこのフィルターで使用できません。", "Seçilemeyen yapılandırılmış anahtarlar: {count}. Kimlikleri bu filtrede kullanılamaz.", "Khóa đã cấu hình không thể chọn: {count}. Không thể dùng ID của chúng trong bộ lọc này.", "Chaves configuradas indisponíveis para seleção: {count}. Seus IDs não podem ser usados neste filtro."], - countsUnavailable: ["Counts unavailable or incomplete.", "건수를 사용할 수 없거나 불완전합니다.", "Anzahlen nicht verfügbar oder unvollständig.", "Comptages indisponibles ou incomplets.", "计数不可用或不完整。", "計數無法使用或不完整。", "Количество недоступно или неполно.", "件数を取得できないか、不完全です。", "Sayılar kullanılamıyor veya eksik.", "Số lượng không khả dụng hoặc chưa đầy đủ.", "Contagens indisponíveis ou incompletas."], - legacy: ["{count} older requests could not be classified by app.", "이전 요청 {count}건의 앱을 분류할 수 없습니다.", "{count} ältere Anfragen konnten keiner App zugeordnet werden.", "{count} anciennes requêtes n’ont pas pu être attribuées à une application.", "{count} 条旧请求无法按应用分类。", "{count} 筆舊請求無法依應用程式分類。", "Старых запросов без классификации по приложению: {count}.", "以前のリクエスト {count} 件はアプリ別に分類できませんでした。", "{count} eski istek uygulamaya göre sınıflandırılamadı.", "Không thể phân loại {count} yêu cầu cũ theo ứng dụng.", "{count} pedidos antigos não puderam ser classificados por aplicativo."], - rangeLabel: ["Time range", "기간", "Zeitraum", "Période", "时间范围", "時間範圍", "Период", "期間", "Zaman aralığı", "Khoảng thời gian", "Período"], - activeDaysFoot: ["Active on {days} days", "{days}일 동안 사용", "An {days} Tagen aktiv", "Actif {days} jours", "{days} 天有活动", "{days} 天有活動", "Активно дней: {days}", "{days} 日間アクティブ", "{days} gün etkin", "Hoạt động {days} ngày", "Ativo em {days} dias"], - tokensSplit: ["In {input} · Out {output}", "입력 {input} · 출력 {output}", "Ein {input} · Aus {output}", "Entrée {input} · Sortie {output}", "输入 {input} · 输出 {output}", "輸入 {input} · 輸出 {output}", "Вход {input} · Выход {output}", "入力 {input} · 出力 {output}", "Giriş {input} · Çıkış {output}", "Vào {input} · Ra {output}", "Entrada {input} · Saída {output}"], - costLabel: ["Estimated cost", "예상 비용", "Geschätzte Kosten", "Coût estimé", "预估费用", "預估費用", "Оценка стоимости", "推定コスト", "Tahmini maliyet", "Chi phí ước tính", "Custo estimado"], - costFoot: ["An estimate, not a bill", "청구 금액이 아닌 추정치", "Schätzung, keine Rechnung", "Une estimation, pas une facture", "估算值,并非账单", "估算值,並非帳單", "Оценка, а не счёт", "請求額ではなく推定値", "Fatura değil, tahmin", "Ước tính, không phải hóa đơn", "Uma estimativa, não uma fatura"], - costMissing: ["This proxy does not report prices", "이 프록시는 가격을 알려 주지 않습니다", "Dieser Proxy meldet keine Preise", "Ce proxy ne fournit pas de prix", "此代理不提供价格", "此代理不提供價格", "Этот прокси не сообщает цены", "このプロキシは価格を返しません", "Bu proxy fiyat bildirmiyor", "Proxy này không báo giá", "Este proxy não informa preços"], + otherApps: ["Other Chat API apps", "기타 Chat API 앱", "Andere Chat-API-Apps", "Autres apps Chat API", "其他 Chat API 应用", "其他 Chat API 應用程式", "Другие приложения Chat API", "その他の Chat API アプリ", "Diğer Chat API uygulamaları", "Ứng dụng Chat API khác", "Outros apps Chat API", "Otras aplicaciones de la API de chat"], + otherDetail: ["Chat API", "Chat API", "Chat API", "API de conversation", "Chat API", "Chat API", "Chat API", "Chat API", "Chat API", "Chat API", "Chat API", "API de chat"], + codexDetail: ["CLI · Desktop · IDE", "CLI · Desktop · IDE", "CLI · Desktop · IDE", "CLI · Application de bureau · IDE", "CLI · Desktop · IDE", "CLI · Desktop · IDE", "CLI · Desktop · IDE", "CLI · Desktop · IDE", "CLI · Desktop · IDE", "CLI · Desktop · IDE", "CLI · Desktop · IDE", "CLI · Escritorio · IDE"], + codexUnclassified: ["{count} unclassified", "미분류 {count}건", "{count} nicht zugeordnet", "{count} non classées", "{count} 条未分类", "{count} 筆未分類", "Без классификации: {count}", "未分類 {count} 件", "{count} sınıflandırılmamış", "{count} chưa phân loại", "{count} não classificados", "Sin clasificar: {count}"], + classificationHelp: ["App counts use recognized client signatures; other traffic remains unknown.", "앱 건수는 식별된 클라이언트 기준이며 나머지는 미분류로 남습니다.", "App-Zahlen erfassen erkannte Clients; anderer Verkehr bleibt unbekannt.", "Les nombres reposent sur les clients reconnus ; le reste demeure inconnu.", "应用计数基于可识别的客户端,其余流量保持未知。", "應用程式計數依已識別的客戶端統計,其餘流量保持未知。", "Числа основаны на распознанных клиентах; остальной трафик неизвестен.", "アプリの件数は識別済みクライアントに基づき、その他は不明のままです。", "Uygulama sayıları tanınan istemcilere dayanır; diğer trafik bilinmez kalır.", "Số lượng ứng dụng dựa trên ứng dụng đã nhận diện; lưu lượng khác vẫn chưa rõ.", "As contagens usam clientes identificados; o restante permanece desconhecido.", "El recuento por aplicación usa identificadores de clientes reconocidos. El resto del tráfico queda sin identificar."], + clientUnverified: ["This app is not identified automatically yet; its traffic may appear as unknown.", "이 앱은 아직 자동으로 식별하지 못해 요청이 미분류로 표시될 수 있습니다.", "Diese App wird noch nicht automatisch erkannt; Anfragen können als unbekannt erscheinen.", "Cette application n’est pas encore reconnue automatiquement ; son trafic peut apparaître comme inconnu.", "此应用尚无法自动识别,其流量可能显示为未知。", "此應用程式尚無法自動識別,其流量可能顯示為未知。", "Приложение пока не распознаётся автоматически; его трафик может быть неизвестным.", "このアプリはまだ自動識別できないため、通信が不明として表示される場合があります。", "Bu uygulama henüz otomatik tanınmıyor; trafiği bilinmeyen olarak görünebilir.", "Ứng dụng này chưa được tự động nhận diện; lưu lượng có thể hiển thị là chưa rõ.", "Este aplicativo ainda não é identificado automaticamente; seu tráfego pode aparecer como desconhecido.", "Esta aplicación aún no se identifica automáticamente. Su tráfico puede aparecer como desconocido."], + remoteLink: ["Remote Link", "Remote Link", "Remote Link", "Remote Link", "Remote Link", "Remote Link", "Remote Link", "Remote Link", "Remote Link", "Remote Link", "Remote Link", "Enlace remoto"], + unknownLinkedDevice: ["Unknown linked device {number}", "알 수 없는 연결 기기 {number}", "Unbekanntes verbundenes Gerät {number}", "Appareil lié inconnu {number}", "未知关联设备 {number}", "未知連結裝置 {number}", "Неизвестное связанное устройство {number}", "不明な連携デバイス {number}", "Bilinmeyen bağlı cihaz {number}", "Thiết bị liên kết không rõ {number}", "Dispositivo vinculado desconhecido {number}", "Dispositivo enlazado desconocido {number}"], + unknownDeviceNumber: ["Unknown device {number}", "알 수 없는 기기 {number}", "Unbekanntes Gerät {number}", "Appareil inconnu {number}", "未知设备 {number}", "未知裝置 {number}", "Неизвестное устройство {number}", "不明なデバイス {number}", "Bilinmeyen cihaz {number}", "Thiết bị không rõ {number}", "Dispositivo desconhecido {number}", "Dispositivo desconocido {number}"], + thisMac: ["This Mac", "이 Mac", "Dieser Mac", "Ce Mac", "此 Mac", "此 Mac", "Этот Mac", "この Mac", "Bu Mac", "Máy Mac này", "Este Mac", "Esta Mac"], + thisDevice: ["This device", "이 기기", "Dieses Gerät", "Cet appareil", "此设备", "此裝置", "Это устройство", "このデバイス", "Bu cihaz", "Thiết bị này", "Este dispositivo", "Este dispositivo"], + homeDevice: ["Home device", "Home 기기", "Home-Gerät", "Appareil Home", "Home 设备", "Home 裝置", "Устройство Home", "Home デバイス", "Home cihazı", "Thiết bị Home", "Dispositivo Home", "Dispositivo Home"], + source: ["Usage source", "사용 출처", "Nutzungsquelle", "Source d’utilisation", "用量来源", "用量來源", "Источник использования", "使用元", "Kullanım kaynağı", "Nguồn sử dụng", "Origem de uso", "Origen del uso"], + searchSources: ["Search apps and devices", "앱과 기기 검색", "Apps und Geräte suchen", "Rechercher apps et appareils", "搜索应用和设备", "搜尋應用程式與裝置", "Поиск приложений и устройств", "アプリとデバイスを検索", "Uygulama ve cihaz ara", "Tìm ứng dụng và thiết bị", "Buscar apps e dispositivos", "Buscar aplicaciones y dispositivos"], + apps: ["Apps", "앱", "Apps", "Applications", "应用", "應用程式", "Приложения", "アプリ", "Uygulamalar", "Ứng dụng", "Aplicativos", "Aplicaciones"], + app: ["App", "앱", "App", "Application", "应用", "應用程式", "Приложение", "アプリ", "Uygulama", "Ứng dụng", "Aplicativo", "Aplicación"], + unclassified: ["Unclassified", "미분류", "Nicht zugeordnet", "Non classé", "未分类", "未分類", "Без классификации", "未分類", "Sınıflandırılmamış", "Chưa phân loại", "Não classificado", "Sin clasificar"], + appsUnavailable: ["App breakdown is unavailable from this proxy.", "이 프록시에서는 앱별 내역을 제공하지 않습니다.", "Dieser Proxy stellt keine Aufschlüsselung nach Apps bereit.", "La répartition par application n’est pas disponible sur ce proxy.", "此代理不提供按应用细分的数据。", "此代理不提供依應用程式細分的資料。", "Этот прокси не предоставляет разбивку по приложениям.", "このプロキシはアプリ別の内訳を提供していません。", "Bu proxy uygulama dökümü sunmuyor.", "Proxy này không cung cấp bảng phân tích theo ứng dụng.", "Este proxy não fornece a discriminação por aplicativo.", "Este proxy no ofrece el desglose por aplicación."], + appsEmpty: ["No app usage in this report.", "이 보고서에 앱 사용량이 없습니다.", "Keine App-Nutzung in diesem Bericht.", "Aucune utilisation d’application dans ce rapport.", "此报告中没有应用用量。", "此報告中沒有應用程式用量。", "В этом отчёте нет использования приложений.", "このレポートにアプリの使用量はありません。", "Bu raporda uygulama kullanımı yok.", "Không có mức dùng ứng dụng trong báo cáo này.", "Não há uso de aplicativos neste relatório.", "Este informe no incluye uso por aplicación."], + devices: ["Devices", "기기", "Geräte", "Appareils", "设备", "裝置", "Устройства", "デバイス", "Cihazlar", "Thiết bị", "Dispositivos", "Dispositivos"], + allApps: ["All apps", "모든 앱", "Alle Apps", "Toutes les applications", "所有应用", "所有應用程式", "Все приложения", "すべてのアプリ", "Tüm uygulamalar", "Tất cả ứng dụng", "Todos os aplicativos", "Todas las aplicaciones"], + allDevices: ["All devices", "모든 기기", "Alle Geräte", "Tous les appareils", "所有设备", "所有裝置", "Все устройства", "すべてのデバイス", "Tüm cihazlar", "Tất cả thiết bị", "Todos os dispositivos", "Todos los dispositivos"], + noKey: ["No key", "키 없음", "Kein Schlüssel", "Sans clé", "无密钥", "無金鑰", "Без ключа", "キーなし", "Anahtar yok", "Không có khóa", "Sem chave", "Sin clave"], + unconfigured: ["Unconfigured keys", "설정되지 않은 키", "Nicht konfigurierte Schlüssel", "Clés non configurées", "未配置的密钥", "未設定的金鑰", "Ненастроенные ключи", "未設定のキー", "Yapılandırılmamış anahtarlar", "Khóa chưa cấu hình", "Chaves não configuradas", "Claves no configuradas"], + other: ["Other", "기타", "Andere", "Autre", "其他", "其他", "Другое", "その他", "Diğer", "Khác", "Outro", "Otros"], + unknown: ["Unknown", "알 수 없음", "Unbekannt", "Inconnu", "未知", "未知", "Неизвестно", "不明", "Bilinmiyor", "Không rõ", "Desconhecido", "Desconocido"], + last30: ["Last 30 days", "최근 30일", "Letzte 30 Tage", "30 derniers jours", "最近 30 天", "最近 30 天", "Последние 30 дней", "過去30日間", "Son 30 gün", "30 ngày qua", "Últimos 30 dias", "Últimos 30 días"], + noKeyHelp: ["No key includes older and environment traffic; it does not prove the originating device.", "키 없음에는 이전 기록과 환경 방식 요청이 포함되며 실제 기기를 식별하지 않습니다.", "Ohne Schlüssel umfasst ältere und Umgebungsanfragen und belegt kein bestimmtes Gerät.", "Sans clé comprend le trafic ancien et d’environnement, sans prouver l’appareil d’origine.", "无密钥包含旧记录和环境流量,不能证明来源设备。", "無金鑰包含舊紀錄和環境流量,無法證明來源裝置。", "Без ключа включает старый трафик и трафик окружения и не определяет устройство.", "キーなしには古い記録や環境経由の通信が含まれ、送信元を特定しません。", "Anahtarsız eski ve ortam trafiğini içerir; kaynak cihazı kanıtlamaz.", "Không có khóa gồm lưu lượng cũ và từ môi trường; không xác định thiết bị gửi.", "Sem chave inclui tráfego antigo e de ambiente; não comprova o dispositivo de origem.", "Sin clave incluye tráfico anterior y tráfico del entorno. No identifica el dispositivo de origen."], + unconfiguredHelp: ["Unconfigured keys are absent from the current configuration; deletion is not established.", "설정되지 않은 키는 현재 설정에 없으며 삭제 여부는 알 수 없습니다.", "Nicht konfigurierte Schlüssel fehlen aktuell; eine Löschung ist nicht belegt.", "Les clés non configurées sont absentes actuellement ; leur suppression n’est pas établie.", "未配置的密钥不在当前配置中,不能证明已删除。", "未設定的金鑰不在目前設定中,不能證明已刪除。", "Ненастроенных ключей нет в текущей конфигурации; удаление не доказано.", "未設定のキーは現在の設定になく、削除されたとは限りません。", "Yapılandırılmamış anahtarlar mevcut yapılandırmada yoktur; silindikleri kesin değildir.", "Khóa chưa cấu hình không có trong cấu hình hiện tại; chưa thể kết luận đã bị xóa.", "Chaves não configuradas estão ausentes da configuração atual; isso não comprova exclusão.", "Las claves no configuradas no aparecen en la configuración actual. Esto no confirma que se hayan eliminado."], + locked: ["This connection is restricted to its authenticated device key.", "이 연결은 인증된 기기 키로 제한됩니다.", "Diese Verbindung ist auf ihren authentifizierten Geräteschlüssel beschränkt.", "Cette connexion est limitée à sa clé d’appareil authentifiée.", "此连接仅限其已认证的设备密钥。", "此連線僅限其已驗證的裝置金鑰。", "Соединение ограничено ключом аутентифицированного устройства.", "この接続は認証済みデバイスのキーに制限されます。", "Bu bağlantı doğrulanmış cihaz anahtarıyla sınırlıdır.", "Kết nối này chỉ được dùng khóa thiết bị đã xác thực.", "Esta conexão está limitada à chave do dispositivo autenticado.", "Esta conexión está limitada a la clave autenticada de su dispositivo."], + unavailableKeys: ["Configured keys unavailable for selection: {count}. Their IDs cannot be used in this filter.", "선택할 수 없는 설정된 키: {count}개. 해당 ID는 이 필터에서 사용할 수 없습니다.", "Nicht auswählbare konfigurierte Schlüssel: {count}. Ihre IDs können in diesem Filter nicht verwendet werden.", "Clés configurées non sélectionnables : {count}. Leurs identifiants ne peuvent pas être utilisés dans ce filtre.", "无法选择的已配置密钥:{count} 个。其 ID 无法用于此筛选器。", "無法選取的已設定金鑰:{count} 個。其 ID 無法用於此篩選器。", "Недоступных для выбора настроенных ключей: {count}. Их идентификаторы нельзя использовать в этом фильтре.", "選択できない設定済みキー: {count} 件。これらの ID はこのフィルターで使用できません。", "Seçilemeyen yapılandırılmış anahtarlar: {count}. Kimlikleri bu filtrede kullanılamaz.", "Khóa đã cấu hình không thể chọn: {count}. Không thể dùng ID của chúng trong bộ lọc này.", "Chaves configuradas indisponíveis para seleção: {count}. Seus IDs não podem ser usados neste filtro.", "Claves configuradas no disponibles para seleccionar: {count}. Sus IDs no se pueden usar en este filtro."], + countsUnavailable: ["Counts unavailable or incomplete.", "건수를 사용할 수 없거나 불완전합니다.", "Anzahlen nicht verfügbar oder unvollständig.", "Comptages indisponibles ou incomplets.", "计数不可用或不完整。", "計數無法使用或不完整。", "Количество недоступно или неполно.", "件数を取得できないか、不完全です。", "Sayılar kullanılamıyor veya eksik.", "Số lượng không khả dụng hoặc chưa đầy đủ.", "Contagens indisponíveis ou incompletas.", "Recuentos no disponibles o incompletos."], + legacy: ["{count} older requests could not be classified by app.", "이전 요청 {count}건의 앱을 분류할 수 없습니다.", "{count} ältere Anfragen konnten keiner App zugeordnet werden.", "{count} anciennes requêtes n’ont pas pu être attribuées à une application.", "{count} 条旧请求无法按应用分类。", "{count} 筆舊請求無法依應用程式分類。", "Старых запросов без классификации по приложению: {count}.", "以前のリクエスト {count} 件はアプリ別に分類できませんでした。", "{count} eski istek uygulamaya göre sınıflandırılamadı.", "Không thể phân loại {count} yêu cầu cũ theo ứng dụng.", "{count} pedidos antigos não puderam ser classificados por aplicativo.", "Solicitudes anteriores que no se pudieron clasificar por aplicación: {count}."], + rangeLabel: ["Time range", "기간", "Zeitraum", "Période", "时间范围", "時間範圍", "Период", "期間", "Zaman aralığı", "Khoảng thời gian", "Período", "Intervalo de tiempo"], + activeDaysFoot: ["Active on {days} days", "{days}일 동안 사용", "An {days} Tagen aktiv", "Actif {days} jours", "{days} 天有活动", "{days} 天有活動", "Активно дней: {days}", "{days} 日間アクティブ", "{days} gün etkin", "Hoạt động {days} ngày", "Ativo em {days} dias", "Actividad en {days} días"], + tokensSplit: ["In {input} · Out {output}", "입력 {input} · 출력 {output}", "Ein {input} · Aus {output}", "Entrée {input} · Sortie {output}", "输入 {input} · 输出 {output}", "輸入 {input} · 輸出 {output}", "Вход {input} · Выход {output}", "入力 {input} · 出力 {output}", "Giriş {input} · Çıkış {output}", "Vào {input} · Ra {output}", "Entrada {input} · Saída {output}", "Entrada {input} · Salida {output}"], + costLabel: ["Estimated cost", "예상 비용", "Geschätzte Kosten", "Coût estimé", "预估费用", "預估費用", "Оценка стоимости", "推定コスト", "Tahmini maliyet", "Chi phí ước tính", "Custo estimado", "Coste estimado"], + costFoot: ["An estimate, not a bill", "청구 금액이 아닌 추정치", "Schätzung, keine Rechnung", "Une estimation, pas une facture", "估算值,并非账单", "估算值,並非帳單", "Оценка, а не счёт", "請求額ではなく推定値", "Fatura değil, tahmin", "Ước tính, không phải hóa đơn", "Uma estimativa, não uma fatura", "Estimación, no factura"], + costMissing: ["This proxy does not report prices", "이 프록시는 가격을 알려 주지 않습니다", "Dieser Proxy meldet keine Preise", "Ce proxy ne fournit pas de prix", "此代理不提供价格", "此代理不提供價格", "Этот прокси не сообщает цены", "このプロキシは価格を返しません", "Bu proxy fiyat bildirmiyor", "Proxy này không báo giá", "Este proxy não informa preços", "Este proxy no informa de los precios"], coverageHint: [ "Share of requests whose token counts are known, measured by the proxy or reported by the provider. The rest are still counted as requests but never shown as zero tokens.", "토큰 수를 알고 있는 요청의 비율입니다. 프록시가 직접 측정했거나 프로바이더가 알려 준 요청이 포함됩니다. 나머지도 요청 수에는 들어가지만 토큰 0으로 표시되지는 않습니다.", @@ -56,12 +56,13 @@ const rows = { "Token sayısı bilinen isteklerin oranı; proxy tarafından ölçülen veya sağlayıcının bildirdiği. Kalanlar istek olarak sayılır ama asla sıfır token olarak gösterilmez.", "Tỷ lệ yêu cầu đã biết số token, do proxy đo hoặc nhà cung cấp báo. Phần còn lại vẫn được tính là yêu cầu nhưng không bao giờ hiển thị là 0 token.", "Parcela de pedidos com contagem de tokens conhecida, medida pelo proxy ou informada pelo provedor. Os demais continuam contados como pedidos, mas nunca aparecem como zero tokens.", + "Proporción de solicitudes con recuento de tokens conocido, medido por el proxy o informado por el proveedor. Las demás cuentan como solicitudes, pero nunca se muestran como cero tokens.", ], - coverageFoot: ["{measured} of {requests} requests measured", "요청 {requests}건 중 {measured}건 측정됨", "{measured} von {requests} Anfragen gemessen", "{measured} requêtes mesurées sur {requests}", "{requests} 个请求中已测量 {measured} 个", "{requests} 個請求中已測量 {measured} 個", "Измерено {measured} из {requests} запросов", "{requests} 件中 {measured} 件を計測", "{requests} isteğin {measured} tanesi ölçüldü", "Đã đo {measured} trên {requests} yêu cầu", "{measured} de {requests} pedidos medidos"], - chartCaption: ["{tokens} tokens in this window", "이 기간 토큰 {tokens}", "{tokens} Tokens in diesem Zeitraum", "{tokens} jetons sur cette période", "此期间共 {tokens} token", "此期間共 {tokens} token", "{tokens} токенов за период", "この期間のトークン {tokens}", "Bu aralıkta {tokens} token", "{tokens} token trong khoảng này", "{tokens} tokens neste período"], - chartView: ["Chart view", "차트 보기", "Diagrammansicht", "Vue du graphique", "图表视图", "圖表檢視", "Вид графика", "グラフ表示", "Grafik görünümü", "Kiểu biểu đồ", "Visualização do gráfico"], - viewBars: ["Bars", "막대", "Balken", "Barres", "柱状", "長條", "Столбцы", "棒グラフ", "Çubuklar", "Cột", "Barras"], - viewCalendar: ["Calendar", "달력", "Kalender", "Calendrier", "日历", "日曆", "Календарь", "カレンダー", "Takvim", "Lịch", "Calendário"], + coverageFoot: ["{measured} of {requests} requests measured", "요청 {requests}건 중 {measured}건 측정됨", "{measured} von {requests} Anfragen gemessen", "{measured} requêtes mesurées sur {requests}", "{requests} 个请求中已测量 {measured} 个", "{requests} 個請求中已測量 {measured} 個", "Измерено {measured} из {requests} запросов", "{requests} 件中 {measured} 件を計測", "{requests} isteğin {measured} tanesi ölçüldü", "Đã đo {measured} trên {requests} yêu cầu", "{measured} de {requests} pedidos medidos", "{measured} de {requests} solicitudes medidas"], + chartCaption: ["{tokens} tokens in this window", "이 기간 토큰 {tokens}", "{tokens} Tokens in diesem Zeitraum", "{tokens} jetons sur cette période", "此期间共 {tokens} token", "此期間共 {tokens} token", "{tokens} токенов за период", "この期間のトークン {tokens}", "Bu aralıkta {tokens} token", "{tokens} token trong khoảng này", "{tokens} tokens neste período", "{tokens} tokens en este intervalo"], + chartView: ["Chart view", "차트 보기", "Diagrammansicht", "Vue du graphique", "图表视图", "圖表檢視", "Вид графика", "グラフ表示", "Grafik görünümü", "Kiểu biểu đồ", "Visualização do gráfico", "Vista del gráfico"], + viewBars: ["Bars", "막대", "Balken", "Barres", "柱状", "長條", "Столбцы", "棒グラフ", "Çubuklar", "Cột", "Barras", "Barras"], + viewCalendar: ["Calendar", "달력", "Kalender", "Calendrier", "日历", "日曆", "Календарь", "カレンダー", "Takvim", "Lịch", "Calendário", "Calendario"], emptyFiltered: [ "Nothing in this window or source. Available history or another source may show older usage.", "이 기간이나 출처에는 기록이 없습니다. 사용 가능한 기록이나 다른 출처를 고르면 이전 사용량이 보일 수 있습니다.", @@ -74,11 +75,12 @@ const rows = { "Bu aralıkta veya kaynakta kayıt yok. Kullanılabilir geçmiş veya başka bir kaynak daha eski kullanımı gösterebilir.", "Không có gì trong khoảng hoặc nguồn này. Lịch sử hiện có hoặc nguồn khác có thể hiển thị mức dùng cũ hơn.", "Nada neste período ou origem. O histórico disponível ou outra origem pode mostrar uso mais antigo.", + "No hay resultados para este intervalo u origen. El historial disponible u otro origen pueden mostrar uso anterior.", ], - companionPreview: ["Widget preview", "위젯 미리 보기", "Widget-Vorschau", "Aperçu du widget", "小组件预览", "小工具預覽", "Предпросмотр виджета", "ウィジェットのプレビュー", "Widget önizlemesi", "Xem trước widget", "Prévia do widget"], - companionSettings: ["Display settings", "표시 설정", "Anzeigeeinstellungen", "Réglages d’affichage", "显示设置", "顯示設定", "Настройки отображения", "表示設定", "Görüntü ayarları", "Cài đặt hiển thị", "Configurações de exibição"], - companionMenuBar: ["Menu bar", "메뉴 막대", "Menüleiste", "Barre des menus", "菜单栏", "選單列", "Строка меню", "メニューバー", "Menü çubuğu", "Thanh menu", "Barra de menus"], - companionChart: ["Chart", "차트", "Diagramm", "Graphique", "图表", "圖表", "График", "グラフ", "Grafik", "Biểu đồ", "Gráfico"], + companionPreview: ["Widget preview", "위젯 미리 보기", "Widget-Vorschau", "Aperçu du widget", "小组件预览", "小工具預覽", "Предпросмотр виджета", "ウィジェットのプレビュー", "Widget önizlemesi", "Xem trước widget", "Prévia do widget", "Vista previa del widget"], + companionSettings: ["Display settings", "표시 설정", "Anzeigeeinstellungen", "Réglages d’affichage", "显示设置", "顯示設定", "Настройки отображения", "表示設定", "Görüntü ayarları", "Cài đặt hiển thị", "Configurações de exibição", "Configuración de visualización"], + companionMenuBar: ["Menu bar", "메뉴 막대", "Menüleiste", "Barre des menus", "菜单栏", "選單列", "Строка меню", "メニューバー", "Menü çubuğu", "Thanh menu", "Barra de menus", "Barra de menús"], + companionChart: ["Chart", "차트", "Diagramm", "Graphique", "图表", "圖表", "График", "グラフ", "Grafik", "Biểu đồ", "Gráfico", "Gráfico"], } satisfies Record; export const usageV2Copy = copyTable("usageV2", rows); diff --git a/gui/src/i18n/vision-reasoning-labels.ts b/gui/src/i18n/vision-reasoning-labels.ts index 600272c2510..475a480dc91 100644 --- a/gui/src/i18n/vision-reasoning-labels.ts +++ b/gui/src/i18n/vision-reasoning-labels.ts @@ -4,6 +4,7 @@ export type VisionReasoningLabelLevel = "low" | "medium" | "high" | "xhigh" | "m const VISION_REASONING_LABELS = { en: { low: "Low", medium: "Medium", high: "High", xhigh: "Extra high", max: "Maximum" }, + es: { low: "Bajo", medium: "Medio", high: "Alto", xhigh: "Muy alto", max: "Máximo" }, de: { low: "Niedrig", medium: "Mittel", high: "Hoch", xhigh: "Sehr hoch", max: "Maximum" }, fr: { low: "Faible", medium: "Moyen", high: "Élevé", xhigh: "Très élevé", max: "Maximum" }, ko: { low: "낮음", medium: "보통", high: "높음", xhigh: "매우 높음", max: "최대" }, diff --git a/gui/src/status-codes.ts b/gui/src/status-codes.ts index f09e35c304c..5a7a9a03fff 100644 --- a/gui/src/status-codes.ts +++ b/gui/src/status-codes.ts @@ -1,11 +1,12 @@ export interface StatusCodeInfo { label: string; description: string } -type Locale = "en" | "de" | "fr" | "ko" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt"; +type Locale = "en" | "de" | "fr" | "ko" | "zh" | "zh-TW" | "ru" | "ja" | "tr" | "vi" | "pt" | "es"; type LocalizedInfo = Record; const STATUS_CODES: Record = { 400: { en: { label: "Bad request", description: "The proxy could not understand the request. Check the model, message shape, headers, and JSON body before retrying." }, + es: { label: "Solicitud incorrecta", description: "El proxy no pudo interpretar la solicitud. Revisa el modelo, la estructura del mensaje, los encabezados y el cuerpo JSON antes de reintentar." }, fr: { label: "Requête incorrecte", description: "Le proxy n’a pas pu comprendre la requête. Vérifiez le modèle, la structure des messages, les en-têtes et le corps JSON avant de réessayer." }, ko: { label: "잘못된 요청", description: "프록시가 요청을 이해할 수 없습니다. 재시도 전에 모델, 메시지 형식, 헤더, JSON 본문을 확인해야 합니다." }, zh: { label: "错误请求", description: "代理无法理解该请求。重试前请检查模型、消息结构、标头和 JSON 正文。" }, @@ -19,6 +20,7 @@ const STATUS_CODES: Record = { }, 401: { en: { label: "Unauthorized", description: "Credentials are missing, expired, or invalid. Re-login or refresh the account/provider credentials used by opencodex." }, + es: { label: "Sin autorización", description: "Faltan credenciales, han caducado o no son válidas. Vuelve a iniciar sesión o actualiza las credenciales de la cuenta o del proveedor que usa opencodex." }, fr: { label: "Non autorisé", description: "Les identifiants sont absents, expirés ou non valides. Reconnectez-vous ou actualisez les identifiants du compte ou du fournisseur utilisés par opencodex." }, ko: { label: "인증 필요", description: "자격 증명이 없거나 만료되었거나 유효하지 않습니다. opencodex에서 사용하는 계정 또는 제공자 자격 증명을 다시 로그인하거나 갱신해야 합니다." }, zh: { label: "未授权", description: "凭据缺失、已过期或无效。请重新登录,或刷新 opencodex 使用的账号/提供商凭据。" }, @@ -32,6 +34,7 @@ const STATUS_CODES: Record = { }, 402: { en: { label: "Payment required", description: "The upstream provider rejected the request because billing, credits, or plan access is not available. Add credits, update billing, or switch provider." }, + es: { label: "Pago requerido", description: "El proveedor de origen rechazó la solicitud por falta de acceso al plan, créditos o facturación. Añade créditos, actualiza la facturación o cambia de proveedor." }, fr: { label: "Paiement requis", description: "Le fournisseur en amont a rejeté la requête, car la facturation, les crédits ou l’accès à l’offre ne sont pas disponibles. Ajoutez des crédits, mettez à jour la facturation ou changez de fournisseur." }, ko: { label: "결제 필요", description: "청구, 크레딧, 플랜 접근 권한 문제로 업스트림 제공자가 요청을 거부했습니다. 크레딧 추가, 결제 정보 갱신, 제공자 전환이 필요합니다." }, zh: { label: "需要付款", description: "上游提供商因账单、额度或套餐权限不可用而拒绝了请求。请充值、更新账单信息或切换提供商。" }, @@ -45,6 +48,7 @@ const STATUS_CODES: Record = { }, 403: { en: { label: "Forbidden", description: "The account is authenticated but not allowed to use this model or operation. Often a plan/subscription gate (e.g. Ollama Cloud Pro), org policy, or model permission — not necessarily a bad API key." }, + es: { label: "Acceso denegado", description: "La cuenta está autenticada, pero no tiene permiso para usar este modelo u operación. Puede deberse al plan o suscripción (por ejemplo, Ollama Cloud Pro), a una política de la organización o a permisos del modelo; no necesariamente a una clave API incorrecta." }, fr: { label: "Accès interdit", description: "Le compte est authentifié, mais n’est pas autorisé à utiliser ce modèle ou cette opération. Il s’agit souvent d’une restriction liée à l’offre ou à l’abonnement (p. ex. Ollama Cloud Pro), à la politique de l’organisation ou aux autorisations du modèle — pas nécessairement d’une clé API incorrecte." }, ko: { label: "권한 없음", description: "계정 인증은 되었지만 이 모델 또는 작업을 사용할 권한이 없습니다. 플랜/구독 제한(예: Ollama Cloud Pro), 조직 정책, 모델 권한 문제인 경우가 많으며 API 키가 잘못된 것은 아닐 수 있습니다." }, zh: { label: "禁止访问", description: "账号已认证,但无权使用此模型或操作。常见原因是套餐/订阅限制(例如 Ollama Cloud Pro)、组织策略或模型权限——不一定是 API 密钥无效。" }, @@ -58,6 +62,7 @@ const STATUS_CODES: Record = { }, 404: { en: { label: "Not found", description: "The requested route, model, account, or upstream resource was not found. Verify the model name and opencodex provider configuration." }, + es: { label: "No encontrado", description: "No se encontró la ruta, el modelo, la cuenta o el recurso solicitado al proveedor de origen. Revisa el nombre del modelo y la configuración del proveedor en opencodex." }, fr: { label: "Introuvable", description: "La route, le modèle, le compte ou la ressource en amont demandés sont introuvables. Vérifiez le nom du modèle et la configuration du fournisseur opencodex." }, ko: { label: "찾을 수 없음", description: "요청한 경로, 모델, 계정 또는 업스트림 리소스를 찾을 수 없습니다. 모델 이름과 opencodex 제공자 설정을 확인해야 합니다." }, zh: { label: "未找到", description: "找不到请求的路由、模型、账号或上游资源。请确认模型名称和 opencodex 提供商配置。" }, @@ -71,6 +76,7 @@ const STATUS_CODES: Record = { }, 408: { en: { label: "Request timeout", description: "The request took too long before the proxy or upstream provider could complete it. Retry with a smaller request or a different provider." }, + es: { label: "Tiempo de espera de la solicitud agotado", description: "El proxy o el proveedor de origen no completaron la solicitud a tiempo. Reintenta con una solicitud más pequeña o con otro proveedor." }, fr: { label: "Délai d’attente de la requête dépassé", description: "La requête a pris trop de temps pour que le proxy ou le fournisseur en amont puisse la traiter. Réessayez avec une requête plus petite ou un autre fournisseur." }, ko: { label: "요청 시간 초과", description: "프록시 또는 업스트림 제공자가 요청을 완료하기 전에 시간이 초과되었습니다. 더 작은 요청으로 재시도하거나 다른 제공자로 전환해야 합니다." }, zh: { label: "请求超时", description: "代理或上游提供商未能在限定时间内完成请求。请缩小请求后重试,或切换提供商。" }, @@ -84,6 +90,7 @@ const STATUS_CODES: Record = { }, 409: { en: { label: "Conflict", description: "The request conflicts with the current account, session, or provider state. Refresh the session or retry after the active operation finishes." }, + es: { label: "Conflicto", description: "La solicitud entra en conflicto con el estado actual de la cuenta, la sesión o el proveedor. Actualiza la sesión o reintenta cuando termine la operación activa." }, fr: { label: "Conflit", description: "La requête entre en conflit avec l’état actuel du compte, de la session ou du fournisseur. Actualisez la session ou réessayez une fois l’opération en cours terminée." }, ko: { label: "상태 충돌", description: "요청이 현재 계정, 세션 또는 제공자 상태와 충돌합니다. 세션을 갱신하거나 진행 중인 작업이 끝난 뒤 재시도해야 합니다." }, zh: { label: "状态冲突", description: "请求与当前账号、会话或提供商状态冲突。请刷新会话,或等待当前操作完成后重试。" }, @@ -97,6 +104,7 @@ const STATUS_CODES: Record = { }, 413: { en: { label: "Request too large", description: "The prompt, attachments, or generated payload exceeds a proxy or upstream limit. Reduce tokens, file size, or conversation history." }, + es: { label: "Solicitud demasiado grande", description: "El mensaje, los archivos adjuntos o el contenido generado superan un límite del proxy o del proveedor. Reduce los tokens, el tamaño del archivo o el historial de la conversación." }, fr: { label: "Requête trop volumineuse", description: "L’invite, les pièces jointes ou la charge utile générée dépassent une limite du proxy ou du fournisseur en amont. Réduisez le nombre de jetons, la taille des fichiers ou l’historique de la conversation." }, ko: { label: "요청 과대", description: "프롬프트, 첨부 파일 또는 생성 페이로드가 프록시나 업스트림 한도를 초과했습니다. 토큰, 파일 크기, 대화 기록을 줄여야 합니다." }, zh: { label: "请求过大", description: "提示、附件或生成的负载超过了代理或上游限制。请减少 token、文件大小或对话历史。" }, @@ -110,6 +118,7 @@ const STATUS_CODES: Record = { }, 422: { en: { label: "Invalid content", description: "The provider accepted the request format but rejected its contents. Check model options, tool definitions, message roles, and unsupported fields." }, + es: { label: "Contenido no válido", description: "El proveedor aceptó el formato de la solicitud, pero rechazó su contenido. Revisa las opciones del modelo, las definiciones de herramientas, los roles de los mensajes y los campos incompatibles." }, fr: { label: "Contenu non valide", description: "Le fournisseur a accepté le format de la requête, mais en a rejeté le contenu. Vérifiez les options du modèle, les définitions des outils, les rôles des messages et les champs non pris en charge." }, ko: { label: "내용 검증 실패", description: "제공자가 요청 형식은 받았지만 내용을 거부했습니다. 모델 옵션, 도구 정의, 메시지 역할, 지원되지 않는 필드를 확인해야 합니다." }, zh: { label: "内容无效", description: "提供商接受了请求格式,但拒绝了其中的内容。请检查模型选项、工具定义、消息角色和不支持的字段。" }, @@ -123,6 +132,7 @@ const STATUS_CODES: Record = { }, 424: { en: { label: "Provider dependency failed", description: "A required upstream dependency failed while opencodex was routing the request. Retry later or switch to another configured provider." }, + es: { label: "Falló una dependencia del proveedor", description: "Falló una dependencia del proveedor de origen mientras opencodex enrutaba la solicitud. Reintenta más tarde o elige otro proveedor configurado." }, fr: { label: "Échec d’une dépendance du fournisseur", description: "Une dépendance en amont requise a échoué pendant le routage de la requête par opencodex. Réessayez plus tard ou sélectionnez un autre fournisseur configuré." }, ko: { label: "제공자 의존성 실패", description: "opencodex가 요청을 라우팅하는 동안 필요한 업스트림 의존성이 실패했습니다. 나중에 재시도하거나 다른 설정된 제공자로 전환해야 합니다." }, zh: { label: "提供商依赖失败", description: "opencodex 路由请求时,必需的上游依赖失败。请稍后重试,或切换到另一个已配置的提供商。" }, @@ -136,6 +146,7 @@ const STATUS_CODES: Record = { }, 429: { en: { label: "Rate limited", description: "The upstream provider rate or quota limit has been reached. Wait for the quota window to reset or switch account/provider." }, + es: { label: "Límite de solicitudes alcanzado", description: "Se alcanzó un límite de frecuencia o cuota del proveedor de origen. Espera al restablecimiento de la cuota o cambia de cuenta o proveedor." }, fr: { label: "Limite de débit atteinte", description: "La limite de débit ou de quota du fournisseur en amont a été atteinte. Attendez la réinitialisation de la fenêtre de quota ou changez de compte ou de fournisseur." }, ko: { label: "한도 초과", description: "업스트림 제공자의 속도 또는 할당량 한도에 도달했습니다. 한도 창이 초기화될 때까지 기다리거나 계정/제공자를 전환해야 합니다." }, zh: { label: "限流", description: "已达到上游提供商的速率或额度限制。请等待额度窗口重置,或切换账号/提供商。" }, @@ -149,6 +160,7 @@ const STATUS_CODES: Record = { }, 499: { en: { label: "Client closed request", description: "The client disconnected or canceled the request before opencodex finished routing it. Retry if the cancellation was accidental." }, + es: { label: "Solicitud cancelada por el cliente", description: "El cliente se desconectó o canceló la solicitud antes de que opencodex terminara de enrutarla. Reintenta si la cancelación fue accidental." }, fr: { label: "Requête fermée par le client", description: "Le client s’est déconnecté ou a annulé la requête avant la fin de son routage par opencodex. Réessayez si l’annulation était involontaire." }, ko: { label: "클라이언트 취소", description: "opencodex가 라우팅을 끝내기 전에 클라이언트 연결이 끊기거나 요청이 취소되었습니다. 의도한 취소가 아니면 다시 시도해야 합니다." }, zh: { label: "客户端已取消", description: "opencodex 完成路由前,客户端已断开连接或取消请求。如果不是有意取消,请重试。" }, @@ -162,6 +174,7 @@ const STATUS_CODES: Record = { }, 500: { en: { label: "Proxy error", description: "opencodex hit an internal error while handling the request. Retry once, then check proxy logs if it repeats." }, + es: { label: "Error del proxy", description: "Se produjo un error interno en opencodex al procesar la solicitud. Reintenta una vez y, si se repite, consulta los registros del proxy." }, fr: { label: "Erreur du proxy", description: "opencodex a rencontré une erreur interne lors du traitement de la requête. Réessayez une fois, puis consultez les journaux du proxy si l’erreur se reproduit." }, ko: { label: "프록시 오류", description: "opencodex가 요청을 처리하는 동안 내부 오류가 발생했습니다. 한 번 재시도하고 반복되면 프록시 로그를 확인해야 합니다." }, zh: { label: "代理错误", description: "opencodex 处理请求时发生内部错误。请先重试一次;如果重复出现,请检查代理日志。" }, @@ -175,6 +188,7 @@ const STATUS_CODES: Record = { }, 502: { en: { label: "Bad upstream response", description: "The upstream provider returned an invalid or failed response through the proxy. Retry or route the request to another provider." }, + es: { label: "Respuesta no válida del proveedor", description: "El proveedor de origen devolvió una respuesta inválida o fallida a través del proxy. Reintenta o enruta la solicitud a otro proveedor." }, fr: { label: "Réponse incorrecte du fournisseur en amont", description: "Le fournisseur en amont a renvoyé une réponse non valide ou en échec par l’intermédiaire du proxy. Réessayez ou acheminez la requête vers un autre fournisseur." }, ko: { label: "업스트림 응답 오류", description: "업스트림 제공자가 프록시를 통해 유효하지 않거나 실패한 응답을 반환했습니다. 재시도하거나 다른 제공자로 라우팅해야 합니다." }, zh: { label: "上游响应错误", description: "上游提供商通过代理返回了无效或失败的响应。请重试,或将请求路由到其他提供商。" }, @@ -188,6 +202,7 @@ const STATUS_CODES: Record = { }, 503: { en: { label: "Provider unavailable", description: "The proxy or upstream provider is temporarily unavailable or overloaded. Wait briefly, then retry or switch provider." }, + es: { label: "Proveedor no disponible", description: "El proxy o el proveedor de origen están temporalmente indisponibles o sobrecargados. Espera un momento y reintenta, o cambia de proveedor." }, fr: { label: "Fournisseur indisponible", description: "Le proxy ou le fournisseur en amont est temporairement indisponible ou surchargé. Patientez un instant, puis réessayez ou changez de fournisseur." }, ko: { label: "제공자 사용 불가", description: "프록시 또는 업스트림 제공자가 일시적으로 사용할 수 없거나 과부하 상태입니다. 잠시 기다린 뒤 재시도하거나 제공자를 전환해야 합니다." }, zh: { label: "提供商不可用", description: "代理或上游提供商暂时不可用或过载。请稍后重试,或切换提供商。" }, @@ -201,6 +216,7 @@ const STATUS_CODES: Record = { }, 504: { en: { label: "Upstream timeout", description: "The upstream provider did not respond before the proxy timeout. Retry with a smaller request or choose a faster provider." }, + es: { label: "Tiempo de espera del proveedor agotado", description: "El proveedor de origen no respondió antes de agotarse el tiempo del proxy. Reintenta con una solicitud más pequeña o elige un proveedor más rápido." }, fr: { label: "Délai d’attente du fournisseur en amont dépassé", description: "Le fournisseur en amont n’a pas répondu avant l’expiration du délai du proxy. Réessayez avec une requête plus petite ou choisissez un fournisseur plus rapide." }, ko: { label: "업스트림 시간 초과", description: "프록시 시간 제한 전에 업스트림 제공자가 응답하지 않았습니다. 더 작은 요청으로 재시도하거나 더 빠른 제공자를 선택해야 합니다." }, zh: { label: "上游超时", description: "上游提供商未在代理超时前响应。请缩小请求后重试,或选择响应更快的提供商。" }, @@ -214,6 +230,7 @@ const STATUS_CODES: Record = { }, 529: { en: { label: "Provider overloaded", description: "The upstream provider is overloaded or capacity-limited. Wait and retry, or switch to another account/provider." }, + es: { label: "Proveedor sobrecargado", description: "El proveedor de origen está sobrecargado o sin capacidad disponible. Espera y reintenta, o cambia de cuenta o proveedor." }, fr: { label: "Fournisseur surchargé", description: "Le fournisseur en amont est surchargé ou sa capacité est limitée. Patientez et réessayez, ou changez de compte ou de fournisseur." }, ko: { label: "제공자 과부하", description: "업스트림 제공자가 과부하 상태이거나 처리 용량이 제한되었습니다. 기다렸다가 재시도하거나 다른 계정/제공자로 전환해야 합니다." }, zh: { label: "提供商过载", description: "上游提供商过载或容量受限。请等待后重试,或切换到其他账号/提供商。" }, @@ -230,6 +247,7 @@ const STATUS_CODES: Record = { const GENERIC_STATUS: { client: LocalizedInfo; server: LocalizedInfo } = { client: { en: { label: "Request error", description: "The proxy or upstream provider rejected the request. Check the request shape, credentials, model name, and provider configuration." }, + es: { label: "Error en la solicitud", description: "El proxy o el proveedor de origen rechazaron la solicitud. Revisa su estructura, las credenciales, el nombre del modelo y la configuración del proveedor." }, fr: { label: "Erreur de requête", description: "Le proxy ou le fournisseur en amont a rejeté la requête. Vérifiez sa structure, les identifiants, le nom du modèle et la configuration du fournisseur." }, ko: { label: "요청 오류", description: "프록시 또는 업스트림 제공자가 요청을 거부했습니다. 요청 형식, 자격 증명, 모델 이름, 제공자 설정을 확인해야 합니다." }, zh: { label: "请求错误", description: "代理或上游提供商拒绝了该请求。请检查请求结构、凭据、模型名称和提供商配置。" }, @@ -243,6 +261,7 @@ const GENERIC_STATUS: { client: LocalizedInfo; server: LocalizedInfo } = { }, server: { en: { label: "Server or upstream error", description: "opencodex or an upstream provider failed while processing the request. Retry later or route the request to another provider." }, + es: { label: "Error del servidor o del proveedor de origen", description: "opencodex o un proveedor de origen fallaron al procesar la solicitud. Reintenta más tarde o enrútala a otro proveedor." }, fr: { label: "Erreur du serveur ou du fournisseur en amont", description: "opencodex ou un fournisseur en amont a échoué lors du traitement de la requête. Réessayez plus tard ou acheminez la requête vers un autre fournisseur." }, ko: { label: "서버 또는 업스트림 오류", description: "opencodex 또는 업스트림 제공자가 요청 처리 중 실패했습니다. 나중에 재시도하거나 다른 제공자로 라우팅해야 합니다." }, zh: { label: "服务器或上游错误", description: "opencodex 或上游提供商处理请求时失败。请稍后重试,或将请求路由到其他提供商。" }, @@ -257,6 +276,7 @@ const GENERIC_STATUS: { client: LocalizedInfo; server: LocalizedInfo } = { }; function normalizeLocale(locale: string): Locale { + if (/^es(?:-|$)/i.test(locale)) return "es"; if (locale.toLowerCase().startsWith("fr")) return "fr"; if (locale.toLowerCase().startsWith("vi")) return "vi"; if (locale.toLowerCase().startsWith("pt")) return "pt"; diff --git a/gui/tests/claude-native-passthrough-setting.test.tsx b/gui/tests/claude-native-passthrough-setting.test.tsx index dd9f41efb34..ff9a66f915a 100644 --- a/gui/tests/claude-native-passthrough-setting.test.tsx +++ b/gui/tests/claude-native-passthrough-setting.test.tsx @@ -94,6 +94,7 @@ describe("Claude native passthrough setting", () => { const descriptions: Record = { de: /Modellauswahl.*Claude Desktop.*vor modelMap/, en: /Claude picker.*Claude Desktop.*before modelMap/, + es: /selector.*Claude Desktop.*antes de modelMap/, fr: /sélecteur.*Claude Desktop.*avant modelMap/, ja: /モデルピッカー.*Claude Desktop.*modelMap より先/, ko: /모델 선택기.*Claude Desktop.*modelMap보다 먼저/, diff --git a/gui/tests/es-localization.test.ts b/gui/tests/es-localization.test.ts new file mode 100644 index 00000000000..81e2fabc4a0 --- /dev/null +++ b/gui/tests/es-localization.test.ts @@ -0,0 +1,193 @@ +import { describe, expect, test } from "bun:test"; +import { runInNewContext } from "node:vm"; +import { en, type TKey } from "../src/i18n/en"; +import { es } from "../src/i18n/es"; +import { DICTS, LOCALES, detectInitial, interpolate } from "../src/i18n/shared"; +import { NATIVE_MAIN_EN, NATIVE_MAIN_TRANSLATIONS } from "../src/i18n/native-main-translations"; +import { labSupplement } from "../src/i18n/lab-translations"; +import { logGuardLabel } from "../src/i18n/log-guard-labels"; +import { logGuardOperationLabel } from "../src/i18n/log-guard-operation-labels"; +import { ROUTING_COMPATIBILITY_FIELD_LABELS } from "../src/i18n/routing-compatibility-labels"; +import { visionReasoningLabel } from "../src/i18n/vision-reasoning-labels"; +import { formatResetFuture } from "../src/components/QuotaBars"; +import { statusCodeInfo } from "../src/status-codes"; + +const placeholders = (value: string): string[] => [...value.matchAll(/\{([a-zA-Z0-9_]+)\}/g)] + .map(match => match[1]!).sort(); + +function numericResidue(english: string, spanish: string): [string[], string[]] { + const tokens = (value: string): string[] => value.match(/\d+(?:[.,]\d+)*/g) ?? []; + const translated = tokens(spanish); + // Retain literal versions, protocol IDs and code samples before interpreting locale separators. + const missing = tokens(english).filter(token => { + const index = translated.indexOf(token); + if (index < 0) return true; + translated.splice(index, 1); + return false; + }); + return [missing.map(value => value.replaceAll(",", "")).sort(), translated.map(value => + /^\d{1,3}(?:\.\d{3})+(?:,\d+)?$/.test(value) + ? value.replaceAll(".", "").replace(",", ".") : value.replace(",", ".")).sort()]; +} + +const machineIdentifiers = /--[a-z][a-z0-9-]*|\/api\/[a-zA-Z0-9_/:.{}-]+|\b[a-z][a-z0-9-]*\/<[a-zA-Z][a-zA-Z0-9_-]*>|\b[a-z][a-z0-9-]*-\*|\b[a-z]+(?:_[a-z]+)+\b|\b[a-z]+(?:[A-Z][a-z0-9]*)+\b|\bcodex-auth export\b|__main__|\[[a-z][a-z0-9_.-]*\]/g; +const machineTokens = (value: string): Set => new Set((value.match(machineIdentifiers) ?? []) + .map(token => token.replace(/\.+$/, ""))); + +// Reviewed identical spellings: Spanish cognates, brands, protocol/strategy names, +// wire identifiers and compact units. New English prose does not enter this list automatically. +const identicalValues = new Set([ + "Error", "Total", "Normal", "Original", "Local", "General", "Alias", "Ultra", "Zoom", "no", "No", "auto", "Manual", "Plan", + "Manual: {mode}", "{active}/{total} visible", " · local", "arena {total}", + "Pool", "Direct", "Home", "Child", "Hub", "Proxy", "Backend", "Combos", "Combo", "Round-robin", "Suite", "Fallback", + "Anthropic", "Anthropic · Pool 2", "OpenAI", "Claude", "Codex", "GitHub", "Google", "Gemini", "Antigravity", "Argon", "Grok", "Grok Build", + "Claude Code", "Claude Desktop", "Kiro CLI", "Builder ID", "Cursor", "OpenCode", "Pi", "OMP", "Hermes", "OpenClaw", + "gjc", "DSH", "DeepSeek Harness (DSH)", "ZCode", "Aside", "Raycast", "omo", "Qoder", "Cline CLI", "Kilo", + "Factory Droid", "GentleShell", "Kimi CLI", "MCode", "Prime CLI", "Codex CLI", "TypeSafe", + "Gentle Shell", "Kimi Code", "MiniMax Code", "Command Code", "Prime Agent", "Command Code - Auth", + "OrcaRouter - API", "OrcaRouter - Auth", "Volcengine Ark", "Volcengine Ark Coding Plan", "Volcengine Ark Agent Plan", + "Command Code - OAuth", "Command Code - API", "Windows PowerShell", "macOS", "Windows", "Linux", + "AWS IAM Identity Center", "npm (global)", "Qoder CN", "WorkBuddy (CN)", "WorkBuddy AI", "T3 Code", "GOAT", + "Responses", "Messages", "Chat Completions", "Responses API", "Messages API", "Chat Completions API", + "CODEX_HOME", "AGENTS.md", "ArrayBuffers", "OAuth", "API", "IR", "ID", "TTFT", "JEV", "RPM", "rev", + "v1", "v2", "base", "200k", "1M", "claude-sonnet-4-6", "OK", "https://...", + "codex-work, codex-alt, team...", + "Opus", "Fable", "Haiku", "Sonnet", + "Tokens", "tokens", "Tokens (30d)", "{tokens} tokens", "{bytes} bytes", "I · {model}", + "{count} req / {errors} err", "Req.", "tok/s", "≥ 50 tok/s", "p50", "p95", "p99", + "d", "h", "m", "s", "/h", "5h", "6h", "24h", "3d", "7d", "30d", "{n}m", "{n}h", "{n}d", "A–Z", "Z–A", +]); + +describe("Spanish localization contract", () => { + test("base and effective catalogs are complete, nonempty, and preserve placeholder multiplicity", () => { + expect(LOCALES.find(locale => locale.code === "es")).toEqual({ code: "es", htmlLang: "es" }); + expect(es["lang.nativeName"]).toBe("Español"); + expect(DICTS.es["shellV2.navHome"]).toBe("Inicio"); + expect(DICTS.es["nav.startup"]).toBe("Arranque"); + for (const catalog of [es, DICTS.es]) { + expect(Object.keys(catalog).sort()).toEqual(Object.keys(en).sort()); + for (const key of Object.keys(en) as TKey[]) { + expect(catalog[key].trim(), key).not.toBe(""); + expect(placeholders(catalog[key]), key).toEqual(placeholders(en[key])); + expect(catalog[key], key).not.toMatch(/ZXQ\d|QXZ|\u2047|\uFFFD/); + expect(catalog[key], key).not.toMatch(/tarifa limitada|teclas (?:API|activas)|rotación de teclas|discapaci|bañera|Herramientas de cabina|\bAmable\b|escritorio Claude|Claude escritorio/i); + } + } + for (const key of Object.keys(NATIVE_MAIN_EN) as (keyof typeof NATIVE_MAIN_EN)[]) { + expect(placeholders(NATIVE_MAIN_TRANSLATIONS.es[key]), key).toEqual(placeholders(NATIVE_MAIN_EN[key])); + } + }); + + test("does not ship untranslated English prose in either catalog", () => { + for (const catalog of [es, DICTS.es]) { + const accidental = (Object.keys(en) as TKey[]).filter(key => catalog[key] === en[key] + && /\p{L}/u.test(en[key].replace(/\{[^}]+\}/g, "")) && !identicalValues.has(en[key])); + expect(accidental).toEqual([]); + } + }); + + test("keeps CLI commands, API routes and environment names executable", () => { + const identifiers = /\bocx (?:start|ensure|tray|claude|opencode|doctor|sync|link|update)\b|(? { + for (const catalog of [es, DICTS.es]) { + for (const key of Object.keys(en) as TKey[]) { + const [canonical, translated] = numericResidue(en[key], catalog[key]); + expect(translated, `${key}: numeric values and versions`).toEqual(canonical); + const actual = machineTokens(catalog[key]); + expect([...machineTokens(en[key])].filter(token => !actual.has(token)), `${key}: machine identifiers`).toEqual([]); + } + } + }); + + test("browser regions, persisted preference and blocked storage agree before and after mount", async () => { + const guards = await Promise.all(["../index.html", "../classic/index.html"].map(async path => { + const html = await Bun.file(new URL(path, import.meta.url)).text(); + const guard = html.match(/", { headers: { "content-type": "text/html" } }); + const { response } = await call(config(), "GET", "/v1/videos/" + handle + "/content?variant=thumbnail"); + expect(response.headers.get("content-type")).toBe("application/octet-stream"); + expect(sent[0]!.url).toBe("https://" + HOST + "/v1/videos/video_up_1/content?variant=thumbnail"); + sent = []; + expect((await call(config(), "GET", "/v1/videos/" + handle + "/content?variant=../x")).response.status).toBe(400); + expect(sent).toEqual([]); + }); + + test("a declared oversized asset is refused", async () => { + const handle = await handleFor(); + answer = () => new Response(MP4, { headers: { "content-type": "video/mp4", "content-length": String(500 * 1024 * 1024) } }); + const { response } = await call(config(), "GET", "/v1/videos/" + handle + "/content"); + expect(response.status).toBe(502); + }); +}); + +describe("review regressions", () => { + test("a slash-containing model reaches images.videoProvider only when written behind its provider", async () => { + const { response } = await create(config({ images: { videoProvider: "aistudio" } }), { model: "aistudio/google/veo-like", prompt: "p" }); + expect(response.status).toBe(200); + expect(sent[0]!.body).toEqual({ model: "google/veo-like", prompt: "p" }); + }); + + test("an unusable handle key refuses the create before the paid request", async () => { + setVideoHandleKeyForTests(undefined); + writeFileSync(join(home, "video-handle-key"), "not-a-key\n", { mode: 0o600 }); + const { response } = await create(config(), { model: "aistudio/m", prompt: "p" }); + expect(response.status).toBe(500); + expect(sent).toEqual([]); + }); + + test("an upstream that echoes the row key or free text in any job field hands none of it to the caller", async () => { + answer = () => Response.json({ + id: "video_up_1", object: KEY, status: KEY, model: KEY, seconds: KEY, size: KEY, prompt: KEY, debug: { auth: "Bearer " + KEY }, + remixed_from_video_id: KEY, progress: 10, created_at: 1700000000, + error: { code: KEY, message: "upstream said " + KEY, param: KEY, type: KEY }, + }); + const { response } = await call(config(), "POST", "/v1/videos", JSON.stringify({ model: "aistudio/m", prompt: "p" })); + expect(response.status).toBe(200); + const text = await response.text(); + expect(text).not.toContain(KEY); + const job = JSON.parse(text) as Record; + expect(Object.keys(job).sort()).toEqual(["created_at", "error", "id", "model", "object", "progress"]); + expect(job).toMatchObject({ object: "video", model: "m", progress: 10, error: { message: "video generation failed" } }); + }); + + test("a secret shaped like a status, error code or job id is never reflected, not even inside the handle", async () => { + const secret = "synthetic_secret_123abc"; + answer = () => Response.json({ id: secret, status: "synthetic_secret", error: { code: secret, message: secret } }); + const { response } = await call(config(), "POST", "/v1/videos", JSON.stringify({ model: "aistudio/m", prompt: "p" })); + expect(response.status).toBe(200); + const text = await response.text(); + expect(text).not.toContain(secret); + expect(text).not.toContain("synthetic_secret"); + const job = JSON.parse(text) as { id: string; status?: string; error?: { code?: string } }; + expect(job.status).toBeUndefined(); + expect(job.error?.code).toBeUndefined(); + expect(Buffer.from(job.id.slice("video_ocx_".length), "base64url").toString("latin1")).not.toContain(secret); + }); + + test("a replacement secret on the same key id does not open the previous holder's handle", async () => { + const { response } = await create(config(), { model: "aistudio/m", prompt: "p" }); + const handle = (await response.json() as { id: string }).id; + sent = []; + const replaced = config(); + replaced.apiKeys![0] = { ...replaced.apiKeys![0]!, key: "ocx_data_" + "z".repeat(40) }; + const poll = await call(replaced, "GET", "/v1/videos/" + handle, undefined, ALICE, {}, "ocx_data_" + "z".repeat(40)); + expect(poll.response.status).toBe(404); + expect(sent).toEqual([]); + expect((await call(config(), "GET", "/v1/videos/" + handle, undefined, ALICE, {})).response.status).not.toBe(404); + }); +}); + +describe("turn lease and listener timeout", () => { + test("shutdown aborts the in-flight paid create through the turn lease and answers 503", async () => { + let bound: AbortController | undefined; + const lease = { bindAbortController(ac: AbortController) { bound = ac; } } as unknown as AdmissionLease; + let started!: () => void; + const sending = new Promise(resolve => { started = resolve; }); + setVideoOutboundDependenciesForTests({ + ...deps, + pinnedPost: async (url, pinned, body, signal) => { + sent.push({ method: "POST", url, address: pinned.address, authorization: null, body: JSON.parse(body) }); + started(); + return new Promise((_resolve, reject) => { + signal?.addEventListener("abort", () => reject(signal.reason), { once: true }); + }); + }, + }); + const url = new URL("http://localhost/v1/videos"); + const req = new Request(url, { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer " + ALICE_SECRET }, body: JSON.stringify({ model: "aistudio/m", prompt: "p" }) }); + const pending = handleVideos(req, url, config(), { kind: "create" }, logContext(), ALICE, { lease }); + await sending; + expect(bound).toBeDefined(); + bound!.abort(new Error("shutdown")); + const response = await pending; + expect(response.status).toBe(503); + expect((await response.json() as { error: { message: string } }).error.message).toBe("video create stopped during shutdown"); + expect(sent).toHaveLength(1); + }); + + test("a create body that keeps trickling is cut off at the whole-body deadline and never reaches upstream", async () => { + setVideoCreateBodyTimeoutForTests(80); + let cancelled = false; + let tick: ReturnType | undefined; + const encoder = new TextEncoder(); + const body = new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode('{"model":"aistudio/m","prompt":"')); + // A byte every 10 ms: never idle long enough for an inactivity timeout, never finished. + tick = setInterval(() => { try { controller.enqueue(encoder.encode("p")); } catch { clearInterval(tick); } }, 10); + }, + cancel() { cancelled = true; clearInterval(tick); }, + }); + try { + const url = new URL("http://localhost/v1/videos"); + const req = new Request(url, { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer " + ALICE_SECRET }, body, duplex: "half" } as RequestInit); + const events: string[] = []; + const response = await handleVideos(req, url, config(), { kind: "create" }, logContext(), ALICE, { onRequestBodyRead: () => events.push("body-read") }); + expect(response.status).toBe(408); + expect(cancelled).toBe(true); + expect(events).toEqual([]); + expect(sent).toEqual([]); + } finally { + clearInterval(tick); + setVideoCreateBodyTimeoutForTests(undefined); + } + }); + + test("a trickling multipart create is cut off at the same deadline", async () => { + setVideoCreateBodyTimeoutForTests(80); + let cancelled = false; + let tick: ReturnType | undefined; + const encoder = new TextEncoder(); + const body = new ReadableStream({ + start(controller) { + controller.enqueue(encoder.encode('--b\r\ncontent-disposition: form-data; name="prompt"\r\n\r\n')); + tick = setInterval(() => { try { controller.enqueue(encoder.encode("p")); } catch { clearInterval(tick); } }, 10); + }, + cancel() { cancelled = true; clearInterval(tick); }, + }); + try { + const url = new URL("http://localhost/v1/videos"); + const req = new Request(url, { method: "POST", headers: { "content-type": "multipart/form-data; boundary=b", authorization: "Bearer " + ALICE_SECRET }, body, duplex: "half" } as RequestInit); + const response = await handleVideos(req, url, config(), { kind: "create" }, logContext(), ALICE); + expect(response.status).toBe(408); + expect(cancelled).toBe(true); + expect(sent).toEqual([]); + } finally { + clearInterval(tick); + setVideoCreateBodyTimeoutForTests(undefined); + } + }); + + test("the listener timeout is lifted only after the create body was read", async () => { + const events: string[] = []; + answer = () => { events.push("upstream"); return Response.json({ id: "video_up_9", status: "queued" }); }; + const url = new URL("http://localhost/v1/videos"); + const headers = { "content-type": "application/json", authorization: "Bearer " + ALICE_SECRET }; + const ok = await handleVideos(new Request(url, { method: "POST", headers, body: JSON.stringify({ model: "aistudio/m", prompt: "p" }) }), + url, config(), { kind: "create" }, logContext(), ALICE, { onRequestBodyRead: () => events.push("body-read") }); + expect(ok.status).toBe(200); + expect(events).toEqual(["body-read", "upstream"]); + events.length = 0; + const bad = await handleVideos(new Request(url, { method: "POST", headers, body: "{not json" }), + url, config(), { kind: "create" }, logContext(), ALICE, { onRequestBodyRead: () => events.push("body-read") }); + expect(bad.status).toBe(400); + expect(events).toEqual([]); + }); +}); + +test("the loopback listener hands /v1/videos paths to the same matcher and nothing broader", async () => { + const source = await Bun.file(repoPath("src", "server", "index.ts")).text(); + const start = source.indexOf("function loopbackRouteAllowed"); + const gate = source.slice(start, source.indexOf("\n }", start)); + expect(gate).toContain('if (path === "/v1/videos" || path.startsWith("/v1/videos/")) return matchVideoRoute(req.method, path) !== undefined;'); + // The one gate line names the bare path and its subtree, and delegates both to matchVideoRoute. + expect(gate.match(/\/v1\/videos/g)?.length).toBe(2); +}); + +test("route matching admits only the three documented shapes", () => { + expect(matchVideoRoute("POST", "/v1/videos")).toEqual({ kind: "create" }); + expect(matchVideoRoute("GET", "/v1/videos/abc")).toEqual({ kind: "retrieve", handle: "abc" }); + expect(matchVideoRoute("GET", "/v1/videos/abc/content")).toEqual({ kind: "content", handle: "abc" }); + for (const [method, path] of [["GET", "/v1/videos"], ["DELETE", "/v1/videos/abc"], ["POST", "/v1/videos/abc/remix"], ["GET", "/v1/videos/a/b"], ["GET", "/v1/videos/%E0%A4%A"]]) { + expect(matchVideoRoute(method!, path!)).toBeUndefined(); + } +}); diff --git a/tests/server/video-handle.test.ts b/tests/server/video-handle.test.ts new file mode 100644 index 00000000000..aa3fb18e05e --- /dev/null +++ b/tests/server/video-handle.test.ts @@ -0,0 +1,128 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { chmodSync, existsSync, mkdtempSync, readdirSync, readFileSync, statSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + openVideoHandle, + sealVideoHandle, + setVideoHandleKeyForTests, + VIDEO_HANDLE_KEY_FILE, + videoHandlePrincipal, +} from "../../src/server/video-handle"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +let home = ""; +const previousHome = process.env.OPENCODEX_HOME; +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "ocx-video-handle-")); + process.env.OPENCODEX_HOME = home; + setVideoHandleKeyForTests(undefined); +}); +afterEach(() => { + setVideoHandleKeyForTests(undefined); + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousHome; + if (home) removeTreeWithRetry(home); +}); + +const claims = { provider: "aistudio", upstreamId: "video_68d7", model: "gemini-omni-1.1-flash" }; + +test("a handle opens for the principal that sealed it, under a key persisted with mode 0600", () => { + const handle = sealVideoHandle(claims, "key:alice"); + expect(handle.startsWith("video_ocx_")).toBe(true); + expect(openVideoHandle(handle, "key:alice")).toEqual(claims); + const file = join(home, VIDEO_HANDLE_KEY_FILE); + expect(existsSync(file)).toBe(true); + expect(readFileSync(file, "utf8").trim()).toMatch(/^[0-9a-f]{64}$/); + if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600); + // A restart re-reads the same key, so a job created before it is still reachable. + setVideoHandleKeyForTests(undefined); + expect(openVideoHandle(handle, "key:alice")).toEqual(claims); +}); + +test("another principal, any edited byte, a foreign key and malformed input do not open", () => { + const handle = sealVideoHandle(claims, "key:alice"); + expect(openVideoHandle(handle, "key:bob")).toBeUndefined(); + expect(openVideoHandle(handle, "loopback")).toBeUndefined(); + const body = handle.slice("video_ocx_".length); + const bytes = Buffer.from(body, "base64url"); + // Nonce, ciphertext and tag: flipping any decoded byte fails authentication. + for (const at of [0, 11, 12, Math.floor(bytes.length / 2), bytes.length - 16, bytes.length - 1]) { + const edited = Buffer.from(bytes); + edited[at] = edited[at]! ^ 0x01; + expect(openVideoHandle("video_ocx_" + edited.toString("base64url"), "key:alice")).toBeUndefined(); + } + // A non-canonical spelling of the same bytes (set unused trailing bits) does not open either. + const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + const last = body[body.length - 1]!; + const sibling = alphabet[alphabet.indexOf(last) ^ 1]!; + const respelled = "video_ocx_" + body.slice(0, -1) + sibling; + // These claims seal to 95 bytes, so the last character carries two unused bits. + expect(bytes.length % 3).toBe(2); + expect(Buffer.from(respelled.slice("video_ocx_".length), "base64url").equals(bytes)).toBe(true); + expect(openVideoHandle(respelled, "key:alice")).toBeUndefined(); + for (const bad of ["", "video_68d7", "video_ocx_", "video_ocx_abc", "video_ocx_" + body + ".x", "video_ocx_" + "a".repeat(9000)]) { + expect(openVideoHandle(bad, "key:alice")).toBeUndefined(); + } + setVideoHandleKeyForTests(Buffer.alloc(32, 1)); + expect(openVideoHandle(handle, "key:alice")).toBeUndefined(); +}); + +test("the handle reveals neither the upstream id nor the model", () => { + setVideoHandleKeyForTests(Buffer.alloc(32, 9)); + const secretish = { provider: "aistudio", upstreamId: "synthetic_secret_123abc", model: "synthetic_model_secret" }; + const handle = sealVideoHandle(secretish, "key:alice"); + const decoded = Buffer.from(handle.slice("video_ocx_".length), "base64url").toString("latin1"); + for (const value of [secretish.upstreamId, secretish.model, secretish.provider]) { + expect(handle).not.toContain(value); + expect(decoded).not.toContain(value); + } + expect(sealVideoHandle(secretish, "key:alice")).not.toBe(handle); + expect(openVideoHandle(handle, "key:alice")).toEqual(secretish); +}); + +test("principals bind the admission kind, key id and the exact presented secret", () => { + const bearer = (secret: string) => new Headers({ authorization: "Bearer " + secret }); + const k1 = videoHandlePrincipal({ kind: "configured", keyId: "k1", source: "bearer" }, bearer("secret-one")); + // The same secret in the dedicated header or x-api-key is the same principal. + expect(videoHandlePrincipal({ kind: "configured", keyId: "k1", source: "dedicated" }, new Headers({ "x-opencodex-api-key": "secret-one" }))).toBe(k1); + expect(videoHandlePrincipal({ kind: "configured", keyId: "k1", source: "x-api-key" }, new Headers({ "x-api-key": "secret-one" }))).toBe(k1); + expect(videoHandlePrincipal({ kind: "configured", keyId: "k1", source: "bearer" }, bearer("secret-two"))).not.toBe(k1); + expect(videoHandlePrincipal({ kind: "configured", keyId: "k2", source: "bearer" }, bearer("secret-one"))).not.toBe(k1); + expect(videoHandlePrincipal({ kind: "environment", source: "bearer" }, bearer("secret-one"))).not.toBe(k1); + expect(k1).not.toContain("secret-one"); + expect(videoHandlePrincipal({ kind: "loopback", source: "loopback" }, new Headers())).toBe("loopback"); + expect(videoHandlePrincipal({ kind: "configured", keyId: "k1", source: "bearer" }, new Headers())).toBeUndefined(); +}); + +test("the largest claims the create admits still seal into an openable handle", () => { + setVideoHandleKeyForTests(Buffer.alloc(32, 3)); + const big = { provider: "p".repeat(128), upstreamId: "\u00e9".repeat(256), model: "m".repeat(256) }; + const handle = sealVideoHandle(big, "key:alice"); + expect(openVideoHandle(handle, "key:alice")).toEqual(big); +}); + +test("an existing key readable by other users, or a symlinked key, fails closed", () => { + if (process.platform === "win32") return; + const file = join(home, VIDEO_HANDLE_KEY_FILE); + writeFileSync(file, "ab".repeat(32) + "\n", { mode: 0o644 }); + chmodSync(file, 0o644); + expect(() => sealVideoHandle(claims, "key:alice")).toThrow("readable by other users"); + unlinkSync(file); + const target = join(home, "elsewhere"); + writeFileSync(target, "ab".repeat(32) + "\n", { mode: 0o600 }); + symlinkSync(target, file); + expect(() => sealVideoHandle(claims, "key:alice")).toThrow("symbolic link"); +}); + +test("a later load reads the published key back and creation leaves no temporary file", () => { + const first = sealVideoHandle(claims, "key:alice"); + setVideoHandleKeyForTests(undefined); + expect(openVideoHandle(first, "key:alice")).toEqual(claims); + expect(readdirSync(home).filter(name => name.endsWith(".tmp"))).toEqual([]); +}); + +test("an unusable key file fails closed instead of minting a process-local key", () => { + writeFileSync(join(home, VIDEO_HANDLE_KEY_FILE), "not-a-key\n", { mode: 0o600 }); + expect(() => sealVideoHandle(claims, "key:alice")).toThrow("video handle key is unavailable"); +}); diff --git a/tests/videos/video-openai-client.test.ts b/tests/videos/video-openai-client.test.ts new file mode 100644 index 00000000000..268db24cade --- /dev/null +++ b/tests/videos/video-openai-client.test.ts @@ -0,0 +1,205 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, readFileSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + createOpenAiVideo, + downloadOpenAiVideoToArtifact, + fetchOpenAiVideoContent, + openAiVideoSize, + pollOpenAiVideoJob, + submitOpenAiVideoJob, + VideoUpstreamError, +} from "../../src/images/openai-video-client"; +import type { VideoOutboundDependencies, VideoProviderAuth } from "../../src/images/xai-video-client"; +import { resolvePublicAddresses } from "../../src/lib/destination-policy"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +// OpenAI Videos wire (#9110). Every case runs on a fake resolver and a fake pinned transport; a raw +// fetch is trapped so a request that skipped the outbound policy fails the test. +const HOST = "videos.relay.example"; +const KEY = "synthetic-openai-video-key"; +const MP4 = new Uint8Array([0, 0, 0, 0x18, 0x66, 0x74, 0x79, 0x70, 0x6d, 0x70, 0x34, 0x32, 1, 2, 3, 4]); + +type Sent = { method: "GET" | "POST"; url: string; address: string; authorization: string | null; body?: unknown }; + +function dns(address: string): NonNullable { + return async (url, options) => { + const target = new URL(url); + if (target.hostname !== HOST) throw new Error("unexpected DNS lookup for " + target.hostname); + target.hostname = address; + return { ...(await resolvePublicAddresses(target.toString(), options)), hostname: HOST }; + }; +} + +function transport(sent: Sent[], answer: (sent: Sent) => Response): Pick { + return { + pinnedPost: async (url, pinned, body, _signal, options) => { + const entry: Sent = { method: "POST", url, address: pinned.address, authorization: new Headers(options?.headers).get("authorization"), body: JSON.parse(body) }; + sent.push(entry); + return answer(entry); + }, + pinnedGet: async (url, pinned, _signal, options) => { + const entry: Sent = { method: "GET", url, address: pinned.address, authorization: new Headers(options?.headers).get("authorization") }; + sent.push(entry); + return answer(entry); + }, + }; +} + +const realFetch = globalThis.fetch; +let rawFetches: string[] = []; +let home = ""; +const previousHome = process.env.OPENCODEX_HOME; +beforeEach(() => { + rawFetches = []; + globalThis.fetch = (async (input: string | URL | Request) => { + rawFetches.push(String(input instanceof Request ? input.url : input)); + return Response.json({ id: "leaked", status: "completed" }); + }) as typeof fetch; + home = mkdtempSync(join(tmpdir(), "ocx-openai-video-")); + process.env.OPENCODEX_HOME = home; +}); +afterEach(() => { + globalThis.fetch = realFetch; + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousHome; + if (home) removeTreeWithRetry(home); +}); + +const auth = (overrides: Partial = {}): VideoProviderAuth => ({ + baseUrl: "https://" + HOST + "/v1", token: KEY, providerName: "aistudio", noProxy: HOST, videoApi: "openai", ...overrides, +}); +const publicDeps = (sent: Sent[], answer: (sent: Sent) => Response) => ({ resolveAddresses: dns("93.184.216.34"), ...transport(sent, answer) }); + +describe("OpenAI Videos submit", () => { + test("posts {baseUrl}/videos with the row key and maps bridge arguments onto the OpenAI fields", async () => { + const sent: Sent[] = []; + const result = await submitOpenAiVideoJob( + { prompt: "a fox", model: "gemini-omni-1.1-flash", duration: 8, resolution: "720p", aspectRatio: "9:16", image: "https://img.example/a.png" }, + auth(), undefined, publicDeps(sent, () => Response.json({ id: "video_123", object: "video", status: "queued" })), + ); + expect(result).toEqual({ requestId: "video_123" }); + expect(sent).toEqual([{ + method: "POST", url: "https://" + HOST + "/v1/videos", address: "93.184.216.34", authorization: "Bearer " + KEY, + body: { prompt: "a fox", model: "gemini-omni-1.1-flash", seconds: "8", size: "720x1280", input_reference: { image_url: "https://img.example/a.png" } }, + }]); + expect(rawFetches).toEqual([]); + }); + + test("refuses frame pins and references before anything is sent", async () => { + const sent: Sent[] = []; + for (const extra of [{ lastFrame: "https://a.example/1.png" }, { keyframes: [{ image: "https://a.example/2.png", timestampS: 1 }] }, { referenceImages: ["https://a.example/3.png"] }]) { + await expect(submitOpenAiVideoJob({ prompt: "p", ...extra }, auth(), undefined, publicDeps(sent, () => Response.json({ id: "x" })))) + .rejects.toThrow("not supported by the OpenAI Videos API"); + } + expect(sent).toEqual([]); + }); + + test("a non-2xx create keeps its status and an unusable id is refused", async () => { + const sent: Sent[] = []; + const error = await createOpenAiVideo({ prompt: "p" }, auth(), undefined, publicDeps(sent, () => Response.json({ error: { message: "nope" } }, { status: 429 }))) + .then(() => undefined, (caught: unknown) => caught); + expect(error).toBeInstanceOf(VideoUpstreamError); + expect((error as VideoUpstreamError).status).toBe(429); + await expect(createOpenAiVideo({ prompt: "p" }, auth(), undefined, publicDeps(sent, () => Response.json({ id: ".." })))) + .rejects.toThrow("usable video id"); + }); + + test("size covers the bridge resolutions and keeps the upstream default when nothing was asked", () => { + expect(openAiVideoSize(undefined, undefined)).toBeUndefined(); + expect(openAiVideoSize("720p", "16:9")).toBe("1280x720"); + expect(openAiVideoSize("1080p", "9:16")).toBe("1080x1920"); + expect(openAiVideoSize("480p", undefined)).toBe("854x480"); + expect(openAiVideoSize(undefined, "1:1")).toBe("720x720"); + }); +}); + +describe("OpenAI Videos poll", () => { + test("maps queued, in_progress, completed and failed; a finished job carries no URL", async () => { + const statuses: Record = { queued: "processing", in_progress: "processing", completed: "done", failed: "failed" }; + for (const [upstream, expected] of Object.entries(statuses)) { + const sent: Sent[] = []; + const poll = await pollOpenAiVideoJob("video_123", auth(), undefined, publicDeps(sent, () => Response.json({ + id: "video_123", status: upstream, progress: 40, + ...(upstream === "failed" ? { error: { code: "internal_error", message: "arbitrary upstream text" } } : {}), + }))); + expect(poll.status).toBe(expected as typeof poll.status); + expect(poll.videoUrl).toBeUndefined(); + expect(sent[0]).toMatchObject({ method: "GET", url: "https://" + HOST + "/v1/videos/video_123", authorization: "Bearer " + KEY }); + if (upstream === "failed") expect(poll.error).toEqual({ code: "internal_error", message: undefined }); + } + }); + + test("a job id that would collapse onto another path is refused before any send", async () => { + const sent: Sent[] = []; + await expect(pollOpenAiVideoJob("..", auth(), undefined, publicDeps(sent, () => Response.json({})))).rejects.toThrow("not usable"); + expect(sent).toEqual([]); + }); +}); + +describe("OpenAI Videos content", () => { + test("downloads /content from the same destination with the same key into a 0600 artifact", async () => { + const sent: Sent[] = []; + const path = await downloadOpenAiVideoToArtifact("video_123", auth(), undefined, undefined, + publicDeps(sent, () => new Response(MP4, { headers: { "content-type": "video/mp4" } }))); + expect(sent).toEqual([{ method: "GET", url: "https://" + HOST + "/v1/videos/video_123/content", address: "93.184.216.34", authorization: "Bearer " + KEY }]); + expect(path.startsWith(join(home, "artifacts"))).toBe(true); + expect(path.endsWith(".mp4")).toBe(true); + expect(new Uint8Array(readFileSync(path))).toEqual(MP4); + if (process.platform !== "win32") expect(statSync(path).mode & 0o777).toBe(0o600); + }); + + test("a redirect is not followed and fails closed", async () => { + const sent: Sent[] = []; + const error = await fetchOpenAiVideoContent("video_123", auth(), {}, publicDeps(sent, () => new Response(null, { status: 302, headers: { location: "https://cdn.other.example/v.mp4" } }))) + .then(() => undefined, (caught: unknown) => caught); + expect(error).toBeInstanceOf(VideoUpstreamError); + expect((error as VideoUpstreamError).status).toBe(302); + expect(sent).toHaveLength(1); + expect(rawFetches).toEqual([]); + }); + + test("an unknown variant is refused before any send", async () => { + const sent: Sent[] = []; + await expect(fetchOpenAiVideoContent("video_123", auth(), { variant: "../../x" }, publicDeps(sent, () => new Response(MP4)))).rejects.toThrow("variant"); + expect(sent).toEqual([]); + }); + + for (const phase of ["submit", "poll", "content"] as const) { + const call = (a: VideoProviderAuth, deps: VideoOutboundDependencies) => phase === "submit" + ? submitOpenAiVideoJob({ prompt: "p" }, a, undefined, deps) + : phase === "poll" ? pollOpenAiVideoJob("video_1", a, undefined, deps) : fetchOpenAiVideoContent("video_1", a, {}, deps); + + test(phase + ": the issue's loopback http row reaches 127.0.0.1 with its own allowPrivateNetwork", async () => { + const sent: Sent[] = []; + const loopback = auth({ baseUrl: "http://127.0.0.1:2048/v1", allowPrivateNetwork: true, noProxy: "127.0.0.1" }); + await call(loopback, { + resolveAddresses: (url, options) => resolvePublicAddresses(url, options), + ...transport(sent, () => phase === "content" ? new Response(MP4) : Response.json({ id: "video_1", status: "queued" })), + }); + expect(sent).toHaveLength(1); + expect(sent[0]).toMatchObject({ address: "127.0.0.1", authorization: "Bearer " + KEY }); + expect(sent[0]!.url.startsWith("http://127.0.0.1:2048/v1/videos")).toBe(true); + expect(rawFetches).toEqual([]); + }); + + test(phase + ": a hostname resolving to loopback never receives the key without allowPrivateNetwork", async () => { + const sent: Sent[] = []; + const error = await call(auth(), { resolveAddresses: dns("127.0.0.1"), ...transport(sent, () => Response.json({ id: "video_1", status: "queued" })) }) + .then(() => undefined, (caught: unknown) => caught); + expect((error as Error).message).toContain("loopback"); + expect(sent).toEqual([]); + expect(rawFetches).toEqual([]); + }); + + test(phase + ": cleartext to a public address is refused even with allowPrivateNetwork", async () => { + const sent: Sent[] = []; + const error = await call(auth({ baseUrl: "http://" + HOST + "/v1", allowPrivateNetwork: true }), publicDeps(sent, () => Response.json({ id: "video_1" }))) + .then(() => undefined, (caught: unknown) => caught); + expect(error).toBeInstanceOf(Error); + expect(sent).toEqual([]); + expect(rawFetches).toEqual([]); + }); + } +}); diff --git a/tests/videos/video-openai-wire-bridge.test.ts b/tests/videos/video-openai-wire-bridge.test.ts new file mode 100644 index 00000000000..9292185d218 --- /dev/null +++ b/tests/videos/video-openai-wire-bridge.test.ts @@ -0,0 +1,135 @@ +/** + * `video_gen` on the OpenAI Videos wire (#9110): a provider row with `videoApi: "openai"` named by + * `images.videoProvider` is submitted, polled and downloaded on that wire, through the real outbound + * policy, against a local fake upstream. No paid API and no real credential is involved. + */ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync, readFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import type { ProviderAdapter } from "../../src/adapters/base"; +import { pollVideoWithHeartbeats } from "../../src/images/fulfill-video"; +import { runWithImageBridge } from "../../src/images/loop"; +import { planVideoBridge } from "../../src/images/plan"; +import { videoWireFor } from "../../src/images/video-wire"; +import type { AdapterEvent, OcxConfig, OcxParsedRequest, OcxProviderConfig } from "../../src/types"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; +import { createTestTranslatorBudget } from "../helpers/translator-budget"; + +const KEY = "synthetic-openai-wire-bridge-key"; +const MP4 = new Uint8Array([0, 0, 0, 0x18, 0x66, 0x74, 0x79, 0x70, 0x6d, 0x70, 0x34, 0x32, 5, 6, 7, 8]); +const parsed = (): OcxParsedRequest => ({ modelId: "m", stream: true, options: {}, context: { messages: [], tools: [] } }) as unknown as OcxParsedRequest; +const routed = { baseUrl: "https://api.anthropic.com", authMode: "key", apiKey: "routed" } as OcxProviderConfig; + +function config(row: Partial, extra: Record = {}): OcxConfig { + return { + providers: { aistudio: { adapter: "openai-chat", authMode: "key", apiKey: KEY, ...row } as OcxProviderConfig, ...extra }, + images: { videoBridgeEnabled: true, videoProvider: "aistudio", videoBridgeModel: "gemini-omni-1.1-flash" }, + } as unknown as OcxConfig; +} + +describe("plan", () => { + test("a row with videoApi openai carries that wire; a row without it keeps the xAI wire", async () => { + const openai = await planVideoBridge(config({ baseUrl: "https://v.example/v1", videoApi: "openai" }), parsed(), routed); + expect(openai?.auth?.videoApi).toBe("openai"); + expect(videoWireFor(openai!.auth!).requireUrl).toBe(false); + const xaiWire = await planVideoBridge(config({ baseUrl: "https://v.example/v1" }), parsed(), routed); + expect(xaiWire?.auth?.videoApi).toBeUndefined(); + expect(videoWireFor(xaiWire!.auth!).requireUrl).toBe(true); + }); + + test("the pinned xai destination stays on the xAI wire whatever its row says", async () => { + const cfg = config({ baseUrl: "https://v.example/v1" }, { + xai: { adapter: "openai-chat", baseUrl: "https://api.x.ai/v1", authMode: "key", apiKey: "xai-synthetic", videoApi: "openai" } as OcxProviderConfig, + }); + (cfg.images as { videoProvider: string }).videoProvider = "xai"; + const plan = await planVideoBridge(cfg, parsed(), routed); + expect(plan?.auth?.providerName).toBe("xai"); + expect(plan?.auth?.videoApi).toBeUndefined(); + }); +}); + +describe("pollVideoWithHeartbeats", () => { + const auth = { baseUrl: "https://v.example/v1", token: "t", providerName: "p" }; + const done = async () => ({ status: "done" as const }); + test("a content-delivered wire finishes without a URL; the xAI wire still requires one", async () => { + const content = pollVideoWithHeartbeats("id", auth, new AbortController().signal, 1000, async () => {}, done, false); + expect((await content.next()).value).toEqual({ ok: true }); + const url = pollVideoWithHeartbeats("id", auth, new AbortController().signal, 1000, async () => {}, done); + expect((await url.next()).value).toEqual({ ok: false, error: "video generation completed but no video URL was returned" }); + }); +}); + +describe("video_gen on the OpenAI wire", () => { + type Seen = { method: string; path: string; authorization: string | null; body?: unknown }; + let upstream: ReturnType | undefined; + let home = ""; + const previousHome = process.env.OPENCODEX_HOME; + beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "ocx-openai-wire-bridge-")); + process.env.OPENCODEX_HOME = home; + }); + afterEach(async () => { + await upstream?.stop(true); + upstream = undefined; + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; + else process.env.OPENCODEX_HOME = previousHome; + if (home) removeTreeWithRetry(home); + }); + + test("submits POST /videos, polls /videos/{id}, downloads /content with the row key, and returns the artifact", async () => { + const seen: Seen[] = []; + upstream = Bun.serve({ + port: 0, hostname: "127.0.0.1", + async fetch(req) { + const path = new URL(req.url).pathname; + const entry: Seen = { method: req.method, path, authorization: req.headers.get("authorization") }; + if (req.method === "POST") entry.body = await req.json(); + seen.push(entry); + if (req.method === "POST" && path === "/v1/videos") return Response.json({ id: "video_abc", object: "video", status: "queued" }); + if (path === "/v1/videos/video_abc") return Response.json({ id: "video_abc", status: "completed", progress: 100 }); + if (path === "/v1/videos/video_abc/content") return new Response(MP4, { headers: { "content-type": "video/mp4" } }); + return new Response("not found", { status: 404 }); + }, + }); + const baseUrl = `http://127.0.0.1:${upstream.port}/v1`; + const plan = await planVideoBridge(config({ baseUrl, videoApi: "openai", allowPrivateNetwork: true, noProxy: "127.0.0.1" }), parsed(), routed); + expect(plan?.auth?.videoApi).toBe("openai"); + + const requests: OcxParsedRequest[] = []; + let iteration = 0; + const adapter: ProviderAdapter = { + name: "openai-wire-fixture", + buildRequest: async () => ({ url: "https://example.invalid/model", method: "POST", headers: {}, body: "{}" }), + fetchResponse: async () => new Response(""), + parseStream: async function* (): AsyncGenerator { /* runTurn only */ }, + runTurn: async (request, _incoming, emit) => { + requests.push(request); + if (iteration++ === 0) { + emit({ type: "tool_call_start", id: "v1", name: "video_gen" }); + emit({ type: "tool_call_delta", arguments: '{"prompt":"a wave","duration":4,"resolution":"720p","aspect_ratio":"16:9"}' }); + emit({ type: "tool_call_end" }); + } else { + emit({ type: "text_delta", text: "done" }); + } + emit({ type: "done" }); + }, + }; + const response = await runWithImageBridge({ + parsed: parsed(), adapter, videoPlan: plan, + incomingMeta: { headers: new Headers(), translatorBudget: createTestTranslatorBudget() }, + }); + expect(await response.text()).toContain("event: response.completed"); + + expect(seen).toEqual([ + { method: "POST", path: "/v1/videos", authorization: "Bearer " + KEY, body: { prompt: "a wave", model: "gemini-omni-1.1-flash", seconds: "4", size: "1280x720" } }, + { method: "GET", path: "/v1/videos/video_abc", authorization: "Bearer " + KEY }, + { method: "GET", path: "/v1/videos/video_abc/content", authorization: "Bearer " + KEY }, + ]); + const toolResult = requests[1]!.context.messages.find(message => message.role === "toolResult"); + const result = JSON.parse((toolResult as { content: string }).content) as { ok: boolean; path: string }; + expect(result.ok).toBe(true); + expect(result.path.startsWith(join(home, "artifacts"))).toBe(true); + expect(new Uint8Array(readFileSync(result.path))).toEqual(MP4); + }); +}); From 6114fed16265c9ec0a0f079e4a6f9b637d6d38e2 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 26 Nov 2026 02:10:16 +0900 Subject: [PATCH 53/60] feat(audio): follow Codex GPT-Live defaults and gpt-transcribe fields (#9139) * feat(audio): follow Codex GPT-Live defaults and gpt-transcribe fields External GPT-Live now defaults to gpt-live-1.1-codex, as openai/codex does since b05266d61b, and resolves the gpt-live-1 and gpt-live-1.1 aliases on call-create sessions and Frameless standalone sockets; the resolved name is the model a key scope judges and the binding records. A session the proxy writes itself gets its voice after the upstream resolves: marin for an OpenAI API key, cove for a ChatGPT account. Client sessions keep their own fields. File transcription accepts gpt-transcribe on the OpenAI API-key relay with repeated keywords[] and languages[] (the singular language is refused for that model and the list fields for every other), and returns the detected languages codes. An extensionless upload is named and typed from its audio signature, since Bun's multipart parser drops the part Content-Type. * docs(audio): scalar-only duplicate rule; test scoped create and rejoin model --- .../261126_realtime_voice_parity/000_plan.md | 68 +++++++++++++++ .../docs/es/reference/proxy-formats.md | 10 ++- .../content/docs/reference/proxy-formats.md | 26 ++++-- src/server/audio-live.ts | 14 +-- src/server/audio-transcriptions.ts | 76 ++++++++++++++-- src/server/audio-upstream.ts | 15 +++- structure/data-planes/inbound-compat.md | 10 +-- tests/server/api-access-endpoints.test.ts | 2 +- tests/server/api-key-scope-audio.test.ts | 81 +++++++++++++++++ tests/server/audio-dictation.test.ts | 45 +++++++++- tests/server/audio-transcriptions.test.ts | 86 +++++++++++++++++++ 11 files changed, 401 insertions(+), 32 deletions(-) create mode 100644 devlog/_fin/261126_realtime_voice_parity/000_plan.md diff --git a/devlog/_fin/261126_realtime_voice_parity/000_plan.md b/devlog/_fin/261126_realtime_voice_parity/000_plan.md new file mode 100644 index 00000000000..10cb6bd48e3 --- /dev/null +++ b/devlog/_fin/261126_realtime_voice_parity/000_plan.md @@ -0,0 +1,68 @@ +# Realtime voice parity with Codex 5505daf388 + +Single implementation cycle. Source: Codex af91f6ef → 5505daf388 (read-only archive), OpenCodex origin/dev c0f59e4542. +Official references read 2026-11-26: developers.openai.com/api/docs/guides/transcription.md, +.../speech-to-text, .../reference/resources/audio/subresources/transcriptions/methods/create.md, +.../models/gpt-transcribe.md, .../models/gpt-live-1.1.md, .../guides/text-to-speech, .../deprecations.md. + +## Why + +Codex moved its default GPT-Live model to `gpt-live-1.1-codex` (b05266d61b, +codex-rs/core/src/realtime_conversation.rs:120) and now leaves the voice unset until the call +destination is known: ChatGPT backend calls get `cove` (codex-api/src/endpoint/realtime_call.rs:143), +API calls get `marin` for Frameless sessions (realtime_websocket/protocol.rs:52). Its backend +transcription client names the upload from the MIME type (backend-client/src/client.rs:514). +OpenAI's file transcription now recommends `gpt-transcribe` with `keywords[]` and `languages[]` +and returns detected `languages`; `gpt-4o-transcribe`, `gpt-4o-mini-transcribe` and `whisper-1` +shut down on 2027-02-26. + +The native Codex relay in src/server/live.ts already forwards every Codex realtime header +(including `voice-session-id`), the client's model and close codes, so it does not change. +Through OpenCodex, Codex sees an API base and serializes an unset voice as `marin`; an explicit +`marin` looks identical, so the proxy cannot restore `cove` there. That stays documented only. + +## Changes + +| File | Change | +| --- | --- | +| src/server/audio-upstream.ts | `LIVE_AUDIO_MODEL = "gpt-live-1.1-codex"`; `resolveLiveAudioModel(model?)` maps `gpt-live-1` → `gpt-live-1-codex`, `gpt-live-1.1` → `gpt-live-1.1-codex`, omitted → default | +| src/server/audio-live.ts | call-create and standalone socket use `resolveLiveAudioModel`; the session the proxy synthesizes gets `audio.output.voice` after the upstream is resolved: keyed API relay `marin`, ChatGPT `cove`. A client-supplied session is never given a voice | +| src/server/audio-transcriptions.ts | keyed relay accepts `gpt-transcribe`; repeated `keywords[]`/`languages[]` only with `gpt-transcribe` on the keyed relay (bounded count, language code check, keyword without `<`, `>`, CR, LF); `language` and `languages[]` together refused; subscription refuses both list fields; JSON result adds well-formed `languages: [{code}]` when upstream returns it; an upload without an extension is named from its MIME (wav, mp3, m4a, webm, ogg) with the old `.webm` fallback | +| tests/server/audio-transcriptions.test.ts | red→green cases for the above | +| tests/server/audio-dictation.test.ts | default/alias handshake URLs; synthesized call-create voice per destination; client session untouched | +| tests/server/api-access-endpoints.test.ts | advertised `liveModel` follows the constant | +| structure/data-planes/inbound-compat.md, docs-site reference/proxy-formats.md (+ es) | default model, aliases, fields, result shape | + +## Checks + +`bun test tests/server/audio-transcriptions.test.ts tests/server/audio-dictation.test.ts tests/server/api-access-endpoints.test.ts tests/server/api-key-scope-audio.test.ts tests/server/api-key-scope-live.test.ts`, +`bun run typecheck`, `bun run structure:check`, `bun run privacy:scan`, docs-*.test.ts, test-layout and file-size ratchet tests. +Tests use fake fetch and local WebSocket fixtures only. + +## Risks + +A key scoped to `gpt-live-1-codex` that relied on the omitted-model default is now judged against +`gpt-live-1.1-codex`; naming `gpt-live-1` or `gpt-live-1-codex` keeps the old model. +NOT RUN: any live GPT-Live or transcription call, including whether the API-key `/v1/live` upstream accepts `gpt-live-1.1-codex`. + + +## Amendment after plan audit round 1 (Terra FAIL, 3 blockers) + +1. `gpt-transcribe` refuses the singular `language` field (400) whether or not `languages[]` is present; other models keep `language` and refuse `languages[]`/`keywords[]`. Tests assert the upstream multipart body. +2. A client call-create session that names no `model` is forwarded with the resolved default model inserted, so the model judged by the key scope and recorded on the binding is the model the upstream runs. Only `model` is inserted; a client session never gains a voice. The admission predicate is unchanged. +3. Alias rewriting applies only to Frameless (`/v1/live` call-create and Frameless standalone sockets). Realtime standalone sockets keep their query model untouched, and bound joins keep the recorded model. Scoped tests prove the authorized model equals the forwarded model for `gpt-live-1`, `gpt-live-1.1`, an omitted model, a client session without a model, and a rejoin. + +Notes adopted: the voice fixture captures call-create bodies; transcription tests cover repeated arrays versus duplicate scalars, array bounds, invalid keywords and codes, malformed `languages` responses, text output, MIME fallback, and Pool versus keyed. `ocx access audio` keeps its own model allowlist (src/cli/access-audio.ts:14) and is unchanged; the docs say `gpt-transcribe` is a keyed HTTP option. + + +## Amendment after plan audit round 2 (Terra FAIL, same class repeated) + +The repeated finding is one class: on the external live paths, a destination that names no model is judged against the default. It covers a Frameless call-create session without `model`, `/v1/realtime/calls` without a session, and a Realtime standalone socket without a query model. The coordinator placed changes to key-scope admission in a separate report-only pull request. That pull request now owns the whole class under one rule: the external path judges the model it forwards, and when nothing names one, a model-scoped key is refused, as on the native path. This unit therefore drops round 1 amendment 2 (inserting a model into a client session). Here, an unnamed destination is judged against the new default exactly as it was judged against the old one, so this unit neither adds nor widens an unnamed case. Every case that names a model, whether directly or through a Frameless alias or the default the proxy itself synthesizes, is forwarded with the model it is judged on. + + +## Implementation notes (B) + +- Call-create aliasing keeps its existing reach: the `gpt-live-1` rewrite already applied to both `/v1/live` and `/v1/realtime/calls` sessions, and `gpt-live-1.1` joins it there. Standalone rewriting stays Frameless-only. +- Bun's multipart parser drops a part's `Content-Type` (observed: a `File` sent as `audio/wav` arrives with `type === ""`), so the upload is identified from its leading bytes (RIFF/WAVE, ID3 or MPEG frame sync, `ftyp`, `OggS`, EBML, `fLaC`) and sent with that name and type. Unknown bytes keep the `.webm` name, as before. +- Red evidence: with the three `origin/dev` sources and the new tests, 12 tests fail; with the change, all pass. + diff --git a/docs-site/src/content/docs/es/reference/proxy-formats.md b/docs-site/src/content/docs/es/reference/proxy-formats.md index bc646a9d9a6..6dd151b5e63 100644 --- a/docs-site/src/content/docs/es/reference/proxy-formats.md +++ b/docs-site/src/content/docs/es/reference/proxy-formats.md @@ -150,7 +150,7 @@ Por separado, en cada cable de entrada, una llamada con espacio de nombres `defa | Anthropic Messages | `POST /v1/messages` | Anthropic `message` JSON | Anthropic Messages SSE | | Anthropic recuento de tokens | `POST /v1/messages/count_tokens` | `{ "input_tokens": number }` | No se requiere | | Descubrimiento del modelo | `GET /v1/models` | Catálogo o instantánea de escritorio explícita | No se requiere | -| Transcripción de archivos | `POST /v1/audio/transcriptions` | `{ "text": string }` o texto sin formato | No se admite en este punto final de archivo | +| Transcripción de archivos | `POST /v1/audio/transcriptions` | `{ "text": string, "languages"?: [...] }` o texto sin formato | No se admite en este punto final de archivo | | Dictado de streaming | `WS /v1/audio/transcriptions/stream` | No se requiere | Dictado de escritorio JSON eventos | | Voz y tiempo real | `POST /v1/live`, `POST /v1/realtime/calls` | Respuesta retransmitida de creación de llamadas | Una banda lateral separada WebSocket retransmite tramas en ambas direcciones | | Responses compactación | `POST /v1/responses/compact` | Historial de reemplazo JSON | No se requiere | @@ -175,9 +175,11 @@ curl "$OPENCODEX_BASE_URL/audio/transcriptions" \ -F 'language=ko' ``` -Configure `OPENCODEX_BASE_URL` en su URL de proxy que termina en `/v1`. Los campos opcionales son `prompt`, `language`, y `response_format` ( `json`, el valor predeterminado, o `text` ). El resultado JSON contiene `text` solamente. Los archivos no deben estar vacíos y no deben tener más de 25.000.000 bytes; los cuerpos de varias partes están limitados a 32 MiB y los campos de texto a 16 KiB. El límite del cuerpo del oyente configurado puede imponer un techo más pequeño. Los campos duplicados o sin soporte, incluyendo `stream`, son rechazados. Este punto final no promete marcas de tiempo, diarización, subtítulos o metadatos de uso de tokens. +Configure `OPENCODEX_BASE_URL` en su URL de proxy que termina en `/v1`. Los campos opcionales son `prompt`, `language`, y `response_format` ( `json`, el valor predeterminado, o `text` ). El resultado JSON contiene `text`, más `languages` (una matriz de `{ "code": string }`) cuando el servicio ascendente informa los idiomas detectados. Los archivos no deben estar vacíos y no deben tener más de 25.000.000 bytes; los cuerpos de varias partes están limitados a 32 MiB y los campos de texto a 16 KiB. El límite del cuerpo del oyente configurado puede imponer un techo más pequeño. Los campos escalares duplicados y los campos sin soporte, incluyendo `stream`, son rechazados. Este punto final no promete marcas de tiempo, diarización, subtítulos o metadatos de uso de tokens. -La ruta de suscripción ChatGPT usa `gpt-4o-transcribe` como identificador de compatibilidad y no envía un nombre de modelo al punto final de transcripción privado. No es evidencia del modelo interno del backend. Un proveedor de claves OpenAI API habilitado también admite `gpt-4o-mini-transcribe` y `whisper-1`; cuando se selecciona un proveedor ChatGPT, un fallo de autenticación no cambia silenciosamente a ese proveedor pagado. El modo Direct utiliza la cuenta principal almacenada según las reglas de admisión de perfil existentes; El modo Pool utiliza la cuenta almacenada seleccionada. Las credenciales faltantes, caducadas o que se agotan devuelven un error. La cancelación detiene la solicitud de salida y el contenido de audio no está escrito para solicitar el historial. +Con un proveedor de claves OpenAI API, `model=gpt-transcribe` acepta campos repetidos `keywords[]` y `languages[]` (hasta 100 entradas cada uno) en lugar de `language`; ese modelo rechaza el campo singular y los demás modelos rechazan los campos de lista. Una carga cuyo nombre de archivo no tiene extensión se nombra y tipifica según su firma de audio (WAV, MP3, M4A, Ogg, WebM o FLAC) antes de enviarse; cualquier otra conserva el nombre `.webm`. + +La ruta de suscripción ChatGPT usa `gpt-4o-transcribe` como identificador de compatibilidad y no envía un nombre de modelo al punto final de transcripción privado. No es evidencia del modelo interno del backend. Un proveedor de claves OpenAI API habilitado también admite `gpt-transcribe`, `gpt-4o-mini-transcribe` y `whisper-1`; cuando se selecciona un proveedor ChatGPT, un fallo de autenticación no cambia silenciosamente a ese proveedor pagado. El modo Direct utiliza la cuenta principal almacenada según las reglas de admisión de perfil existentes; El modo Pool utiliza la cuenta almacenada seleccionada. Las credenciales faltantes, caducadas o que se agotan devuelven un error. La cancelación detiene la solicitud de salida y el contenido de audio no está escrito para solicitar el historial. @@ -488,7 +490,7 @@ Los clientes de Gemini, como el SDK google-genai con una URL base personalizada, ### Claves API externas -Los clientes externos usan una clave OpenCodex en cualquier encabezado de credencial de audio compatible, o el par de subprotocolos del navegador descrito anteriormente. Independiente `WS /v1/live?model=gpt-live-1-codex` utiliza el protocolo Frameless; un modelo omitido por defecto a ese identificador y `gpt-live-1` es su alias proxy. Esta no es una afirmación de que cada clave pública OpenAI Realtime SDK o API sea compatible con GPT-Live. +Los clientes externos usan una clave OpenCodex en cualquier encabezado de credencial de audio compatible, o el par de subprotocolos del navegador descrito anteriormente. Independiente `WS /v1/live?model=gpt-live-1.1-codex` utiliza el protocolo Frameless. Un modelo omitido usa por defecto ese identificador, el modelo GPT-Live actual de Codex; `gpt-live-1` y `gpt-live-1.1` son alias proxy de `gpt-live-1-codex` y `gpt-live-1.1-codex`, y los mismos alias se aplican a una sesión de creación de llamada. Una clave limitada a un modelo en vivo se evalúa con el nombre resuelto. Cuando `POST /v1/live` no lleva sesión, OpenCodex escribe una con ese modelo predeterminado y la voz predeterminada del destino: `cove` para una cuenta ChatGPT y `marin` para una clave OpenAI API. Una sesión que usted envía conserva sus propios campos; solo se resuelve un alias de modelo en ella. Esta no es una afirmación de que cada clave pública OpenAI Realtime SDK o API sea compatible con GPT-Live. Para una nueva conexión independiente, envíe la inicialización compatible con la fuente a continuación después de que se abra el socket y espere a `session.started` con un `session.id` no vacío. Un evento de sesión actualizada con la misma forma también es aceptado por el cliente nativo. diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index ec6b577433a..a51ffae897f 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -206,7 +206,7 @@ to the bare tool name the request declared (`default.Read` → `Read`). | Anthropic Messages | `POST /v1/messages` | Anthropic `message` JSON | Anthropic Messages SSE | | Anthropic token count | `POST /v1/messages/count_tokens` | `{ "input_tokens": number }` | Not applicable | | Model discovery | `GET /v1/models` | Catalog or explicit Desktop snapshot | Not applicable | -| File transcription | `POST /v1/audio/transcriptions` | `{ "text": string }` or plain text | Not supported on this file endpoint | +| File transcription | `POST /v1/audio/transcriptions` | `{ "text": string, "languages"?: [...] }` or plain text | Not supported on this file endpoint | | Streaming dictation | `WS /v1/audio/transcriptions/stream` | Not applicable | Desktop dictation JSON events | | Voice and Realtime | `POST /v1/live`, `POST /v1/realtime/calls` | Relayed call-creation response | A separate sideband WebSocket relays frames in both directions | | Responses compaction | `POST /v1/responses/compact` | Replacement-history JSON | Not applicable | @@ -243,16 +243,23 @@ curl "$OPENCODEX_BASE_URL/audio/transcriptions" \ Set `OPENCODEX_BASE_URL` to your proxy URL ending in `/v1`. Optional fields are `prompt`, `language`, and `response_format` (`json`, the default, or `text`). The -JSON result contains `text` only. Files must be nonempty and no larger than +JSON result contains `text`, plus `languages` (an array of `{ "code": string }`) when +the upstream reports detected languages. Files must be nonempty and no larger than 25,000,000 bytes; multipart bodies are limited to 32 MiB and text fields to 16 KiB. The configured listener body limit can impose a smaller ceiling. -Duplicate or unsupported fields, including `stream`, are rejected. This endpoint +Duplicate scalar fields and unsupported fields, including `stream`, are rejected. This endpoint does not promise timestamps, diarization, subtitles, or token-usage metadata. +With an OpenAI API-key provider, `model=gpt-transcribe` takes repeated `keywords[]` +and `languages[]` fields (up to 100 entries each) instead of `language`; that model +refuses the singular field, and every other model refuses the list fields. An upload +whose filename has no extension is named and typed from its audio signature (WAV, MP3, +M4A, Ogg, WebM or FLAC) before it is sent upstream; anything else keeps the `.webm` name. + The ChatGPT subscription path uses `gpt-4o-transcribe` as a compatibility identifier and does not send a model name to the private transcription endpoint. It is not evidence of the backend's internal model. An enabled OpenAI API-key provider also -supports `gpt-4o-mini-transcribe` and `whisper-1`; when a ChatGPT provider is selected, +supports `gpt-transcribe`, `gpt-4o-mini-transcribe` and `whisper-1`; when a ChatGPT provider is selected, an authentication failure does not silently switch to that paid provider. Direct mode uses the stored main account under the existing profile admission rules; Pool mode uses the selected stored account. Missing, expired or draining @@ -907,9 +914,14 @@ from the URL and headers before the request is logged or forwarded. Errors use G External clients use an OpenCodex key in any supported audio credential header, or the browser subprotocol pair described above. Standalone -`WS /v1/live?model=gpt-live-1-codex` uses the Frameless protocol; an omitted model -defaults to that identifier and `gpt-live-1` is its proxy alias. This is not a -claim that every public OpenAI Realtime SDK or API key supports GPT-Live. +`WS /v1/live?model=gpt-live-1.1-codex` uses the Frameless protocol. An omitted model +defaults to that identifier, Codex's current GPT-Live model; `gpt-live-1` and +`gpt-live-1.1` are proxy aliases for `gpt-live-1-codex` and `gpt-live-1.1-codex`, and +the same aliases apply to a call-create session. A key scoped to a live model is judged +on the resolved name. When `POST /v1/live` carries no session, OpenCodex writes one +with that default model and the destination's default voice: `cove` for a ChatGPT +account and `marin` for an OpenAI API key. A session you send keeps its own fields; only a model alias in it is resolved. +This is not a claim that every public OpenAI Realtime SDK or API key supports GPT-Live. For a new standalone connection, send the source-compatible initialization below after socket open and wait for `session.started` with a nonempty `session.id`. diff --git a/src/server/audio-live.ts b/src/server/audio-live.ts index d4446a5706a..13b56cbb543 100644 --- a/src/server/audio-live.ts +++ b/src/server/audio-live.ts @@ -9,7 +9,7 @@ import { captureExplicitOpenAiCallerAuth } from "../providers/openai-sidecar"; import type { OcxConfig } from "../types"; import type { AudioClient } from "./audio-client"; import { finishAudioUpstream, type AudioSocketTarget } from "./audio-dictation"; -import { LIVE_AUDIO_MODEL, resolveAudioUpstream, type AudioUpstream } from "./audio-upstream"; +import { LIVE_AUDIO_MODEL, resolveAudioUpstream, resolveLiveAudioModel, type AudioUpstream } from "./audio-upstream"; import { registerTurn, unregisterTurn } from "./lifecycle"; import { backendJsonBodyFromApiMultipart, buildLiveSidebandUpstreamWsUrl, forwardLiveUrl, keyedLiveUrl, @@ -75,10 +75,12 @@ export async function handleExternalLive( if (offer instanceof Response) return offer; if (!options.bindings.hasCapacity()) return formatErrorResponse(503, "server_busy", "Live call capacity reached"); const frameless = new URL(req.url).pathname === "/v1/live"; - let session = offer.session ? { ...offer.session } : frameless ? { - model: LIVE_AUDIO_MODEL, instructions: "", audio: { output: { voice: "cove" } }, delegation: { type: "client" }, + // Only a session the proxy writes itself gets a voice, and only once its destination is known. + const synthesized = !offer.session && frameless; + let session: Record | undefined = offer.session ? { ...offer.session } : frameless ? { + model: LIVE_AUDIO_MODEL, instructions: "", delegation: { type: "client" }, } : undefined; - if (session?.model === "gpt-live-1") session.model = LIVE_AUDIO_MODEL; + if (typeof session?.model === "string" && session.model) session.model = resolveLiveAudioModel(session.model); const model = typeof session?.model === "string" ? session.model : LIVE_AUDIO_MODEL; const resolved = await resolveAudioUpstream(options.client.headers, config, log, { admission: options.client.admission, model, lease: options.lease, signal: deadline.signal, @@ -87,6 +89,8 @@ export async function handleExternalLive( deadline.signal.throwIfAborted(); if (resolved instanceof Response) return resolved; relay = resolved; + // openai/codex realtime_call.rs inserts cove for ChatGPT calls; an API Frameless call defaults to marin. + if (synthesized && session) session = { ...session, audio: { output: { voice: relay.keyed ? "marin" : "cove" } } }; session = isolateCodexPoolClientMetadata(session, relay.authContext?.kind === "pool" ? relay.authContext.chatgptAccountId : undefined) as typeof session; const headers = protocolHeaders(options.client, relay, frameless); @@ -160,7 +164,7 @@ export async function resolveExternalLiveSocket( const frameless = upstreamTarget.style === "frameless-path" || upstreamTarget.style === "frameless-standalone"; if (upstreamTarget.style === "frameless-standalone") { const query = new URLSearchParams(upstreamTarget.query); - if (!query.has("model") || query.get("model") === "gpt-live-1") query.set("model", LIVE_AUDIO_MODEL); + query.set("model", resolveLiveAudioModel(query.get("model"))); upstreamTarget = { ...upstreamTarget, query: query.toString() }; } // What this socket will actually run: the model a bound call settled on when diff --git a/src/server/audio-transcriptions.ts b/src/server/audio-transcriptions.ts index c06a93e6d81..165bf6c2966 100644 --- a/src/server/audio-transcriptions.ts +++ b/src/server/audio-transcriptions.ts @@ -15,13 +15,21 @@ const AUDIO_FIELD_MAX_BYTES = 16 * 1024; const AUDIO_RESPONSE_MAX_BYTES = 2 * 1024 * 1024; const AUDIO_TIMEOUT_MS = 120_000; const FIELDS = new Set(["file", "model", "prompt", "language", "response_format"]); -const MODELS = new Set([TRANSCRIPTION_MODEL, "gpt-4o-mini-transcribe", "whisper-1"]); +/** Repeated multipart arrays, as OpenAI's create-transcription reference spells them. */ +const LIST_FIELDS = new Set(["keywords[]", "languages[]"]); +const LIST_MAX_ITEMS = 100; +/** OpenAI's recommended file model; it takes keywords[] and languages[] instead of language. */ +const LIST_MODEL = "gpt-transcribe"; +const MODELS = new Set([TRANSCRIPTION_MODEL, "gpt-4o-mini-transcribe", "whisper-1", LIST_MODEL]); +const LANGUAGE_CODE = /^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})?$/; interface TranscriptionInput { file: File; model: string; prompt?: string; language?: string; + keywords: string[]; + languages: string[]; format: "json" | "text"; } @@ -57,8 +65,9 @@ async function parseTranscription(req: Request, operationSignal: AbortSignal): P } const seen = new Set(); for (const [name, value] of form) { - if (!FIELDS.has(name)) return invalid(`Unsupported transcription field: ${name.slice(0, 64)}`); - if (seen.has(name)) return invalid(`Duplicate transcription field: ${name}`); + const list = LIST_FIELDS.has(name); + if (!FIELDS.has(name) && !list) return invalid(`Unsupported transcription field: ${name.slice(0, 64)}`); + if (seen.has(name) && !list) return invalid(`Duplicate transcription field: ${name}`); seen.add(name); if (name !== "file" && (typeof value !== "string" || Buffer.byteLength(value) > AUDIO_FIELD_MAX_BYTES)) { return invalid("Audio text fields must be strings no larger than 16 KiB", 413); @@ -73,8 +82,58 @@ async function parseTranscription(req: Request, operationSignal: AbortSignal): P if (format !== "json" && format !== "text") return invalid("response_format must be json or text"); const prompt = form.get("prompt") as string | null; const language = form.get("language") as string | null; - if (language !== null && !/^[a-z]{2,3}(?:-[A-Za-z0-9]{2,8})?$/.test(language)) return invalid("Invalid transcription language"); - return { file, model, format, ...(prompt !== null ? { prompt } : {}), ...(language !== null ? { language } : {}) }; + if (language !== null && !LANGUAGE_CODE.test(language)) return invalid("Invalid transcription language"); + const keywords = form.getAll("keywords[]") as string[]; + const languages = form.getAll("languages[]") as string[]; + if (keywords.length > LIST_MAX_ITEMS || languages.length > LIST_MAX_ITEMS) { + return invalid(`keywords[] and languages[] accept at most ${LIST_MAX_ITEMS} entries each`); + } + if (model === LIST_MODEL) { + if (language !== null) return invalid(`${LIST_MODEL} takes languages[] instead of language`); + } else if (keywords.length > 0 || languages.length > 0) { + return invalid(`keywords[] and languages[] require ${LIST_MODEL}`); + } + if (keywords.some(keyword => !keyword.trim() || /[<>\r\n]/.test(keyword))) return invalid("Invalid transcription keyword"); + if (languages.some(code => !LANGUAGE_CODE.test(code))) return invalid("Invalid transcription language"); + return { + file, model, format, keywords, languages, + ...(prompt !== null ? { prompt } : {}), ...(language !== null ? { language } : {}), + }; +} + +type UploadFormat = { extension: string; type: string }; + +/** + * The container a file's leading bytes declare. openai/codex names its upload from the clip's MIME + * type (backend-client client.rs transcribe_audio), but Bun's multipart parser drops a part's + * Content-Type, so the bytes are the only type evidence that survives ingress here. + */ +function sniffAudioFormat(head: Uint8Array): UploadFormat | undefined { + const ascii = (start: number, text: string) => [...text].every((char, index) => head[start + index] === char.charCodeAt(0)); + if (ascii(0, "RIFF") && ascii(8, "WAVE")) return { extension: ".wav", type: "audio/wav" }; + if (ascii(0, "OggS")) return { extension: ".ogg", type: "audio/ogg" }; + if (ascii(0, "fLaC")) return { extension: ".flac", type: "audio/flac" }; + if (ascii(4, "ftyp")) return { extension: ".m4a", type: "audio/mp4" }; + if (head[0] === 0x1a && head[1] === 0x45 && head[2] === 0xdf && head[3] === 0xa3) return { extension: ".webm", type: "audio/webm" }; + // ID3 tag, or an MPEG audio frame sync whose layer bits are set (ADTS AAC leaves them zero). + if (ascii(0, "ID3") || (head[0] === 0xff && (head[1]! & 0xe0) === 0xe0 && ((head[1]! >> 1) & 3) !== 0)) { + return { extension: ".mp3", type: "audio/mpeg" }; + } + return undefined; +} + +/** Name and type the upstream part so it can be identified; an unknown extensionless clip keeps the old .webm name. */ +async function uploadFile(file: File): Promise { + const sniffed = sniffAudioFormat(new Uint8Array(await file.slice(0, 12).arrayBuffer())); + const extension = /\.[a-z0-9]{1,8}$/i.exec(file.name)?.[0] ?? sniffed?.extension ?? ".webm"; + return new File([file], "audio" + extension, sniffed ? { type: sniffed.type } : {}); +} + +/** Detected languages, reduced to their codes; anything else in the upstream array is dropped. */ +function detectedLanguages(payload: object): Array<{ code: string }> | undefined { + if (!("languages" in payload) || !Array.isArray(payload.languages)) return undefined; + return payload.languages.flatMap(entry => entry && typeof entry === "object" && "code" in entry + && typeof entry.code === "string" && LANGUAGE_CODE.test(entry.code) ? [{ code: entry.code }] : []); } async function transcribeAdmitted( @@ -109,9 +168,11 @@ async function transcribeAdmitted( if (!headers.has("originator")) headers.set("originator", "codex_cli_rs"); } const form = new FormData(); - form.append("file", input.file, "audio" + (/\.[a-z0-9]{1,8}$/i.exec(input.file.name)?.[0] ?? ".webm")); + form.append("file", await uploadFile(input.file)); if (input.prompt !== undefined) form.append("prompt", input.prompt); if (input.language !== undefined) form.append("language", input.language); + for (const keyword of input.keywords) form.append("keywords[]", keyword); + for (const code of input.languages) form.append("languages[]", code); if (relay.keyed) { form.append("model", input.model); form.append("response_format", "json"); @@ -137,9 +198,10 @@ async function transcribeAdmitted( if (!payload || typeof payload !== "object" || !("text" in payload) || typeof payload.text !== "string") { return formatErrorResponse(502, "upstream_error", "Audio upstream response is missing text"); } + const languages = detectedLanguages(payload); return input.format === "text" ? new Response(payload.text, { headers: { "content-type": "text/plain; charset=utf-8" } }) - : Response.json({ text: payload.text }); + : Response.json({ text: payload.text, ...(languages ? { languages } : {}) }); } catch { if (operation.signal.aborted) { outcome = operation.didExpire() ? "timeout" : undefined; diff --git a/src/server/audio-upstream.ts b/src/server/audio-upstream.ts index 9b8dd015828..0a841f4a90c 100644 --- a/src/server/audio-upstream.ts +++ b/src/server/audio-upstream.ts @@ -32,7 +32,20 @@ import { authorizationCredential } from "../lib/authorization-scheme"; import { nativeMainRefreshFailureResponse } from "./responses/codex-auth-error"; export const TRANSCRIPTION_MODEL = "gpt-4o-transcribe"; -export const LIVE_AUDIO_MODEL = "gpt-live-1-codex"; +/** Codex's GPT-Live default since openai/codex b05266d61b (core/src/realtime_conversation.rs). */ +export const LIVE_AUDIO_MODEL = "gpt-live-1.1-codex"; + +/** Public GPT-Live names a Frameless client may use for the Codex live models this relay reaches. */ +const LIVE_MODEL_ALIASES = new Map([ + ["gpt-live-1", "gpt-live-1-codex"], + ["gpt-live-1.1", "gpt-live-1.1-codex"], +]); + +/** The live model a Frameless request will run: an alias resolved, nothing named meaning the default. */ +export function resolveLiveAudioModel(model: string | null | undefined): string { + if (!model) return LIVE_AUDIO_MODEL; + return LIVE_MODEL_ALIASES.get(model) ?? model; +} /** Audio keys remain identifiable even on the otherwise unauthenticated local listener. */ export function resolveAudioAdmission( diff --git a/structure/data-planes/inbound-compat.md b/structure/data-planes/inbound-compat.md index cc58d5cbc4b..0457357fb31 100644 --- a/structure/data-planes/inbound-compat.md +++ b/structure/data-planes/inbound-compat.md @@ -35,9 +35,9 @@ ChatGPT authentication failure never falls through to the paid OpenAI provider; The bounded multipart input accepts one nonempty file up to 25,000,000 bytes within a 32 MiB body, required model, and optional prompt, language and JSON/text response format. Unknown or -duplicate fields fail. Subscription requests use the compatibility identifier gpt-4o-transcribe -and send no model upstream; the keyed API also accepts gpt-4o-mini-transcribe and whisper-1. -Responses retain only text. Manual redirects, capped response reads and linked cancellation +duplicate scalar fields fail. Subscription requests use the compatibility identifier gpt-4o-transcribe and send no model upstream; the keyed API also accepts gpt-transcribe, gpt-4o-mini-transcribe and whisper-1. +gpt-transcribe alone takes repeated keywords[] and languages[] (at most 100 each) and refuses the singular language. Responses retain text and a code-only languages array when the upstream reports one. +An extensionless upload is named and typed from its audio signature, because Bun's multipart parser drops the part Content-Type; unknown bytes keep the .webm name. Manual redirects, capped response reads and linked cancellation keep credentials and audio content out of redirects, request logs and durable storage. `tests/server/audio-transcriptions.test.ts` exercises the real ingress and synthetic upstream; `tests/server/api-key-attribution.test.ts` uses multipart fixtures for the HTTP auth matrix. @@ -75,8 +75,8 @@ maps opaque rtc_ocx_ aliases to the creating key, provider, physical account and Expired aliases never fall through to native joins. Reconnect resolves the recorded account freshly; keyed provider replacement fails unless its credential digest still matches. The registry is per server, holds at most 1024 entries for 30 minutes and is cleared on shutdown. -It does not proxy WebRTC media or execute delegation requests. Standalone Frameless defaults -to gpt-live-1-codex; gpt-live-1 is an explicit alias. Dictation and Frameless event formats remain +It does not proxy WebRTC media or execute delegation requests. Frameless defaults to Codex's gpt-live-1.1-codex (`resolveLiveAudioModel` in `src/server/audio-upstream.ts`); gpt-live-1 and gpt-live-1.1 alias the -codex models for call-create sessions and Frameless standalone sockets, and the resolved name is the one a key scope judges and the binding records; Realtime standalone queries pass unchanged. +Only a session the proxy synthesizes gets a voice, chosen after the upstream resolves: marin for a keyed API relay, cove for ChatGPT, matching openai/codex. Dictation and Frameless event formats remain separate. Coverage lives in `tests/server/audio-client.test.ts`, `tests/server/audio-dictation.test.ts` and `tests/server/live-call-bindings.test.ts`. diff --git a/tests/server/api-access-endpoints.test.ts b/tests/server/api-access-endpoints.test.ts index a9d41c79165..2b3f1ae806e 100644 --- a/tests/server/api-access-endpoints.test.ts +++ b/tests/server/api-access-endpoints.test.ts @@ -142,7 +142,7 @@ describe("buildApiAccessEndpoints", () => { dictationStreamEndpoint: "wss://[2001:db8::1]:8443/v1/audio/transcriptions/stream", liveEndpoint: "wss://[2001:db8::1]:8443/v1/live", realtimeCallsEndpoint: "https://[2001:db8::1]:8443/v1/realtime/calls", - transcriptionModel: "gpt-4o-transcribe", liveModel: "gpt-live-1-codex", + transcriptionModel: "gpt-4o-transcribe", liveModel: "gpt-live-1.1-codex", transcriptionConfigured: false, dictationConfigured: false, liveConfigured: false, }); const companion = buildApiAccessEndpoints({ hostname: "0.0.0.0", port: 10100, unauthenticatedLoopbackListener: { enabled: true, port: 10104 } }); diff --git a/tests/server/api-key-scope-audio.test.ts b/tests/server/api-key-scope-audio.test.ts index eaa7c916402..83c781960c5 100644 --- a/tests/server/api-key-scope-audio.test.ts +++ b/tests/server/api-key-scope-audio.test.ts @@ -237,6 +237,87 @@ test("rejoining a call is judged on the model that call settled on", async () => expect((await denial(resolved as Response)).model).toBe(OTHER_LIVE_MODEL); }); +test.each([ + ["model=gpt-live-1.1", "gpt-live-1.1-codex"], + ["", "gpt-live-1.1-codex"], + ["model=gpt-live-1.1-codex", "gpt-live-1.1-codex"], +] as const)("a Frameless standalone socket %p is admitted and forwarded as the model it is judged on", async (query, model) => { + const cfg = config({ allowedModels: ["gpt-live-1.1-codex"] }); + const resolved = await resolveExternalLiveSocket( + client(cfg), cfg, logContext(), { style: "frameless-standalone", query }, { lease: lease(), bindings: new LiveCallBindings() }, + ); + expect(resolved).not.toBeInstanceOf(Response); + if (resolved instanceof Response) return; + try { + expect(new URL(resolved.upstreamWsUrl).searchParams.get("model")).toBe(model); + } finally { resolved.finish(); } +}); + +test("the gpt-live-1 alias is judged as the model it forwards", async () => { + const cfg = config({ allowedModels: ["gpt-live-1.1-codex"] }); + const resolved = await resolveExternalLiveSocket( + client(cfg), cfg, logContext(), { style: "frameless-standalone", query: "model=gpt-live-1" }, { lease: lease(), bindings: new LiveCallBindings() }, + ); + expect(resolved).toBeInstanceOf(Response); + expect((resolved as Response).status).toBe(403); + expect((await denial(resolved as Response)).model).toBe("gpt-live-1-codex"); +}); + +test("a call-create alias is judged as the model it forwards", async () => { + const cfg = config({ allowedModels: ["gpt-live-1.1-codex"] }); + const create = (model: string) => handleExternalLive( + new Request("http://localhost/v1/live", { + method: "POST", + headers: { "content-type": "application/json", "x-opencodex-api-key": SCOPED_KEY }, + body: JSON.stringify({ sdp: "v=0", session: { model } }), + }), + cfg, logContext(), { client: client(cfg), lease: lease(), bindings: new LiveCallBindings() }, + ); + const refused = await create("gpt-live-1"); + expect(refused.status).toBe(403); + expect((await denial(refused)).model).toBe("gpt-live-1-codex"); + expect(upstreamCalls).toEqual([]); + // The admitted alias reaches the keyed upstream; the fixture's JSON answer is not an SDP call. + const admitted = await create("gpt-live-1.1"); + expect(admitted.status).not.toBe(403); + expect(upstreamCalls).toEqual(["https://api.openai.com/v1/live"]); +}); + + +test("a scoped call-create forwards, binds and rejoins on the model it was judged on", async () => { + const cfg = config({ allowedModels: ["gpt-live-1.1-codex"] }); + const sessions: unknown[] = []; + globalThis.fetch = (async (input: unknown, init?: RequestInit) => { + upstreamCalls.push(String(input)); + const form = init?.body as FormData; + sessions.push(JSON.parse(String(form.get("session")))); + return new Response("v=0\r\n", { status: 201, headers: { "content-type": "application/sdp", location: "https://api.openai.com/v1/live/rtc_scope_fixture" } }); + }) as unknown as typeof fetch; + const audio = client(cfg); + const bindings = new LiveCallBindings(); + const created = await handleExternalLive( + new Request("http://localhost/v1/live", { + method: "POST", + headers: { "content-type": "application/json", "x-opencodex-api-key": SCOPED_KEY }, + body: JSON.stringify({ sdp: "v=0", session: { model: "gpt-live-1.1", instructions: "client" } }), + }), + cfg, logContext(), { client: audio, lease: lease(), bindings }, + ); + expect(created.status).toBe(201); + await created.text(); + expect(sessions).toEqual([{ model: "gpt-live-1.1-codex", instructions: "client" }]); + const alias = created.headers.get("location")!.split("/").at(-1)!; + expect(bindings.get(alias, audio.owner)?.model).toBe("gpt-live-1.1-codex"); + const joined = await resolveExternalLiveSocket( + audio, cfg, logContext(), { style: "frameless-path", callId: alias }, { lease: lease(), bindings }, + ); + expect(joined).not.toBeInstanceOf(Response); + if (joined instanceof Response) return; + try { + expect(joined.upstreamWsUrl).toBe("wss://api.openai.com/v1/live/rtc_scope_fixture"); + } finally { joined.finish(); } +}); + test("a key with no scope keeps every audio destination", async () => { const cfg = config({ allowedProviders: ["some-other-provider"] }); const response = await handleAudioTranscriptions( diff --git a/tests/server/audio-dictation.test.ts b/tests/server/audio-dictation.test.ts index 602e1e20357..861c4e071e8 100644 --- a/tests/server/audio-dictation.test.ts +++ b/tests/server/audio-dictation.test.ts @@ -47,6 +47,7 @@ const scribeStart = { function createFixture(options: { failDictation?: boolean; finalOnClose?: boolean; answer?: "invalid" | "ok200" } = {}) { const creates: Headers[] = []; + const createRequests: Request[] = []; const handshakes: Array<{ url: string; headers: Headers; protocols?: string[] }> = []; const frames: string[] = []; const upstreamClosed = Promise.withResolvers(); @@ -85,6 +86,7 @@ function createFixture(options: { failDictation?: boolean; finalOnClose?: boolea if (["chatgpt.com", "api.openai.com"].includes(new URL(req.url).hostname)) { if (new URL(req.url).pathname.endsWith("/realtime/calls") || new URL(req.url).pathname === "/v1/live") { creates.push(new Headers(req.headers)); + createRequests.push(req.clone()); if (options.answer === "invalid") return new Response("", { status: 200 }); if (options.answer === "ok200") return new Response("v=0\r\n", { status: 200, headers: { "content-type": "application/sdp", location: `https://api.openai.com/v1/live/rtc_upstream_${creates.length}` } }); return new Response("v=0\r\n", { status: 201, headers: { "content-type": "application/sdp", location: `https://api.openai.com/v1/live/rtc_upstream_${creates.length}` } }); @@ -102,7 +104,7 @@ function createFixture(options: { failDictation?: boolean; finalOnClose?: boolea return socket; }, }); - return { server, upstream, creates, handshakes, frames, upstreamClosed: upstreamClosed.promise }; + return { server, upstream, creates, createRequests, handshakes, frames, upstreamClosed: upstreamClosed.promise }; } beforeEach(() => { @@ -375,9 +377,48 @@ describe("external audio sockets", () => { fixture = createFixture(); const ws = socket("/v1/live"); expect(await receive(ws, "fixture-echo", "fixture-echo")).toBe("fixture-echo"); - expect(fixture.handshakes[0]!.url).toBe("wss://api.openai.com/v1/live?model=gpt-live-1-codex"); + expect(fixture.handshakes[0]!.url).toBe("wss://api.openai.com/v1/live?model=gpt-live-1.1-codex"); expect(fixture.handshakes[0]!.headers.get("openai-alpha")).toBe("quicksilver=v2"); }); + test("Frameless aliases name Codex live models while Realtime queries pass unchanged", async () => { + fixture = createFixture(); + for (const path of ["/v1/live?model=gpt-live-1", "/v1/live?model=gpt-live-1.1", "/v1/realtime?model=gpt-live-1.1"]) { + await receive(socket(path), "alias-echo", "alias-echo"); + } + expect(fixture.handshakes.map(handshake => handshake.url)).toEqual([ + "wss://api.openai.com/v1/live?model=gpt-live-1-codex", + "wss://api.openai.com/v1/live?model=gpt-live-1.1-codex", + "wss://api.openai.com/v1/realtime?model=gpt-live-1.1", + ]); + }); + test("a session the proxy synthesizes uses the ChatGPT voice default", async () => { + fixture = createFixture(); + await createCall(); + const body = await fixture.createRequests[0]!.json() as { session: Record }; + expect(body.session).toEqual({ model: "gpt-live-1.1-codex", instructions: "", audio: { output: { voice: "cove" } }, delegation: { type: "client" } }); + }); + test("a session the proxy synthesizes for an API key uses the API voice default", async () => { + saveConfig({ port: 0, hostname: "127.0.0.1", defaultProvider: "openai-apikey", openaiProviderTierVersion: 2, + providers: { "openai-apikey": { adapter: "openai-responses", baseUrl: "https://api.openai.com/v1", apiKey: "sk-fixture-keyed", authMode: "key" } }, + apiKeys: [{ id: "one", name: "one", key: KEY, createdAt: "2026-09-12T00:00:00Z" }], + }); + fixture = createFixture(); + await createCall(); + expect(fixture.createRequests[0]!.url).toBe("https://api.openai.com/v1/live"); + const form = await fixture.createRequests[0]!.formData(); + expect(JSON.parse(String(form.get("session")))).toEqual({ model: "gpt-live-1.1-codex", instructions: "", audio: { output: { voice: "marin" } }, delegation: { type: "client" } }); + }); + test("a client session keeps its own fields while its Frameless alias is resolved", async () => { + fixture = createFixture(); + const response = await fetchOriginal(new URL("/v1/live", fixture.server.url), { + method: "POST", headers: { authorization: `Bearer ${KEY}`, "content-type": "application/json" }, + body: JSON.stringify({ sdp: "v=0\r\n", session: { model: "gpt-live-1.1", instructions: "client" } }), + }); + expect(response.status).toBe(201); + await response.text(); + const body = await fixture.createRequests[0]!.json() as { session: Record }; + expect(body.session).toEqual({ model: "gpt-live-1.1-codex", instructions: "client" }); + }); test("connectivity-only completion does not claim inference recovery", async () => { fixture = createFixture(); const outcomes = spyOn(routing, "recordCodexUpstreamOutcome"); diff --git a/tests/server/audio-transcriptions.test.ts b/tests/server/audio-transcriptions.test.ts index 1144dddaaa5..213f770eeac 100644 --- a/tests/server/audio-transcriptions.test.ts +++ b/tests/server/audio-transcriptions.test.ts @@ -466,3 +466,89 @@ describe("standalone transcription API", () => { } finally { fault.mockRestore(); release.mockRestore(); } }); }); + +describe("gpt-transcribe fields and upload naming", () => { + function transcribeForm(model: string, extra: Array<[string, string]> = []): FormData { + const data = new FormData(); + data.append("file", new File([new Uint8Array([82, 73, 70, 70, 0, 0])], "sample.wav", { type: "audio/wav" })); + data.append("model", model); + for (const [name, value] of extra) data.append(name, value); + return data; + } + + test("keyed relay forwards gpt-transcribe with repeated keywords and languages and returns detected languages", async () => { + respond = () => Response.json({ text: "bonjour", languages: [{ code: "fr", extra: 1 }, { code: 7 }, "en"], usage: { seconds: 1 } }); + const response = await request(transcribeForm("gpt-transcribe", [ + ["keywords[]", "AC-42"], ["keywords[]", "premium plan"], ["languages[]", "fr"], ["languages[]", "en"], ["prompt", "support call"], + ])); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ text: "bonjour", languages: [{ code: "fr" }] }); + const data = await captured[0]!.formData(); + expect(data.get("model")).toBe("gpt-transcribe"); + expect(data.getAll("keywords[]")).toEqual(["AC-42", "premium plan"]); + expect(data.getAll("languages[]")).toEqual(["fr", "en"]); + expect(data.get("language")).toBeNull(); + expect(data.get("prompt")).toBe("support call"); + }); + + test("a response without a languages array keeps the text-only result", async () => { + respond = () => Response.json({ text: "plain", languages: "fr" }); + const response = await request(transcribeForm("gpt-transcribe")); + expect(await response.json()).toEqual({ text: "plain" }); + respond = () => Response.json({ text: "plain", languages: [] }); + expect(await (await request(transcribeForm("gpt-transcribe"))).json()).toEqual({ text: "plain", languages: [] }); + const text = await request(transcribeForm("gpt-transcribe", [["response_format", "text"]])); + expect(await text.text()).toBe("plain"); + }); + + test("list fields are refused where the model or destination cannot take them", async () => { + const cases: FormData[] = [ + transcribeForm("gpt-transcribe", [["language", "fr"]]), + transcribeForm("gpt-transcribe", [["language", "fr"], ["languages[]", "fr"]]), + transcribeForm("gpt-4o-transcribe", [["keywords[]", "AC-42"]]), + transcribeForm("gpt-4o-transcribe", [["languages[]", "fr"]]), + transcribeForm("gpt-transcribe", [["keywords[]", "bad ["keywords[]", "k" + i] as [string, string])), + transcribeForm("gpt-transcribe", [["keywords", "AC-42"]]), + ]; + for (const body of cases) expect((await request(body)).status).toBe(400); + expect(captured).toHaveLength(0); + }); + + test("ChatGPT subscription refuses gpt-transcribe and its list fields", async () => { + savePoolConfig(); + for (const body of [transcribeForm("gpt-transcribe"), transcribeForm("gpt-4o-transcribe", [["languages[]", "fr"]])]) { + expect((await request(body)).status).toBe(400); + } + expect(captured).toHaveLength(0); + }); + + test("subscription uploads without an extension are named and typed from their content", async () => { + savePoolConfig(); + const bytes = (...parts: Array) => new Uint8Array(parts.flatMap(part => typeof part === "string" ? [...part].map(char => char.charCodeAt(0)) : part)); + const cases: Array<[string, Uint8Array, string, string | null]> = [ + ["blob", bytes("RIFF", [0, 0, 0, 0], "WAVE"), "audio.wav", "audio/wav"], + ["clip", bytes("ID3", [3, 0, 0]), "audio.mp3", "audio/mpeg"], + ["clip", bytes([0xff, 0xfb, 0x90, 0x00]), "audio.mp3", "audio/mpeg"], + ["clip", bytes([0, 0, 0, 0x20], "ftypM4A "), "audio.m4a", "audio/mp4"], + ["clip", bytes("OggS", [0, 2]), "audio.ogg", "audio/ogg"], + ["clip", bytes([0x1a, 0x45, 0xdf, 0xa3, 1]), "audio.webm", "audio/webm"], + ["clip", bytes("fLaC", [0]), "audio.flac", "audio/flac"], + ["clip", bytes([0xff, 0xf1, 0x50, 0x80]), "audio.webm", null], + ["voice.flac", bytes("RIFF", [0, 0, 0, 0], "WAVE"), "audio.flac", "audio/wav"], + ]; + for (const [name, content, expected, type] of cases) { + captured = []; + const data = new FormData(); + data.append("file", new File([content], name)); + data.append("model", "gpt-4o-transcribe"); + expect((await request(data)).status).toBe(200); + const raw = await captured[0]!.text(); + expect(raw).toContain(`filename="${expected}"`); + if (type) expect(raw).toContain(`Content-Type: ${type}`); + } + }); +}); + From 2d016f6871c9df73a9278db9e1f11eda994cf02b Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 26 Nov 2026 02:40:59 +0900 Subject: [PATCH 54/60] fix(audio): align live scope checks between the native and external paths (#9141) * fix(audio): judge unnamed external live requests like the native path The native voice path refuses a model-scoped key when a request names no model. The external path judged the same requests against the default live model. Both now treat a call-create session without a model, /v1/realtime/calls without a session and a Realtime standalone socket without a model query as unnamed destinations. * fix(audio): treat a blank live session model as unnamed; cover unnamed binds and rejoins --- .../261126_live_scope_alignment/000_plan.md | 21 +++ .../docs/es/reference/proxy-formats.md | 2 +- .../content/docs/reference/proxy-formats.md | 3 +- src/server/audio-live.ts | 10 +- src/server/audio-upstream.ts | 13 +- structure/data-planes/inbound-compat.md | 8 +- tests/server/api-key-scope-audio.test.ts | 133 +++++++++++++++++- 7 files changed, 173 insertions(+), 17 deletions(-) create mode 100644 devlog/_plan/261126_live_scope_alignment/000_plan.md diff --git a/devlog/_plan/261126_live_scope_alignment/000_plan.md b/devlog/_plan/261126_live_scope_alignment/000_plan.md new file mode 100644 index 00000000000..1a238cf204e --- /dev/null +++ b/devlog/_plan/261126_live_scope_alignment/000_plan.md @@ -0,0 +1,21 @@ +# Align live scope checks between the native and external paths + +## Why + +The native voice path (src/server/live.ts) judges a request that names no model as an unnamed destination: a key with a model list is refused, and a provider-only scope or an unscoped key is unchanged. The external path (src/server/audio-live.ts) judged the same requests against the default live model instead. The two paths disagreed for three request shapes: a call-create session without `model`, `/v1/realtime/calls` without a session, and a Realtime standalone socket without a `model=` query. + +## Change + +| File | Change | +| --- | --- | +| src/server/audio-upstream.ts | `AudioUpstreamOptions.model` may be undefined; scope is judged on it unchanged (`admissionScopeDenial` already handles unnamed destinations); account selection keeps the default model id; the request log keeps its route label when nothing is named | +| src/server/audio-live.ts | call-create judges only a named model; a socket judges its binding's model or its own query model, never an assumed default | +| tests/server/api-key-scope-audio.test.ts | refusal for each unnamed shape with a model-scoped key; an unscoped key still reaches an unnamed Realtime socket | +| structure/data-planes/inbound-compat.md, docs-site reference/proxy-formats.md (+ es) | one rule for both paths | + +Named requests are unchanged: an explicit model, a Frameless alias, the Frameless standalone default and a session the proxy writes itself still name their model. + +## Checks + +Red first: the four new refusal cases fail on the previous source and pass here. Focused audio/live scope, binding and dictation suites, typecheck, structure:check, privacy:scan and the docs/test-layout/file-size guards pass. NOT RUN: live voice sessions. + diff --git a/docs-site/src/content/docs/es/reference/proxy-formats.md b/docs-site/src/content/docs/es/reference/proxy-formats.md index 6dd151b5e63..b3f40cc83fe 100644 --- a/docs-site/src/content/docs/es/reference/proxy-formats.md +++ b/docs-site/src/content/docs/es/reference/proxy-formats.md @@ -490,7 +490,7 @@ Los clientes de Gemini, como el SDK google-genai con una URL base personalizada, ### Claves API externas -Los clientes externos usan una clave OpenCodex en cualquier encabezado de credencial de audio compatible, o el par de subprotocolos del navegador descrito anteriormente. Independiente `WS /v1/live?model=gpt-live-1.1-codex` utiliza el protocolo Frameless. Un modelo omitido usa por defecto ese identificador, el modelo GPT-Live actual de Codex; `gpt-live-1` y `gpt-live-1.1` son alias proxy de `gpt-live-1-codex` y `gpt-live-1.1-codex`, y los mismos alias se aplican a una sesión de creación de llamada. Una clave limitada a un modelo en vivo se evalúa con el nombre resuelto. Cuando `POST /v1/live` no lleva sesión, OpenCodex escribe una con ese modelo predeterminado y la voz predeterminada del destino: `cove` para una cuenta ChatGPT y `marin` para una clave OpenAI API. Una sesión que usted envía conserva sus propios campos; solo se resuelve un alias de modelo en ella. Esta no es una afirmación de que cada clave pública OpenAI Realtime SDK o API sea compatible con GPT-Live. +Los clientes externos usan una clave OpenCodex en cualquier encabezado de credencial de audio compatible, o el par de subprotocolos del navegador descrito anteriormente. Independiente `WS /v1/live?model=gpt-live-1.1-codex` utiliza el protocolo Frameless. Un modelo omitido usa por defecto ese identificador, el modelo GPT-Live actual de Codex; `gpt-live-1` y `gpt-live-1.1` son alias proxy de `gpt-live-1-codex` y `gpt-live-1.1-codex`, y los mismos alias se aplican a una sesión de creación de llamada. Una clave limitada a un modelo en vivo se evalúa con el nombre resuelto y debe nombrar su modelo: una sesión sin modelo, `/v1/realtime/calls` sin sesión y un socket Realtime sin `model=` se rechazan para ella. Cuando `POST /v1/live` no lleva sesión, OpenCodex escribe una con ese modelo predeterminado y la voz predeterminada del destino: `cove` para una cuenta ChatGPT y `marin` para una clave OpenAI API. Una sesión que usted envía conserva sus propios campos; solo se resuelve un alias de modelo en ella. Esta no es una afirmación de que cada clave pública OpenAI Realtime SDK o API sea compatible con GPT-Live. Para una nueva conexión independiente, envíe la inicialización compatible con la fuente a continuación después de que se abra el socket y espere a `session.started` con un `session.id` no vacío. Un evento de sesión actualizada con la misma forma también es aceptado por el cliente nativo. diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index a51ffae897f..60ec89ce1b8 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -918,7 +918,8 @@ or the browser subprotocol pair described above. Standalone defaults to that identifier, Codex's current GPT-Live model; `gpt-live-1` and `gpt-live-1.1` are proxy aliases for `gpt-live-1-codex` and `gpt-live-1.1-codex`, and the same aliases apply to a call-create session. A key scoped to a live model is judged -on the resolved name. When `POST /v1/live` carries no session, OpenCodex writes one +on the resolved name, and such a key must name its model: a session without one, +`/v1/realtime/calls` without a session and a Realtime socket without `model=` are refused for it. When `POST /v1/live` carries no session, OpenCodex writes one with that default model and the destination's default voice: `cove` for a ChatGPT account and `marin` for an OpenAI API key. A session you send keeps its own fields; only a model alias in it is resolved. This is not a claim that every public OpenAI Realtime SDK or API key supports GPT-Live. diff --git a/src/server/audio-live.ts b/src/server/audio-live.ts index 13b56cbb543..bb3a7fb2e08 100644 --- a/src/server/audio-live.ts +++ b/src/server/audio-live.ts @@ -81,7 +81,9 @@ export async function handleExternalLive( model: LIVE_AUDIO_MODEL, instructions: "", delegation: { type: "client" }, } : undefined; if (typeof session?.model === "string" && session.model) session.model = resolveLiveAudioModel(session.model); - const model = typeof session?.model === "string" ? session.model : LIVE_AUDIO_MODEL; + // Only a named model is judged as one, blank counting as none (as in live.ts liveCallCreateModel); + // a session the proxy writes always names the default. + const model = typeof session?.model === "string" && session.model.trim() ? session.model : undefined; const resolved = await resolveAudioUpstream(options.client.headers, config, log, { admission: options.client.admission, model, lease: options.lease, signal: deadline.signal, }); @@ -169,9 +171,9 @@ export async function resolveExternalLiveSocket( } // What this socket will actually run: the model a bound call settled on when // this same key created it, or the one a standalone session forwards in its - // own query. Reading only the Frameless query left a Realtime standalone - // socket judged as the default while its query carried another model. - const model = binding?.model ?? liveSidebandModel(upstreamTarget) ?? LIVE_AUDIO_MODEL; + // own query. When neither names one, the destination is unnamed and judged as + // such, never as the default. + const model = binding ? binding.model : liveSidebandModel(upstreamTarget); const relay = await resolveAudioUpstream(client.headers, config, log, { admission: client.admission, model, lease: options.lease, signal: options.signal, diff --git a/src/server/audio-upstream.ts b/src/server/audio-upstream.ts index 0a841f4a90c..4b43cc212c6 100644 --- a/src/server/audio-upstream.ts +++ b/src/server/audio-upstream.ts @@ -76,7 +76,11 @@ export interface AudioUpstream { export interface AudioUpstreamOptions { admission: DataPlaneAdmission; - model: string; + /** + * The model the upstream will run, or undefined when the request names none. A key with a + * model list is then refused, as on the native voice path (`src/server/live.ts`). + */ + model: string | undefined; lease?: AdmissionLease; exactAccountId?: string; providerName?: string; @@ -132,7 +136,8 @@ export async function resolveAudioUpstream( admission: options.admission, beginCodexAccountSelection, signal: options.signal, - ...(options.exactAccountId ? { exactAccount: { accountId: options.exactAccountId, modelId: options.model } } : {}), + // Account selection needs some model id; an unnamed live call keeps the default it always used. + ...(options.exactAccountId ? { exactAccount: { accountId: options.exactAccountId, modelId: options.model ?? LIVE_AUDIO_MODEL } } : {}), }); if (!resolved) return formatErrorResponse(401, "authentication_error", "Connect a ChatGPT account to use audio"); context = resolved.authContext; @@ -158,7 +163,7 @@ export async function resolveAudioUpstream( return forwardDenial; } log.provider = formatCodexProviderForLog(candidate.providerName, context.accountId, config); - log.model = options.model; + if (options.model !== undefined) log.model = options.model; return { providerName: candidate.providerName, providerBaseUrl: candidate.provider.baseUrl, @@ -180,7 +185,7 @@ export async function resolveAudioUpstream( }); if (keyedDenial) return keyedDenial; log.provider = providerName; - log.model = options.model; + if (options.model !== undefined) log.model = options.model; return { providerName, providerBaseUrl: provider.baseUrl, headers: Object.fromEntries(selected), keyed: true, release: () => {}, diff --git a/structure/data-planes/inbound-compat.md b/structure/data-planes/inbound-compat.md index 0457357fb31..fee5a9164f8 100644 --- a/structure/data-planes/inbound-compat.md +++ b/structure/data-planes/inbound-compat.md @@ -49,11 +49,9 @@ socket names in its own query, or the model a bound call settled on when the sam and a refused forward request releases its probe lease. `LiveCallBinding` records that model for exactly this reason, so a reconnect is judged on the call it rejoins rather than on a default. -The native voice path in `src/server/live.ts` applies the same predicate but can name less. It -records only which call ids it created (`src/server/live-native-calls.ts`), never their model or -account, so a join, and a call-create that sends no session -model, name no destination at all; a key carrying a model list is refused there rather than -admitted against an assumed default, while a provider-only scope and an unscoped key are +Both live paths treat a request that names no model the same way. The native path in `src/server/live.ts` records only which call ids it created (`src/server/live-native-calls.ts`), never their model or account, so a join, and a call-create that sends no session +model, name no destination at all. On the external path a call-create session without a model, `/v1/realtime/calls` without a session and a Realtime standalone socket without a query model are unnamed too, and a binding stores no model for them. +A key carrying a model list is refused for every unnamed destination rather than admitted against an assumed default, while a provider-only scope and an unscoped key are unchanged, on both join credentials described under streaming audio. Coverage lives in `tests/server/api-key-scope-audio.test.ts`, `tests/server/api-key-scope-live.test.ts` and `tests/server/server-live-existing-call.test.ts`. diff --git a/tests/server/api-key-scope-audio.test.ts b/tests/server/api-key-scope-audio.test.ts index 83c781960c5..74760be48e2 100644 --- a/tests/server/api-key-scope-audio.test.ts +++ b/tests/server/api-key-scope-audio.test.ts @@ -6,7 +6,7 @@ * `resolveAudioUpstream`, and the model it is given is the model the upstream * will run, so the refusal is asserted once per endpoint that reaches it. */ -import { afterEach, beforeEach, expect, test } from "bun:test"; +import { afterEach, beforeEach, expect, spyOn, test } from "bun:test"; import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -15,7 +15,8 @@ import { resolveAudioClient, type AudioClient } from "../../src/server/audio-cli import { resolveDictationSocket } from "../../src/server/audio-dictation"; import { handleExternalLive, resolveExternalLiveSocket } from "../../src/server/audio-live"; import { handleAudioTranscriptions } from "../../src/server/audio-transcriptions"; -import { LIVE_AUDIO_MODEL, TRANSCRIPTION_MODEL } from "../../src/server/audio-upstream"; +import { LIVE_AUDIO_MODEL, resolveAudioUpstream, TRANSCRIPTION_MODEL } from "../../src/server/audio-upstream"; +import * as openAiSidecar from "../../src/providers/openai-sidecar"; import { LiveCallBindings } from "../../src/server/live-call-bindings"; import { tryAdmitTurn } from "../../src/server/lifecycle"; import type { RequestLogContext } from "../../src/server/request-log"; @@ -318,6 +319,134 @@ test("a scoped call-create forwards, binds and rejoins on the model it was judge } finally { joined.finish(); } }); + +test.each([ + ["a Realtime standalone socket", "intent=transcription"], + ["a Realtime standalone socket with an empty model", "intent=quicksilver&model="], +] as const)("%s that names no model is refused for a model-scoped key, as on the native path", async (_label, query) => { + const cfg = config({ allowedModels: [LIVE_AUDIO_MODEL] }); + const resolved = await resolveExternalLiveSocket( + client(cfg), cfg, logContext(), { style: "realtime-standalone", query }, { lease: lease(), bindings: new LiveCallBindings() }, + ); + expect(resolved).toBeInstanceOf(Response); + expect((resolved as Response).status).toBe(403); + expect((await denial(resolved as Response)).type).toBe(MODEL_NOT_ALLOWED_FOR_KEY); +}); + +test.each([ + ["/v1/realtime/calls with no session", "http://localhost/v1/realtime/calls", { sdp: "v=0" }], + ["/v1/live with a session that names no model", "http://localhost/v1/live", { sdp: "v=0", session: { instructions: "client" } }], +] as const)("call-create %s is refused for a model-scoped key, as on the native path", async (_label, url, payload) => { + const cfg = config({ allowedModels: [LIVE_AUDIO_MODEL] }); + const response = await handleExternalLive( + new Request(url, { + method: "POST", + headers: { "content-type": "application/json", "x-opencodex-api-key": SCOPED_KEY }, + body: JSON.stringify(payload), + }), + cfg, logContext(), { client: client(cfg), lease: lease(), bindings: new LiveCallBindings() }, + ); + expect(response.status).toBe(403); + expect((await denial(response)).type).toBe(MODEL_NOT_ALLOWED_FOR_KEY); + expect(upstreamCalls).toEqual([]); +}); + +test("an unnamed live destination stays open to a key without a model list", async () => { + const cfg = config({ allowedModels: [LIVE_AUDIO_MODEL] }); + const resolved = await resolveExternalLiveSocket( + client(cfg, OPEN_KEY), cfg, logContext(), { style: "realtime-standalone", query: "intent=transcription" }, + { lease: lease(), bindings: new LiveCallBindings() }, + ); + expect(resolved).not.toBeInstanceOf(Response); + if (resolved instanceof Response) return; + try { + expect(resolved.upstreamWsUrl).toBe("wss://api.openai.com/v1/realtime?intent=transcription"); + } finally { resolved.finish(); } +}); + + +test.each(["", " "])("call-create with a blank session model %p is an unnamed destination", async model => { + const cfg = config({ allowedModels: [LIVE_AUDIO_MODEL] }); + const response = await handleExternalLive( + new Request("http://localhost/v1/live", { + method: "POST", + headers: { "content-type": "application/json", "x-opencodex-api-key": SCOPED_KEY }, + body: JSON.stringify({ sdp: "v=0", session: { model } }), + }), + cfg, logContext(), { client: client(cfg), lease: lease(), bindings: new LiveCallBindings() }, + ); + expect(response.status).toBe(403); + expect((await denial(response)).type).toBe(MODEL_NOT_ALLOWED_FOR_KEY); + expect(upstreamCalls).toEqual([]); + // A key the blank model does not stop records the call as unnamed, never as a model called "". + globalThis.fetch = (async (input: unknown) => { + upstreamCalls.push(String(input)); + return new Response("v=0\r\n", { status: 201, headers: { "content-type": "application/sdp", location: "https://api.openai.com/v1/live/rtc_blank_fixture" } }); + }) as unknown as typeof fetch; + const providerOnly = config({ allowedProviders: ["openai-apikey"] }); + const audio = client(providerOnly); + const bindings = new LiveCallBindings(); + const created = await handleExternalLive( + new Request("http://localhost/v1/live", { + method: "POST", + headers: { "content-type": "application/json", "x-opencodex-api-key": SCOPED_KEY }, + body: JSON.stringify({ sdp: "v=0", session: { model } }), + }), + providerOnly, logContext(), { client: audio, lease: lease(), bindings }, + ); + expect(created.status).toBe(201); + await created.text(); + expect(bindings.get(created.headers.get("location")!.split("/").at(-1)!, audio.owner)?.model).toBeUndefined(); +}); + +test("an unnamed call binds no model, and its rejoin is judged as unnamed", async () => { + globalThis.fetch = (async (input: unknown) => { + upstreamCalls.push(String(input)); + return new Response("v=0\r\n", { status: 201, headers: { "content-type": "application/sdp", location: "https://api.openai.com/v1/live/rtc_unnamed_fixture" } }); + }) as unknown as typeof fetch; + const providerOnly = config({ allowedProviders: ["openai-apikey"] }); + const audio = client(providerOnly); + const bindings = new LiveCallBindings(); + const created = await handleExternalLive( + new Request("http://localhost/v1/live", { + method: "POST", + headers: { "content-type": "application/json", "x-opencodex-api-key": SCOPED_KEY }, + body: JSON.stringify({ sdp: "v=0", session: { instructions: "client" } }), + }), + providerOnly, logContext(), { client: audio, lease: lease(), bindings }, + ); + expect(created.status).toBe(201); + await created.text(); + const alias = created.headers.get("location")!.split("/").at(-1)!; + expect(bindings.get(alias, audio.owner)?.model).toBeUndefined(); + const target = { style: "frameless-path", callId: alias } as const; + const joined = await resolveExternalLiveSocket(audio, providerOnly, logContext(), target, { lease: lease(), bindings }); + expect(joined).not.toBeInstanceOf(Response); + if (!(joined instanceof Response)) joined.finish(); + const modelScoped = config({ allowedModels: [LIVE_AUDIO_MODEL] }); + const refused = await resolveExternalLiveSocket(client(modelScoped), modelScoped, logContext(), target, { lease: lease(), bindings }); + expect(refused).toBeInstanceOf(Response); + expect((refused as Response).status).toBe(403); +}); + +test("an unnamed bound join still selects its account with the default live model id", async () => { + const cfg = { + ...config({}), + defaultProvider: "openai", + providers: { openai: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward", codexAccountMode: "pool" } }, + codexAccounts: [{ id: "pool-a", email: "a@example.test", isMain: false, chatgptAccountId: "acct-a" }], + } as OcxConfig; + const select = spyOn(openAiSidecar, "resolveFirstUsableOpenAiSidecar").mockResolvedValue(null); + try { + const result = await resolveAudioUpstream(new Headers(), cfg, logContext(), { + admission: client(cfg, OPEN_KEY).admission, model: undefined, exactAccountId: "pool-a", + }); + expect(result).toBeInstanceOf(Response); + expect(select).toHaveBeenCalledTimes(1); + expect(select.mock.calls[0]![3]?.exactAccount).toEqual({ accountId: "pool-a", modelId: LIVE_AUDIO_MODEL }); + } finally { select.mockRestore(); } +}); + test("a key with no scope keeps every audio destination", async () => { const cfg = config({ allowedProviders: ["some-other-provider"] }); const response = await handleAudioTranscriptions( From 5be4bb4530353353d1d216042c993a3acbd357c1 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 26 Nov 2026 02:44:12 +0900 Subject: [PATCH 55/60] fix(responses): Codex 5505daf388 passthrough parity (stream exclusions, advertised WS limit) (#9140) * fix(responses): forward Codex stream-exclusion headers to the canonical backend Codex sends x-codex-exclude (tools, usage.attribution) and x-codex-exclude-stream-fields (delta.sequence_number, reasoning.added.encrypted_content) on every Responses request and WebSocket handshake (openai/codex 8ecb4c9d0f, ae6c0c8ac1, a4ee1058d9, 98f8a3311b). OpenCodex dropped both because they were missing from FORWARD_HEADERS. As a result, the ChatGPT backend echoed the full tool catalog in every lifecycle snapshot. Both headers are now forwarded to the canonical destination only. * fix(responses): honor the upstream advertised WebSocket message limit before sending Codex reads x-codex-websocket-max-message-bytes from the Responses WebSocket handshake and sends a request strictly larger than it over HTTP, before uploading anything (openai/codex ed7ca22bb6; codex-rs/codex-api/src/endpoint/ responses_websocket.rs:371-375 and :908-912 @5505daf388). OpenCodex's upstream dial used only its static 16 MiB ceiling. The session now records the advertised ceiling. A larger create frame, incremental recovery frame or native steering frame never leaves: the opening frame falls back to SSE once, and under native control it is refused rather than degraded. Zero is a valid advertisement; malformed or repeated values are ignored. * fix(responses): typed refusal for oversized native frames and usize-compatible limit parse Review follow-up: an oversized steering or injection frame is now a NativeSteeringError, so the channel rolls it back and accepts a corrected frame instead of treating it as an unknown delivery. The advertised limit now uses Rust usize syntax: an optional plus sign and leading zeros are accepted, and a value beyond safe integers limits nothing. The docs now describe the delta-recovery, native-control and static-ceiling paths accurately. * test(responses): drive the real injection channel through an advertised limit Review follow-up: an injection channel attached through the exchange rolls an oversized result back and accepts the corrected result on the same socket. The corrected frame's receipt is awaited through a deterministic server-side signal. * fix(responses): refuse an oversized queued injection before queuing it Review follow-up (CodeRabbit): an injection submitted while another awaits acknowledgement is prepared later in a microtask. A size refusal raised there failed the whole channel. At attach, the exchange now hands the socket's advertised limit to the control. NativeInjectionChannel checks it in assertOutboundFrame, so the oversized result is refused synchronously in inject() and the channel stays open. * fix(responses): set the native transport limit only after a successful attach Review follow-up: a refused second attach to a live channel no longer changes that channel's advertised message limit. --- .../docs/es/guides/codex-integration.md | 2 + .../content/docs/guides/codex-integration.md | 13 + src/codex/forward-transport-headers.ts | 8 + src/server/responses/codex-ws-exchange.ts | 27 +- src/server/responses/codex-ws-metadata.ts | 34 ++ src/server/responses/codex-ws-session.ts | 14 +- src/server/responses/codex-ws-wire.ts | 9 + src/server/responses/native-injection.ts | 6 + .../responses/native-response-control.ts | 6 + .../providers/codex-installation-identity.md | 6 + structure/transports/responses-wire-shapes.md | 2 +- .../codex-metadata-integrity.test.ts | 57 +++ tests/responses/codex-ws-handshake.test.ts | 382 +++++++++++++++++- 13 files changed, 558 insertions(+), 8 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/codex-integration.md b/docs-site/src/content/docs/es/guides/codex-integration.md index eec1821211c..5b6ac3370de 100644 --- a/docs-site/src/content/docs/es/guides/codex-integration.md +++ b/docs-site/src/content/docs/es/guides/codex-integration.md @@ -74,6 +74,8 @@ Las solicitudes enrutadas a través de opencodex por el inicio de sesión canón Solo algunos giros toman el transporte websocket ChatGPT, el mismo carril `responses_websockets` Codex CLI predeterminado. Un turno es elegible cuando el entorno de ejecución Bun soporta el relé limitado, la solicitud es un `POST` a la URL canónica Responses o una ruta WebSocket configurada, y su cuerpo JSON establece `stream` a `true` en la raíz. Todo lo demás permanece en SSE sobre HTTP, y un giro elegible sigue cayendo de nuevo a él cuando la solicitud no se puede preparar, la trama `response.create` excede su límite de tamaño, o la ruta proxy no puede llevar el socket. +El límite de tamaño también sigue el anuncio del propio backend de ChatGPT. Cuando el handshake del socket trae `x-codex-websocket-max-message-bytes`, una trama mayor que ese valor no se envía por ese socket. Un `response.create` inicial vuelve a SSE antes de subir nada, igual que hace Codex. Si ya se envió un delta incremental y el backend pide la trama completa, una trama completa por encima del límite también toma la ruta SSE. Un giro que necesita direccionamiento o inyección nativos no puede usar SSE: una trama inicial demasiado grande falla de forma visible, y una trama de direccionamiento o inyección demasiado grande se rechaza para que el cliente pueda enviar una corregida. Sin anuncio se aplica el techo fijo, justo por debajo de 16 MiB, y esa comprobación previa a la conexión vuelve a SSE. En esta ruta el proxy también reenvía sin cambios los encabezados de solicitud `x-codex-exclude` y `x-codex-exclude-stream-fields` de Codex, de modo que el backend puede omitir los campos que Codex nombra en ellos. De forma predeterminada son el catálogo de herramientas repetido, la atribución de uso por elemento, los números de secuencia de los deltas y el texto cifrado preliminar del razonamiento. Los demás destinos nunca reciben estos encabezados. + Para mantener el proveedor ChatGPT incorporado en HTTP / SSE, configure `providers.openai.upstreamWebsocket` a `false` en `~/.opencodex/config.json` y reinicie el proxy. Fusione este campo en el proveedor `openai` existente; conserve su modo de cuenta y otras configuraciones. Omite el campo para restaurar la selección predeterminada de aguas arriba WebSocket. Esta configuración no cambia el conmutador `websockets` orientado al cliente ni la cuenta ChatGPT utilizada para la solicitud. La dirección y la inyección nativas a mitad de giro necesitan corriente arriba WebSocket y no están disponibles mientras están apagadas. **Metadatos de uso del razonamiento (disponibles desde la versión 2.90.0).** Para los clientes HTTP/SSE de la ruta canónica de ChatGPT, el relé WebSocket conserva el encabezado real de respuesta de conexión `x-reasoning-included` cuando Bun lo expone, también al reutilizar una conexión. Este encabezado indica a Codex que el uso informado por el servidor ya incluye el razonamiento anterior. Los metadatos recibidos antes del primer evento de Responses tienen prioridad; los posteriores permanecen en el flujo, pero no pueden modificar los encabezados ya enviados. El relé no inventa esta señal ni altera las cifras de uso. La ausencia de la señal del servidor y el ciclo de contabilización propio de Codex son problemas distintos: este cambio por sí solo no demuestra que se haya corregido la compactación anticipada. Las conexiones WebSocket del cliente ya completaron su actualización de protocolo antes de la respuesta del servidor de origen y no pueden recibir la señal retroactivamente como encabezado de esa actualización. diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md index 1e54553e9f4..f1f1544e931 100644 --- a/docs-site/src/content/docs/guides/codex-integration.md +++ b/docs-site/src/content/docs/guides/codex-integration.md @@ -162,6 +162,19 @@ is a `POST` to the canonical Responses URL or a configured WebSocket route, and falls back to it when the request cannot be prepared, the `response.create` frame exceeds its size limit, or the proxy route cannot carry the socket. +The size limit also follows the ChatGPT backend's own advertisement. When the socket's handshake +carries `x-codex-websocket-max-message-bytes`, a frame larger than that value is not sent on that +socket. An opening `response.create` falls back to SSE before anything is uploaded, as Codex itself +does. If an incremental delta was already sent and the backend asks for the full frame, a full frame +above the limit also takes the SSE path. A turn that needs native steering or injection cannot use +SSE: an oversized opening frame fails visibly, and an oversized steering or injection frame is +refused so that the client can send a corrected one. Without an advertisement, the fixed ceiling +just below 16 MiB applies, and that pre-dial check falls back to SSE. On this route the proxy also +forwards Codex's `x-codex-exclude` and `x-codex-exclude-stream-fields` request headers unchanged, +so the backend can leave out the fields Codex names in them. By default these are the echoed tool +catalog, per-item usage attribution, delta sequence numbers and preliminary reasoning ciphertext. +Other destinations never receive these headers. + To keep the built-in ChatGPT provider on HTTP/SSE, set `providers.openai.upstreamWebsocket` to `false` in `~/.opencodex/config.json` and restart the proxy. Merge this field into the existing `openai` provider; preserve its account mode and other settings. Omit the field diff --git a/src/codex/forward-transport-headers.ts b/src/codex/forward-transport-headers.ts index ff532293eeb..248b8819cf6 100644 --- a/src/codex/forward-transport-headers.ts +++ b/src/codex/forward-transport-headers.ts @@ -8,6 +8,13 @@ export const CODEX_INSTALLATION_ID_HEADER = "x-codex-installation-id"; export const CODEX_TURN_METADATA_HEADER = "x-codex-turn-metadata"; export const CODEX_TURN_STATE_HEADER = "x-codex-turn-state"; export const CODEX_ATTESTATION_HEADER = "x-oai-attestation"; +/** + * Codex's stream-exclusion requests (openai/codex 8ecb4c9d0f, ae6c0c8ac1, a4ee1058d9, 98f8a3311b): + * the backend omits the echoed tool catalog, per-item usage attribution, delta sequence numbers and + * preliminary reasoning ciphertext. No canonical-path consumer here reads those fields. + */ +export const CODEX_EXCLUDE_HEADER = "x-codex-exclude"; +export const CODEX_EXCLUDE_STREAM_FIELDS_HEADER = "x-codex-exclude-stream-fields"; // Caller credentials are forwarded only to the canonical Codex destination, never by capability. export const FORWARD_HEADERS = [ @@ -15,6 +22,7 @@ export const FORWARD_HEADERS = [ "thread-id", "x-client-request-id", "x-codex-beta-features", "x-codex-installation-id", "x-codex-parent-thread-id", "x-codex-turn-metadata", "x-codex-turn-state", "x-codex-window-id", "x-oai-attestation", "x-openai-subagent", "x-responsesapi-include-timing-metrics", "version", CODEX_RESPONSES_LITE_HEADER, + CODEX_EXCLUDE_HEADER, CODEX_EXCLUDE_STREAM_FIELDS_HEADER, ]; const MAX_ROUTING_MODEL_BYTES = 256; diff --git a/src/server/responses/codex-ws-exchange.ts b/src/server/responses/codex-ws-exchange.ts index 33b1f1c6bb5..f0eb3b6dab3 100644 --- a/src/server/responses/codex-ws-exchange.ts +++ b/src/server/responses/codex-ws-exchange.ts @@ -14,7 +14,8 @@ import { captureSendAdmission } from "./send-admission"; import { UPGRADE_DEADLINE_MS, CODEX_WS_LIVENESS_PING_INTERVAL_MS, CODEX_WS_RESPONSE_PRELUDE_TIMEOUT_MS, CODEX_WS_COMMITTED_SILENT_INTERVALS, MAX_CODEX_WS_FRAME_BYTES, MAX_CODEX_WS_QUEUE_BYTES, markCodexWsResponse, markCodexWsPreludeProjection, normalizeResponsesWsRelayEvent, closedBeforeTerminalMessage, - codexWsCreateFrameExceedsLimit, codexWsFailureDetail, codexWsPreResponseFailure, markCodexWsStage, codexWsOcxVersion, + codexWsCreateFrameExceedsLimit, codexWsFrameExceedsAdvertisedLimit, codexWsFailureDetail, codexWsPreResponseFailure, + markCodexWsStage, codexWsOcxVersion, markCodexWsSocketDeath, codexWsWrapperStatus, isCodexWsTerminalEvent, type CodexWsFailureStage, type CodexWsStageRecord, type CodexWsTerminalEvent, codexWsPreOutputRefusalStatus, isEmptyCodexWsLifecycleEvent, codexWsFrameResponseIds, markCodexWsPreOutputRefusal, responsesFrameIsReplayUnsafe, type CodexWsPreOutputRefusalHold } from "./codex-ws-wire"; @@ -489,6 +490,19 @@ export function codexWsExchange(options: ExchangeOptions): Promise { if (settledPreOpen) return; clearTimeout(upgradeTimer); opened = true; + // openai/codex ed7ca22bb6: a frame larger than this connection's advertised ceiling never + // leaves. Nothing was sent, so the SSE resend cannot double-generate. Native control has no + // SSE equivalent and is refused rather than quietly losing its channel. + if (!signal?.aborted && codexWsFrameExceedsAdvertisedLimit(frameText, session.advertisedMessageLimit())) { + settledPreOpen = true; + terminal = true; + cleanup(); + session.dispose(); + if (nativeControl) { + reject(new Error("Codex WebSocket request exceeds the upstream's advertised message limit; native control requires the WebSocket transport")); + } else resolve(sseFallback(url, init)); + return; + } try { beforeDispatch?.(new Headers(headers)); } catch (error) { @@ -534,8 +548,10 @@ export function codexWsExchange(options: ExchangeOptions): Promise { } const text = JSON.stringify(outgoing); nativeControl.assertOutboundFrame?.(text); - if (codexWsCreateFrameExceedsLimit(text)) { - throw new Error("Native steering frame exceeds the transport byte limit"); + if (codexWsCreateFrameExceedsLimit(text) || codexWsFrameExceedsAdvertisedLimit(text, session.advertisedMessageLimit())) { + // A typed refusal is a known non-delivery: the channel rolls the frame back so a + // corrected one can be queued, instead of failing as an unknown delivery. + throw new NativeSteeringError("invalid_input", "Native steering frame exceeds the transport byte limit"); } return { outgoing, text }; }; @@ -572,6 +588,8 @@ export function codexWsExchange(options: ExchangeOptions): Promise { )); } else sendControl(); }, error => failStream(error)); + // Only the owner whose attach succeeded sets the limit; a refused second attach changes nothing. + nativeControl.setTransportMessageLimit?.(session.advertisedMessageLimit()); } } catch (error) { // An attach failure is an ownership conflict, not a failed send: no frame @@ -715,7 +733,8 @@ export function codexWsExchange(options: ExchangeOptions): Promise { if (terminal || responseCommitted) return; if (signal?.aborted) { onAbort(); return; } const send = async () => { - if (codexWsCreateFrameExceedsLimit(frameText)) { + if (codexWsCreateFrameExceedsLimit(frameText) + || codexWsFrameExceedsAdvertisedLimit(frameText, session.advertisedMessageLimit())) { terminal = true; cleanup(); session.dispose(); diff --git a/src/server/responses/codex-ws-metadata.ts b/src/server/responses/codex-ws-metadata.ts index 9d64242eed8..9b353f55543 100644 --- a/src/server/responses/codex-ws-metadata.ts +++ b/src/server/responses/codex-ws-metadata.ts @@ -9,12 +9,46 @@ export const CODEX_WS_METADATA_MAX_VALUE_BYTES = 4096; export type CodexWsQuotaObserver = (headers: Headers) => void; const REASONING_INCLUDED_HEADER = "x-reasoning-included"; +/** Connection-scoped upload ceiling the backend may advertise on the 101 (openai/codex ed7ca22bb6). */ +export const CODEX_WS_MAX_MESSAGE_BYTES_HEADER = "x-codex-websocket-max-message-bytes"; const HTTP_HEADER_TOKEN = /^[!#$%&'*+.^_`|~0-9a-z-]+$/i; function record(value: unknown): value is Record { return value !== null && typeof value === "object" && !Array.isArray(value); } +/** + * The advertised message ceiling, read like Codex's `usize` parse: an optional `+` and decimal + * digits, leading zeros allowed, zero included (nothing fits). A value beyond JavaScript's safe + * integers is larger than any frame this process can build, so it limits nothing. A missing, + * repeated, negative, exponent or non-digit value is no advertisement, which leaves the static + * ceiling alone in charge. + */ +export function readCodexWsAdvertisedMessageLimit(payload: unknown): number | undefined { + try { + if (!record(payload) || payload.statusCode !== 101 || !Array.isArray(payload.rawHeaders) + || payload.rawHeaders.length % 2 !== 0 || payload.rawHeaders.length > CODEX_WS_METADATA_MAX_HEADERS * 2) return undefined; + let limit: number | undefined; + let seen = false; + for (let i = 0; i < payload.rawHeaders.length; i += 2) { + const name = payload.rawHeaders[i]; + const value = payload.rawHeaders[i + 1]; + if (typeof name !== "string" || typeof value !== "string") return undefined; + if (name.toLowerCase() !== CODEX_WS_MAX_MESSAGE_BYTES_HEADER) continue; + if (seen) return undefined; + seen = true; + const match = /^\+?(\d+)$/.exec(value.trim()); + if (!match) return undefined; + const digits = match[1]!.replace(/^0+(?=\d)/, ""); + const parsed = digits.length <= 16 ? Number(digits) : Number.POSITIVE_INFINITY; + limit = Number.isSafeInteger(parsed) ? parsed : undefined; + } + return limit; + } catch { + return undefined; + } +} + /** Bun emits this payload before validating the upgrade; the session must wait for open. */ export function readCodexWsUpgradeHeaders(payload: unknown): Headers { try { diff --git a/src/server/responses/codex-ws-session.ts b/src/server/responses/codex-ws-session.ts index b4ca734bb62..13c999926f6 100644 --- a/src/server/responses/codex-ws-session.ts +++ b/src/server/responses/codex-ws-session.ts @@ -1,5 +1,5 @@ import { codexWsIncrementalUploadEnabled, forgetIncrementalSession } from "./codex-ws-incremental"; -import { readCodexWsUpgradeHeaders } from "./codex-ws-metadata"; +import { readCodexWsAdvertisedMessageLimit, readCodexWsUpgradeHeaders } from "./codex-ws-metadata"; export const MAX_CODEX_WS_SESSION_EXCHANGES = 32; export const CODEX_WS_SESSION_CLOSE_GRACE_MS = 1_000; @@ -51,6 +51,8 @@ export class CodexWsSession { private idlePing?: ReturnType; private pendingUpgradeHeaders?: Headers; private connectionHeaders?: Headers; + private pendingMessageLimit?: number; + private messageLimit?: number; constructor(url: string, headers: Record, readonly retainable = false, private readonly changed: () => void = () => {}, proxy?: string) { @@ -65,6 +67,8 @@ export class CodexWsSession { get reused(): boolean { return this.completedIds.size > 0; } hasCompleted(id: string): boolean { return this.completedIds.has(id); } upgradeHeaders(): Headers { return new Headers(this.opened && !this.closed ? this.connectionHeaders : undefined); } + /** The upload ceiling this connection's 101 advertised, if any; Codex refuses a frame strictly larger. */ + advertisedMessageLimit(): number | undefined { return this.opened && !this.closed ? this.messageLimit : undefined; } reserve(): boolean { if (this.closed || this.busy || (this.opened && this.socket.readyState !== undefined && this.socket.readyState !== 1)) return false; @@ -125,13 +129,17 @@ export class CodexWsSession { private onHandshake = (event: Event): void => { if (this.opened || this.closed) return; - this.pendingUpgradeHeaders = readCodexWsUpgradeHeaders((event as MessageEvent).data); + const payload = (event as MessageEvent).data; + this.pendingUpgradeHeaders = readCodexWsUpgradeHeaders(payload); + this.pendingMessageLimit = readCodexWsAdvertisedMessageLimit(payload); }; private onOpen = (): void => { if (this.closed) return; // A 101 payload alone is not proof that Bun accepted the handshake. this.connectionHeaders = this.pendingUpgradeHeaders; this.pendingUpgradeHeaders = undefined; + this.messageLimit = this.pendingMessageLimit; + this.pendingMessageLimit = undefined; this.socket.removeEventListener("handshake", this.onHandshake); this.opened = true; }; @@ -152,6 +160,8 @@ export class CodexWsSession { forgetIncrementalSession(this); this.pendingUpgradeHeaders = undefined; this.connectionHeaders = undefined; + this.pendingMessageLimit = undefined; + this.messageLimit = undefined; this.socket.removeEventListener("handshake", this.onHandshake); this.socket.removeEventListener("open", this.onOpen); this.socket.removeEventListener("message", this.onIdleMessage); diff --git a/src/server/responses/codex-ws-wire.ts b/src/server/responses/codex-ws-wire.ts index 53f27b6142d..e8a2cab3b05 100644 --- a/src/server/responses/codex-ws-wire.ts +++ b/src/server/responses/codex-ws-wire.ts @@ -643,3 +643,12 @@ export function codexWsCreateFrameExceedsLimit( if (frameText.length * 3 < limitBytes) return false; return Buffer.byteLength(frameText, "utf8") >= limitBytes; } + +/** + * True when the frame is strictly larger than the ceiling the connection advertised + * (`x-codex-websocket-max-message-bytes`), the comparison Codex itself makes before it sends + * (openai/codex ed7ca22bb6). No advertisement leaves only the static ceiling above. + */ +export function codexWsFrameExceedsAdvertisedLimit(frameText: string, advertisedBytes: number | undefined): boolean { + return advertisedBytes !== undefined && codexWsCreateFrameExceedsLimit(frameText, advertisedBytes + 1); +} diff --git a/src/server/responses/native-injection.ts b/src/server/responses/native-injection.ts index 85ac6615023..9f7472b6844 100644 --- a/src/server/responses/native-injection.ts +++ b/src/server/responses/native-injection.ts @@ -71,7 +71,13 @@ export class NativeInjectionChannel implements NativeResponseControl { if (!checkOutboundBodySize(text, this.maxUpstreamBodyBytes).admitted) { injectionError("outbound_body_too_large", "Native injection frame exceeds the configured upstream body limit."); } + if (this.transportMessageLimit !== undefined && Buffer.byteLength(text) > this.transportMessageLimit) { + injectionError("outbound_body_too_large", "Native injection frame exceeds the upstream's advertised WebSocket message limit."); + } } + private transportMessageLimit?: number; + /** Codex refuses a frame strictly larger than the socket's advertised ceiling (openai/codex ed7ca22bb6). */ + setTransportMessageLimit(bytes: number | undefined): void { this.transportMessageLimit = bytes; } /** Report that the real dispatch boundary has selected this owner. */ get attached(): boolean { return this.everAttached; } /** A terminal is not final until submitted results have acknowledgements. */ diff --git a/src/server/responses/native-response-control.ts b/src/server/responses/native-response-control.ts index c990c41dcd1..3dd48ce5c6e 100644 --- a/src/server/responses/native-response-control.ts +++ b/src/server/responses/native-response-control.ts @@ -22,6 +22,12 @@ export interface NativeResponseControl { continue(frame: Record): boolean; /** Apply operator-configured limits to the exact reconstructed upstream frame. */ assertOutboundFrame?(text: string): void; + /** + * The upload ceiling the attached socket's handshake advertised (`x-codex-websocket-max-message-bytes`). + * A control that queues frames checks it before queuing, so a refusal reaches its caller as a known + * non-delivery instead of failing the channel when the queued frame is finally prepared. + */ + setTransportMessageLimit?(bytes: number | undefined): void; } export const OPENAI_API_RESPONSES_URL = "https://api.openai.com/v1/responses"; diff --git a/structure/providers/codex-installation-identity.md b/structure/providers/codex-installation-identity.md index f5f262e0148..6d79332b279 100644 --- a/structure/providers/codex-installation-identity.md +++ b/structure/providers/codex-installation-identity.md @@ -24,6 +24,12 @@ while empty installation and turn-metadata headers retain their existence gates. `src/codex/forward-transport-headers.ts` also isolates a present installation field inside native turn metadata and strips caller attestations from substituted credentials. Its selected-header merge prevents removed identity fields from reappearing through provider defaults. +Its `FORWARD_HEADERS` allowlist also carries Codex's stream-exclusion requests, `x-codex-exclude` +and `x-codex-exclude-stream-fields`, to the canonical destination only. These requests keep the +backend from echoing the tool catalog and per-item usage attribution, and from sending delta sequence +numbers or preliminary reasoning ciphertext. No canonical-path consumer reads those fields; sequence +numbers are validated only when present. Destinations OpenCodex does not operate never receive the +headers (`tests/codex-integration/codex-metadata-integrity.test.ts`). For an object with a nonblank string `installation_id`, including one already matching the selected identity, turn-metadata JSON is canonicalized and escapes every code unit outside printable ASCII: `JSON.stringify` escapes U+0000–U+001F (with short forms such as `\n` and diff --git a/structure/transports/responses-wire-shapes.md b/structure/transports/responses-wire-shapes.md index ea7efa23faa..e349085d85d 100644 --- a/structure/transports/responses-wire-shapes.md +++ b/structure/transports/responses-wire-shapes.md @@ -465,7 +465,7 @@ identity can reuse the new socket. Malformed native metadata retains HTTP fallba without rewriting its body. Canonical WS quota and response metadata preceding the first Responses event are projected into bounded, allowlisted HTTP headers before commitment; each name and value follows the [response metadata header contract](../data-planes/error-detail.md#response-metadata-headers). -`src/server/responses/codex-ws-session.ts` also retains the `x-reasoning-included` upgrade header when Bun exposes its handshake event, promoting the bounded candidate only after `open` validates the connection; the seed keeps the header present but carries only an exact `true`/`false` or an empty value. No other upgrade header is retained: request ids, model, turn state, quota and credits are response-scoped. +`src/server/responses/codex-ws-session.ts` also retains the `x-reasoning-included` upgrade header when Bun exposes its handshake event, promoting the bounded candidate only after `open` validates the connection; the seed keeps the header present but carries only an exact `true`/`false` or an empty value. No other upgrade header reaches the client: request ids, model, turn state, quota and credits are response-scoped. The session also records the connection-scoped `x-codex-websocket-max-message-bytes` ceiling (`readCodexWsAdvertisedMessageLimit`, Rust `usize` syntax: optional `+`, leading zeros, zero included; a value beyond safe integers limits nothing; a repeated or malformed value is no advertisement). It is promoted at `open` like the inclusion header and never seeded into response metadata. `codex-ws-exchange.ts` compares each create frame, incremental recovery frame and native steering frame with it strictly by UTF-8 bytes, as Codex does (openai/codex ed7ca22bb6). An oversized opening frame never leaves: it takes the SSE fallback once, or, under native control, rejects before the channel attaches. An oversized full recovery frame after a sent delta takes the SSE path, and an oversized steering or injection frame throws the typed `NativeSteeringError`, so the channel rolls it back and accepts a corrected frame. At attach, the exchange hands the limit to the control (`setTransportMessageLimit`). `NativeInjectionChannel.assertOutboundFrame` therefore refuses an oversized injection before queuing it, even when it would wait behind an unacknowledged one. The static 16 MiB pre-dial ceiling is unchanged, including its SSE fallback when control is set (`tests/responses/codex-ws-handshake.test.ts`). `src/server/responses/codex-ws-metadata.ts` rejects malformed or oversized raw headers and connection-nominated inclusion headers without changing transport failure or replay policy. Each canonical exchange starts from that connection signal; its own prelude metadata wins, including an explicit `false` value, and no prior exchange's metadata carries over. No signal is inferred from a model, configuration or encrypted input, and usage numbers are unchanged. Later metadata remains in the SSE body, while quota observations update only the captured serving account; neither changes committed HTTP headers. The pre-output hold freezes the same snapshot at its first Responses event. A client-facing WebSocket upgrade is already complete before upstream dispatch and cannot acquire this HTTP/SSE response header retroactively. `tests/responses/codex-ws-handshake.test.ts` and `tests/responses/codex-ws-handshake-validation.test.ts` cover the native loopback, reuse, bounds and failed-upgrade boundaries. Control frames remain bounded, and provider credential/cookie headers are not forwarded. diff --git a/tests/codex-integration/codex-metadata-integrity.test.ts b/tests/codex-integration/codex-metadata-integrity.test.ts index c52b8d1e86f..212e1f210d6 100644 --- a/tests/codex-integration/codex-metadata-integrity.test.ts +++ b/tests/codex-integration/codex-metadata-integrity.test.ts @@ -620,3 +620,60 @@ describe("Lite follows the serialized wire model", () => { } }); }); + +describe("Codex stream-exclusion headers (openai/codex 8ecb4c9d0f, ae6c0c8ac1, a4ee1058d9, 98f8a3311b)", () => { + // Codex sends both on every Responses HTTP request and WebSocket handshake (core/src/client.rs + // build_responses_headers and with_default_stream_exclusions @5505daf388). The canonical backend + // then omits the echoed tool catalog, per-item usage attribution, delta sequence numbers and + // preliminary reasoning ciphertext. + const exclusions = { + "x-codex-exclude": "tools,usage.attribution", + "x-codex-exclude-stream-fields": "delta.sequence_number,reasoning.added.encrypted_content", + }; + const canonical: OcxProviderConfig = { + adapter: "openai-responses", + baseUrl: "https://chatgpt.com/backend-api/codex", + authMode: "forward", + }; + + test("the canonical forward request and its WebSocket handshake carry both headers verbatim", async () => { + const { prepareCodexWsRequest } = await import("../../src/server/responses/codex-ws-request"); + const built = await createResponsesPassthroughAdapter(canonical).buildRequest(minimalParsed(), { + headers: new Headers({ authorization: "Bearer caller-token", ...exclusions }), + }); + const sent = new Headers(built.headers); + for (const [name, value] of Object.entries(exclusions)) expect(sent.get(name)).toBe(value); + const prepared = prepareCodexWsRequest("https://chatgpt.com/backend-api/codex/responses", { body: built.body, headers: built.headers }); + for (const [name, value] of Object.entries(exclusions)) expect(prepared!.headers[name]).toBe(value); + }); + + test("a pool account override keeps both headers", async () => { + const pooled = { ...canonical, _codexAccountRequired: true, _codexAccountOverride: { + accessToken: accountA.accessToken, chatgptAccountId: accountA.chatgptAccountId } } as OcxProviderConfig; + const built = await createResponsesPassthroughAdapter(pooled).buildRequest(minimalParsed(), { + headers: new Headers({ authorization: "Bearer caller-token", ...exclusions }), + }); + const sent = new Headers(built.headers); + for (const [name, value] of Object.entries(exclusions)) expect(sent.get(name)).toBe(value); + const materialized = headersForCodexAuthContext(new Headers(exclusions), poolAuthContext); + for (const [name, value] of Object.entries(exclusions)) expect(materialized.get(name)).toBe(value); + }); + + test("the inbound WebSocket snapshot keeps both headers for the reconstructed turn", async () => { + const { selectForwardHeaders } = await import("../../src/server/ws-bridge"); + const selected = selectForwardHeaders(new Headers(exclusions)); + for (const [name, value] of Object.entries(exclusions)) expect(selected.get(name)).toBe(value); + }); + + test("a destination OpenCodex does not operate never receives them", async () => { + for (const authMode of ["key", "forward"] as const) { + const built = await createResponsesPassthroughAdapter({ adapter: "openai-responses", authMode, + baseUrl: "https://gateway.example/v1", apiKey: "gateway-key" }).buildRequest(minimalParsed(), { + headers: new Headers(exclusions), + }); + const sent = new Headers(built.headers); + for (const name of Object.keys(exclusions)) expect(sent.has(name)).toBe(false); + } + }); +}); + diff --git a/tests/responses/codex-ws-handshake.test.ts b/tests/responses/codex-ws-handshake.test.ts index c060126a69c..7a8795a6cc5 100644 --- a/tests/responses/codex-ws-handshake.test.ts +++ b/tests/responses/codex-ws-handshake.test.ts @@ -1,4 +1,10 @@ -import { afterEach, beforeEach, expect, test } from "bun:test"; +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import type { IncrementalPlan } from "../../src/server/responses/codex-ws-incremental"; +import { readCodexWsAdvertisedMessageLimit } from "../../src/server/responses/codex-ws-metadata"; +import { codexWsUpstreamFetch } from "../../src/server/responses/ws-upstream"; +import type { NativeResponseControl } from "../../src/server/responses/native-response-control"; +import { NativeSteeringError } from "../../src/server/responses/native-steering"; +import { NativeInjectionChannel } from "../../src/server/responses/native-injection"; import { codexWsExchange } from "../../src/server/responses/codex-ws-exchange"; import { CodexWsSession } from "../../src/server/responses/codex-ws-session"; import { CODEX_RESPONSES_HTTP_URL, prepareCodexWsRequest } from "../../src/server/responses/codex-ws-request"; @@ -192,3 +198,377 @@ test("an invalid 101 handshake cannot contaminate the HTTP fallback", async () = listener.stop(true); } }); + +/* + * Upstream advertised WebSocket message ceiling (openai/codex ed7ca22bb6, + * codex-rs/codex-api/src/endpoint/responses_websocket.rs:371-375 and :908-912 @5505daf388). + * + * Codex reads `x-codex-websocket-max-message-bytes` from the 101 response and sends a request + * strictly larger than that over HTTP before uploading anything. The OpenCodex upstream dial does + * the same: an oversized frame never leaves, and the turn takes the SSE path exactly once. Native + * control has no SSE equivalent and is refused instead. + */ +const HEADER = "x-codex-websocket-max-message-bytes"; +function sizedRequest(input: unknown[] = []) { + const init: RequestInit = { + method: "POST", signal: AbortSignal.timeout(3000), + headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "fixture-model", stream: true, input }), + }; + return { init, prepared: prepareCodexWsRequest(CODEX_RESPONSES_HTTP_URL, init)! }; +} + +const bytes = (text: string) => Buffer.byteLength(text, "utf8"); +const handshake = (headers: [string, string][]) => ({ statusCode: 101, rawHeaders: headers.flat() }); + +describe("advertisement parsing", () => { + test("one unsigned decimal is the limit, zero included", () => { + expect(readCodexWsAdvertisedMessageLimit(handshake([[HEADER, "1048576"]]))).toBe(1048576); + expect(readCodexWsAdvertisedMessageLimit(handshake([["X-Codex-WebSocket-Max-Message-Bytes", " 64 "]]))).toBe(64); + expect(readCodexWsAdvertisedMessageLimit(handshake([[HEADER, "0"]]))).toBe(0); + }); + + test("Rust usize syntax: a plus sign and leading zeros are valid", () => { + expect(readCodexWsAdvertisedMessageLimit(handshake([[HEADER, "+7"]]))).toBe(7); + expect(readCodexWsAdvertisedMessageLimit(handshake([[HEADER, "000064"]]))).toBe(64); + expect(readCodexWsAdvertisedMessageLimit(handshake([[HEADER, "00000000000000000000"]]))).toBe(0); + expect(readCodexWsAdvertisedMessageLimit(handshake([[HEADER, "0000000000000000000000064"]]))).toBe(64); + // Larger than any frame this process can build: it limits nothing. + expect(readCodexWsAdvertisedMessageLimit(handshake([[HEADER, "99999999999999999999"]]))).toBeUndefined(); + }); + + test("anything else is no advertisement", () => { + for (const value of ["", "abc", "-5", "1e3", "+", "++7", "1.5", "0x10"]) { + expect(readCodexWsAdvertisedMessageLimit(handshake([[HEADER, value]]))).toBeUndefined(); + } + expect(readCodexWsAdvertisedMessageLimit(handshake([[HEADER, "10"], [HEADER, "20"]]))).toBeUndefined(); + expect(readCodexWsAdvertisedMessageLimit(handshake([["x-other", "10"]]))).toBeUndefined(); + expect(readCodexWsAdvertisedMessageLimit({ statusCode: 200, rawHeaders: [HEADER, "10"] })).toBeUndefined(); + }); +}); + +type Reply = "complete" | "cache-miss" | "created" | "call"; + +/** Real Bun upgrade that advertises a ceiling; no credentials and no provider traffic. */ +async function withAdvertisingServer( + advertised: string | undefined, + reply: (index: number) => Reply, + run: (fixture: { session: CodexWsSession; frames: string[]; received: (count: number) => Promise }) => Promise, +) { + const frames: string[] = []; + const waiters: { count: number; resolve: () => void }[] = []; + const received = (count: number) => frames.length >= count ? Promise.resolve() + : new Promise(resolve => { waiters.push({ count, resolve }); }); + const server = Bun.serve({ + hostname: "127.0.0.1", port: 0, + fetch(req, srv) { + if (srv.upgrade(req, { headers: advertised === undefined ? {} : { [HEADER]: advertised } })) return; + return new Response(null, { status: 400 }); + }, + websocket: { + message(ws, message) { + frames.push(String(message)); + for (const waiter of waiters.splice(0)) { + if (frames.length >= waiter.count) waiter.resolve(); else waiters.push(waiter); + } + const send = (event: unknown) => ws.send(JSON.stringify(event)); + if (reply(frames.length - 1) === "cache-miss") { + send({ type: "error", error: { type: "invalid_request_error", code: "previous_response_not_found", message: "miss" } }); + return; + } + const id = `response-${frames.length}`; + if (reply(frames.length - 1) === "call") { + if (frames.length === 1) { + send({ type: "response.created", response: { id, status: "in_progress", output: [] } }); + for (const [index, call] of ["c", "d"].entries()) { + const item = { id: `item-${call}`, type: "function_call", call_id: call, name: "fixture", arguments: "{}" }; + send({ type: "response.output_item.added", output_index: index, item }); + send({ type: "response.output_item.done", output_index: index, item }); + } + } + return; + } + if (reply(frames.length - 1) === "created") { + if (frames.length === 1) send({ type: "response.created", response: { id, status: "in_progress", output: [] } }); + return; + } + send({ type: "response.created", response: { id, status: "in_progress", output: [] } }); + send({ type: "response.completed", response: { id, status: "completed", output: [], usage } }); + }, + }, + }); + const session = new CodexWsSession(`ws://127.0.0.1:${server.port}`, sizedRequest().prepared.headers, true); + try { + await run({ session, frames, received }); + } finally { + session.dispose(); + await server.stop(true); + } +} + +type Counters = { fallbacks: number; dispatches: number; physical: number }; + +async function exchange(session: CodexWsSession, input: unknown[], counters: Counters, extra: { + incrementalPlan?: IncrementalPlan; nativeControl?: NativeResponseControl; +} = {}) { + expect(session.busy || session.reserve()).toBe(true); + const { init, prepared } = sizedRequest(input); + const fallback = new Response("fallback-body", { headers: { "content-type": "text/event-stream" } }); + const response = await codexWsExchange({ + session, url: CODEX_RESPONSES_HTTP_URL, init, bunVersion: Bun.version, + prepared: extra.incrementalPlan ? { ...prepared, frameText: extra.incrementalPlan.frameText } : prepared, + ...extra, + beforeDispatch: () => { counters.dispatches++; }, + onPhysicalDispatch: () => { counters.physical++; }, + beforeContinuation: async () => {}, + sseFallback: (async () => { counters.fallbacks++; return fallback; }) as typeof fetch, + }); + return { response, fallback, frameText: prepared.frameText }; +} + +const fresh = (): Counters => ({ fallbacks: 0, dispatches: 0, physical: 0 }); + +describe("fresh and retained connections", () => { + test("a frame above the advertised limit never leaves and falls back once", async () => { + await withAdvertisingServer("64", () => "complete", async ({ session, frames }) => { + const counters = fresh(); + const { response, fallback } = await exchange(session, [{ role: "user", content: "x".repeat(200) }], counters); + expect(response).toBe(fallback); + expect(await response.text()).toBe("fallback-body"); + expect(frames).toHaveLength(0); + expect(counters).toEqual({ fallbacks: 1, dispatches: 0, physical: 0 }); + }); + }); + + test("the comparison is strict and counts UTF-8 bytes, not code units", async () => { + const input = [{ role: "user", content: "한글 boundary" }]; + const frameText = sizedRequest(input).prepared.frameText; + expect(bytes(frameText)).toBeGreaterThan(frameText.length); + await withAdvertisingServer(String(bytes(frameText)), () => "complete", async ({ session, frames }) => { + const counters = fresh(); + const { response } = await exchange(session, input, counters); + expect(response.status).toBe(200); + expect(await response.text()).toContain("response.completed"); + expect(frames).toEqual([frameText]); + expect(counters).toEqual({ fallbacks: 0, dispatches: 1, physical: 1 }); + }); + await withAdvertisingServer(String(bytes(frameText) - 1), () => "complete", async ({ session, frames }) => { + const counters = fresh(); + await exchange(session, input, counters); + expect(frames).toHaveLength(0); + expect(counters.fallbacks).toBe(1); + }); + }); + + test("an advertised zero refuses every frame; an invalid advertisement is ignored", async () => { + await withAdvertisingServer("0", () => "complete", async ({ session, frames }) => { + const counters = fresh(); + await exchange(session, [], counters); + expect(frames).toHaveLength(0); + expect(counters.fallbacks).toBe(1); + }); + for (const value of ["abc", "-5", "1e3"]) { + await withAdvertisingServer(value, () => "complete", async ({ session, frames }) => { + const counters = fresh(); + const { response } = await exchange(session, [{ role: "user", content: "x".repeat(200) }], counters); + expect(await response.text()).toContain("response.completed"); + expect(frames).toHaveLength(1); + expect(counters.fallbacks).toBe(0); + }); + } + }); + + test("a retained connection keeps applying the limit its handshake advertised", async () => { + const small = [{ role: "user", content: "hi" }]; + const limit = bytes(sizedRequest(small).prepared.frameText) + 16; + await withAdvertisingServer(String(limit), () => "complete", async ({ session, frames }) => { + const counters = fresh(); + const first = await exchange(session, small, counters); + expect(await first.response.text()).toContain("response.completed"); + expect(frames).toHaveLength(1); + expect(session.closed).toBe(false); + const second = await exchange(session, [{ role: "user", content: "x".repeat(limit) }], counters); + expect(second.response).toBe(second.fallback); + expect(frames).toHaveLength(1); + expect(counters).toEqual({ fallbacks: 1, dispatches: 1, physical: 1 }); + }); + }); +}); + +describe("stateful paths", () => { + test("a fitting delta whose full recovery exceeds the limit falls back once without a second frame", async () => { + const full = sizedRequest([{ role: "user", content: "x".repeat(400) }]).prepared.frameText; + const delta = sizedRequest([{ role: "user", content: "d" }]).prepared.frameText; + const limit = bytes(delta) + 32; + expect(bytes(full)).toBeGreaterThan(limit); + await withAdvertisingServer(String(limit), index => index === 0 ? "cache-miss" : "complete", async ({ session, frames }) => { + const counters = fresh(); + const plan: IncrementalPlan = { + session, caller: "fixture-caller", frameText: delta, fullFrameText: full, fullBytes: bytes(full), + sentBytes: bytes(delta), delta: true, envelope: "fixture-envelope", items: [], retainable: false, + }; + const { response, fallback } = await exchange(session, [{ role: "user", content: "x".repeat(400) }], counters, { incrementalPlan: plan }); + expect(response).toBe(fallback); + expect(frames).toEqual([delta]); + expect(counters.fallbacks).toBe(1); + expect(counters.physical).toBe(1); + }); + }); + + test("an oversized native control frame is a typed refusal the channel can roll back", async () => { + const opening = [{ role: "user", content: "hi" }]; + const limit = bytes(sizedRequest(opening).prepared.frameText) + 64; + await withAdvertisingServer(String(limit), () => "created", async ({ session, frames, received }) => { + let send: ((frame: Record) => void) | undefined; + const nativeControl = { + kind: "injection", + attach: (sender: (frame: Record) => void) => { send = sender; return () => {}; }, + observe: () => false, + } as unknown as NativeResponseControl; + const { response } = await exchange(session, opening, fresh(), { nativeControl }); + expect(response.status).toBe(200); + expect(frames).toHaveLength(1); + const oversized = { type: "response.inject", response_id: "response-1", input: [{ type: "function_call_output", call_id: "c", output: "x".repeat(limit) }] }; + expect(() => send!(oversized)).toThrow(NativeSteeringError); + expect(frames).toHaveLength(1); + // The corrected frame still goes out on the same channel. + send!({ type: "response.inject", response_id: "response-1", input: [{ type: "function_call_output", call_id: "c", output: "ok" }] }); + await received(2); + expect(frames).toHaveLength(2); + expect(JSON.parse(frames[1]!).input[0].output).toBe("ok"); + }); + }); + + test("a real injection channel rolls an oversized result back and accepts the corrected one", async () => { + const opening = [{ role: "user", content: "hi" }]; + const limit = bytes(sizedRequest(opening).prepared.frameText) + 256; + await withAdvertisingServer(String(limit), () => "call", async ({ session, frames, received }) => { + const channel = new NativeInjectionChannel({ type: "response.create", model: "fixture-model", multi_agent: { enabled: true } }); + const { response } = await exchange(session, opening, fresh(), { nativeControl: channel }); + expect(response.status).toBe(200); + const body = response.body!.getReader(); + const decoder = new TextDecoder(); + let seen = ""; + // The call must be advertised on this response before a result for it can be injected. + while ((seen.match(/response\.output_item\.done/g) ?? []).length < 2) { + const chunk = await body.read(); + if (chunk.done) throw new Error("stream ended before the call was advertised"); + seen += decoder.decode(chunk.value, { stream: true }); + } + expect(() => channel.inject({ type: "response.inject", response_id: "response-1", + input: [{ type: "function_call_output", call_id: "c", output: "x".repeat(limit) }] })).toThrow(NativeSteeringError); + expect(frames).toHaveLength(1); + expect(channel.ended).toBe(false); + channel.inject({ type: "response.inject", response_id: "response-1", input: [{ type: "function_call_output", call_id: "c", output: "ok" }] }); + await received(2); + expect(JSON.parse(frames[1]!).input[0].output).toBe("ok"); + await body.cancel(); + }); + }); + + test("an oversized injection queued behind an unacknowledged one is refused without failing the channel", async () => { + const opening = [{ role: "user", content: "hi" }]; + const limit = bytes(sizedRequest(opening).prepared.frameText) + 256; + await withAdvertisingServer(String(limit), () => "call", async ({ session, frames, received }) => { + const channel = new NativeInjectionChannel({ type: "response.create", model: "fixture-model", multi_agent: { enabled: true } }); + const { response } = await exchange(session, opening, fresh(), { nativeControl: channel }); + const body = response.body!.getReader(); + const decoder = new TextDecoder(); + let seen = ""; + while ((seen.match(/response\.output_item\.done/g) ?? []).length < 2) { + const chunk = await body.read(); + if (chunk.done) throw new Error("stream ended before both calls were advertised"); + seen += decoder.decode(chunk.value, { stream: true }); + } + channel.inject({ type: "response.inject", response_id: "response-1", input: [{ type: "function_call_output", call_id: "c", output: "first" }] }); + await received(2); + // The first result is still unacknowledged, so the second would queue. The refusal is synchronous. + expect(() => channel.inject({ type: "response.inject", response_id: "response-1", + input: [{ type: "function_call_output", call_id: "d", output: "x".repeat(limit) }] })).toThrow(NativeSteeringError); + expect(channel.ended).toBe(false); + expect(frames).toHaveLength(2); + await body.cancel(); + }); + }); + + test("native control above the limit is refused rather than degraded to plain SSE", async () => { + await withAdvertisingServer("64", () => "complete", async ({ session, frames }) => { + const counters = fresh(); + let attached = 0; + const nativeControl = { + kind: "steering", + attach: () => { attached++; return () => {}; }, + observe: () => false, + } as unknown as NativeResponseControl; + await expect(exchange(session, [{ role: "user", content: "x".repeat(200) }], counters, { nativeControl })) + .rejects.toThrow("advertised message limit"); + expect(attached).toBe(0); + expect(frames).toHaveLength(0); + expect(counters).toEqual({ fallbacks: 0, dispatches: 0, physical: 0 }); + }); + }); +}); + +type Listener = (event: unknown) => void; + +/** Scriptable stand-in for Bun's WebSocket, used only to reach the public upstream entry. */ +class FakeWebSocket { + static instances: FakeWebSocket[] = []; + static script: (ws: FakeWebSocket) => void = () => {}; + sent: string[] = []; + closed = false; + readyState = 0; + listeners = new Map(); + constructor(readonly url: string) { + FakeWebSocket.instances.push(this); + queueMicrotask(() => FakeWebSocket.script(this)); + } + addEventListener(type: string, listener: Listener) { + this.listeners.set(type, [...(this.listeners.get(type) ?? []), listener]); + } + removeEventListener(type: string, listener: Listener) { + this.listeners.set(type, (this.listeners.get(type) ?? []).filter(value => value !== listener)); + } + emit(type: string, event: unknown = {}) { + for (const listener of this.listeners.get(type) ?? []) listener(event); + } + send(data: string) { this.sent.push(data); } + close() { + if (this.closed) return; + this.closed = true; + this.readyState = 3; + this.emit("close", {}); + } +} + +test("the public upstream entry checks dispatch once before dialing and sends nothing past the advertisement", async () => { + FakeWebSocket.instances = []; + FakeWebSocket.script = ws => { + ws.emit("handshake", { data: handshake([[HEADER, "64"]]) }); + ws.readyState = 1; + ws.emit("open", {}); + }; + const realWebSocket = globalThis.WebSocket; + globalThis.WebSocket = FakeWebSocket as unknown as typeof WebSocket; + try { + let fallbacks = 0; + let dispatches = 0; + let physical = 0; + const fallback = new Response("fallback-body"); + const init: RequestInit = { + method: "POST", + headers: { "content-type": "application/json", authorization: "Bearer test" }, + body: JSON.stringify({ model: "gpt-5.5", stream: true, input: [{ role: "user", content: "x".repeat(200) }] }), + }; + const response = await codexWsUpstreamFetch(CODEX_RESPONSES_HTTP_URL, init, + (async () => { fallbacks++; return fallback; }) as typeof fetch, + "1.4.0", undefined, () => { dispatches++; }, undefined, undefined, () => { physical++; }); + expect(response).toBe(fallback); + expect(FakeWebSocket.instances).toHaveLength(1); + expect(FakeWebSocket.instances[0]!.sent).toHaveLength(0); + expect({ fallbacks, dispatches, physical }).toEqual({ fallbacks: 1, dispatches: 1, physical: 0 }); + } finally { + globalThis.WebSocket = realWebSocket; + } +}); + From db90fcf36c4ec203200ec47b20f60782d4d0a6b5 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 26 Nov 2026 02:46:10 +0900 Subject: [PATCH 56/60] feat(sponsors): RunAPI Standard sponsor preset, README row and docs (#9047) * feat(sponsors): add RunAPI Standard sponsor preset * docs: sync RunAPI preset counts and Spanish guide * feat(sponsors): fill the RunAPI listing from RunAPI's public materials RunAPI has not sent its logo pack, blurb or test key yet, so the listing uses what RunAPI publishes itself (read 2026-11-26, no login): - logo: https://runapi.co/logo.png (the only brand asset on the site; one dark tile that reads on both themes), shipped in the npm files list - blurb in all nine READMEs, from RunAPI's own inquiry email and site copy: 200+ models, Chat Completions / Responses / Anthropic Messages / Gemini formats (https://runapi.co/api/pricing supported_endpoint), smart routing with failover, pay-as-you-go - provider guide (en, es): live discovery, and runapi.host as the mirror RunAPI announced for networks that cannot reach runapi.co - preset comment records the public contract and the agreement date * docs(sponsors): describe RunAPI formats as varying by model Review follow-up: 200+ is the overall catalog (208 public), while Chat Completions covers 200, Responses 53, Anthropic Messages 37 and Gemini 25, so the README rows and the preset note now say the formats vary by model. --- README.md | 4 ++++ assets/sponsors/runapi.png | Bin 0 -> 17950 bytes .../docs/es/getting-started/quickstart.md | 2 +- .../content/docs/es/guides/api-key-catalog.md | 2 +- .../src/content/docs/es/guides/providers.md | 10 ++++++++++ .../docs/fr/getting-started/quickstart.md | 2 +- .../src/content/docs/fr/guides/providers.md | 2 +- .../docs/getting-started/quickstart.md | 2 +- .../content/docs/guides/api-key-catalog.md | 2 +- .../src/content/docs/guides/providers.md | 10 ++++++++++ .../docs/ja/getting-started/quickstart.md | 2 +- .../src/content/docs/ja/guides/providers.md | 2 +- .../docs/ko/getting-started/quickstart.md | 2 +- .../src/content/docs/ko/guides/providers.md | 2 +- .../docs/ru/getting-started/quickstart.md | 2 +- .../src/content/docs/ru/guides/providers.md | 2 +- .../docs/tr/getting-started/quickstart.md | 2 +- .../src/content/docs/tr/guides/providers.md | 2 +- .../docs/zh-cn/getting-started/quickstart.md | 2 +- .../content/docs/zh-cn/guides/providers.md | 2 +- .../docs/zh-tw/getting-started/quickstart.md | 2 +- .../content/docs/zh-tw/guides/providers.md | 2 +- package.json | 1 + readme/README.es.md | 4 ++++ readme/README.fr.md | 4 ++++ readme/README.ja.md | 4 ++++ readme/README.ko.md | 4 ++++ readme/README.ru.md | 4 ++++ readme/README.tr.md | 4 ++++ readme/README.zh-CN.md | 4 ++++ readme/README.zh-TW.md | 4 ++++ readme/i18n-manifest.json | 16 ++++++++-------- src/providers/registry/entries-extended.ts | 18 ++++++++++++++++++ structure/dashboard-and-usage.md | 2 +- structure/ops/docs-and-release.md | 2 +- tests/providers/sponsor-presets.test.ts | 12 ++++++++++++ 36 files changed, 115 insertions(+), 28 deletions(-) create mode 100644 assets/sponsors/runapi.png diff --git a/README.md b/README.md index 2590d14cfaf..5753efb75bb 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,10 @@ See [SPONSORS.md](./SPONSORS.md). TokenLab Thanks to TokenLab for sponsoring this project! TokenLab gives coding agents one API key for leading models, supporting OpenAI Responses and Chat Completions, Anthropic Messages, and Gemini's native API formats, with streaming and tool calling. It also provides an MCP server and agent Skills for easy integration. Choose your delivery mode and pay as you go. Pick TokenLab in the Add provider picker or run ocx provider add tokenlab.
    TokenLab 为编程智能体提供统一的多模型 API,一枚 API Key 即可接入主流模型,支持 OpenAI Responses、Chat Completions、Anthropic Messages 和 Gemini 原生 API 格式,以及流式输出和工具调用。同时提供 MCP 服务器和 Agent Skills,方便接入现有工作流;交付模式可选,按量付费。 + +RunAPI +Thanks to RunAPI for sponsoring this project! RunAPI is a unified AI API gateway: one API key opens a catalog of 200+ models from OpenAI, Anthropic, Google, xAI, DeepSeek, Alibaba, Moonshot and more, served over the OpenAI Chat Completions and Responses, Anthropic Messages, and Gemini native API formats, with the formats available varying by model. Smart routing sends each request to a fast, stable provider node with automatic failover, and pricing is pay-as-you-go, typically well below standard rates. Pick RunAPI in the Add provider picker or run ocx provider add runapi. + diff --git a/assets/sponsors/runapi.png b/assets/sponsors/runapi.png new file mode 100644 index 0000000000000000000000000000000000000000..1b481a07ef0bb09f62300161b2c09bcab15e0a79 GIT binary patch literal 17950 zcmYIu18}BI(Cr)Bwr$%sHnx+EoxHJaXJgy8?QAx-la1}%{qFtizf;w7`kCsfnyRVi z%;~OY}F3mgx5N^d4YWNkc9>J z_vMn(d&D{lMWHAuEPn zrDbJ#d^|j_zkmGrp_HAGp(n(_!4uq^nPJq|u3Nf1Nk-GDsEfrAt~wc1G>VIUVao-U zu}NS%zdKIZJ__E|0{1y@ zK=A&Bo_>=@NXY-OHZ&BjtD}SIV!h=rt#D-lJ>fQE+tiS05C`u&&W|5#eKE6w-d+}7 zmk&$my!ch!&&y=z7sgWWbs+)1@nMmz3xHczO;|r>=wCUj314JM-;segG~#`aiRB_M zzFK;xFJ;D~ea2oE#~0>oY{_WJ8E3$#w2H_2&5th59Tc)Y^p~$G#mX|D+e}gIum! zSS=V__@FxCPX_o9xo2ArLKYr_Zc7@APo-L|hW%tZ&DxL5qp5TSrwadJUc;+}!5(#R zQ3TCP`u-FK6eP3ad@EwY0!q=Vkdw?I?5b)!5_%N1a54EH{%raUoXfd6(*%E-cK6*I z$BFpCS26?u{c~TV$NRJ>wiH4w74vzp(YpLqRvnf3675_ z81L#{;rC<>*!BE2TzI|K={1qq5SqAetzlSs79usQcDr*FA#@jivOKO24A-L%k9kTA zZ+1Q^uY6Mms)tCQVq?yw9p`~@!g7`I2Q889HEpp?Z z$oP{&>kiPbdJpUR;e9($;seV_sw@ku_T8}t{$Zz52>7wrYWfW5+0t!{oBrJ{@I>wE3bMP?HprOeh|ga!{dg2MT8$W zGyt5xUf4^51n_>dPk+SM={2DC7^Z)s2CyE`N&h5Z>cHf=mPef!!~r{CrL2%0Vw}!F zPg4vbm#Z{4q;0+y{Xq~GqQ@h&9bPc~>)krBN8ImOr!b#Xta(gK+mC|W_&FP@_{uo9fVuk^H@ zO*Ni~K{DIIUc4GXa5o)8J~2B?oH=l~Ip4b6w|uF^uBiIP0TI-^oRivc`opKyC6xl) zu*ER6#`h#fryCQV;p7}?1+0mDOx^f#)a64zjF5lkSFRw~dXF&&Qhcw~Y~bU?-qMg! zZb)Uz(wlFJm?`nY@ZUo?H21<}vBr7;;cAYD!NLXBkhwi>SghIPcRy%%bS z$9l7yYCy#}OmUVMgGY>XMP+Wh$8i>>Nq?o zC`Lo8tNOrO4ZxfjmPJ1oiBZ%onNY%*l-6rXy3R`iHisAB^kdr*<{B;yZQ0J$-92axi#aRdO* zaYtHsMeLl<1M09w+*zw?b*U<6X>D*`a`mOI*e zPAx(h{M_)kK)fxotZWXQm@bis3$Q+MHc__W_6>+FL;&Fxr&wD3giULO{=G=TAzh{3 zQZ#B4wRBWmM*&(NIvj?E7tq0*x3%0q7_Rw?_6anxAz{>Lb9vdw_3AuXepNOo=B}Rc zQaQY1Gl3jlR)@l^p7-bAI2MqB9>eYeQln7TSYjx0%$IC$YolU9h7fd_GNbVTvj4o| zpQ?Ck^RYpJ0pVpN zETaEhBXiZI*o~QWq7*42gwTN!FFntT&nUUvVvbhLwe2~_5Mn8hIDI$E=!L}(QU4ql zFS{5A^z$5;I--G)LFjKqkLl?`6G|%0iTaFRW^5A|bmOuxZwxZJO8;DGLa5H7X3^G? zQG<=s4!3G!_};Fp5U+8{>qdEG~eDK?+|=3R9}wE(2oOgM)+W zT~SDg0u#D6`bs<)Osdv&q`TH*X9j3yW4L}*dS35MSWHuVg^}80S2f9K3(%%j#yD4` zGh^VL2mZ8gaSORm?GJD%2k=~D^59g`wb%?2soH2Df}eVY(ZBH1JI%`lkV3#fB{HXk zW^3)7))@}WFR57=HCPuTBnO1y%o{Vu1()K z$qk!Nj)y&HZV&yLKx(ACdLO07a2G1FkBFjKRJ+!v>>1|a<%QRq;23}ah(J?9QiC-^ zQZAOL@Z^S(-8j)MdKB6aFRu5{smbq$SVC?sGp`;L!$c4e>IDx|>4?yFDcJomf-K31 zHNbuqRy6)W7*vln39xM{lpOU@XU#+lPylj9r7Q4SFOh8HmVr3tJ=K(|Z{Q<^g?fjYZ5`r6qWdB8c_&q%V7P zd8yTSN(4SqpEOEHAK5`ynf! zt`|3T9{QZu8p41Y|T(quP zyvJRV4x)`&c)>EU)T7&zGKIiNoP6~(%s{?diNumBS_TkU%OS@$P*}BMa4aRl>bi?} z_Dsn4Ln8LUEQ%rGU}&yP?`;V3DSsm-13dKcx?KXPJf9*P$>uouW5o`$l z&78B%{WvUhjTd-3wdng(B0ge%z$Rz8$CTRV}R0cXRLFKog6qmu~(lx;FtJBTr# z&N&zaS&z6PW>%iOJGh^^ahktlCx}ARN^&0qh9?Gr=I=cJ!@Sr`P22XmKJX}YW(3P{ zQ_pV%!#2zPPo*y|f9Obvks$__$aTd+!+m-ukMpn*wbd=?IK}&A+uH=1XIo57@Z^A0 zn1r%6Cp;N*N?XP)UsgDw5Au%1+Mn#(Y)g;2&$&9gIqriP`#j&LHG+wRhwly6?XACz zeIIwnpV$8W@3-;(-D{kD8y9WYy;>L=X%M5dL^B+#UI09 zR3!+tjx%Z)^;3>{>e(t0J=~E8*>J_b)vlD%m4knu7i4C7p3bzJJ`J{QX5qtO8Uzna zL!f0lDxtMC*s>6Z#05Bwfjd9tmw&@&fv%yE&35iPs-vE1_PzZ%j&<-cy??CxHVuYZ ztX{WNf6FZ~o@Uz9c*?zN)D*R)B<1RJ;^9an z{l7nFWa9nxo=2E`3cMey47c{Ph8TkPun4x0aFyKcVMJR*8n_a#{|NrP$?)Ao;NFM3MhC*y$WZCFi=z+qYI(t<&_|916y22 zIR38$5NyiLArwn$mpRW-wqH#7HGa2PhT8%U^TE7o%=S(Tfr24#lyfn`d8?pQiqOCN z;Umh(P5=o-gSD~EQn@&dzZ0@--QR8RiQ`<#vhPB!e&>CuH5m^<5?B$0dNs+_JE@MB z#LX}!W_R_14Wl)s<$&=4paVr4Mx8d||Bj9daAx_YajoPkk=jtJ2I|GAk(%~UbTsy~ zhfod2{laBG>J9>5&p$CLED6IxHDf{OCd9We8q5tJMe@6;v-;zEVM=84s%Md>UZr*A zVDQ+RP@+tHwCm(w)XqW`SnWBG9Bx)!z*$uZBX5<1|yLPqc*Cxu67VRmx|!HlI{Mp>ZO{Pc2FU z@rj?q+5no~!9sXr{?#{*AnmH9@71?T2G7_jvEk17@=J!=^eOxc-1j zld$pgFDOE*+F=}K+Dal(JFcrYTGfkaDM(~E`9&w%37>uLMJvbF(~h?ht+BxAce z@xw>0;7E;QcJeeydEc`uxn`c1-Qcb;XS5&2EK|BFDdn8B8W2k?@C* zx8>uPgZPz#A(MrK!vKd|=eHm0SiLtATT+5|DAll2xOyep{U)SBz7jg8`lENum}8!e zFMx!tfOdzhaWP{dy@2Zy4kqt2IXBFyH3tGKY`?yMmHu|z{*HmN4IH&7Aqut*6P;Mi z^B*(<;Q`fdF5i%q#okfvfCZ~;z78Pfj0pj>)R9}=Vftk3rS=IUjFk@lZ*zu#FqoAvj=$e}JHTOI`lRSK?2 z=dyS@)j@+>6B)Ao1SoR}Rn)8k&?)x2C>mLH?69H=(?O*?x`ALgj9e=!mLg3Kk1e3) z`=n-XW6x2Vt`7nTAx1-|>kL|+r;hh@!`S-V(Da-L4tb;pIUd8_jAaU0`7Ky}e`ArX z)>4nK4#ChZqSt-7ltAT%<6$Cmn8G*mAA`qB2M?mR`Ea#c)x?X^r1(QtdR(eP6WrK5 z1OKpWe>gq^k2&L!L4EFA05A1H@YdqIxQ=!@DU9n#6o;O0ti#Rj z+jlf~;I;+TI3mKhiWK3*!u<5#1Y93^I?J>)AAy#dDqEGfE_ig)c7^dRbC8o3Fey5` zr-0ArYsbsUWLzy7l;pbCtCp4XPInL20@FYANx$IqQ-36#R2bjiZq+NW#p4Vot9>K{ z*|*&F^7XymV&lM^j|4OPzG+v)(3{To#vz035`vV=2dTMbCUGqRr*?NEBv|RjYBtwg$++j{H0+`Cmi15 zw8kFCXgwux8kiVHDV1TSAfALs7KEa54agQ>ab;Zw8!1R(b;)*;$b>@vUyVhtG4Hi} z*Y@rgn+ptvt$LDHm5rbu!)Ik&{+MJIDTOPqJVEP!IIz_5#K00qrl9D!seT$fXZ5Xh ze;hG6AoAbzqcjC0@|J7&`T5>oSPFIde*XQ|eJ)|rU+uovzqajt`{QqQ^Vfs>ZyZ@k z=5mjEm^bWnPrXUMn;{~0p^t$}%+4Bs@n#P2ICBPuDm%ZVos}3X zBG=JpAmW{peGVP}x@n`8L&)Vxdn^6>>$+>D_o=1ELr{|#mCjty|0Vytx@p#$>E#1r zM%Vw@V_?yZSLsI5tmxSXM-ztKHEmL9K|->#c%KJ4x7WSz>u+Cey4bW>eyaP5zK4Dp z(eBdwuLV%~12MgE^I(1M$nt1nK#?K*0yLTuHr7R9rsLE`Du2g@&-L-s;uIqXC^axE zxfZAdP{Q5t==rO^HT~c^cHrcoTR7!ZA3@@(+h%WPa2ut`p7%1`k-eo>RW(G!t52z8 zGPEj;i~M37bL`=F;_(upku!+42~NgZjwz$CBlRf9uGhc!6A$v-|21~UYF6<5g4-B1 zfyG&8%lR(@LT#>2FIhnN&qp&vtLWgLg49Q+UV`uH0e^1riad3=K5bq^BHW&`0BfGZ zn8&S|-XQ@P0c`=mjz$}M&HJSEZg9!!pgqrsel6R0;04QNBvtOJ&)=*aTZg^_#62Ev zPtXa-GvAkk3BT6a%<;H+BpSXrR(HEEQn+i@JMQnqc%KxH+5O>2mEkcm%^-mOo|6T| zl~pU%dMm5;qU@S{?t{;BK0<*Yz6J#3OWRYI=eqHm5{I#Z{><)hSSzT?t zk2SnJ%VxKfMMQ7!H{n8?e&@+~OQ}IUWV?ZBo(ycAmI~JI2mGh*A3+(ptP%upp>R5z z_8-T;KA(j!+GsgUi(H0`JZOTCthVE#5??;<9nDy~P6tI>E2KlZUa@_4TKzaC)oV7S5w+^w42FV_(X3=7QwmqIDYR;uc_9P;}Mk!J^oa(;oNo%CWO2t0CA=# zWbr+ofdtq&h6ZAZwqBiuCSdGn^?1$v^oifZH*XX;;lXRYxy&QryX{;_?qu@2jrQu6 z;h_!r>IYh{?ifAXtmb=p@X)qG5YAeTu>0$<8Xg`+?4lOon|>JKRp@tJbPa{ zYdLm56f2Tan;4>>A4}lCv(aUDA3~MAcmtmH414qArQ6Jw%f4Hrtx=oni4zK7Dya=z zF7VO9S`K^!nMDNp$X3osML`SzR$otYz3uOFpFb*U#Xb8>VDr8x$rrvR)^%ckMdKM@ zw2cEIFe^)si*e(Q@uSm*kMd||ADD!0Kw?d%al1$W*mxV2lQ;yxsMlXFpoF2abQnZT zLtN|8$sy1mY%#cZ=T&v1dk61Un>6~`{FfCjtdn8L??a+cso|d zjt+!R%>a$Ss9+YU>ZPm%u&6I_Dz<157GspmU8m0X%N;+L=SdfXk|7)i#62$D%cuJ3 zFupqDS}PpzFb)qfKDu~#09;%RD?2ojHcDd*2M!<5FuVR{5n}B4iS5L<)c3e4_fPKu z!S$)%O)!xa@v7Cyc_c-Of_?CiYwc1%K{obAMq~KW4IY<0ea|#V_{t0h{CR<}?1}0* z9fz7-R!=`b=He&C32h{ep84SUt=@&kd#_S#)#xZBYL^?{}BTfJodK?gdL0}30W zWlXx;sE`=jNX_Y05z(jBSeDAQ=NM5xS1(gQ>jqR?6%X{NJ#JI&nR=wJTGco{MaRje z^@BHv+KVSfscJ0ST;usDBnlPMw)qh8E|#$8vG=pS$8Ay>@Sjj$;YW&(_CKG_TV&Ag zok5}zf(-l zFJ8RJHx0vn5k;^ba-t-3><5`)Xxpqr?78lJ@9etj>{|Pmz`FSg@(kQ#UOOTJ-jhL`bq8tp`kS@ClZE%d z)C8AFGr^R)-uh9kf|<2>b=krst{KYzL8Otuj3EVCN18K5gZ`w=z``{%ytxN1-Jd`B z%g~d4TJlJ?0hUSB8FK+q?qan*8j3yQ3J2iv?fV?9>sM27_)G1=%suE22+Y~qT7pzI zcT2vZv6w}JE}zkOAZT53LB!wFv>mIU04kRmB>$J8r`I|E-mPp9o}(UxIGTc4_Tm1_ zwC5U6hr0o&w&ssCWc!%2!_02}$kDtVm21?E9c2x6Z3BEB_H+nD*m%+?(_Bam3>QhW z0n0_f%Cs0mu$|Dx!3kukJ6ZUU9Bwv)eln#^$37hP`T$^z!ddYp8t{5ET1 zb4Z_QNB717y@@*AmbM+gE*;2oQDt8KiQ(v+5ltv@?15yhJ)^OZWwd>X8q8LiyJj)@^o^k3&i-Dj2_5{qSVJF}g|Ujum$GalP2y zNimHUbuK@E5ifFK&UKAm1uMk8wyC?Q=ggWG-%Ba81rk$HdkmrXdBe=x7{BDy39Me< z{fk0&7B&U!xffQWN;~h3S-i*Ms^d=QN7V5@vGN;!KYy3Y_QqWSCLw3;RJx!>6WUl| z%BZ3+Y3LO)%?>d@X7e@60nxCl7I@6&zsQT&g!xR)KEH-vEw^1r_`wMdb@QxZ{1@!&`8)IERtXnsUl^L`-xlm{u|m53h#L1HLQqm@6^o36J+!xykJ=Z@&GN zowF6i7t%Cy{`q8+`5)ED^S8W{ke#9|L2DB1zG8qrCUXHP+y5k@DyAt+e z3G=L~nl)DQnN}X1=HIAwIY+=}EmQ%rLgt6WHC7=E<40f%UUa5O@=e_pWxoY@SwFlJWVg_3pQ>TMY-d z##WJ~;^myV2l`lL)RXnvZ1?V%qhvIu9i*eVh zbH*Gh1c9GLLSF}%b7U8lgO)r{L6E^elB9?z58;7JbxUikL~l3Yzy8*~=R)EjiFw-B ziQ&ww3Wc$vUb!G>(!gnFG0UOwiHc z1i<%QQt70aPF~F@U~cF|^p_XN8w-#wXVuTApafw;0sei3Z^lDP^cjkxirJ&OfO{P$ z#Y##1C2>`M0?A!~g2P80w90hj)FnP8d!U3>1(#eWG7d+;LoYgn6~ ze`a@svHN?@=XG~8@MO)sc81Ci-})n54Z&UsB+_ySzv1e}eXG-rm&-`)=%NRy|TC$bjSgF-M5q0 z{44Y&wr+7HmX3~_$<~c=j?;2HU(`jARmORqlA6*8G51k%GJE1nin<+jgh$Dr*{;CQ z(|u`}<)uWZOhoqsB~S=b8T%Y#9=6apxo<`W^KNm`lY{gMO1Eq=Tg*s_i89Nrf3@3| zo!8m67cm&G5P8WU*%z%QH3qCD$olz+SZkNp!xD6^Qf?ZXIi8dBc2w7s?0edWP{_cC zb%}BML;mP~=OLG{<7}7Ny-SO3G$a4hY~I;&`GqjAS|Y1a=k53 zM4N>1eCgqYURrHvmym!U_8s;Ua?(to;i53S()z3dTO{}!8-lamN79@@dO=i2Y+m%#eW$vyh3 zlbdg#R39{|s~X`$=1J2a77>;o{Y~Q8r*b{!9j-_baI|i_$ zn8wGRFnGcg0XH^wmUk8NavqzSLR*QtiA$YB%w;in-Q|Dcd@x#4ZF_Cl5$rth9Hk^@ zS@M6L@iv#c2w>-u*ABulDE+&St0^phb*3=qU9F}F=uPL{xHIx}{q8KY7e^dJ;p{IC zyw6am;3vtuKfVn=3EPZ$6gDYWi?}7 zGrviJcqV~t2QQ~8yZokg%TVY}a2er+EAo&ua2$y97(2yiGxvGeahc<>xkeE1{_1I$ z^Sp+kxys^B|4cwM(0k=pXCri@Ni@&FgQU_5gxCz;7sFdK&qEN5p16~!TP3~+nSA*< z)Vaqj%&gJBu}+Y|Ek)pl4hfP5Xh{JcQLr-RZP+-0PX1Bnns@wNVGl!ZoMMAZhl@x@ z<^UdB4Zs%06_vx2iVI?robkTzzB;+w5?dxLoDv>2OR1#e^|iczHvD3xi<*4!$BrVg z?Bl8HG%lNzM$z$V<$v~@M@D;H9q7*O{YTANLLWs!);rJX{uOBL2zZ>QxY<>61fC2C z9>`8<{si_vc1pTjd{PLqMlf2KnRt}{Hr(VQ8fW(3+t(x=Z9vkQxKL;WA>b`@{YAkt z6=r`*=Z2I zyya{sz0oY-tkCmJVt|d)H0O9sA9W4&TS5hzN;x6@941U=e6>mX!C#~xMvRJ0KwfmKqVFYQ+^bTDG z1-|8E>j|ORf-bpl{i>R6fuY3e}%0Jhgf9OyFLt_ zz;R<4gOf9eC0BARSEtBfH`5$ZxX^mJn*r1!_?!Y$-x{Mrb<5E?o_xOI z^TF^BL~p>5`18v_=MQcNP5var^0I3B+*)tU2dFzOw-xcdM(LMFBH=Xt;crhUTntJ8 z$GgWBqQ#gqz%@jqz>74*IMMF)Nu`M4VqPeH`ICwgwjYCu;>j$DixR~VLP3B7I56JE zWY(2e0%jN76LRjXK6aoay75bC{i}~nCFk-A%F<6JPzh?I`AL+fmKIXO`4+2OPOAu` z;<=qOr8RtIXwMSW9RJo4bgy^@WD4%ECBAw!E_ZhBVOJcxI${nyTEDRd-*hwd-=!nYrWsM;f2gP7?FsY z{SAH}&%fuqb8Cm{I?p!{wrlP;MidVpvLQc|{0g-dvGdqVjMa)yd}gxGWowQ9L{8hg0O|J`k$?7mnQ`pF?Rvl?9p? zECB8S+eBz89tFfybAGoWH(>@(do#d;g5(XDh`2mUWdx>PSRVh0uQMm?9i0Du4 zh`tE@r zXeQA_k@2lxiBIC3I>brwMqt0n)m*(PNUl&+OzlRbdVJIovq%uAL>Zs?iP~=p;oK|} z#=ef|_OFTuZ0^O^3M*J70In>4|C%Q-AP@f4q{&~Rl;Z?pAxZYCgFHZp_TK^Rm)>7H ze!aj2IDbVCC>0W7Ij~NQI;G33W+TxeEY^QSTVJ@TCj|%=JJ;e=X7|hs4Nb-~wKPU?b|Mn6V^_{TNa6u`Z%$KMwpNpc*-%V_;-*lCR$m7o#W-<@@^8{PxTAnR z-%Djev1QgCw^?IhMJTkoAMH!jtFXLIyIaa%Ogd9P%J454<^8av$#;Z{T(%Afd#V4rh@|k@%5%2 zo?)Eeh@RK28j+}QoyRhr!69HpXJD zC|)E$;2GvXb`6;f-(!}f2P+orN4ikjL^wa!W_`ow=Bs}dQ+NIJJLrdVYX7gaovG9YJ%%+J+Iu3o zezu3)9>Lpt>}#^j34Pyl-|EH^Ie58-uZ-#l=AAG(@4>G?_YeR@^JziyjQKi)z#Ss)KudwmiC?k)Bj1t7Kb~E$1c&^RLMc$d%h`)G=t>%nDU?LX*yVuye zQw$7D=^eLvk#qy-g8Z&`@1XpDPo`R0CCFWE1AhiZV?`*Bp)gItt0v;giDC|n1DL(q z;0i&J0yCnU!Idd`vLQ)8Pa@&z#&q+1OfwMr2l^pbu*CPf1D5wh8Hbog)biaT`S*@#Cw?XW?8aVbrh1;@?ID4q?HPib68c`ju}W-Z2)4!Gy=`1NSq z-tpCJlSRNsaqb+kXj(9H_ricQ3aS6Dvfm0D#5t2+S36c8m4gf$$Wyz`b6?m~qgu|b z0j81b9Ov8xe<(kpn4@IioC})P5$Ztq_$-#y+nNT7mA!Nk*QRr&P|FV24vewv8lIlp zE`;G0Mo)B)LzcP24eOUqt?Ktds%xR4hn+YD>|!}o5E|2S=1y!w&u$jn&thTCz>_i9 zOosJGE*_$%30bNauA^aO5AmyLQ_-bI3V>6BrC4#;JKVrG*r$DJig~~cknSN*DuCfY zEGrUDH_$+NpNrW&VWJr#rxoExS7d`g7;8;K5z^6V?R7+tm;ZI>aSw+LuUU|5=$){N z{L{R;D~;m;P3y~p$NJlHqyN|9gMFDP(fwK!(2tdiT%}lpA=8dlDwR}piJm>9F9FH z535G45b-%4OH424xr5V=V%2bFK1qEovz5XA@auq#MK_=7FOHa$hHYHMe2NQJ3`a43 zS2nW+wkjlu%x+03JxmmW>E%16o=-n=Y5d7VKP#6`rUM|SCxDPUBP@wb@`P8sBB_lHQc z;!^fLrz9Pc6FxfLo&K_!3=%rSR3Xx-3Kg1?AA2GBNl*$2Pi84l@#tM%R2Bw6vl^B_d{!Y@EqtbSQkzgiJ<%6!)O4rDraKX^pw{Ay3RW%Cw1xYI0-* z__1Np5QzM#n1r@yKJ@TdH%aV-ez>yqJ^p(os&0WCxj|e+8Gu{Be;ZNf-=4?0XCB%2JrJA>+Qu0?&pr-zq6*%!2LeehIiH%JQg-i%3EJzh2M2Kj#)yuV$Y*#Lu5AUeX>7Qld7atvE z*k?4Oj1zbrh8cuy_=#2uS}!of6AQyQitbp%EU3&n#jqiRj9uzWQOo_B!AT!Vs14$% z?`0@J2y@Vtn{)3;yhr6Dm2Y22uEccg(m|9gTC7mwRtP;7Ee~48nbM!SG!DhPEFtp) zVM4^pQHoYXT$tqVB#FaD1TJVnA|^arlJ_VFJxwX{kZJ+1hjG3^7JbwzYpvQ~PWqM! zd0_Bs?FRpUInHKDCxc{Hpmxp60|n(1qy++aw6Kqc>iGB4tHqQtCM5-n8b&o-2DjTZ zp>g4lYNI$(@cMBqS9F-cG$x3-DTo&O6~$U^P^%P9j3L5`c-GNl`5S#rX~L&MiD6Ov zz|EATp(x3IQE2KivGh<933E8xRiL&OBD3Dk+}y_JiwWB?GGOI~l}uH`7@y zB~>+9#KI04L|F$W<+-0nBdStVmcX0T0c)a>)TD6dX1HCn7MSxkNaDI6|0F!iGAGm1!E|l+a9qO*1XBDvcQvwJsc=qjWRCdl@6!KY?-;% zF8QE?I~_Y2k`;LZ9advof8f~UA1Gc)?=h@{>zP)*{oofwHDt__=QjG3b=C)q%g zs-oees1x2;NsD{s(}Y+rdedMAwC>Q+3dWWV>;P#tMi=x|%bDz#^6v{?sLmPa?1?aPi-3O2k4d_T{$zNxQVbuJxbY(Wqx!jw2e;IOs-|pP~z$(LJ+i( zygh`ukvYk60qqN!MJh(Ldt&udqrOGh^Q;Vg&bLv+1b3qMY%>HHUcc>n*qk`&yXHn zjj4E~kAE_H;n&6GfYvw}plGsvKG81*(^8ov6()poKX>bAHD=w3OpQ`2F^DF8Q`kCk z3AF7K9g`Yv*>16N7~lB~&E+|1WjjwAm4C*t$DW%bVnD-2AsFB^G{=SS8+o)nV0vts z1Sxo6R0G>yH8$BhL?HE^nTB9L#1?W=I}gFKoEAUgReL4t!)C6qhD6_oV72W1J}D(A{|KBFqr} zOvF*n6U{IGwD{~S6Yb#(w|T^g(6@2_!s%XG-ylYmP&iHME@nHRRFubb9Hxb2RsVQ} zn3AIS0aQYJIw(E3^+sxLq1e)rW$hdw5rX~mhDEKD5&-UQ2#$(iRH{yeJw*X6bFQd` z`4cM?J2yo{;+q2dxPd48+3Cimr)}Tu!!Y!LsE_EyPc+)4Pks^Im9gpc3mVfh-xy;a|tS^BHBrcHbvK$2o>M z!E(I~{^20vbhw^3zv|uviX1{W?(K;5D(I8qmJ>JFoZv4d?WVi}RIL*tCTQH4C$drumT3G(ql3I=@HZw>}?syc* zV0}1T%f2MrlV8`DJp03ht6W2$6@TMEk#$6Zg41~di!~{FvquW7zV-nNa)MEOX(XI= z_QP(YbvrEb4b`VMB*HgKAC0r|@{F7rZ+-{tg(f}SIK($f=zU+o092(Ppbfk8Ld1%y z&E7&*g#SD0D5ea7YZBqFR{$uMbE}ql7zl_&WVeGcmbu)eFv?9#B76{i5yDhSUjh}Q z;CNj7+|zWlCSMSg4uVCq{V4%aIe8dl63&{=YHfZ+{)s$eH#~8 z0ROO1L|^_ZY)q?A_Esx_kj0E6_OH;fB!~!SaXqur8f#+8cQRX?bON3_9w((=0t`J=HdFOT7r{_7ICC5mMRvwz?nN$$NcrcMB-dOVZ`#9 z0T%?t;c&wBH=gOYCc~Q`EWH-vp)m6mJr@L`BMZ$D_l&hH5abZF7jK?>2hSnA?FfhW z-j{+JB)j1mNY7wg6x~xyv%{h|&fg>qph%X=3;cI%od1Yod0J|1o3U`ok{w;JmYSaX zIG9cmwJC{r5=^Z7%x-2%umsKsoU|Y_V-h3~j<=X!sS*z`%zSlI*WFb%dE0vEun{EG zd7CDN#B+$HB=q^f_ph0;j$z1wmA>Qt%)?<8Bx1$=dCQ~iUl&XE>+8R!-M_UxPwRaH zI49`#e1!2?l2iL(Dn^-UysQVY$QU$}q|Ctqqc9{>0|$2Ck#>qS0eiLvKN5ZpF)r2< zjo~%k^dmO-lfc+`IytV2|3b#}RxPeJ(ijySCoZ8sz~e2)wzNbr|xUgaaJ}gKn?Nb?-A^x8LjRkW0I_RJlU-@3R{`%`r z#*ZDp2H*UB0e%l)wZ7`i%7h0*&kAs(C^{j_q+DdTJKXNLc4tRdSsy&Z5Mtg(Rk9iz zglPZ(1v5!RK~z5MDGU9OXNc+Pdxd^H;fG5-XFP7~;O_3OuV4_oABW)!4>{zJdHk`- z7I*u0?Yr;3bC{Iud_KZux}+^)UJ}?rwBctW1_8eJKaH8+;fFr(8#nhHgX7UzxJvjL z{3ygpxNKa`D+aC%G~<}a4dR?NfpRP+j9{M*lXjv+85ruJBfvqMj07S&Z^V0S#ndw* zjxz;GFDi;-b^hmiWUPb2rT`EPM&?{{79`wQH}yOy7x4 zpMq`|PX6ZbOCs~P-F6#atpA-xzn(WpN0W&EWUJd1il-;1_J^=hQXggVWUR~k>+NyJollk?k#8gY(q&d zM?T}3Cu7z{x$kL+iGz!=0V}i2W110ujp{y5oehz?939W)9Zz4k;XeM|nDIB^Dct3g zZF>n;*sIs9S+g0k3D~q;39!n}apq(4%^$dF(>xyb?{()h(qU~Q`lY0_20)gY>=w4gO9qv&;ib40WOScL2~~aA+W`U%!45vwQ-xeu5p3lM|)P<5;CZ zz)Iqy&hD0V?XvCQz^{Zwj}O+F7JuupV9lWufqZAX6MtP4 zPPow-HU!!3!r*3p8Du-)Zy7RFFK?G)1n=lLi0KC(&V&WdcC4gIS>_>?GadtA0iD0F zY11b1an>`g_#nIYTdK_78xJhV#ST%5bAuM6Rs#XErsV*@dBUW3zW$sX^D7osXhzL1 zpXVxo!{0(Lromu{xN{`>Fep;0RVQ*=HSpc&5o4oiJ>I@93Npc(S+ZTXQN0Q8?ZV?~f0gF&;M1A>A` z+4&qClyPI3jlk3-d)^10X`uJUK5Q0CgP#Lo*x}jdV)j|i&W&=mWoM@jCnP#Nry&oD zhm|h5fghHaYW&abuX_HsnJWY3-)8tfj{3(f@Z%Qv*WCjD4|iAEXC*S`q5uE@07*qo IM6N<$f-7Qu=l}o! literal 0 HcmV?d00001 diff --git a/docs-site/src/content/docs/es/getting-started/quickstart.md b/docs-site/src/content/docs/es/getting-started/quickstart.md index 4f045d47283..a9b92be1c93 100644 --- a/docs-site/src/content/docs/es/getting-started/quickstart.md +++ b/docs-site/src/content/docs/es/getting-started/quickstart.md @@ -23,7 +23,7 @@ ocx init `ocx init` te guía por estos pasos: -1. **Elegir un proveedor**: selecciona uno de los 113 preajustes del registro integrado o `custom` para introducir una URL base y un adaptador. +1. **Elegir un proveedor**: selecciona uno de los 114 preajustes del registro integrado o `custom` para introducir una URL base y un adaptador. 2. **Clave API**: pega una clave o indica una variable de entorno como `${ANTHROPIC_API_KEY}`. 3. **Modelo predeterminado**: para proveedores con clave, locales o personalizados, acepta el preajuste o introduce un identificador de modelo. 4. **Puerto del proxy**: `10100` de forma predeterminada. diff --git a/docs-site/src/content/docs/es/guides/api-key-catalog.md b/docs-site/src/content/docs/es/guides/api-key-catalog.md index c22fcec8abf..110c4558391 100644 --- a/docs-site/src/content/docs/es/guides/api-key-catalog.md +++ b/docs-site/src/content/docs/es/guides/api-key-catalog.md @@ -9,7 +9,7 @@ de cuentas y los proveedores locales siguen en esa página. Para rotar cuentas de suscripción, consulta [`reset-near-weighted`](/es/reference/configuration/providers/#reset-near-weighted) en los grupos OAuth de Codex y Anthropic. Los grupos de claves API usan sus propios [ajustes de selección de claves](/es/reference/configuration/providers/). -opencodex incluye 113 preajustes integrados: 91 con clave, 18 OAuth, tres locales y uno predeterminado de reenvío a ChatGPT. El selector **Añadir proveedor** abre el formulario del proveedor con clave, valida la credencial cuando el proveedor permite comprobarla y la guarda; cada proveedor tiene su propia validación. Entre ellos: +opencodex incluye 114 preajustes integrados: 92 con clave, 18 OAuth, tres locales y uno predeterminado de reenvío a ChatGPT. El selector **Añadir proveedor** abre el formulario del proveedor con clave, valida la credencial cuando el proveedor permite comprobarla y la guarda; cada proveedor tiene su propia validación. Entre ellos: **ClinePass** utiliza una clave API de Cline con el [catálogo oficial de suscripción](https://docs.cline.bot/getting-started/clinepass) y el [punto final de Chat Completions](https://docs.cline.bot/api/chat-completions), operados por Cline Bot Inc. bajo [los términos de Cline](https://cline.bot/tos). Un id enrutado como `cline-pass/cline-pass/kimi-k3` es intencional: el primer segmento selecciona el proveedor de opencodex, mientras que `cline-pass/kimi-k3` es el identificador de modelo completo que se envía aguas arriba. La cuota de ClinePass se comparte por cuenta entre límites rotativos de 5 horas, semanales y mensuales. Una sonda en vivo del 2026-08-13 verificó que todos los modelos estáticos de ClinePass aceptan `low`, `medium`, `high`, `xhigh` y `max` en el límite de entrada de la pasarela. opencodex conserva los niveles solicitados; cualquier normalización específica del backend sigue siendo responsabilidad de ClinePass. diff --git a/docs-site/src/content/docs/es/guides/providers.md b/docs-site/src/content/docs/es/guides/providers.md index 9e3b8c636cd..c2a8d4923d3 100644 --- a/docs-site/src/content/docs/es/guides/providers.md +++ b/docs-site/src/content/docs/es/guides/providers.md @@ -478,6 +478,16 @@ están en la página [Catálogo de proveedores con clave API](/es/guides/api-key +### RunAPI + +[RunAPI](https://runapi.co) es un patrocinador Standard. Selecciona **RunAPI** en **Añadir proveedor** +o ejecuta `ocx provider add runapi` e introduce una clave API de RunAPI. El preajuste usa Chat +Completions de OpenAI con la URL base `https://runapi.co/v1`, y el descubrimiento en vivo muestra +los modelos que tu clave puede usar. RunAPI es una pasarela unificada a más de 200 modelos de OpenAI, +Anthropic, Google, xAI, DeepSeek, Alibaba, Moonshot y otros, con pago por uso. RunAPI también sirve la +misma API en `https://runapi.host`, un espejo para redes que no llegan a `runapi.co`; para usarlo, +cambia la URL base del proveedor a `https://runapi.host/v1`. + ## 4. Proveedores locales Apunte opencodex a un servidor local compatible con OpenAI, normalmente con una clave en blanco: diff --git a/docs-site/src/content/docs/fr/getting-started/quickstart.md b/docs-site/src/content/docs/fr/getting-started/quickstart.md index 602ea289365..7bd670a556e 100644 --- a/docs-site/src/content/docs/fr/getting-started/quickstart.md +++ b/docs-site/src/content/docs/fr/getting-started/quickstart.md @@ -13,7 +13,7 @@ ocx init `ocx init` vous accompagne dans les étapes suivantes : -1. **Choix d’un fournisseur** — sélectionnez l’un des 113 préréglages intégrés au registre, ou `custom` pour saisir une +1. **Choix d’un fournisseur** — sélectionnez l’un des 114 préréglages intégrés au registre, ou `custom` pour saisir une URL de base et un adaptateur. 2. **Clé API** — collez une clé ou référencez une variable d’environnement telle que `${ANTHROPIC_API_KEY}`. 3. **Modèle par défaut** — pour les fournisseurs clés, locaux et personnalisés, acceptez le préréglage ou saisissez un identifiant de modèle. diff --git a/docs-site/src/content/docs/fr/guides/providers.md b/docs-site/src/content/docs/fr/guides/providers.md index 53c39ace106..e27c6c03c47 100644 --- a/docs-site/src/content/docs/fr/guides/providers.md +++ b/docs-site/src/content/docs/fr/guides/providers.md @@ -310,7 +310,7 @@ existante n'est pas concernée. ## 3. Catalogue des clés API -opencodex fournit 113 préréglages intégrés : 91 à clé, 18 OAuth, trois locaux et un préréglage par défaut de +opencodex fournit 114 préréglages intégrés : 92 à clé, 18 OAuth, trois locaux et un préréglage par défaut de transfert ChatGPT. Dans le tableau de bord, le sélecteur **Ajouter un fournisseur** ouvre le tableau de bord du fournisseur à clé, valide la clé et l'enregistre ; la validation dépend du fournisseur. Parmi les entrées notables : diff --git a/docs-site/src/content/docs/getting-started/quickstart.md b/docs-site/src/content/docs/getting-started/quickstart.md index 2873c05324e..978486e0057 100644 --- a/docs-site/src/content/docs/getting-started/quickstart.md +++ b/docs-site/src/content/docs/getting-started/quickstart.md @@ -21,7 +21,7 @@ ocx init `ocx init` walks you through: -1. **Pick a provider** — choose one of the 113 built-in registry presets or `custom` to type a base +1. **Pick a provider** — choose one of the 114 built-in registry presets or `custom` to type a base URL and adapter. 2. **API key** — paste a key, or reference an environment variable like `${ANTHROPIC_API_KEY}`. 3. **Default model** — for key, local, and custom providers, accept the preset or enter a model id. diff --git a/docs-site/src/content/docs/guides/api-key-catalog.md b/docs-site/src/content/docs/guides/api-key-catalog.md index 2f9d30d437f..f17effbf93c 100644 --- a/docs-site/src/content/docs/guides/api-key-catalog.md +++ b/docs-site/src/content/docs/guides/api-key-catalog.md @@ -9,7 +9,7 @@ stay on that page. For subscription account rotation, see [`reset-near-weighted`](/reference/configuration/providers/#reset-near-weighted) for the Codex and Anthropic OAuth pools. API-key pools use their own [key selection settings](/reference/configuration/providers/). -opencodex ships 113 built-in presets: 91 key-based, 18 OAuth, three local, and one default +opencodex ships 114 built-in presets: 92 key-based, 18 OAuth, three local, and one default ChatGPT-forward preset. The dashboard's **Add provider** picker opens a key provider's dashboard, validates the key where the provider can check one, and stores it. Notable entries: diff --git a/docs-site/src/content/docs/guides/providers.md b/docs-site/src/content/docs/guides/providers.md index 4464bc0b88b..8471f7e2c74 100644 --- a/docs-site/src/content/docs/guides/providers.md +++ b/docs-site/src/content/docs/guides/providers.md @@ -815,6 +815,16 @@ are on the [API-key catalog](/guides/api-key-catalog/) page. Its sections: - [GPT-5.6 preview paths](/guides/api-key-catalog/#gpt-56-preview-paths) - [Ollama Cloud](/guides/api-key-catalog/#ollama-cloud) +### RunAPI + +[RunAPI](https://runapi.co) is a Standard sponsor. Select **RunAPI** in **Add provider** or +run `ocx provider add runapi` and enter a RunAPI API key. The preset uses OpenAI Chat +Completions with the base URL `https://runapi.co/v1`, and live discovery lists the models your +key can use. RunAPI is a unified gateway to 200+ models from OpenAI, Anthropic, Google, xAI, +DeepSeek, Alibaba, Moonshot and others, billed pay-as-you-go. RunAPI also serves the same API at +`https://runapi.host`, a mirror for networks that cannot reach `runapi.co`; to use it, change the +provider's base URL to `https://runapi.host/v1`. + ## 4. Local providers Point opencodex at a local OpenAI-compatible server — usually with a blank key: diff --git a/docs-site/src/content/docs/ja/getting-started/quickstart.md b/docs-site/src/content/docs/ja/getting-started/quickstart.md index 84f7da28caf..9013e36b79d 100644 --- a/docs-site/src/content/docs/ja/getting-started/quickstart.md +++ b/docs-site/src/content/docs/ja/getting-started/quickstart.md @@ -18,7 +18,7 @@ ocx init `ocx init` では次の手順を説明します。 -1. **プロバイダーを選択してください** — 113 個の組み込みレジストリプリセットのいずれか、または `custom` を選択してベース URL とアダプターを入力します。 +1. **プロバイダーを選択してください** — 114 個の組み込みレジストリプリセットのいずれか、または `custom` を選択してベース URL とアダプターを入力します。 2. **API キー** — キーを貼り付けるか、`${ANTHROPIC_API_KEY}` のような環境変数を参照します。 3. **デフォルト モデル** — キー、ローカル、カスタム プロバイダーの場合は、プリセットを受け入れるか、モデル ID を入力します。 4. **プロキシ ポート** — デフォルトは `10100` です。 diff --git a/docs-site/src/content/docs/ja/guides/providers.md b/docs-site/src/content/docs/ja/guides/providers.md index e0e46c7c6ea..d7adaf3b968 100644 --- a/docs-site/src/content/docs/ja/guides/providers.md +++ b/docs-site/src/content/docs/ja/guides/providers.md @@ -210,7 +210,7 @@ Kiro のログインには Kiro CLI が必要です。Unix では `curl -fsSL ht ## 3. API キーカタログ -opencodex には組み込みプリセットが 113 個含まれています。キー方式 91、OAuth 18、ローカル 3、 +opencodex には組み込みプリセットが 114 個含まれています。キー方式 92、OAuth 18、ローカル 3、 デフォルト ChatGPT 転送プリセット 1 です。ダッシュボードの **Add provider** ピッカーはキー発行ページを開き、 入力したキーを検証した後保存します(検証はプロバイダー固有です)。主な項目は以下のとおりです: diff --git a/docs-site/src/content/docs/ko/getting-started/quickstart.md b/docs-site/src/content/docs/ko/getting-started/quickstart.md index 00b7a092bce..10b0d95769d 100644 --- a/docs-site/src/content/docs/ko/getting-started/quickstart.md +++ b/docs-site/src/content/docs/ko/getting-started/quickstart.md @@ -18,7 +18,7 @@ ocx init `ocx init`은 다음 과정을 안내합니다: -1. **프로바이더 선택** — 내장 레지스트리 프리셋 113개 중 하나를 고르거나 `custom`을 선택해 base URL과 adapter를 직접 입력합니다. +1. **프로바이더 선택** — 내장 레지스트리 프리셋 114개 중 하나를 고르거나 `custom`을 선택해 base URL과 adapter를 직접 입력합니다. 2. **API 키** — 키를 붙여넣거나 `${ANTHROPIC_API_KEY}` 같은 환경 변수를 참조합니다. 3. **기본 모델** — 키, 로컬, custom 프로바이더에서는 프리셋을 그대로 쓰거나 모델 ID를 직접 입력합니다. 4. **프록시 포트** — 기본값은 `10100`입니다. diff --git a/docs-site/src/content/docs/ko/guides/providers.md b/docs-site/src/content/docs/ko/guides/providers.md index f4b027c5b17..12b9cd9552f 100644 --- a/docs-site/src/content/docs/ko/guides/providers.md +++ b/docs-site/src/content/docs/ko/guides/providers.md @@ -212,7 +212,7 @@ Kiro 로그인에는 Kiro CLI가 필요합니다. Unix에서는 `curl -fsSL http ## 3. API 키 카탈로그 -opencodex에는 빌트인 프리셋이 113개 들어 있습니다. 키 방식 91개, OAuth 18개, 로컬 3개, +opencodex에는 빌트인 프리셋이 114개 들어 있습니다. 키 방식 92개, OAuth 18개, 로컬 3개, 기본 ChatGPT 포워드 프리셋 1개입니다. 대시보드의 **Add provider** 선택기는 키 발급 페이지를 열고, 입력한 키를 검증한 뒤 저장합니다(검증은 프로바이더별로 다릅니다). 주요 항목은 다음과 같습니다: diff --git a/docs-site/src/content/docs/ru/getting-started/quickstart.md b/docs-site/src/content/docs/ru/getting-started/quickstart.md index b435866488b..9c66af66383 100644 --- a/docs-site/src/content/docs/ru/getting-started/quickstart.md +++ b/docs-site/src/content/docs/ru/getting-started/quickstart.md @@ -18,7 +18,7 @@ ocx init `ocx init` проведёт вас по следующим шагам: -1. **Выбор провайдера** — выберите один из 113 встроенных пресетов реестра или `custom`, чтобы +1. **Выбор провайдера** — выберите один из 114 встроенных пресетов реестра или `custom`, чтобы ввести базовый URL и адаптер вручную. 2. **API-ключ** — вставьте ключ или сошлитесь на переменную окружения вида `${ANTHROPIC_API_KEY}`. 3. **Модель по умолчанию** — для провайдеров с ключом, локальных и `custom` примите значение из diff --git a/docs-site/src/content/docs/ru/guides/providers.md b/docs-site/src/content/docs/ru/guides/providers.md index 6a4c65a89e3..b2e11ff6b5f 100644 --- a/docs-site/src/content/docs/ru/guides/providers.md +++ b/docs-site/src/content/docs/ru/guides/providers.md @@ -222,7 +222,7 @@ Inline JSON и лишние позиционные аргументы откло ## 3. Каталог API-ключей -opencodex поставляется с 113 встроенными пресетами: 91 на основе ключей, 18 OAuth, три локальных и +opencodex поставляется с 114 встроенными пресетами: 92 на основе ключей, 18 OAuth, три локальных и один пресет ChatGPT-форварда по умолчанию. Селектор **Add provider** в дашборде открывает страницу выдачи ключей провайдера, проверяет ключ и сохраняет его; проверка зависит от провайдера. Наиболее заметные записи: diff --git a/docs-site/src/content/docs/tr/getting-started/quickstart.md b/docs-site/src/content/docs/tr/getting-started/quickstart.md index 674db589571..0fec7366913 100644 --- a/docs-site/src/content/docs/tr/getting-started/quickstart.md +++ b/docs-site/src/content/docs/tr/getting-started/quickstart.md @@ -13,7 +13,7 @@ ocx init `ocx init` adım adım size rehberlik eder: -1. **Bir sağlayıcı seçin** — yerleşik kayıt defterindeki 113 önayardan birini +1. **Bir sağlayıcı seçin** — yerleşik kayıt defterindeki 114 önayardan birini veya bir temel URL ile adaptör yazmak için `custom` seçeneğini belirleyin. 2. **API anahtarı** — bir anahtar yapıştırın veya `${ANTHROPIC_API_KEY}` gibi bir ortam değişkenine başvurun. diff --git a/docs-site/src/content/docs/tr/guides/providers.md b/docs-site/src/content/docs/tr/guides/providers.md index 5e41868ee1d..cf43259e362 100644 --- a/docs-site/src/content/docs/tr/guides/providers.md +++ b/docs-site/src/content/docs/tr/guides/providers.md @@ -342,7 +342,7 @@ olmayan bir makineden oturum açmak bundan etkilenmez. ## 3. API anahtarı kataloğu -opencodex 113 yerleşik önayar ile birlikte gelir: 91 anahtar tabanlı, 18 +opencodex 114 yerleşik önayar ile birlikte gelir: 92 anahtar tabanlı, 18 OAuth, üç yerel ve bir varsayılan ChatGPT iletme önayarı. Kontrol panelinin **Sağlayıcı ekle** seçicisi bir anahtar sağlayıcısının kontrol panelini açar, anahtarı doğrular ve saklar; doğrulama sağlayıcıya özgüdür. Dikkate değer diff --git a/docs-site/src/content/docs/zh-cn/getting-started/quickstart.md b/docs-site/src/content/docs/zh-cn/getting-started/quickstart.md index 4d85a88a4d3..54cadb4456e 100644 --- a/docs-site/src/content/docs/zh-cn/getting-started/quickstart.md +++ b/docs-site/src/content/docs/zh-cn/getting-started/quickstart.md @@ -18,7 +18,7 @@ ocx init `ocx init` 会引导你完成: -1. **选择 provider** — 从内置 registry 的 113 个预设中选择一个,或选择 `custom` 手动输入 base URL 和 adapter。 +1. **选择 provider** — 从内置 registry 的 114 个预设中选择一个,或选择 `custom` 手动输入 base URL 和 adapter。 2. **API key** — 粘贴一个 key,或引用一个环境变量,例如 `${ANTHROPIC_API_KEY}`。 3. **默认模型** — 对于 key、本地和 custom provider,接受预设值或输入模型 id。 4. **代理端口** — 默认为 `10100`。 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 8292d0fa675..d728b71b769 100644 --- a/docs-site/src/content/docs/zh-cn/guides/providers.md +++ b/docs-site/src/content/docs/zh-cn/guides/providers.md @@ -222,7 +222,7 @@ API Key 提供商,也不负责让 WorkBuddy 桌面客户端使用 OpenCodex ## 3. API 密钥目录 -opencodex 内置 113 个预设:91 个密钥预设、18 个 OAuth 预设、3 个本地预设,以及 1 个默认的 +opencodex 内置 114 个预设:92 个密钥预设、18 个 OAuth 预设、3 个本地预设,以及 1 个默认的 ChatGPT 转发预设。仪表盘的 **Add provider** 选择器会打开密钥提供商的控制台,验证并保存密钥。 验证因提供商而异。主要条目包括: diff --git a/docs-site/src/content/docs/zh-tw/getting-started/quickstart.md b/docs-site/src/content/docs/zh-tw/getting-started/quickstart.md index 1dd6c8bde30..0d33d047922 100644 --- a/docs-site/src/content/docs/zh-tw/getting-started/quickstart.md +++ b/docs-site/src/content/docs/zh-tw/getting-started/quickstart.md @@ -13,7 +13,7 @@ ocx init `ocx init` 會引導你完成: -1. **選擇 provider** —— 從內建 registry 的 113 個預設中選擇一個,或選擇 `custom` 手動輸入 +1. **選擇 provider** —— 從內建 registry 的 114 個預設中選擇一個,或選擇 `custom` 手動輸入 base URL 和 adapter。 2. **API key** —— 貼上一個 key,或引用一個環境變數,例如 `${ANTHROPIC_API_KEY}`。 3. **預設模型** —— 對於 API key、本機和 custom provider,可接受預設值或輸入模型 id。 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 41811a72da6..67df5b65b21 100644 --- a/docs-site/src/content/docs/zh-tw/guides/providers.md +++ b/docs-site/src/content/docs/zh-tw/guides/providers.md @@ -264,7 +264,7 @@ database 並移除目前的 WAL、SHM 與 journal sidecar,再發布先前的 s ## 3. API 金鑰目錄 -opencodex 內建 113 個 preset:91 個 key-based、18 個 OAuth、3 個 local,以及 1 個預設 ChatGPT-forward +opencodex 內建 114 個 preset:92 個 key-based、18 個 OAuth、3 個 local,以及 1 個預設 ChatGPT-forward preset。儀表板的 **Add provider** picker 會開啟 key provider 的 dashboard、驗證金鑰並儲存;驗證方式 依 provider 而異。主要條目如下。 diff --git a/package.json b/package.json index 2a9de5f4a41..d7a70991f55 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "assets/sponsors/orcarouter.png", "assets/sponsors/tokenlab-light.png", "assets/sponsors/tokenlab-dark.png", + "assets/sponsors/runapi.png", "README.md", "SPONSORS.md", "AGENTS_INSTALL.md", diff --git a/readme/README.es.md b/readme/README.es.md index 660543643e7..cbe512fef5f 100644 --- a/readme/README.es.md +++ b/readme/README.es.md @@ -152,6 +152,10 @@ Los patrocinadores permiten mantener opencodex al día con los cambios de protoc TokenLab Gracias a TokenLab por patrocinar este proyecto. TokenLab ofrece a los agentes de programación una clave API para los principales modelos. Admite OpenAI Responses y Chat Completions, Anthropic Messages y los formatos nativos de Gemini, con streaming y llamadas a herramientas. También proporciona un servidor MCP y skills para facilitar la integración. Puedes elegir el modo de entrega y pagar según el uso. Selecciona TokenLab en Añadir proveedor o ejecuta ocx provider add tokenlab.
    TokenLab unifica el acceso a varios modelos con una clave API, admite los protocolos y herramientas indicados y permite integrar el servidor MCP y las skills en los flujos de trabajo existentes, con modos de entrega opcionales y pago por uso. + +RunAPI +Gracias a RunAPI por patrocinar este proyecto. RunAPI es una pasarela unificada de API de IA: una sola clave API abre un catálogo de más de 200 modelos de OpenAI, Anthropic, Google, xAI, DeepSeek, Alibaba, Moonshot y otros, servidos mediante los formatos OpenAI Chat Completions y Responses, Anthropic Messages y la API nativa de Gemini; los formatos disponibles varían según el modelo. El enrutamiento inteligente envía cada solicitud a un nodo de proveedor rápido y estable, con conmutación automática ante fallos, y el pago es por uso, normalmente muy por debajo de las tarifas estándar. Selecciona RunAPI en Añadir proveedor o ejecuta ocx provider add runapi. + diff --git a/readme/README.fr.md b/readme/README.fr.md index 607600439fa..91411537bc3 100644 --- a/readme/README.fr.md +++ b/readme/README.fr.md @@ -159,6 +159,10 @@ Voir [SPONSORS.md](../SPONSORS.md). TokenLab Merci à TokenLab pour son soutien à ce projet ! TokenLab donne aux agents de code une seule clé API pour les principaux modèles, avec les formats OpenAI Responses et Chat Completions, Anthropic Messages et l'API native de Gemini, streaming et appel d'outils compris. Il fournit aussi un serveur MCP et des Skills pour agents afin de faciliter l'intégration. Choisissez votre mode de livraison et payez à l'usage. Choisissez TokenLab dans le sélecteur Add provider ou exécutez ocx provider add tokenlab.
    TokenLab 为编程智能体提供统一的多模型 API,一枚 API Key 即可接入主流模型,支持 OpenAI Responses、Chat Completions、Anthropic Messages 和 Gemini 原生 API 格式,以及流式输出和工具调用。同时提供 MCP 服务器和 Agent Skills,方便接入现有工作流;交付模式可选,按量付费。 + +RunAPI +Merci à RunAPI de sponsoriser ce projet ! RunAPI est une passerelle d'API d'IA unifiée : une seule clé d'API ouvre un catalogue de plus de 200 modèles d'OpenAI, Anthropic, Google, xAI, DeepSeek, Alibaba, Moonshot et d'autres, servis via les formats OpenAI Chat Completions et Responses, Anthropic Messages et l'API native de Gemini ; les formats disponibles varient selon le modèle. Le routage intelligent envoie chaque requête vers un nœud fournisseur rapide et stable, avec basculement automatique, et la facturation se fait à l'usage, généralement bien en dessous des tarifs standard. Choisissez RunAPI dans le sélecteur Add provider ou exécutez ocx provider add runapi. + diff --git a/readme/README.ja.md b/readme/README.ja.md index a7477ff89ee..a67f8b53396 100644 --- a/readme/README.ja.md +++ b/readme/README.ja.md @@ -156,6 +156,10 @@ ocx start # プロキシとダッシュボードが loca TokenLab このプロジェクトを支援してくださる TokenLab に感謝します。TokenLab はコーディングエージェントに主要モデル向けの API キーを 1 つだけ提供し、OpenAI Responses と Chat Completions、Anthropic Messages、Gemini ネイティブ API の各形式に、ストリーミングとツール呼び出し込みで対応しています。MCP サーバーとエージェント Skills も用意されており、簡単に組み込めます。配信モードを選び、使った分だけ支払えます。Add provider ピッカーで TokenLab を選ぶか ocx provider add tokenlab を実行してください。
    TokenLab 为编程智能体提供统一的多模型 API,一枚 API Key 即可接入主流模型,支持 OpenAI Responses、Chat Completions、Anthropic Messages 和 Gemini 原生 API 格式,以及流式输出和工具调用。同时提供 MCP 服务器和 Agent Skills,方便接入现有工作流;交付模式可选,按量付费。 + +RunAPI +このプロジェクトを支援してくださる RunAPI に感謝します。RunAPI は統合 AI API ゲートウェイで、1 つの API キーで OpenAI、Anthropic、Google、xAI、DeepSeek、Alibaba、Moonshot などの 200 以上のモデルのカタログを利用でき、OpenAI Chat Completions と Responses、Anthropic Messages、Gemini ネイティブ API の各形式で提供されます(使える形式はモデルによって異なります)。スマートルーティングがリクエストごとに高速で安定したプロバイダーノードを選び、障害時は自動で切り替えます。料金は使った分だけの従量課金で、多くの場合は標準価格より大幅に安くなります。Add provider ピッカーで RunAPI を選ぶか ocx provider add runapi を実行してください。 + diff --git a/readme/README.ko.md b/readme/README.ko.md index e0c35fad868..206f8ad9aaf 100644 --- a/readme/README.ko.md +++ b/readme/README.ko.md @@ -155,6 +155,10 @@ ocx start # 프록시 + 대시보드: localhost:10100 TokenLab TokenLab의 후원에 감사합니다. TokenLab은 코딩 에이전트에게 주요 모델용 API 키 하나를 제공하며, OpenAI Responses와 Chat Completions, Anthropic Messages, Gemini 네이티브 API 형식을 스트리밍과 도구 호출까지 지원합니다. MCP 서버와 에이전트 Skills도 제공해 쉽게 연동할 수 있습니다. 전달 모드를 고르고 쓴 만큼 결제하세요. Add provider 선택기에서 TokenLab을 고르거나 ocx provider add tokenlab을 실행하세요.
    TokenLab 为编程智能体提供统一的多模型 API,一枚 API Key 即可接入主流模型,支持 OpenAI Responses、Chat Completions、Anthropic Messages 和 Gemini 原生 API 格式,以及流式输出和工具调用。同时提供 MCP 服务器和 Agent Skills,方便接入现有工作流;交付模式可选,按量付费。 + +RunAPI +이 프로젝트를 후원해 주시는 RunAPI에 감사합니다. RunAPI는 통합 AI API 게이트웨이로, API 키 하나로 OpenAI, Anthropic, Google, xAI, DeepSeek, Alibaba, Moonshot 등 200개 이상 모델의 카탈로그를 쓸 수 있으며, OpenAI Chat Completions와 Responses, Anthropic Messages, Gemini 네이티브 API 형식으로 제공됩니다(쓸 수 있는 형식은 모델마다 다릅니다). 스마트 라우팅이 요청마다 빠르고 안정적인 공급자 노드를 고르고 장애가 나면 자동으로 전환하며, 요금은 쓴 만큼 내는 방식으로 대개 표준 요금보다 훨씬 저렴합니다. Add provider 선택기에서 RunAPI를 고르거나 ocx provider add runapi를 실행하세요. + diff --git a/readme/README.ru.md b/readme/README.ru.md index 72ddf55e9eb..2b192dd7cc3 100644 --- a/readme/README.ru.md +++ b/readme/README.ru.md @@ -160,6 +160,10 @@ ocx start # прокси + панель управлен TokenLab Благодарим TokenLab за спонсорскую поддержку проекта! TokenLab даёт агентам для программирования один API-ключ для ведущих моделей с поддержкой форматов OpenAI Responses и Chat Completions, Anthropic Messages и нативного API Gemini, включая стриминг и вызов инструментов. Также доступны MCP-сервер и Skills для агентов, чтобы упростить интеграцию. Выберите режим доставки и платите по мере использования. Выберите TokenLab в селекторе Add provider или выполните ocx provider add tokenlab.
    TokenLab 为编程智能体提供统一的多模型 API,一枚 API Key 即可接入主流模型,支持 OpenAI Responses、Chat Completions、Anthropic Messages 和 Gemini 原生 API 格式,以及流式输出和工具调用。同时提供 MCP 服务器和 Agent Skills,方便接入现有工作流;交付模式可选,按量付费。 + +RunAPI +Спасибо RunAPI за поддержку проекта! RunAPI — единый шлюз к API ИИ: один API-ключ открывает каталог из более чем 200 моделей OpenAI, Anthropic, Google, xAI, DeepSeek, Alibaba, Moonshot и других, доступных через форматы OpenAI Chat Completions и Responses, Anthropic Messages и нативный API Gemini; набор форматов зависит от модели. Умная маршрутизация отправляет каждый запрос на быстрый и стабильный узел поставщика с автоматическим переключением при сбоях, а оплата идёт по факту использования, обычно заметно ниже стандартных цен. Выберите RunAPI в селекторе Add provider или выполните ocx provider add runapi. + diff --git a/readme/README.tr.md b/readme/README.tr.md index 835c6dd71b7..583541f27cf 100644 --- a/readme/README.tr.md +++ b/readme/README.tr.md @@ -159,6 +159,10 @@ Her yukarı akış protokol değişiminde opencodex'in bakımını sürdürebilm TokenLab Bu projeye sponsor olduğu için TokenLab'a teşekkürler! TokenLab, kodlama ajanlarına önde gelen modeller için tek bir API anahtarı sunar; OpenAI Responses ve Chat Completions, Anthropic Messages ve Gemini'nin yerel API biçimleri, akış ve araç çağırma ile desteklenir. Kolay entegrasyon için bir MCP sunucusu ve ajan Skills'i de sağlar. Teslimat modunuzu seçin, kullandıkça ödeyin. Add provider seçicisinden TokenLab seçin ya da ocx provider add tokenlab çalıştırın.
    TokenLab 为编程智能体提供统一的多模型 API,一枚 API Key 即可接入主流模型,支持 OpenAI Responses、Chat Completions、Anthropic Messages 和 Gemini 原生 API 格式,以及流式输出和工具调用。同时提供 MCP 服务器和 Agent Skills,方便接入现有工作流;交付模式可选,按量付费。 + +RunAPI +Bu projeye sponsor olduğu için RunAPI'ye teşekkürler! RunAPI birleşik bir yapay zekâ API ağ geçididir: tek bir API anahtarı OpenAI, Anthropic, Google, xAI, DeepSeek, Alibaba, Moonshot ve diğerlerinden 200'den fazla modellik bir kataloğu açar; modeller OpenAI Chat Completions ve Responses, Anthropic Messages ve Gemini'nin yerel API biçimleriyle sunulur ve kullanılabilen biçimler modele göre değişir. Akıllı yönlendirme her isteği hızlı ve kararlı bir sağlayıcı düğümüne gönderir ve arızada otomatik olarak geçiş yapar; ücretlendirme kullandıkça öde şeklindedir ve genellikle standart fiyatların epey altındadır. Add provider seçicisinden RunAPI seçin ya da ocx provider add runapi çalıştırın. + diff --git a/readme/README.zh-CN.md b/readme/README.zh-CN.md index 616d75e3f19..603ad6d828a 100644 --- a/readme/README.zh-CN.md +++ b/readme/README.zh-CN.md @@ -156,6 +156,10 @@ WidgetKit 扩展,可显示代理状态、今日用量和提供商配额;它 TokenLab 感谢 TokenLab 赞助本项目!TokenLab 为编程智能体提供统一的多模型 API,一枚 API Key 即可接入主流模型,支持 OpenAI Responses、Chat Completions、Anthropic Messages 和 Gemini 原生 API 格式,以及流式输出和工具调用。同时提供 MCP 服务器和 Agent Skills,方便接入现有工作流;交付模式可选,按量付费。在添加提供商选择器中选择 TokenLab,或运行 ocx provider add tokenlab。 + +RunAPI +感谢 RunAPI 赞助本项目!RunAPI 是统一的 AI API 网关,一个 API Key 即可使用涵盖 OpenAI、Anthropic、Google、xAI、DeepSeek、阿里巴巴、Moonshot 等厂商 200 多个模型的目录,通过 OpenAI Chat Completions 与 Responses、Anthropic Messages 以及 Gemini 原生 API 格式提供(可用格式因模型而异)。智能路由会为每个请求选择快速稳定的供应商节点,并在故障时自动切换;按量付费,价格通常远低于官方标准价。在添加提供商选择器中选择 RunAPI,或运行 ocx provider add runapi。 + diff --git a/readme/README.zh-TW.md b/readme/README.zh-TW.md index b73935cbda3..cf5f2051af7 100644 --- a/readme/README.zh-TW.md +++ b/readme/README.zh-TW.md @@ -156,6 +156,10 @@ WidgetKit 擴充套件,可顯示代理狀態、今日用量與供應商配額 TokenLab 感謝 TokenLab 贊助本專案!TokenLab 為程式設計智慧體提供統一的多模型 API,一把 API Key 即可接入主流模型,支援 OpenAI Responses、Chat Completions、Anthropic Messages 和 Gemini 原生 API 格式,以及串流輸出和工具呼叫。同時提供 MCP 伺服器和 Agent Skills,方便接入現有工作流程;交付模式可選,按量付費。在「新增供應商」選擇器選 TokenLab,或執行 ocx provider add tokenlab。 + +RunAPI +感謝 RunAPI 贊助本專案!RunAPI 是統一的 AI API 閘道,一組 API 金鑰即可使用涵蓋 OpenAI、Anthropic、Google、xAI、DeepSeek、阿里巴巴、Moonshot 等廠商 200 多個模型的目錄,透過 OpenAI Chat Completions 與 Responses、Anthropic Messages 以及 Gemini 原生 API 格式提供(可用格式因模型而異)。智慧路由會為每個請求選擇快速穩定的供應商節點,並在故障時自動切換;按量計費,價格通常遠低於官方標準價。在「新增供應商」選擇器選 RunAPI,或執行 ocx provider add runapi。 + diff --git a/readme/i18n-manifest.json b/readme/i18n-manifest.json index 1fe22b82896..39d2e58683c 100644 --- a/readme/i18n-manifest.json +++ b/readme/i18n-manifest.json @@ -6,49 +6,49 @@ "file": "readme/README.fr.md", "label": "Français", "docsPath": "fr", - "sourceSha256": "3285b30e16e2d695fdb4347b4622a3c85ec34ecb9fe0562ab19006808cab07ad" + "sourceSha256": "7ca38ee4232f7f7fcdd0537c866656109faf70748f181c8e4d8c2b3e7f2022c9" }, "ko": { "file": "readme/README.ko.md", "label": "한국어", "docsPath": "ko", - "sourceSha256": "3285b30e16e2d695fdb4347b4622a3c85ec34ecb9fe0562ab19006808cab07ad" + "sourceSha256": "7ca38ee4232f7f7fcdd0537c866656109faf70748f181c8e4d8c2b3e7f2022c9" }, "zh-CN": { "file": "readme/README.zh-CN.md", "label": "简体中文", "docsPath": "zh-cn", - "sourceSha256": "3285b30e16e2d695fdb4347b4622a3c85ec34ecb9fe0562ab19006808cab07ad" + "sourceSha256": "7ca38ee4232f7f7fcdd0537c866656109faf70748f181c8e4d8c2b3e7f2022c9" }, "zh-TW": { "file": "readme/README.zh-TW.md", "label": "繁體中文", "docsPath": "zh-tw", - "sourceSha256": "3285b30e16e2d695fdb4347b4622a3c85ec34ecb9fe0562ab19006808cab07ad" + "sourceSha256": "7ca38ee4232f7f7fcdd0537c866656109faf70748f181c8e4d8c2b3e7f2022c9" }, "ru": { "file": "readme/README.ru.md", "label": "Русский", "docsPath": "ru", - "sourceSha256": "3285b30e16e2d695fdb4347b4622a3c85ec34ecb9fe0562ab19006808cab07ad" + "sourceSha256": "7ca38ee4232f7f7fcdd0537c866656109faf70748f181c8e4d8c2b3e7f2022c9" }, "ja": { "file": "readme/README.ja.md", "label": "日本語", "docsPath": "ja", - "sourceSha256": "3285b30e16e2d695fdb4347b4622a3c85ec34ecb9fe0562ab19006808cab07ad" + "sourceSha256": "7ca38ee4232f7f7fcdd0537c866656109faf70748f181c8e4d8c2b3e7f2022c9" }, "tr": { "file": "readme/README.tr.md", "label": "Türkçe", "docsPath": "tr", - "sourceSha256": "3285b30e16e2d695fdb4347b4622a3c85ec34ecb9fe0562ab19006808cab07ad" + "sourceSha256": "7ca38ee4232f7f7fcdd0537c866656109faf70748f181c8e4d8c2b3e7f2022c9" }, "es": { "file": "readme/README.es.md", "label": "Español", "docsPath": "es", - "sourceSha256": "3285b30e16e2d695fdb4347b4622a3c85ec34ecb9fe0562ab19006808cab07ad" + "sourceSha256": "7ca38ee4232f7f7fcdd0537c866656109faf70748f181c8e4d8c2b3e7f2022c9" } } } diff --git a/src/providers/registry/entries-extended.ts b/src/providers/registry/entries-extended.ts index 1a25dc2045b..141efff6152 100644 --- a/src/providers/registry/entries-extended.ts +++ b/src/providers/registry/entries-extended.ts @@ -1305,6 +1305,24 @@ export const PROVIDER_REGISTRY_EXTENDED: readonly ProviderRegistryEntry[] = [ }, note: "Sionic AI's OpenAI-compatible gateway. Public live discovery lists active models served on Chat Completions (plus pinned Responses-only rows), with Sionic-served ultrafast models first. The public catalog cannot validate keys.", }, + { + // Public contract checked 2026-11-26 without a key: https://runapi.co/api/pricing lists 208 + // models with their supported endpoints (Chat Completions on 200, Responses on 53, Anthropic + // Messages on 37); /v1/models and /v1/chat/completions answer 401 without a token. runapi.co is + // canonical; runapi.host serves the same deployment as a mirror for mainland-China access. + // Standard sponsor under SPONSORS.md (agreement dated 2026-11-25). Pins the row in the picker + // and adds the chip; nothing about routing, discovery or defaults changes. + id: "runapi", + label: "RunAPI", + adapter: "openai-chat", + baseUrl: "https://runapi.co/v1", + authKind: "key", + dashboardUrl: "https://runapi.co", + sponsor: { tier: "standard", url: "https://runapi.co" }, + liveModels: true, + preserveCustomDestination: true, + note: "Unified AI API gateway with a 200+ model catalog; this preset uses OpenAI Chat Completions, which most catalog models support. Use a RunAPI key; live discovery lists the models that key can use.", + }, { // Public contract checked 2026-09-29: https://docs.tokenlab.sh/api-reference/models/list-models // A supplied key is validated and scopes the catalog; anonymous discovery is also public. diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 8f235d1c98a..3dcf72589b6 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -106,7 +106,7 @@ The API workspace gives `gui/src/components/section-tabs.tsx` its mobile reading line so scroll-spy and the top-bar offset agree; other consumers keep their existing reading line. The section strip stays one row at every width. -Provider Overview consumes the existing shared `add-provider-presets` resource for sponsor +RunAPI joins the Standard tier through the registry. Provider Overview consumes the shared `add-provider-presets` resource for sponsor presentation. `matchingWorkspacePreset` requires the configured id, adapter and normalized endpoint to match; a custom endpoint or absent sponsor metadata suppresses the introduction. `ProviderSponsor` keeps localized promotional copy and outbound HTTP(S) links separate from diff --git a/structure/ops/docs-and-release.md b/structure/ops/docs-and-release.md index f975b62d4d2..de16d10b66f 100644 --- a/structure/ops/docs-and-release.md +++ b/structure/ops/docs-and-release.md @@ -86,7 +86,7 @@ Manual navigation is defined in `docs-site/astro.config.mjs`. When adding a publ sidebar and either add localized copies or intentionally accept Starlight fallback behavior. Use slugs for local pages, including Platform Support and OS Keychain, so navigation preserves the selected locale. `tests/ci-workflows/docs-spanish-localization.test.ts` guards canonical Spanish coverage, literal provider-key references, protected remote examples, foreground quickstart alternatives, separate-terminal and Bash/stdin pairing recipes, Pi reasoning metadata, and the data/management credential and admission-header distinctions across shipped locale copies, including empty-header bearer fallback. `tests/ci-workflows/docs-remote-hub-claims.test.ts` validates Docker initialization against the image seed and configuration schema; `tests/ci-workflows/docs-bun-source-requirement.test.ts` checks current bundle claims against the package pin. Provider preset totals are recounted from the current registry when a preset lands. The -documented split is 113 total: 91 key-based, 18 OAuth, three local, and one default +documented split is 114 total: 92 key-based, 18 OAuth, three local, and one default ChatGPT-forward preset. The English and Spanish API-key catalog pages, every other locale's provider guide, and every locale's quickstart carry the same counts. Section 3 of the provider guide lives on its own page, `docs-site/src/content/docs/guides/api-key-catalog.md` (with its Spanish copy), so the guide stays under the file-size ratchet's 2,000-line default; the guide keeps a section 3 stub that links every moved heading anchor, and other locales keep section 3 in their provider guide until they add a translated catalog page. diff --git a/tests/providers/sponsor-presets.test.ts b/tests/providers/sponsor-presets.test.ts index 740e52a36be..019a3c86b6e 100644 --- a/tests/providers/sponsor-presets.test.ts +++ b/tests/providers/sponsor-presets.test.ts @@ -10,6 +10,18 @@ import { pinSponsorRows, pinSponsorsWithinKind } from "../../src/providers/spons * dashboard and `ocx provider presets` read, and that every sponsor entry carries a landing URL. */ describe("sponsor presets", () => { + test("RunAPI exposes its Standard sponsor key preset", () => { + expect(deriveProviderPresets().find(preset => preset.id === "runapi")).toMatchObject({ + label: "RunAPI", + adapter: "openai-chat", + auth: "key", + baseUrl: "https://runapi.co/v1", + sponsor: "standard", + sponsorUrl: "https://runapi.co", + }); + expect(PROVIDER_REGISTRY.find(entry => entry.id === "runapi")?.defaultModel).toBeUndefined(); + }); + test("registry sponsor entries surface tier and URL on the derived preset", () => { const sponsors = PROVIDER_REGISTRY.filter(entry => entry.sponsor); const presets = deriveProviderPresets(); From d7e8015f624a5836b9cf0334a52264898eca0758 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 26 Nov 2026 03:16:19 +0900 Subject: [PATCH 57/60] Refresh provider model catalogs against vendor sources (Gemini, Copilot, GLM-5.4, qwen4-max, DeepSeek, OpenRouter, Cursor) (#9143) * test(registry): every seeded preset defaults to a model it seeds * fix(google): default to gemini-3.6-flash, seed Gemini 4 Neon/Hydrogen/Carbon, price Argon/Carbon at list rate Google no longer offers gemini-3.5-flash or gemini-3.7-flash in AI Studio and routes their endpoints to gemini-3.6-flash / gemini-3.8-flash (ai.google.dev deprecations, 2026-11-26). The default follows the named replacement and both ids leave the picker while their metadata stays for saved selections. Gemini 4 Neon, Hydrogen and Carbon are GA on the models page. Argon and Carbon use the published $4/$20/$0.20 list rate; the introductory rate through 2026-11-30 is a time-boxed promo (DEVIN_SWE2_NOTE policy). * fix(github-copilot): default to gpt-5.3-codex and drop retired ids from the cold-start seed GitHub lists gpt-4.1, claude-sonnet-4, gemini-2.5-pro, gpt-5-mini, gpt-5.4, gpt-5.4-mini, gpt-5.5 and gpt-5.6-terra as retired, and gpt-4o / gpt-4.1-mini are not on the supported list (docs.github.com supported-models, 2026-11-26). GPT-5.3-Codex is the long-term support fallback GitHub names. Live discovery and wire defaults are unchanged. * feat(zai): add GLM-5.4 to the Z.ai and BigModel Coding Plan presets GLM-5.4 is live on every GLM Coding Plan tier (docs.z.ai/devpack/latest-model.md, docs.bigmodel.cn/cn/coding-plan/latest-model.md, 2026-11-26). docs.z.ai/guides/llm/glm-5.4.md: 1M context, 128K output, video/image/text/file input, and the GLM-5.3 low/high/max effort fold with default max. It joins the 5.x family constants as a native VLM (never through the vision sidecar) on zai, zhipu-bigmodel-coding and zhipu-bigmodel-responses; defaults stay glm-5.3 and pay-as-you-go BigModel is unchanged until the Model API ships. * feat(alibaba-token-plan): add qwen4-max to the Beijing Token Plan qwen4-max is on the Token Plan Personal Edition supported list (help.aliyun.com token-plan-personal-quick-start, 2026-11-26). Its model page documents 1,000,000 context, 131,072 output, text/image/video input and direct reasoning_effort low/high/xhigh with default high. It joins the Beijing seed only: the window, output ceiling and modality live in Beijing-only maps so the International row (whose modality map spreads the Beijing one) publishes nothing for it. A saved row holding the exact pre-Qwen4 Beijing seed is refreshed by STALE_MODEL_ROSTERS; operator-edited lists are left alone. * fix(deepseek): drop discontinued deepseek-chat/deepseek-reasoner from the seed DeepSeek discontinued both names on 2026-07-24 and its API reference model enum is now deepseek-flash | deepseek-v4-pro (api-docs.deepseek.com/api/create-chat-completion, 2026-11-26), so the seed now leads with the deepseek-flash default. deepseek-v4-flash and the vision preview stay as documented accepted names. Saved configs are not rewritten: their noVisionModels handling is unchanged, and the stale-roster target follows the registry seed as its invariant requires. * fix(openrouter): stop seeding the openai/gpt-5.6 alias OpenRouter does not list OpenAI documents bare gpt-5.6 as an alias of GPT-5.6 Sol, but OpenRouter public /api/v1/models (472 rows, 2026-11-26) lists only the gpt-5.6-sol/terra/luna slugs. The tier slugs stay seeded; saved configs are not rewritten. * feat(cursor): add gemini-4-neon to the cold-start fallback seed Cursor models page lists Gemini 4 Neon with model ID gemini-4-neon (cursor.com/docs/models/gemini-4-neon, 2026-11-26). It is a preemptive fallback row like Hydrogen and Carbon: exposed before live discovery confirms the account, with Google low..xhigh ladder (Cursor publishes no effort section, so no default is claimed) and Cursor 1M maximum context. * docs(providers): note the Moonshot K2 retirement source and the frozen Vertex default Moonshot K2: the Kimi API pricing page still states the end-of-December 2026 retirement plan on 2026-11-26; seeds keep the ids until a date is published. google-vertex keeps gemini-3-pro as default until Vertex AI lifecycle evidence exists; the Gemini API deprecation schedule covers AI Studio only. * fix(rosters): refresh saved static seeds for Gemini and GLM-5.4 without orphaning dropped ids Terra r3: the DeepSeek roster target dropped deepseek-chat/reasoner from historical saved rows (a saved default could be orphaned), static BigModel/Z.ai rows never received GLM-5.4, and BigModel rows lacked the GLM-5.4 output cap/default. STALE_MODEL_ROSTERS gains an optional retain list (ids the seed dropped that a refreshed row keeps); DeepSeek and the Gemini API row use it. zai, zhipu-bigmodel-coding and zhipu-bigmodel-responses refresh their exact previous seed on official destinations, filling window, 131072 output and max default for GLM-5.4. Both BigModel rows now declare that cap and default. * docs(google): saved Gemini lists keep the redirected Flash ids --- .../content/docs/es/guides/api-key-catalog.md | 9 + .../content/docs/es/guides/google-vertex.md | 5 + .../src/content/docs/es/guides/providers.md | 4 +- .../es/reference/configuration/providers.md | 2 +- .../content/docs/guides/api-key-catalog.md | 25 ++ .../src/content/docs/guides/google-vertex.md | 5 + .../src/content/docs/guides/providers.md | 13 +- .../docs/reference/configuration/providers.md | 2 +- scripts/test-layout/layout-providers.json | 4 +- src/adapters/cursor/catalog.ts | 11 + src/adapters/cursor/effort-map.ts | 2 + src/providers/registry/entries-core.ts | 22 +- src/providers/registry/entries-extended.ts | 64 +++-- src/providers/registry/model-seeds.ts | 44 +++- src/providers/stale-model-roster-migration.ts | 62 ++++- src/usage/expected-prices.ts | 24 +- structure/providers-and-adapters.md | 2 +- .../adapters/google/google-hardening.test.ts | 4 +- tests/cli/cli-models.test.ts | 2 +- tests/codex-integration/codex-catalog.test.ts | 1 + tests/fixtures/test-layout-expected.json | 2 + tests/gui/alibaba-intl-token-plan.test.ts | 2 +- ...alibaba-token-plan-responses-optin.test.ts | 2 +- .../gpt61-terra-provider-rows.test.ts | 2 +- .../model-roster-seed-repair.test.ts | 2 +- .../provider-registry-parity.test.ts | 19 +- .../registry-default-in-seed.test.ts | 20 ++ .../providers/vendor-catalog-refresh.test.ts | 238 ++++++++++++++++++ 28 files changed, 523 insertions(+), 71 deletions(-) create mode 100644 tests/providers/registry-default-in-seed.test.ts create mode 100644 tests/providers/vendor-catalog-refresh.test.ts diff --git a/docs-site/src/content/docs/es/guides/api-key-catalog.md b/docs-site/src/content/docs/es/guides/api-key-catalog.md index 110c4558391..d964e899ed0 100644 --- a/docs-site/src/content/docs/es/guides/api-key-catalog.md +++ b/docs-site/src/content/docs/es/guides/api-key-catalog.md @@ -92,6 +92,8 @@ las suscripciones y el pago por uso según la energía de GPU, por lo que la est **Alibaba Token Plan** ofrece los presets Personal Edition de Beijing y Team Edition internacional. Ambas regiones ofrecen los dos niveles de suscripción. Las listas de modelos de chat son estáticas porque el descubrimiento del proveedor también incluye modelos que no son de chat. Se conservan las selecciones existentes y los endpoints internacionales configurados explícitamente. +El preset de Beijing también incluye `qwen4-max`, el modelo insignia más reciente de Alibaba, que figura en la lista de modelos de la edición Personal ([guía de inicio](https://help.aliyun.com/en/model-studio/token-plan-personal-quick-start), consultado el 2026-11-26). Acepta entrada de texto e imágenes, tiene un contexto de 1.000.000 de tokens y un límite de salida de 131.072 tokens, y admite razonamiento `low`, `high` o `xhigh` (`high` por defecto). El preset internacional no lo incluye porque la descripción general de la edición Team tampoco lo hace. + Ambos presets incluyen `deepseek-v4.1-flash-1017`, con entrada de texto e imágenes, salida de texto, contexto de 1.000.000 de tokens y razonamiento `low`, `high` y `max` (`high` por defecto). Su límite de salida de 393.216 sigue la normalización del presupuesto publicado; no es un límite medido. El Lab informa 384.000. Los esquemas estrictos son rechazados y `json_object` no está verificado para este identificador exacto, por lo que las solicitudes Chat omiten `response_format`: la salida es texto de mejor esfuerzo, sin garantía de JSON. La degradación JSON verificada del modelo sin sufijo y las asignaciones existentes a Responses no cambian. Beijing también incluye `deepseek-v4-pro-0813`, ahora publicado. La región internacional omite los retirados `deepseek-v3.2` y `deepseek-v4-flash` sin sufijo, pero conserva `deepseek-v4-flash-0731`. Los presets mantienen los hosts de sus guías oficiales: Beijing usa `https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1` y la región internacional `https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1`. El preset Qwen Cloud usa el host Token Plan independiente documentado arriba. Consulta la [ficha del modelo 1017](https://www.qianwenai.com/models/deepseek-v4.1-flash-1017), la [referencia Chat](https://docs.qwencloud.com/api-reference/chat/openai-chat) y la [guía Personal](https://help.aliyun.com/en/model-studio/token-plan-personal-overview). **Morph (Ultra plan)** sirve `https://api.morphllm.com/v1` y siembra solo los modelos cubiertos por Ultra, `morph-kimik31` (Kimi K3.1) y `morph-dsv41flash-1017` (DeepSeek V4.1 Flash, instantánea del 17 de octubre): cualquier otro modelo de Morph se factura por token, y `morph-dsv41flash-abliterated` está cubierto por Ultra solo para cuentas con aprobación de acceso privilegiado. @@ -154,6 +156,8 @@ El Plan de codificación y el Plan de agente de Volcengine usan sus endpoints na El preajuste integrado de DeepSeek también enruta `deepseek-v4-flash` por su endpoint nativo de Responses y mantiene habilitado el streaming SSE ascendente. Si ese modelo termina todos los elementos de salida pero omite el evento Responses final, opencodex aplica una reparación de gracia de cinco segundos limitada a ese modelo; los flujos mal formados o parciales se cierran como incompletos en lugar de informarse como exitosos. El modelo propio `deepseek-flash` anuncia entrada nativa `text` e `image`, por lo que las solicitudes de imagen se envían directamente a DeepSeek de forma predeterminada en lugar de pasar por el sidecar de visión. Las declaraciones explícitas de `noVisionModels` o de solo texto siguen siendo autoritativas. Los modelos propios `deepseek-chat`, `deepseek-reasoner` y `deepseek-v4-flash` siguen respaldados por el sidecar de forma predeterminada. Las rutas de Zen no cambian y no se sondearon en esta actualización. +El preajuste de DeepSeek incluye `deepseek-flash` (el predeterminado), `deepseek-v4-flash`, `deepseek-v4-pro` y `deepseek-v4-flash-vision-exp`. DeepSeek dejó de ofrecer `deepseek-chat` y `deepseek-reasoner` el 24 de julio de 2026, y su [referencia de la API](https://api-docs.deepseek.com/api/create-chat-completion) solo acepta `deepseek-flash` y `deepseek-v4-pro` (consultado el 2026-11-26), por lo que las instalaciones nuevas ya no los incluyen. Una lista de modelos guardada conserva lo que ya contiene. + **Capacidades de razonamiento.** Los metadatos distinguen `supportsReasoning`, `supportsThinkingToggle` y `supportsReasoningEffort`. Un valor omitido es desconocido; `false` es una declaración explícita. `defaultThinkingEnabled` registra el estado predeterminado del interruptor y `reasoningEfforts` enumera los niveles de intensidad reales. Las declaraciones por modelo se guardan en `modelCapabilities`; los ejes se combinan con el registro sin distinguir mayúsculas en el identificador, y prevalece lo configurado por el operador. `/v1/models` publica `supports_reasoning`, `supports_thinking_toggle`, `supports_reasoning_effort` y `default_thinking_enabled` dentro de `capabilities`, sin inventar niveles para modelos de intensidad fija. Las configuraciones antiguas con una lista de esfuerzos explícitamente vacía y sin declaraciones de capacidades siguen publicando `capabilities.supports_reasoning: false` en `/v1/models`. Un `supportsReasoning: true` o `supportsThinkingToggle: true` explícito todavía anuncia pensamiento aunque la lista esté vacía. @@ -452,6 +456,7 @@ El preajuste utiliza un **Lista estática** (`liveModels: false`) tomado del [Do | Modelo | Tokens de contexto | Esfuerzo seleccionable ascendente | Esfuerzo predeterminado | Resúmenes de razonamiento | | --- | ---: | --- | --- | --- | +| `glm-5.4` | 1,048,576 | `low`, `high`, `max` | `max` | Apoyado | | `glm-5.3` | 1,048,576 | `low`, `high`, `max` | `max` | Apoyado | | `glm-5.3-flash` | 1,048,576 | `low`, `high`, `max` | `max` | Apoyado | | `glm-5-turbo` | 204,800 | Ninguno (lista vacía) | `max` | Apoyado | @@ -460,6 +465,8 @@ El preajuste utiliza un **Lista estática** (`liveModels: false`) tomado del [Do `glm-5.3-flash` es la excepción: declara la entrada nativa `text` y `image`, porque upstream lo documenta como un modelo multimodal nativo. Por lo tanto, lee imágenes directamente en lugar de ser enrutado a través del desvío del primer sidecar descrito. +`glm-5.4` también lee imágenes de forma nativa: upstream declara entrada de vídeo, imagen, texto y archivo. El GLM Coding Plan lo ofrece en todos los niveles ([cómo cambiar de modelo](https://docs.bigmodel.cn/cn/coding-plan/latest-model.md), consultado el 2026-11-26); los preajustes `zai` y `zhipu-bigmodel-coding` también lo incluyen, con el alias local `glm-5.4[1m]`. + El modelo predeterminado es `glm-5.3`; Responses El contenido de razonamiento se conserva en la repetición. La exportación Codex existente agrega su nivel de compatibilidad `ultra` a GLM-5.3 y omite el campo de esfuerzo predeterminado de Turbo porque Turbo no tiene una escalera seleccionable; los metadatos del proveedor aún registran `max` para ambos modelos. Para Turbo, las solicitudes salientes Responses omiten `reasoning.effort`, incluyendo `max` o `ultra` de la persona que llama, mientras se conservan los resúmenes de razonamiento solicitados. Esto deja la selección de esfuerzo en el valor por defecto ascendente; opencodex no inyecta un protocolo seleccionable o `max`. El `models.json` del ejemplo es un archivo de catálogo local, no una respuesta documentada de la lista de modelos HTTP, y no el conjunto de modelos que sirve el punto final: las páginas del Plan de codificación indican que cada nivel del plan alcanza GLM-5.3 y GLM-5.3-Flash, y que las llamadas GLM-5-Turbo se cambian automáticamente a Flash, por lo que este punto final ya estaba sirviendo Flash bajo el Turbo id. Este preajuste aún no realiza el descubrimiento de modelos en vivo. Un proveedor personalizado existente con el mismo nombre mantiene su destino y metadatos configurados. El inicio de sesión de clave CLI también omite la sonda indocumentada `/models` e informa la validación como desconocida; la autenticación de clave exitosa se establece mediante una solicitud de inferencia posterior. @@ -513,6 +520,8 @@ La configuración del proveedor selecciona el adaptador; la selección de transp **GitHub Copilot** es un proveedor de OAuth (`ocx login github-copilot`) que canjea un inicio de sesión de GitHub mediante flujo de dispositivo por un token de API de Copilot de corta duración, no por una clave de API pegada. **GitLab Duo** sigue siendo una puerta de enlace de clave/token de suscripción en su punto final compatible con OpenAI. **Cloudflare AI Gateway** necesita que su cuenta y los identificadores de la puerta de enlace se rellenen en la URL. +La lista de modelos de Copilot procede del catálogo en vivo de su cuenta. Antes de la primera consulta correcta, el preajuste ofrece una lista de respaldo con modelos GPT actuales y usa `gpt-5.3-codex` como predeterminado, que GitHub designa como su modelo de soporte a largo plazo. Los modelos que GitHub ha retirado, como `gpt-4o`, `gpt-4.1` y `gpt-5.5`, ya no forman parte de esa lista ([modelos compatibles](https://docs.github.com/en/copilot/reference/ai-models/supported-models), consultado el 2026-11-26). + Copilot usa Auto automáticamente cuando cada fila válida de un catálogo de cuenta no vacío informa explícitamente que la selección manual no está disponible. Los permisos ausentes o mal formados conservan las rutas con nombre; el selector solo elimina las filas denegadas explícitamente. El descubrimiento de solo Auto suministra `github-copilot/auto`, y GitHub selecciona el modelo real en cada solicitud. Esto no cambia los permisos de suscripción. Las listas de permisos de modelos ordinarios, el estado pendiente/deshabilitado y la política de nuevo modelo también se aplican a la visibilidad automática. Si las selecciones guardadas o la directiva ocultan Auto, seleccione o habilite la fila Auto antes de usarla. Las preferencias manuales existentes permanecen guardadas. Un modelo llamado `auto` solo no anula la evidencia de la cuenta. Auto sigue el protocolo de sesión e intención de la [implementación pública de VS Code Copilot Chat](https://github.com/microsoft/vscode-copilot-chat/blob/7b70532a4cbdfa61c2b30fe4ccffda3d89336a4d/src/platform/endpoint/node/automodeService.ts). Se trata de una integración experimental de cliente, no de un contrato de API de terceros documentado; GitHub puede cambiar el protocolo o los permisos de la cuenta. Auto usa el punto final anunciado del modelo seleccionado en cada solicitud. El enrutamiento por intención envía solo el último texto del usuario, limitado localmente a 32.768 unidades de código UTF-16; la inferencia real conserva la entrada completa. La negociación tiene presupuestos defensivos locales de 512 entradas de catálogo/grupo/candidato, 1 MiB por respuesta correcta y ocho segundos por llamada, incluidos el ritmo y las lecturas del cuerpo. Son salvaguardas de OpenCodex, no límites documentados de GitHub; catálogos de gran tamaño, una negociación lenta o un extracto de intención truncado pueden afectar la compatibilidad. diff --git a/docs-site/src/content/docs/es/guides/google-vertex.md b/docs-site/src/content/docs/es/guides/google-vertex.md index 0271e869cd4..2cb6fa556a4 100644 --- a/docs-site/src/content/docs/es/guides/google-vertex.md +++ b/docs-site/src/content/docs/es/guides/google-vertex.md @@ -32,6 +32,11 @@ predeterminado) y xhigh; Gemini 4 Carbon y Argon ofrecen low, medium y high. Un preajuste no asigna niveles, como `gemini-3-pro`, no muestra ninguno, porque sus solicitudes no llevan nivel de razonamiento. +El modelo predeterminado del preajuste sigue siendo `gemini-3-pro` hasta que se verifique para él el +ciclo de vida de modelos propio de Vertex AI. El [calendario de retirada de la Gemini API](https://ai.google.dev/gemini-api/docs/deprecations) +cubre AI Studio, no Vertex AI, por lo que no cambia este valor. El descubrimiento en vivo muestra los +modelos que tu proyecto puede usar; elige uno de ellos como predeterminado si `gemini-3-pro` no figura. + ## Imágenes de herramientas en Gemini 3+ En Vertex AI, los modelos Gemini 3 y posteriores (incluidos `gemini-3.8-flash`, `gemini-4-argon`, diff --git a/docs-site/src/content/docs/es/guides/providers.md b/docs-site/src/content/docs/es/guides/providers.md index c2a8d4923d3..2c09aa7be8b 100644 --- a/docs-site/src/content/docs/es/guides/providers.md +++ b/docs-site/src/content/docs/es/guides/providers.md @@ -160,6 +160,8 @@ La pestaña Cuentas Antigravity muestra un nivel de membresía observado como un Gemini 4 Argon (`gemini-4-argon`) aparece en el preajuste `google` con niveles de pensamiento bajos, medios (el predeterminado) y altos. Google lo ofrece solo en el nivel pagado Gemini API, no en el nivel gratuito. El `google-antigravity`, Argon aparece con los mismos tres niveles, que se asignan a los modelos del protocolo `gemini-4-argon-low`, `-medium` y `-high`. Google lo limita a las cuentas AI Ultra y Enterprise elegibles. Cloud Code Assist sirve Argon solo al cliente Antigravity CLI, por lo que OpenCodex envía todas las solicitudes de modelos Gemini 4 y el descubrimiento de modelos con el CLI User-Agent (`antigravity/cli/1.3.4` ) y mantiene el IDE User-Agent para cualquier otro modelo. Gemini 4 Hydrogen (low, medium, high por defecto y xhigh) aparece en `google-antigravity` solo cuando la lista de modelos de tu cuenta lo incluye, y cada nivel se asigna a su modelo del protocolo `gemini-4-hydrogen-*`; solicitar `max` o `ultra` también selecciona xhigh. +El preajuste `google` incluye Gemini 4 Neon, Hydrogen, Carbon y Argon, Gemini 3.8 Flash, Gemini 3.6 Flash, Gemini 3.5 Flash-Lite y Gemini 3.1 Pro Preview, y usa `gemini-3.6-flash` como modelo predeterminado. Google ya no ofrece `gemini-3.5-flash` ni `gemini-3.7-flash` en AI Studio y redirige sus endpoints a `gemini-3.6-flash` y `gemini-3.8-flash` ([deprecaciones](https://ai.google.dev/gemini-api/docs/deprecations), consultado el 2026-11-26), por lo que las instalaciones nuevas ya no los incluyen. Una lista de modelos guardada los conserva y una selección guardada sigue funcionando. Las estimaciones de uso de Gemini 4 Argon y Carbon usan la tarifa de lista de Google: 4 USD de entrada, 20 USD de salida y 0,20 USD de entrada en caché por millón de tokens. No se aplica la tarifa introductoria vigente hasta el 30 de noviembre de 2026. + En Vertex AI, los modelos Gemini 3 y posteriores (incluidos `gemini-4-argon`, `gemini-4-carbon`, `gemini-4-hydrogen` y `gemini-4-neon`) reciben las imágenes devueltas por herramientas, como capturas de pantalla, dentro de la respuesta de función correspondiente. El descubrimiento de modelos de Vertex AI, sus reglas de credenciales y este tratamiento se describen en [Google Vertex AI](/es/guides/google-vertex/). Para Gemini en Antigravity, incluyendo Argon, los resúmenes de pensamiento marcados por el proveedor se mantienen separados de la respuesta: Responses usa elementos de resumen de razonamiento, Chat Completions usa `reasoning_content` y Messages usa `thinking` bloques. Los clientes deciden cómo mostrar esos campos. Un cliente Responses puede solicitar `reasoning.summary: "none"` para suprimir resúmenes; esto no desactiva el razonamiento interno del modelo. Una firma de pensamiento es metadatos de continuación y puede acompañar al texto ordinario, por lo que su presencia por sí sola no oculta ese texto. OpenCodex conserva texto de respuesta sin marcar incluso cuando su redacción suena como planificación o análisis. @@ -275,7 +277,7 @@ Los precios de uso de Kimi Coding para `k3`, `k3[1m]`, `k3-256k`, `k3.1-pro` y ` El preajuste `moonshot` (Kimi API) incluye `kimi-k3.1-pro` y `kimi-k3.1-pro-highspeed` junto a `kimi-k3` y los identificadores K2 aún admitidos. K3.1 tiene contexto de 1M de tokens, entrada de texto e imágenes y razonamiento obligatorio. El selector ofrece `low` / `high` / `max` (`max` de forma predeterminada); los esfuerzos Codex `medium` se envían como `high`, y `xhigh` como `max`. Un `none` explícito omite `reasoning_effort` para utilizar el valor predeterminado del proveedor. No se envían parámetros fijos de muestreo, como `temperature`, `top_p` o penalizaciones. -Al iniciar, una lista guardada de modelos `moonshot` que aún coincida con la lista integrada anterior recibe ambos identificadores si apunta al endpoint internacional o de China. Esta actualización no añade modelos a listas editadas ni a una URL personalizada; la migración de identificadores retirados se aplica por separado. El preajuste usa ahora `kimi-k3.1-pro`, recomendado por el proveedor. `kimi-k2.5`, retirado el 2026-08-31, desaparece de los modelos iniciales de la API. Las selecciones guardadas en los endpoints oficiales internacional o chino migran a `kimi-k3.1-pro`, actualizando los metadatos integrados antiguos de contexto y razonamiento y conservando las anulaciones explícitas. Los destinos personalizados mantienen sus selecciones. `kimi-k2.6` y `kimi-k2.7-code`, incluido highspeed, siguen disponibles para usuarios existentes. Moonshot cierra la serie K2 a cuentas nuevas el 2026-10-31 y prevé retirarla a finales de diciembre de 2026; consulta la [lista de modelos de Kimi API](https://platform.kimi.ai/docs/models.md), comprobada el 2026-10-28. +Al iniciar, una lista guardada de modelos `moonshot` que aún coincida con la lista integrada anterior recibe ambos identificadores si apunta al endpoint internacional o de China. Esta actualización no añade modelos a listas editadas ni a una URL personalizada; la migración de identificadores retirados se aplica por separado. El preajuste usa ahora `kimi-k3.1-pro`, recomendado por el proveedor. `kimi-k2.5`, retirado el 2026-08-31, desaparece de los modelos iniciales de la API. Las selecciones guardadas en los endpoints oficiales internacional o chino migran a `kimi-k3.1-pro`, actualizando los metadatos integrados antiguos de contexto y razonamiento y conservando las anulaciones explícitas. Los destinos personalizados mantienen sus selecciones. `kimi-k2.6` y `kimi-k2.7-code`, incluido highspeed, siguen disponibles para usuarios existentes. Moonshot cierra la serie K2 a cuentas nuevas el 2026-10-31 y prevé retirarla a finales de diciembre de 2026; consulta la [lista de modelos de Kimi API](https://platform.kimi.ai/docs/models.md), comprobada el 2026-10-28, y la [página de precios de Kimi API](https://platform.kimi.ai/docs/pricing/chat), que mantenía ese plan el 2026-11-26. Los modelos iniciales conservan ambos identificadores hasta que Moonshot publique la fecha de retirada. Un proveedor personalizado de `openai-chat` puede habilitar esta opción cuando su proveedor documente compatibilidad con `prompt_cache_key`: diff --git a/docs-site/src/content/docs/es/reference/configuration/providers.md b/docs-site/src/content/docs/es/reference/configuration/providers.md index 18a95b6138b..1eb3daef7cc 100644 --- a/docs-site/src/content/docs/es/reference/configuration/providers.md +++ b/docs-site/src/content/docs/es/reference/configuration/providers.md @@ -1135,7 +1135,7 @@ Las claves API y las referencias a credenciales se pueden guardar en el almacén ## Listas de modelos estáticos -El preajuste `zhipu-bigmodel-responses` incluye inicialmente `glm-5.3`, `glm-5.3-flash` y `glm-5-turbo` con `liveModels: false` para `https://open.bigmodel.cn/api/v1`. Su lista estática y el contexto por modelo, el esfuerzo y los metadatos de resumen provienen del [Guía BigModel Responses](/es/guides/api-key-catalog/#bigmodel-coding-plan-over-responses). El ejemplo oficial local `models.json` no establece un vivo `/models` API. +El preajuste `zhipu-bigmodel-responses` incluye inicialmente `glm-5.4`, `glm-5.3`, `glm-5.3-flash` y `glm-5-turbo` con `liveModels: false` para `https://open.bigmodel.cn/api/v1`. Su lista estática y el contexto por modelo, el esfuerzo y los metadatos de resumen provienen del [Guía BigModel Responses](/es/guides/api-key-catalog/#bigmodel-coding-plan-over-responses). El ejemplo oficial local `models.json` no establece un vivo `/models` API. Con `liveModels: false`, un `models` vacío u omitido inicia primero el `defaultModel` configurado, seguido por `retainModels`; se eliminan los ID duplicados mientras se conserva la primera aparición. Una lista explícita no vacía de `models` en cambio siembra `models` seguido de `retainModels`, sin agregar implícitamente un `defaultModel` diferente. Ese valor predeterminado todavía se puede enumerar explícitamente en `models` o `retainModels`. Si ninguno de estos campos proporciona un id, la semilla estática está vacía. Este es el orden de la semilla, no una promesa del orden final del selector. `selectedModels`, `disabledModels` y la política de proveedores desactivados todavía se aplican. `authMode: "forward"` mantiene su rama separada y no usa esta semilla estática enrutada. Estas reglas no cambian el fracaso del descubrimiento en vivo. diff --git a/docs-site/src/content/docs/guides/api-key-catalog.md b/docs-site/src/content/docs/guides/api-key-catalog.md index f17effbf93c..9729fd87d98 100644 --- a/docs-site/src/content/docs/guides/api-key-catalog.md +++ b/docs-site/src/content/docs/guides/api-key-catalog.md @@ -123,6 +123,13 @@ presets. Both regions offer both subscription tiers. The presets keep static cha lists because upstream discovery also includes non-chat models. Existing selections and explicit International endpoint overrides are preserved. +The Beijing preset also lists `qwen4-max`, Alibaba's newest flagship, which the Personal +Edition model list includes +([quick start](https://help.aliyun.com/en/model-studio/token-plan-personal-quick-start), checked +2026-11-26). It accepts text and image input, has a 1,000,000-token context and a 131,072-token +output ceiling, and takes `low`, `high` or `xhigh` reasoning (default `high`). The +International preset does not list it because the Team Edition overview does not. + Both presets include `deepseek-v4.1-flash-1017` with text/image input, text output, 1,000,000 context and `low`/`high`/`max` reasoning (default `high`). Its 393,216 output budget follows the existing published-budget normalization, not a measured boundary; @@ -392,6 +399,11 @@ are sent directly to DeepSeek by default instead of through the vision sidecar. `noVisionModels` or text-only declarations remain authoritative. First-party `deepseek-chat`, `deepseek-reasoner`, and `deepseek-v4-flash` remain sidecar-backed by default. Zen routes are unchanged and were not probed in this update. +The DeepSeek preset lists `deepseek-flash` (the default), `deepseek-v4-flash`, `deepseek-v4-pro` +and `deepseek-v4-flash-vision-exp`. DeepSeek discontinued `deepseek-chat` and `deepseek-reasoner` +on July 24, 2026, and its [API reference](https://api-docs.deepseek.com/api/create-chat-completion) +accepts only `deepseek-flash` and `deepseek-v4-pro` (checked 2026-11-26), so new installs no +longer list them. A saved model list keeps whatever it already holds. > **Three Volcengine billing routes:** `volcengine` is the pay-as-you-go Ark API, > `volcengine-coding-plan` consumes Coding Plan quota, and `volcengine-agent-plan` consumes Agent @@ -986,6 +998,7 @@ The preset uses a **static roster** (`liveModels: false`) taken from the publish | Model | Context tokens | Upstream selectable effort | Default effort | Reasoning summaries | | --- | ---: | --- | --- | --- | +| `glm-5.4` | 1,048,576 | `low`, `high`, `max` | `max` | Supported | | `glm-5.3` | 1,048,576 | `low`, `high`, `max` | `max` | Supported | | `glm-5.3-flash` | 1,048,576 | `low`, `high`, `max` | `max` | Supported | | `glm-5-turbo` | 204,800 | None (empty list) | `max` | Supported | @@ -999,6 +1012,11 @@ sidecar and does not claim native BigModel image support. upstream documents it as a natively multimodal model. It therefore reads pictures directly instead of being routed through the describe-it-first sidecar detour. +`glm-5.4` also reads images natively: upstream lists video, image, text and file input for it. The +GLM Coding Plan offers it on every tier +([how to switch models](https://docs.bigmodel.cn/cn/coding-plan/latest-model.md), checked 2026-11-26); +the `zai` and `zhipu-bigmodel-coding` presets list it too, with the local `glm-5.4[1m]` alias. + 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 @@ -1098,6 +1116,13 @@ device-flow login for a short-lived Copilot API token — not a pasted API key. a key/subscription-token gateway on its OpenAI-compatible endpoint. **Cloudflare AI Gateway** needs your account + gateway ids filled into the URL. +Copilot's model list comes from your account's live catalog. Before the first successful fetch the +preset offers a fallback list of current GPT models and defaults to `gpt-5.3-codex`, which GitHub +names its long-term support model. Models GitHub has retired, such as `gpt-4o`, `gpt-4.1` and +`gpt-5.5`, are no longer in that fallback +([supported models](https://docs.github.com/en/copilot/reference/ai-models/supported-models), +checked 2026-11-26). + Copilot automatically uses Auto when every valid row in a nonempty account catalog explicitly reports that manual selection is unavailable. Missing or malformed permissions retain named routes; the picker removes only explicitly denied rows. Auto-only discovery supplies `github-copilot/auto`, diff --git a/docs-site/src/content/docs/guides/google-vertex.md b/docs-site/src/content/docs/guides/google-vertex.md index a72b70b3ae2..aed7f2cfa7e 100644 --- a/docs-site/src/content/docs/guides/google-vertex.md +++ b/docs-site/src/content/docs/guides/google-vertex.md @@ -30,6 +30,11 @@ Reasoning levels follow the preset: Gemini 4 Hydrogen and Neon offer low, medium xhigh; Gemini 4 Carbon and Argon offer low, medium and high. A model the preset gives no levels to, such as `gemini-3-pro`, shows none, because requests to it carry no thinking level. +The preset's default model stays `gemini-3-pro` until Vertex AI's own model lifecycle is verified for +it. Google's [Gemini API deprecation schedule](https://ai.google.dev/gemini-api/docs/deprecations) +covers AI Studio, not Vertex AI, so it does not move this default. Live discovery lists the models +your project can use; pick one of them as your default if `gemini-3-pro` is not among them. + ## Tool images on Gemini 3+ On Vertex AI, Gemini 3 and later models (including `gemini-3.8-flash`, `gemini-4-argon`, diff --git a/docs-site/src/content/docs/guides/providers.md b/docs-site/src/content/docs/guides/providers.md index 8471f7e2c74..a23b743a71a 100644 --- a/docs-site/src/content/docs/guides/providers.md +++ b/docs-site/src/content/docs/guides/providers.md @@ -298,6 +298,15 @@ eligible Enterprise accounts. Cloud Code Assist serves Argon only to the Antigra OpenCodex sends every Gemini 4 model request and model discovery with the CLI User-Agent (`antigravity/cli/1.3.4`) and keeps the IDE User-Agent for every other model. Gemini 4 Hydrogen (low, medium, high by default, and xhigh) appears on `google-antigravity` only when your account's model list includes it, each level mapping to its `gemini-4-hydrogen-*` wire model; requesting `max` or `ultra` also selects xhigh. +The `google` preset lists Gemini 4 Neon, Hydrogen, Carbon and Argon, Gemini 3.8 Flash, Gemini 3.6 +Flash, Gemini 3.5 Flash-Lite and Gemini 3.1 Pro Preview, and defaults to `gemini-3.6-flash`. +Google no longer offers `gemini-3.5-flash` or `gemini-3.7-flash` in AI Studio and routes their +endpoints to `gemini-3.6-flash` and `gemini-3.8-flash` +([deprecations](https://ai.google.dev/gemini-api/docs/deprecations), checked 2026-11-26), so new +installs no longer list them. A saved model list keeps them, and a saved selection keeps working. Usage estimates for Gemini 4 Argon and +Carbon use Google's list rate of $4 input, $20 output and $0.20 cached input per million tokens. +The introductory rate that runs through November 30, 2026 is not applied. + Vertex AI model discovery, its credential rules and how Vertex Gemini 3+ models (including Gemini 4 Argon, Carbon, Hydrogen and Neon) receive tool images are described in [Google Vertex AI](/guides/google-vertex/). @@ -507,7 +516,9 @@ endpoint migrate to `kimi-k3.1-pro`, refreshing old built-in context and reasoni preserving explicit overrides. Custom destinations keep their saved selections. `kimi-k2.6` and `kimi-k2.7-code` (including highspeed) remain selectable for existing users: Moonshot closes the K2 series to new accounts on 2026-10-31 and plans to retire it by the end of December 2026; see the -[Kimi API model list](https://platform.kimi.ai/docs/models.md) (checked 2026-10-28). +[Kimi API model list](https://platform.kimi.ai/docs/models.md) (checked 2026-10-28) and the +[Kimi API pricing page](https://platform.kimi.ai/docs/pricing/chat), which still states that plan on +2026-11-26. The seeds keep both ids until Moonshot publishes the retirement date. A custom `openai-chat` provider can opt in when its upstream documents support for `prompt_cache_key`: diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index 911c6e3fa2a..06a24ab7cff 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -1670,7 +1670,7 @@ API keys and credential references can be stored in the OS credential store (mac ## Static model allowlists -The `zhipu-bigmodel-responses` preset seeds `glm-5.3`, `glm-5.3-flash` and `glm-5-turbo` with +The `zhipu-bigmodel-responses` preset seeds `glm-5.4`, `glm-5.3`, `glm-5.3-flash` 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/api-key-catalog/#bigmodel-coding-plan-over-responses). diff --git a/scripts/test-layout/layout-providers.json b/scripts/test-layout/layout-providers.json index 42c9a5ba0e9..2a545688438 100644 --- a/scripts/test-layout/layout-providers.json +++ b/scripts/test-layout/layout-providers.json @@ -28,5 +28,7 @@ "claude-cli-fixture-stdout-flush.test.ts": "providers", "alibaba-token-plan-developer-role.test.ts": "providers", "provider-quota-probe-isolation.test.ts": "providers", - "api-key-cooldown-store.test.ts": "providers" + "api-key-cooldown-store.test.ts": "providers", + "registry-default-in-seed.test.ts": "providers", + "vendor-catalog-refresh.test.ts": "providers" } diff --git a/src/adapters/cursor/catalog.ts b/src/adapters/cursor/catalog.ts index c4a863825b7..d6499753e72 100644 --- a/src/adapters/cursor/catalog.ts +++ b/src/adapters/cursor/catalog.ts @@ -260,6 +260,17 @@ export const CURSOR_CAPABILITIES: Record = { defaultVariant: "regular", variants: { regular: { levels: ["low", "medium", "high", "xhigh"] } }, }, + // 261126 preemptive cold-start fallback: Cursor's models page lists Gemini 4 Neon with model ID + // gemini-4-neon (cursor.com/docs/models/gemini-4-neon). cursorUmbrellaRows() exposes this row in + // CURSOR_STATIC_MODELS before live discovery confirms the account serves it. Cursor publishes no + // effort section for Neon, so the ladder is Google's (low..xhigh) and no default is claimed. The + // window is Cursor's published 1M maximum, the same value the Hydrogen row uses for that pair. + "gemini-4-neon": { + displayName: "Gemini 4 Neon", + window: CONTEXT_GEMINI, + defaultVariant: "regular", + variants: { regular: { levels: ["low", "medium", "high", "xhigh"] } }, + }, "gemini-4-carbon": { displayName: "Gemini 4 Carbon", window: CONTEXT_GEMINI, diff --git a/src/adapters/cursor/effort-map.ts b/src/adapters/cursor/effort-map.ts index af0051d0c99..e57a7862fa1 100644 --- a/src/adapters/cursor/effort-map.ts +++ b/src/adapters/cursor/effort-map.ts @@ -62,6 +62,8 @@ const CURSOR_MODEL_EFFORT_TIERS: Record = { // #8918: Gemini 4 Hydrogen (low..xhigh) and Carbon (low..high), per Cursor's models pages. "gemini-4-hydrogen": ["low", "medium", "high", "xhigh"], "gemini-4-carbon": ["low", "medium", "high"], + // 261126 preemptive: Gemini 4 Neon, Google's low..xhigh ladder (Cursor publishes none). + "gemini-4-neon": ["low", "medium", "high", "xhigh"], // Explicit-thinking variants (260825 live roster). Tiers are the rungs the wire actually // lists for each family, which is not always the same set the non-thinking id carries: // 4.6-opus thinks only at high/max, 4.5-opus only at high, 4.6-sonnet only at medium. diff --git a/src/providers/registry/entries-core.ts b/src/providers/registry/entries-core.ts index b8428f14b1e..939aa968bb2 100644 --- a/src/providers/registry/entries-core.ts +++ b/src/providers/registry/entries-core.ts @@ -36,6 +36,7 @@ import { ANTHROPIC_DEFAULT_MAX_OUTPUT_TOKENS, ANTHROPIC_MODEL_MAX_OUTPUT_TOKENS, ANTHROPIC_MODEL_REASONING_EFFORTS, + GOOGLE_GEMINI_API_MODELS, ZAI_GLM_52_REASONING_EFFORTS, ZAI_GLM_53_REASONING_EFFORTS, OPENAI_GPT56_MODELS, @@ -1224,7 +1225,11 @@ export const PROVIDER_REGISTRY_CORE: readonly ProviderRegistryEntry[] = [ // devlog/_plan/260710_provider_hardening/001_research_frontier.md. { id: "google", label: "Google Gemini", adapter: "google", baseUrl: "https://generativelanguage.googleapis.com", authKind: "key", featured: true, - dashboardUrl: "https://aistudio.google.com/apikey", defaultModel: "gemini-3.5-flash", models: ["gemini-4-argon", "gemini-3.8-flash", "gemini-3.6-flash", "gemini-3.5-flash", "gemini-3.5-flash-lite", "gemini-3.1-pro-preview", "gemini-3.7-flash"], + // 2026-11-26 (ai.google.dev deprecations): gemini-3.5-flash and gemini-3.7-flash are no longer + // offered in AI Studio and their endpoints route to gemini-3.6-flash / gemini-3.8-flash, so they + // leave the picker; their metadata rows stay so saved selections keep resolving. The default + // follows Google's named replacement. Gemini 4 Neon/Hydrogen/Carbon are GA on the models page. + dashboardUrl: "https://aistudio.google.com/apikey", defaultModel: "gemini-3.6-flash", models: GOOGLE_GEMINI_API_MODELS, modelContextWindows: { "gemini-4-neon": 1_048_576, "gemini-4-hydrogen": 1_048_576, "gemini-4-carbon": 1_048_576, "gemini-4-argon": 1_048_576, "gemini-3.8-flash": 1_048_576, "gemini-3.6-flash": 1_048_576, "gemini-3.5-flash": 1_000_000, "gemini-3.5-flash-lite": 1_048_576, "gemini-3.7-flash": 1_048_576 }, modelInputModalities: { "gemini-4-neon": ["text", "image"], "gemini-4-hydrogen": ["text", "image"], "gemini-4-carbon": ["text", "image"], "gemini-4-argon": ["text", "image"], "gemini-3.8-flash": ["text", "image"], "gemini-3.6-flash": ["text", "image"], "gemini-3.5-flash-lite": ["text", "image"], "gemini-3.7-flash": ["text", "image"] }, modelReasoningEfforts: { ...GEMINI_MODEL_REASONING_EFFORTS }, @@ -1265,14 +1270,13 @@ export const PROVIDER_REGISTRY_CORE: readonly ProviderRegistryEntry[] = [ // back to the 128k strict-fields default (scripts/model-metadata.source.json, // verified 2026-08-08). jawcodeBundle: "deepseek", - // deepseek-chat/deepseek-reasoner were deprecated upstream on 2026-07-24 15:59 UTC; - // the current official identifier is deepseek-flash. They stay in - // the list only as compatibility aliases so existing saved configs and requests - // keep validating and routing (they previously mapped to v4-flash; devlog - // _fin/260710_provider_hardening/002_research_cn.md). The current offerings are - // V4.1-Flash and V4 Pro; Flash remains the default. - // Keep the legacy vision-preview alias; see DEEPSEEK_VISION_PREVIEW_MODEL. - models: ["deepseek-chat", "deepseek-reasoner", ...DEEPSEEK_NATIVE_THINKING_MODELS, DEEPSEEK_VISION_PREVIEW_MODEL], + // deepseek-chat/deepseek-reasoner were discontinued upstream on 2026-07-24, and the API + // reference's model enum is now deepseek-flash | deepseek-v4-pro (checked 2026-11-26: + // api-docs.deepseek.com/api/create-chat-completion), so they leave the seed. A saved config + // that still lists them keeps its list; their noVisionModels entries below stay for it. + // deepseek-v4-flash and the vision preview remain documented accepted names served by V4.1 + // Flash (pricing page note 1); see DEEPSEEK_VISION_PREVIEW_MODEL. Flash remains the default. + models: [...DEEPSEEK_NATIVE_THINKING_MODELS, DEEPSEEK_VISION_PREVIEW_MODEL], // V4.1-Flash is the first-party default; `deepseek-v4-flash` now routes there // as a compatibility alias, so a new install should ask for the live id by name. defaultModel: "deepseek-flash", diff --git a/src/providers/registry/entries-extended.ts b/src/providers/registry/entries-extended.ts index 141efff6152..139c610b536 100644 --- a/src/providers/registry/entries-extended.ts +++ b/src/providers/registry/entries-extended.ts @@ -30,6 +30,10 @@ import type { ProviderRegistryEntry } from "./types"; import { AGY_ACP_DEFAULT_MODEL, AGY_ACP_SEED_MODELS } from "./agy-acp-models"; import { ZAI_GLM_53_MODELS, + ZAI_GLM_53_CONTRACT_MODELS, + ZAI_GLM_54_MODELS, + ZAI_CODING_PLAN_MODELS, + BIGMODEL_RESPONSES_MODELS, ZAI_GLM_5X_MODELS, ZAI_GLM_5X_SIDECAR_VISION_MODELS, ZAI_GLM_5X_INPUT_MODALITIES, @@ -52,6 +56,8 @@ import { ZHIPU_BIGMODEL_THINKING_TOGGLE_MODELS, THINKING_BUDGET_EFFORTS, QWEN38_REASONING_EFFORTS, + QWEN4_MAX, + QWEN4_MAX_REASONING_EFFORTS, DEEPSEEK_V4_LEGACY_MODELS, DEEPSEEK_GATEWAY_THINKING_MODELS, DEEPSEEK_VISION_PREVIEW_MODEL, @@ -66,6 +72,9 @@ import { ALIBABA_TOKEN_PLAN_QWEN_MODELS, ALIBABA_TOKEN_PLAN_INPUT_MODALITIES, ALIBABA_TOKEN_PLAN_CONTEXT_WINDOWS, + ALIBABA_TOKEN_PLAN_BEIJING_CONTEXT_WINDOWS, + ALIBABA_TOKEN_PLAN_BEIJING_INPUT_MODALITIES, + ALIBABA_TOKEN_PLAN_BEIJING_MAX_OUTPUT_TOKENS, ALIBABA_TOKEN_PLAN_MAX_OUTPUT_TOKENS, ALIBABA_TOKEN_PLAN_NO_VISION, ALIBABA_TOKEN_PLAN_PRESERVE_REASONING, @@ -599,17 +608,18 @@ export const PROVIDER_REGISTRY_EXTENDED: readonly ProviderRegistryEntry[] = [ destinationAliases: [{ baseUrl: "https://api.z.ai/api/coding/paas/v4", adapter: "openai-chat" }], dashboardUrl: "https://z.ai/manage-apikey/apikey-list", defaultModel: "glm-5.3", note: "GLM-5.3 coding subscription", - models: ["glm-5.3", "glm-5.3[1m]", "glm-5.3-flash", "glm-5.2", "glm-5.2[1m]", "glm-5.1", "glm-5", "glm-4.6"], + models: ZAI_CODING_PLAN_MODELS, // The upstream catalog reports 1_048_576 for the 5.3 family, which is what the domestic - // Responses row already carries. Both are documented as "1M"; this is that number. - modelContextWindows: { "glm-5.3": 1_048_576, "glm-5.3[1m]": 1_048_576, "glm-5.3-flash": 1_048_576, "glm-5.2": 1_000_000, "glm-5.2[1m]": 1_000_000 }, + // Responses row already carries. Both are documented as "1M"; this is that number. GLM-5.4 is + // documented as "1M" too and follows the same convention. + modelContextWindows: { "glm-5.4": 1_048_576, "glm-5.4[1m]": 1_048_576, "glm-5.3": 1_048_576, "glm-5.3[1m]": 1_048_576, "glm-5.3-flash": 1_048_576, "glm-5.2": 1_000_000, "glm-5.2[1m]": 1_000_000 }, // Z.AI returns 400 for bracketed model ids on both wires; the aliases are local. modelSuffixBracketStrip: true, noVisionModels: ZAI_GLM_5X_SIDECAR_VISION_MODELS, modelInputModalities: ZAI_GLM_5X_INPUT_MODALITIES, modelReasoningEfforts: ZAI_GLM_5X_REASONING_EFFORTS, - modelDefaultReasoningEfforts: Object.fromEntries(ZAI_GLM_53_MODELS.map(id => [id, "max"])), - modelMaxOutputTokens: Object.fromEntries(ZAI_GLM_53_MODELS.map(id => [id, 131_072])), + modelDefaultReasoningEfforts: Object.fromEntries(ZAI_GLM_53_CONTRACT_MODELS.map(id => [id, "max"])), + modelMaxOutputTokens: Object.fromEntries(ZAI_GLM_53_CONTRACT_MODELS.map(id => [id, 131_072])), modelSupportsReasoningSummaries: Object.fromEntries(ZAI_GLM_5X_MODELS.map(id => [id, true])), preserveReasoningContentModels: ZAI_GLM_5X_MODELS, // Responses replay uses this provider-level flag; the model list above still covers a @@ -686,9 +696,12 @@ export const PROVIDER_REGISTRY_EXTENDED: readonly ProviderRegistryEntry[] = [ authKind: "key", dashboardUrl: "https://bigmodel.cn/console/usercenter/apikeys", defaultModel: "glm-5.3", - models: ["glm-5.3", "glm-5.3[1m]", "glm-5.3-flash", "glm-5.2", "glm-5.2[1m]", "glm-5.1", "glm-5", "glm-4.6"], + models: ZAI_CODING_PLAN_MODELS, jawcodeBundle: "zai", - modelContextWindows: { "glm-5.3": 1_000_000, "glm-5.3[1m]": 1_000_000, "glm-5.3-flash": 1_000_000, "glm-5.2": 1_000_000, "glm-5.2[1m]": 1_000_000 }, + modelContextWindows: { "glm-5.4": 1_000_000, "glm-5.4[1m]": 1_000_000, "glm-5.3": 1_000_000, "glm-5.3[1m]": 1_000_000, "glm-5.3-flash": 1_000_000, "glm-5.2": 1_000_000, "glm-5.2[1m]": 1_000_000 }, + // GLM-5.4: 128K output and default effort max (docs.z.ai/guides/llm/glm-5.4.md, devpack/latest-model.md). + modelMaxOutputTokens: Object.fromEntries(ZAI_GLM_54_MODELS.map(id => [id, 131_072])), + modelDefaultReasoningEfforts: Object.fromEntries(ZAI_GLM_54_MODELS.map(id => [id, "max"])), modelSuffixBracketStrip: true, noVisionModels: ZAI_GLM_5X_SIDECAR_VISION_MODELS, modelInputModalities: ZAI_GLM_5X_INPUT_MODALITIES, @@ -727,7 +740,9 @@ export const PROVIDER_REGISTRY_EXTENDED: readonly ProviderRegistryEntry[] = [ authKind: "key", dashboardUrl: "https://bigmodel.cn/console/usercenter/apikeys", defaultModel: "glm-5.3", - models: ["glm-5.3", "glm-5.3-flash", "glm-5-turbo"], + // GLM-5.4 joined every Coding Plan tier on the same Codex base URL (2026-11-26, + // docs.bigmodel.cn/cn/coding-plan/latest-model.md). + models: BIGMODEL_RESPONSES_MODELS, liveModels: false, // The local Codex catalog does not establish an authenticated HTTP /models contract. apiKeyValidation: "unknown", @@ -738,14 +753,16 @@ export const PROVIDER_REGISTRY_EXTENDED: readonly ProviderRegistryEntry[] = [ // models are documented as "1M", and this preset expresses that family's 1M the way // BigModel's own Codex declaration does. Splitting the two would leave one preset // claiming two different sizes for one documented window. - modelContextWindows: { "glm-5.3": 1_048_576, "glm-5.3-flash": 1_048_576, "glm-5-turbo": 204_800 }, + modelContextWindows: { "glm-5.4": 1_048_576, "glm-5.3": 1_048_576, "glm-5.3-flash": 1_048_576, "glm-5-turbo": 204_800 }, // Flash is the only row here that can actually see an image. Its siblings are declared // text-only and get `image` back from the vision sidecar at catalog-build time; declaring // Flash text-only would route a native VLM's pictures through a describe-it-first detour // and hand the model prose about an image it could have read (same defect // ZAI_GLM_5X_SIDECAR_VISION_MODELS exists to prevent on the Chat rows). - modelInputModalities: { "glm-5.3": ["text"], "glm-5.3-flash": ["text", "image"], "glm-5-turbo": ["text"] }, + modelInputModalities: { "glm-5.4": ["text", "image"], "glm-5.3": ["text"], "glm-5.3-flash": ["text", "image"], "glm-5-turbo": ["text"] }, modelReasoningEfforts: { + // GLM-5.4 documents the same low/high/max fold as GLM-5.3 (docs.z.ai/devpack/latest-model.md). + "glm-5.4": ZAI_GLM_53_REASONING_EFFORTS, "glm-5.3": ZAI_GLM_53_REASONING_EFFORTS, // Same three effective tiers: upstream documents Flash's text parameters as identical // to GLM-5.3, and the Codex effort table folds every inbound value into low/high/max. @@ -753,8 +770,9 @@ export const PROVIDER_REGISTRY_EXTENDED: readonly ProviderRegistryEntry[] = [ // Explicitly empty: Turbo must not inherit the generic selectable effort ladder. "glm-5-turbo": [], }, - modelDefaultReasoningEfforts: { "glm-5.3": "max", "glm-5.3-flash": "max", "glm-5-turbo": "max" }, - modelSupportsReasoningSummaries: { "glm-5.3": true, "glm-5.3-flash": true, "glm-5-turbo": true }, + modelDefaultReasoningEfforts: { "glm-5.4": "max", "glm-5.3": "max", "glm-5.3-flash": "max", "glm-5-turbo": "max" }, + modelMaxOutputTokens: { "glm-5.4": 131_072 }, + modelSupportsReasoningSummaries: { "glm-5.4": true, "glm-5.3": true, "glm-5.3-flash": 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", @@ -935,12 +953,13 @@ export const PROVIDER_REGISTRY_EXTENDED: readonly ProviderRegistryEntry[] = [ "glm-5.3": { wire: "openai-responses", inbound: ["responses"] }, }, note: "Token Plan Personal Edition · China (Beijing)", - modelInputModalities: ALIBABA_TOKEN_PLAN_INPUT_MODALITIES, - modelContextWindows: ALIBABA_TOKEN_PLAN_CONTEXT_WINDOWS, - modelMaxOutputTokens: ALIBABA_TOKEN_PLAN_MAX_OUTPUT_TOKENS, + modelInputModalities: ALIBABA_TOKEN_PLAN_BEIJING_INPUT_MODALITIES, + modelContextWindows: ALIBABA_TOKEN_PLAN_BEIJING_CONTEXT_WINDOWS, + modelMaxOutputTokens: ALIBABA_TOKEN_PLAN_BEIJING_MAX_OUTPUT_TOKENS, modelReasoningEfforts: { ...Object.fromEntries(ALIBABA_TOKEN_PLAN_QWEN_MODELS.map(id => [id, THINKING_BUDGET_EFFORTS])), ...Object.fromEntries(QWEN38_FAMILY.map(id => [id, QWEN38_REASONING_EFFORTS])), + [QWEN4_MAX]: QWEN4_MAX_REASONING_EFFORTS, "glm-5.2": ZAI_GLM_52_REASONING_EFFORTS, "glm-5.3": ZAI_GLM_53_REASONING_EFFORTS, "deepseek-v4-pro": deepseekThinkingEffortsFor("deepseek-v4-pro"), @@ -963,10 +982,10 @@ export const PROVIDER_REGISTRY_EXTENDED: readonly ProviderRegistryEntry[] = [ noJsonSchemaModels: ["deepseek-v4.1-flash"], // 261020 strict schema rejected; json_object unverified. Omit rather than invent a fallback. noStructuredOutputModels: ["deepseek-v4.1-flash-1017"], - modelDefaultReasoningEfforts: { ...Object.fromEntries(QWEN38_FAMILY.map(id => [id, "xhigh"])), "deepseek-v4.1-flash-1017": "high" }, - directReasoningEffortModels: QWEN38_FAMILY, + modelDefaultReasoningEfforts: { ...Object.fromEntries(QWEN38_FAMILY.map(id => [id, "xhigh"])), [QWEN4_MAX]: "high", "deepseek-v4.1-flash-1017": "high" }, + directReasoningEffortModels: [...QWEN38_FAMILY, QWEN4_MAX], thinkingBudgetModels: ALIBABA_TOKEN_PLAN_QWEN_MODELS.filter(id => !QWEN38_FAMILY.includes(id)), - preserveReasoningContentModels: ALIBABA_TOKEN_PLAN_PRESERVE_REASONING, + preserveReasoningContentModels: [...ALIBABA_TOKEN_PLAN_PRESERVE_REASONING, QWEN4_MAX], // Responses replay uses this provider-level flag, not the Chat-path model list above; // measured live on this gateway (see the pin comment). The model list still covers a // caller who opts back into Chat. @@ -1682,8 +1701,13 @@ export const PROVIDER_REGISTRY_EXTENDED: readonly ProviderRegistryEntry[] = [ featured: false, dashboardUrl: "https://github.com/settings/copilot", liveModels: true, - models: ["gpt-4o", "gpt-4.1", "gpt-4.1-mini", "claude-sonnet-4", "gemini-2.5-pro", "gpt-5-mini", "gpt-5.3-codex", "gpt-5.4", "gpt-5.4-mini", "gpt-5.5", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-5.6-terra", "gpt-6.2-sol", "gpt-6.2-astra", "gpt-6.1-sol", "gpt-6.1-terra", "gpt-6-sol", "gpt-6-luna"], - defaultModel: "gpt-4o", + // 2026-11-26 (docs.github.com/en/copilot/reference/ai-models/supported-models): retired ids + // leave the cold-start seed (gpt-4.1 06-01, claude-sonnet-4 05-01, gemini-2.5-pro 07-31, + // gpt-5-mini/5.4/5.4-mini/5.5 10-19, gpt-5.6-terra 11-16; gpt-4o and gpt-4.1-mini are not on + // the supported list). The default is GPT-5.3-Codex, which GitHub names its long-term support + // model and the fallback when no other model is available. Wire defaults below are untouched. + models: ["gpt-5.3-codex", "gpt-5.6-luna", "gpt-5.6-sol", "gpt-6.2-sol", "gpt-6.2-astra", "gpt-6.1-sol", "gpt-6.1-terra", "gpt-6-sol", "gpt-6-luna"], + defaultModel: "gpt-5.3-codex", // Copilot fronts a mixed-wire catalog: these models reject /chat/completions for // real Codex-agent traffic (function tools + reasoning), so every inbound wire // rides Responses. Evidence: issue #748 field runs, pi.dev/models/github-copilot/* diff --git a/src/providers/registry/model-seeds.ts b/src/providers/registry/model-seeds.ts index 38bfd986fdc..57ad3693898 100644 --- a/src/providers/registry/model-seeds.ts +++ b/src/providers/registry/model-seeds.ts @@ -102,7 +102,22 @@ export const ANTHROPIC_MODEL_REASONING_EFFORTS: Record = Objec // disappears. export const ZAI_GLM_53_MODELS = ["glm-5.3", "glm-5.3[1m]", "glm-5.3-flash"]; export const ZAI_GLM_52_MODELS = ["glm-5.2", "glm-5.2[1m]"]; -export const ZAI_GLM_5X_MODELS = [...ZAI_GLM_53_MODELS, ...ZAI_GLM_52_MODELS]; +// 261126 GLM-5.4: on every GLM Coding Plan tier (docs.z.ai/devpack/latest-model.md, +// docs.bigmodel.cn/cn/coding-plan/latest-model.md); the pay-as-you-go Model API is still pending. +// docs.z.ai/guides/llm/glm-5.4.md: 1M context, 128K output, video/image/text/file input, and the +// same low/high/max effort fold (default max) as GLM-5.3. +export const ZAI_GLM_54_MODELS = ["glm-5.4", "glm-5.4[1m]"]; +export const ZAI_GLM_5X_MODELS = [...ZAI_GLM_54_MODELS, ...ZAI_GLM_53_MODELS, ...ZAI_GLM_52_MODELS]; +/** 5.x members whose effort ladder, default effort and output cap follow the 5.3 contract. */ +export const ZAI_GLM_53_CONTRACT_MODELS = [...ZAI_GLM_54_MODELS, ...ZAI_GLM_53_MODELS]; +/** Native VLMs in the 5.x family: images go straight to the model, never through the sidecar. */ +export const ZAI_GLM_5X_NATIVE_VISION_MODELS = ["glm-5.3-flash", ...ZAI_GLM_54_MODELS]; +/** Static roster of the Z.ai and BigModel Chat Coding Plan rows (one list, two hosts). */ +export const ZAI_CODING_PLAN_MODELS = [...ZAI_GLM_54_MODELS, "glm-5.3", "glm-5.3[1m]", "glm-5.3-flash", "glm-5.2", "glm-5.2[1m]", "glm-5.1", "glm-5", "glm-4.6"]; +/** Static roster of the BigModel Coding Plan Responses row. */ +export const BIGMODEL_RESPONSES_MODELS = ["glm-5.4", "glm-5.3", "glm-5.3-flash", "glm-5-turbo"]; +/** Static Gemini API (AI Studio) roster; see the google entry for the 2026-11-26 sources. */ +export const GOOGLE_GEMINI_API_MODELS = ["gemini-4-neon", "gemini-4-hydrogen", "gemini-4-carbon", "gemini-4-argon", "gemini-3.8-flash", "gemini-3.6-flash", "gemini-3.5-flash-lite", "gemini-3.1-pro-preview"]; /** * The 5.x rows whose images the PROXY has to describe, which is NOT the same set as * the 5.x rows themselves. @@ -117,7 +132,7 @@ export const ZAI_GLM_5X_MODELS = [...ZAI_GLM_53_MODELS, ...ZAI_GLM_52_MODELS]; * constant also drives `modelSupportsReasoningSummaries` and * `preserveReasoningContentModels`, where flash DOES belong. */ -export const ZAI_GLM_5X_SIDECAR_VISION_MODELS = ZAI_GLM_5X_MODELS.filter(id => id !== "glm-5.3-flash"); +export const ZAI_GLM_5X_SIDECAR_VISION_MODELS = ZAI_GLM_5X_MODELS.filter(id => !ZAI_GLM_5X_NATIVE_VISION_MODELS.includes(id)); /** * Positive input-modality declaration for the Chat-path GLM rows. * @@ -140,7 +155,7 @@ export const ZAI_GLM_5X_SIDECAR_VISION_MODELS = ZAI_GLM_5X_MODELS.filter(id => i */ export const ZAI_GLM_5X_INPUT_MODALITIES: Record = { ...Object.fromEntries(ZAI_GLM_5X_SIDECAR_VISION_MODELS.map(id => [id, ["text"]])), - "glm-5.3-flash": ["text", "image"], + ...Object.fromEntries(ZAI_GLM_5X_NATIVE_VISION_MODELS.map(id => [id, ["text", "image"]])), }; export const ZAI_GLM_52_REASONING_EFFORTS = ["low", "medium", "high", "xhigh", "max"]; /** @@ -153,7 +168,7 @@ export const ZAI_GLM_52_REASONING_EFFORTS = ["low", "medium", "high", "xhigh", " export const ZAI_GLM_53_REASONING_EFFORTS = ["low", "high", "max"]; /** Per-model ladders for the Coding Plan rows: 5.3 gets its three effective tiers, 5.2 keeps five. */ export const ZAI_GLM_5X_REASONING_EFFORTS: Record = { - ...Object.fromEntries(ZAI_GLM_53_MODELS.map(id => [id, ZAI_GLM_53_REASONING_EFFORTS])), + ...Object.fromEntries(ZAI_GLM_53_CONTRACT_MODELS.map(id => [id, ZAI_GLM_53_REASONING_EFFORTS])), ...Object.fromEntries(ZAI_GLM_52_MODELS.map(id => [id, ZAI_GLM_52_REASONING_EFFORTS])), }; // 260710 MiniMax models and context windows: Tier-2 evidence in @@ -311,7 +326,9 @@ export const OPENAI_DAYBREAK_MAX_INPUT_TOKENS: Record = { export const OPENAI_DAYBREAK_REASONING_EFFORTS: Record = Object.fromEntries( OPENAI_DAYBREAK_MODELS.map(id => [id, [] as string[]]), ); -export const OPENROUTER_GPT56_MODELS = OPENAI_GPT56_MODELS.map(id => `openai/${id}`); +// OpenAI documents bare `gpt-5.6` as an alias of GPT-5.6 Sol; OpenRouter's public catalog lists +// only the tier slugs (openrouter.ai/api/v1/models, 2026-11-26), so the alias is not seeded there. +export const OPENROUTER_GPT56_MODELS = OPENAI_GPT56_MODELS.filter(id => id !== "gpt-5.6").map(id => `openai/${id}`); export const XAI_MODELS = [ "grok-4.7", "grok-4.6", @@ -381,6 +398,11 @@ export const THINKING_BUDGET_EFFORTS = ["low", "medium", "high", "xhigh", "max"] // Qwen3.8-Max is the first Qwen3.x model with official direct `reasoning_effort` support. // Evidence: https://qwen.ai/blog?id=qwen3.8 export const QWEN38_REASONING_EFFORTS = ["low", "medium", "xhigh"]; +// Qwen4-Max takes direct `reasoning_effort` low/high/xhigh (default high; minimal->low, +// medium->high, max->xhigh) on Chat Completions, Responses and Anthropic Messages. +// Evidence: https://www.alibabacloud.com/help/en/model-studio/qwen4-max (2026-11-26). +export const QWEN4_MAX = "qwen4-max"; +export const QWEN4_MAX_REASONING_EFFORTS = ["low", "high", "xhigh"]; export const THINKING_BUDGET_MODELS = [ "qwen3.5-397b", "qwen3.6-35b", "qwen3.5-plus", "qwen3.6-plus", "qwen3.7-max", "qwen3.7-plus", @@ -593,10 +615,15 @@ export const deepseekReasoningMapFor = (modelId: string): Record // untested on this exact id. Published 1M context and 393K output use 393216 here, // consistent with the existing plan budget convention, not a measured boundary; // the lab's 384000 precision differs. Do not inherit the bare model's JSON fallback. -export const ALIBABA_TOKEN_PLAN_MODELS = [ +export const ALIBABA_TOKEN_PLAN_MODELS_BEFORE_QWEN4 = [ "qwen3.8-max", "qwen3.8-flash", "qwen3.7-max", "qwen3.7-plus", "qwen3.6-flash", "deepseek-v4-pro", "deepseek-v4-pro-0813", "deepseek-v4-flash-0731", "deepseek-v4.1-flash", "deepseek-v4.1-flash-1017", "glm-5.2", "glm-5.3", ]; +// 261126: qwen4-max is on the Personal Edition supported list +// (https://help.aliyun.com/en/model-studio/token-plan-personal-quick-start). The International +// Team overview publishes no equivalent, so it is Beijing-only: its window and output ceiling live +// in the BEIJING maps below, not in the maps the International row shares. +export const ALIBABA_TOKEN_PLAN_MODELS = [QWEN4_MAX, ...ALIBABA_TOKEN_PLAN_MODELS_BEFORE_QWEN4]; export const ALIBABA_TOKEN_PLAN_QWEN_MODELS = [ "qwen3.8-max", "qwen3.8-flash", "qwen3.7-max", "qwen3.7-plus", "qwen3.6-flash", ]; @@ -739,6 +766,11 @@ export const ALIBABA_TOKEN_PLAN_MAX_OUTPUT_TOKENS: Record = { "glm-5.2": 131_072, "glm-5.3": 131_072, "glm-5.1": 128_000, "glm-5": 16_384, "MiniMax-M2.5": 32_768, }; +// qwen4-max model page: text/image/video input, 1,000,000 context, 131,072 maximum output (non-thinking). +// The International modality map spreads the shared Beijing one, so qwen4-max gets its own map. +export const ALIBABA_TOKEN_PLAN_BEIJING_INPUT_MODALITIES: Record = { ...ALIBABA_TOKEN_PLAN_INPUT_MODALITIES, [QWEN4_MAX]: ["text", "image"] }; +export const ALIBABA_TOKEN_PLAN_BEIJING_CONTEXT_WINDOWS: Record = { ...ALIBABA_TOKEN_PLAN_CONTEXT_WINDOWS, [QWEN4_MAX]: 1_000_000 }; +export const ALIBABA_TOKEN_PLAN_BEIJING_MAX_OUTPUT_TOKENS: Record = { ...ALIBABA_TOKEN_PLAN_MAX_OUTPUT_TOKENS, [QWEN4_MAX]: 131_072 }; export const ALIBABA_TOKEN_PLAN_NO_VISION = [ "qwen3.7-max", "deepseek-v4-pro", "deepseek-v4-pro-0813", "deepseek-v4-flash-0731", "glm-5.2", "glm-5.3", "glm-5.1", "glm-5", "MiniMax-M2.5", diff --git a/src/providers/stale-model-roster-migration.ts b/src/providers/stale-model-roster-migration.ts index 806c62762b3..144111c2ca9 100644 --- a/src/providers/stale-model-roster-migration.ts +++ b/src/providers/stale-model-roster-migration.ts @@ -22,6 +22,10 @@ import { ALIBABA_INTL_TOKEN_PLAN_MODELS, ALIBABA_TOKEN_PLAN_CONTEXT_WINDOWS, ALIBABA_TOKEN_PLAN_MAX_OUTPUT_TOKENS, + ALIBABA_TOKEN_PLAN_BEIJING_CONTEXT_WINDOWS, + ALIBABA_TOKEN_PLAN_BEIJING_MAX_OUTPUT_TOKENS, + ALIBABA_TOKEN_PLAN_MODELS_BEFORE_QWEN4, + QWEN4_MAX, KIMI_API_DEFAULT_REASONING_EFFORTS, KIMI_API_MODEL_CONTEXT_WINDOWS, KIMI_API_MODELS, @@ -37,6 +41,9 @@ import { MINIMAX_MODELS_BEFORE_M31, MINIMAX_MODEL_CONTEXT_WINDOWS, NEURALWATT_MODEL_HINTS, + GOOGLE_GEMINI_API_MODELS, + ZAI_CODING_PLAN_MODELS, + BIGMODEL_RESPONSES_MODELS, } from "./registry/model-seeds"; import type { OcxConfig } from "../types"; import { modelRecordValue } from "../reasoning-effort"; @@ -49,6 +56,11 @@ export interface StaleModelRoster { /** Exact old roster after id renames; metadata additions still compare against `from`. */ afterModelRenames?: readonly string[]; to: readonly string[]; + /** + * Ids `from` carries that the registry has since dropped. A refreshed row keeps them after + * `to`, so a saved defaultModel or selection naming one is never orphaned by the refresh. + */ + retain?: readonly string[]; /** Per-model seed values for the added ids, written only into containers that exist. */ contextWindows?: Readonly>; /** @@ -114,10 +126,41 @@ export const STALE_MODEL_ROSTERS: readonly StaleModelRoster[] = [ { provider: "deepseek", from: ["deepseek-chat", "deepseek-reasoner", "deepseek-flash", "deepseek-v4-flash", "deepseek-v4-flash-vision-exp"], - to: ["deepseek-chat", "deepseek-reasoner", "deepseek-flash", "deepseek-v4-flash", "deepseek-v4-pro", "deepseek-v4-flash-vision-exp"], + // The target is the registry seed today; deepseek-chat/reasoner left it on 2026-11-26 but a + // saved row keeps them, since its defaultModel may still name one. + to: ["deepseek-flash", "deepseek-v4-flash", "deepseek-v4-pro", "deepseek-v4-flash-vision-exp"], + retain: ["deepseek-chat", "deepseek-reasoner"], contextWindows: { "deepseek-v4-pro": 1_048_576 }, destinationBaseUrls: ["https://api.deepseek.com", "https://api.deepseek.com/v1"], }, + // 261126 Gemini API refresh: Gemini 4 Neon/Hydrogen/Carbon join; the redirected 3.5/3.7 Flash ids + // left the picker but stay on a saved row, whose defaultModel may name one. + { + provider: "google", + from: ["gemini-4-argon", "gemini-3.8-flash", "gemini-3.6-flash", "gemini-3.5-flash", "gemini-3.5-flash-lite", "gemini-3.1-pro-preview", "gemini-3.7-flash"], + to: GOOGLE_GEMINI_API_MODELS, + retain: ["gemini-3.5-flash", "gemini-3.7-flash"], + contextWindows: { "gemini-4-neon": 1_048_576, "gemini-4-hydrogen": 1_048_576, "gemini-4-carbon": 1_048_576 }, + defaultReasoningEfforts: { "gemini-4-neon": "high", "gemini-4-hydrogen": "high" }, + destinationBaseUrls: ["https://generativelanguage.googleapis.com"], + }, + // 261126 GLM-5.4 joined every Coding Plan tier; each static row's previous seed picks it up. + ...([ + ["zai", ZAI_CODING_PLAN_MODELS, 1_048_576, ["https://api.z.ai"]], + ["zhipu-bigmodel-coding", ZAI_CODING_PLAN_MODELS, 1_000_000, ["https://open.bigmodel.cn/api/coding/paas/v4"]], + ["zhipu-bigmodel-responses", BIGMODEL_RESPONSES_MODELS, 1_048_576, ["https://open.bigmodel.cn/api/v1"]], + ] as const).map(([provider, to, window, destinationBaseUrls]) => { + const added = to.filter(id => id.startsWith("glm-5.4")); + return { + provider, + from: to.filter(id => !id.startsWith("glm-5.4")), + to, + contextWindows: Object.fromEntries(added.map(id => [id, window])), + maxOutputTokens: Object.fromEntries(added.map(id => [id, 131_072])), + defaultReasoningEfforts: Object.fromEntries(added.map(id => [id, "max"])), + destinationBaseUrls, + }; + }), ...["minimax", "minimax-cn"].map(provider => ({ provider, from: MINIMAX_MODELS_BEFORE_M31, @@ -130,7 +173,16 @@ export const STALE_MODEL_ROSTERS: readonly StaleModelRoster[] = [ .flatMap(url => [url, `${url}/chat/completions`]), })), ...[ - { provider: "alibaba-token-plan", from: ALIBABA_TOKEN_PLAN_MODELS_BEFORE_1017, to: ALIBABA_TOKEN_PLAN_MODELS }, + { + provider: "alibaba-token-plan", from: ALIBABA_TOKEN_PLAN_MODELS_BEFORE_1017, to: ALIBABA_TOKEN_PLAN_MODELS, + contextWindows: ALIBABA_TOKEN_PLAN_BEIJING_CONTEXT_WINDOWS, maxOutputTokens: ALIBABA_TOKEN_PLAN_BEIJING_MAX_OUTPUT_TOKENS, + }, + // 261126 qwen4-max: a row saved with the pre-Qwen4 Beijing seed picks the new flagship up. + { + provider: "alibaba-token-plan", from: ALIBABA_TOKEN_PLAN_MODELS_BEFORE_QWEN4, to: ALIBABA_TOKEN_PLAN_MODELS, + contextWindows: ALIBABA_TOKEN_PLAN_BEIJING_CONTEXT_WINDOWS, maxOutputTokens: ALIBABA_TOKEN_PLAN_BEIJING_MAX_OUTPUT_TOKENS, + defaultReasoningEfforts: { [QWEN4_MAX]: "high" }, + }, // International honors pay-as-you-go and Custom URLs, which may still serve the retired ids. // Beijing needs no guard: the router pins it to the registry Token Plan host. { @@ -138,10 +190,10 @@ export const STALE_MODEL_ROSTERS: readonly StaleModelRoster[] = [ destinationBaseUrls: [ALIBABA_INTL_TOKEN_PLAN_BASE_URL], }, ].map(entry => ({ - ...entry, contextWindows: ALIBABA_TOKEN_PLAN_CONTEXT_WINDOWS, maxOutputTokens: ALIBABA_TOKEN_PLAN_MAX_OUTPUT_TOKENS, - defaultReasoningEfforts: { "deepseek-v4.1-flash-1017": "high" }, + ...entry, + defaultReasoningEfforts: { "deepseek-v4.1-flash-1017": "high", ...("defaultReasoningEfforts" in entry ? entry.defaultReasoningEfforts : {}) }, })), // Kimi K3.1 Pro (#7653). Both the International and China platforms list kimi-k3.1-pro and // -highspeed; a Custom URL may be another gateway, so it keeps its saved list. @@ -213,7 +265,7 @@ export function projectStaleModelRosters( } if (!sameList(prov.models, entry.from) && !(entry.afterModelRenames && sameList(prov.models, entry.afterModelRenames))) continue; - prov.models = [...entry.to]; + prov.models = [...entry.to, ...(entry.retain ?? []).filter(id => entry.from.includes(id) && !entry.to.includes(id))]; fillExisting(prov.modelContextWindows, entry.contextWindows, added); fillExisting(prov.modelMaxOutputTokens, entry.maxOutputTokens, added); fillExisting(prov.modelDefaultReasoningEfforts, entry.defaultReasoningEfforts, added); diff --git a/src/usage/expected-prices.ts b/src/usage/expected-prices.ts index 998681e9122..3264bf62c7b 100644 --- a/src/usage/expected-prices.ts +++ b/src/usage/expected-prices.ts @@ -94,10 +94,12 @@ const GEMINI_37_FLASH: Cost4 = { input: 0.75, output: 3.75, cacheRead: 0.075, ca // rising to $1.50 / $7.50 on 2027-01-01. A SEPARATE constant on purpose: equal today, but // aliasing them would silently drag 3.8 along if 3.7's row is ever re-verified differently. const GEMINI_38_FLASH: Cost4 = { input: 0.75, output: 3.75, cacheRead: 0.075, cacheWrite: 0 }; -// Gemini 4 Argon introductory paid-tier rate: $2 in / $10 out (thinking included) / $0.10 cached -// per 1M through 2026-11-30, stepping up to $4 / $20 / $0.20 on 2026-12-01. Revisit this row -// then. No free tier. Implicit caching only, so there is no per-token cache-write price. -const GEMINI_4_ARGON: Cost4 = { input: 2, output: 10, cacheRead: 0.1, cacheWrite: 0 }; +// Gemini 4 Argon and Carbon list rate: $4 in / $20 out (thinking included) / $0.20 cached per 1M. +// Google's $2 / $10 / $0.10 introductory rate through 2026-11-30 is a time-boxed promo and, like +// DEVIN_SWE2_NOTE, is not baked in. No free tier. Implicit caching only, so no cache-write price. +// Two constants on purpose: equal today, but one model's re-verification must not drag the other. +const GEMINI_4_ARGON: Cost4 = { input: 4, output: 20, cacheRead: 0.2, cacheWrite: 0 }; +const GEMINI_4_CARBON: Cost4 = { input: 4, output: 20, cacheRead: 0.2, cacheWrite: 0 }; // Standard paid Gemini API rates. Antigravity uses the same token rates as an // estimated reference. Its generation usage reports cache hits but no cache-write count. const GEMINI_4_API_RATES = [ @@ -232,7 +234,8 @@ export function cursorFastPriceSource(provider: string, modelId: string): string const GEMINI_PRICING = "https://ai.google.dev/gemini-api/docs/pricing (2026-07-22); cacheWrite=0: storage is billed per-hour, not per-token"; const GEMINI_37_PRICING = "https://ai.google.dev/gemini-api/docs/pricing (2026-08-14); promotional rate through 2026-12-31, rises to 1.50/7.50 on 2027-01-01; cacheWrite=0: storage is billed per-hour, not per-token"; -const GEMINI_4_ARGON_PRICING = "https://ai.google.dev/gemini-api/docs/pricing (2026-10-14); introductory rate through 2026-11-30, rises to 4/20 (0.20 cached) on 2026-12-01; cacheWrite=0: implicit caching only"; +const GEMINI_4_ARGON_PRICING = "https://ai.google.dev/gemini-api/docs/pricing#gemini-4-argon (2026-11-26); list rate 4/20 (0.20 cached) from 2026-12-01; the 2/10 (0.10 cached) introductory rate through 2026-11-30 is a time-boxed promo, not baked in; cacheWrite=0: implicit caching only"; +const GEMINI_4_CARBON_PRICING = "https://ai.google.dev/gemini-api/docs/pricing#gemini-4-carbon (2026-11-26); list rate 4/20 (0.20 cached) from 2026-12-01; the 2/10 (0.10 cached) introductory rate through 2026-11-30 is a time-boxed promo, not baked in; cacheWrite=0: implicit caching only"; const GEMINI_38_PRICING = "https://ai.google.dev/gemini-api/docs/pricing (2026-09-03); promotional rate through 2026-12-31, rises to 1.50/7.50 on 2027-01-01; cacheWrite=0: storage is billed per-hour, not per-token"; const MINIMAX_PRICING = "https://platform.minimax.io/docs/guides/pricing-paygo"; const OPENAI_GPT56_PRICING = "https://developers.openai.com/api/docs/pricing"; @@ -471,10 +474,10 @@ export const EXPECTED_PRICE_OVERLAYS: readonly ExpectedPriceOverlay[] = [ }))), // Gemini 4 Argon on Antigravity (AI Ultra / Enterprise only): the picker id plus its three // verified CCA wire ids. Billing equivalence to the API price is inferred. - { provider: "google-antigravity", modelId: "gemini-4-argon", cost4: GEMINI_4_ARGON, source: `derived: Gemini 4 Argon introductory rate through 2026-11-30 ${GEMINI_4_ARGON_PRICING}`, verifiedAt: "2026-10-14", status: "verified-derived" }, - { provider: "google-antigravity", modelId: "gemini-4-argon-low", cost4: GEMINI_4_ARGON, source: `derived: gemini-4-argon ${GEMINI_4_ARGON_PRICING}`, verifiedAt: "2026-10-14", status: "verified-derived" }, - { provider: "google-antigravity", modelId: "gemini-4-argon-medium", cost4: GEMINI_4_ARGON, source: `derived: gemini-4-argon ${GEMINI_4_ARGON_PRICING}`, verifiedAt: "2026-10-14", status: "verified-derived" }, - { provider: "google-antigravity", modelId: "gemini-4-argon-high", cost4: GEMINI_4_ARGON, source: `derived: gemini-4-argon ${GEMINI_4_ARGON_PRICING}`, verifiedAt: "2026-10-14", status: "verified-derived" }, + { provider: "google-antigravity", modelId: "gemini-4-argon", cost4: GEMINI_4_ARGON, source: `derived: Gemini API list rate ${GEMINI_4_ARGON_PRICING}`, verifiedAt: "2026-11-26", status: "verified-derived" }, + { provider: "google-antigravity", modelId: "gemini-4-argon-low", cost4: GEMINI_4_ARGON, source: `derived: gemini-4-argon ${GEMINI_4_ARGON_PRICING}`, verifiedAt: "2026-11-26", status: "verified-derived" }, + { provider: "google-antigravity", modelId: "gemini-4-argon-medium", cost4: GEMINI_4_ARGON, source: `derived: gemini-4-argon ${GEMINI_4_ARGON_PRICING}`, verifiedAt: "2026-11-26", status: "verified-derived" }, + { provider: "google-antigravity", modelId: "gemini-4-argon-high", cost4: GEMINI_4_ARGON, source: `derived: gemini-4-argon ${GEMINI_4_ARGON_PRICING}`, verifiedAt: "2026-11-26", status: "verified-derived" }, { provider: "google-antigravity", modelId: "gemini-3.8-flash", cost4: GEMINI_38_FLASH, source: `derived: Gemini 3.8 Flash promotional rate through 2026-12-31 ${GEMINI_38_PRICING}`, verifiedAt: "2026-09-03", status: "verified-derived" }, { provider: "google-antigravity", modelId: "gemini-3.8-flash-low", cost4: GEMINI_38_FLASH, source: `derived: gemini-3.8-flash ${GEMINI_38_PRICING}`, verifiedAt: "2026-09-03", status: "verified-derived" }, { provider: "google-antigravity", modelId: "gemini-3.8-flash-medium", cost4: GEMINI_38_FLASH, source: `derived: gemini-3.8-flash ${GEMINI_38_PRICING}`, verifiedAt: "2026-09-03", status: "verified-derived" }, @@ -533,7 +536,8 @@ export const EXPECTED_PRICE_OVERLAYS: readonly ExpectedPriceOverlay[] = [ // Developer API row: the price IS published for this surface, so `verified`. { provider: "google", modelId: "gemini-3.7-flash", cost4: GEMINI_37_FLASH, source: GEMINI_37_PRICING, verifiedAt: "2026-08-14", status: "verified" }, { provider: "google", modelId: "gemini-3.8-flash", cost4: GEMINI_38_FLASH, source: GEMINI_38_PRICING, verifiedAt: "2026-09-03", status: "verified" }, - { provider: "google", modelId: "gemini-4-argon", cost4: GEMINI_4_ARGON, source: GEMINI_4_ARGON_PRICING, verifiedAt: "2026-10-14", status: "verified" }, + { provider: "google", modelId: "gemini-4-argon", cost4: GEMINI_4_ARGON, source: GEMINI_4_ARGON_PRICING, verifiedAt: "2026-11-26", status: "verified" }, + { provider: "google", modelId: "gemini-4-carbon", cost4: GEMINI_4_CARBON, source: GEMINI_4_CARBON_PRICING, verifiedAt: "2026-11-26", status: "verified" }, { provider: "google-antigravity", modelId: "gemini-3.1-pro-preview", cost4: GEMINI_31_PRO, source: GEMINI_PRICING, verifiedAt: "2026-07-20", status: "verified" }, // Antigravity-bundled third-party models — derived from the underlying vendor's // official API price (Antigravity itself bills via subscription quota). diff --git a/structure/providers-and-adapters.md b/structure/providers-and-adapters.md index c6017de6779..c8d45908872 100644 --- a/structure/providers-and-adapters.md +++ b/structure/providers-and-adapters.md @@ -396,7 +396,7 @@ axis that outranks every source here, so it is where a deliberate text-only over (`ocx provider edit --model --text-only` writes it) and the one declaration a restart cannot take back. -When `/models` omits MiniMax-M3.1-Flash, `src/providers/stale-model-roster-migration.ts` replaces only a saved roster identical to the old seed and fills existing window, output-limit and default-effort records during startup; `CALLABLE_CONFIGURED_COMPATIBILITY_MODELS` (`src/codex/catalog/model-hints.ts`) retains it in the live catalog. `MODEL_RENAMES` (`src/providers/model-rename-migration.ts`) repairs saved rows that still name the retired MiniMax-M3.1-Flash-Preview id. The same startup projection restores DeepSeek V4 Pro only for the exact previous native seed on the official destination and registry adapter, filling missing Pro context in existing maps. It also replaces the exact previous Neuralwatt seed with the live chat-model roster on `https://api.neuralwatt.com/v1`. Operator lists (including empty lists), custom destinations and explicit context overrides remain unchanged; normal registry enrichment supplies Pro's reasoning metadata. +When `/models` omits MiniMax-M3.1-Flash, `src/providers/stale-model-roster-migration.ts` replaces only a saved roster identical to the old seed and fills existing window, output-limit and default-effort records during startup; `CALLABLE_CONFIGURED_COMPATIBILITY_MODELS` (`src/codex/catalog/model-hints.ts`) retains it in the live catalog. `MODEL_RENAMES` (`src/providers/model-rename-migration.ts`) repairs saved rows that still name the retired MiniMax-M3.1-Flash-Preview id. The same startup projection restores DeepSeek V4 Pro only for the exact previous native seed on the official destination and registry adapter, filling missing Pro context in existing maps. It also replaces the exact previous Neuralwatt seed with the live chat-model roster on `https://api.neuralwatt.com/v1`. Operator lists (including empty lists), custom destinations and explicit context overrides remain unchanged; normal registry enrichment supplies Pro's reasoning metadata. An entry's `retain` list names ids the registry seed has dropped that a refreshed row keeps after the new seed, so a saved `defaultModel` naming one is never orphaned: DeepSeek keeps `deepseek-chat`/`deepseek-reasoner` and the Gemini API row keeps `gemini-3.5-flash`/`gemini-3.7-flash` while gaining Gemini 4 Neon/Hydrogen/Carbon. The same exact-previous-seed rule adds GLM-5.4 to the static `zai`, `zhipu-bigmodel-coding` and `zhipu-bigmodel-responses` rows on their official destinations. Both MiniMax Coding Plan presets declare `text` and `image` for M3 and M3.1 in `src/providers/registry/model-seeds.ts`; registry enrichment fills missing saved declarations, so id-only live rows enable the Combo image switch when every target supports images. Explicit overrides still win; video is outside Codex's catalog input enum. MiniMax seed refresh and partial output-limit backfill apply only to the official HTTPS `/v1` endpoints (including `/chat/completions`) or an absent/empty saved URL; Custom destinations keep their roster and metadata maps. diff --git a/tests/adapters/google/google-hardening.test.ts b/tests/adapters/google/google-hardening.test.ts index dab2f5a08e7..27bd8324862 100644 --- a/tests/adapters/google/google-hardening.test.ts +++ b/tests/adapters/google/google-hardening.test.ts @@ -773,8 +773,8 @@ describe("google provider hardening", () => { const google = PROVIDER_REGISTRY.find(entry => entry.id === "google"); const vertex = PROVIDER_REGISTRY.find(entry => entry.id === "google-vertex"); - expect(google?.defaultModel).toBe("gemini-3.5-flash"); - expect(google?.models).toEqual(["gemini-4-argon", "gemini-3.8-flash", "gemini-3.6-flash", "gemini-3.5-flash", "gemini-3.5-flash-lite", "gemini-3.1-pro-preview", "gemini-3.7-flash"]); + expect(google?.defaultModel).toBe("gemini-3.6-flash"); + expect(google?.models).toEqual(["gemini-4-neon", "gemini-4-hydrogen", "gemini-4-carbon", "gemini-4-argon", "gemini-3.8-flash", "gemini-3.6-flash", "gemini-3.5-flash-lite", "gemini-3.1-pro-preview"]); expect(google?.modelContextWindows?.["gemini-3.8-flash"]).toBe(1_048_576); expect(google?.modelInputModalities?.["gemini-3.8-flash"]).toEqual(["text", "image"]); // `minimal` is a documented validation error on this generation, so the ladder must not diff --git a/tests/cli/cli-models.test.ts b/tests/cli/cli-models.test.ts index 4ca7e9c8f0e..018eb4824d6 100644 --- a/tests/cli/cli-models.test.ts +++ b/tests/cli/cli-models.test.ts @@ -554,7 +554,7 @@ describe("ocx models", () => { const result = runCli(["models", "--json"], { OPENCODEX_HOME: dir }); expect(result.status).toBe(0); const rows = JSON.parse(result.stdout).models as Array<{ provider: string; model: string }>; - expect(rows.filter(row => row.provider === "deepseek").map(row => row.model)).toContain("deepseek-chat"); + expect(rows.filter(row => row.provider === "deepseek").map(row => row.model)).toContain("deepseek-flash"); expect(rows.filter(row => row.provider === "mimo-free").map(row => row.model)).toEqual(["my-model"]); } finally { removeTreeWithRetry(dir); } const matching = freshConfig({ providers: { "mimo-free": { adapter: "mimo-free", diff --git a/tests/codex-integration/codex-catalog.test.ts b/tests/codex-integration/codex-catalog.test.ts index 1b3b5185d2e..c30e84febd1 100644 --- a/tests/codex-integration/codex-catalog.test.ts +++ b/tests/codex-integration/codex-catalog.test.ts @@ -6208,6 +6208,7 @@ describe("Codex catalog routed normalization", () => { }; enrichProviderFromRegistry("GLM", opinionated); expect(opinionated.modelSupportsReasoningSummaries).toEqual({ + "glm-5.4": true, "glm-5.4[1m]": true, "glm-5.2": false, "glm-5.2[1m]": true, "glm-5.3": true, diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index d8027b849f9..29963e66760 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -1272,6 +1272,8 @@ "opper-provider.test.ts": "providers", "tokenlab-protocols.test.ts": "providers", "modelflare-provider.test.ts": "providers", "gpt61-terra-provider-rows.test.ts": "providers", + "registry-default-in-seed.test.ts": "providers", + "vendor-catalog-refresh.test.ts": "providers", "gpt62-provider-rows.test.ts": "providers", "aistupidlevel-provider.test.ts": "providers", "cheapaimodel-provider.test.ts": "providers", diff --git a/tests/gui/alibaba-intl-token-plan.test.ts b/tests/gui/alibaba-intl-token-plan.test.ts index 3f432afc509..2954f42ee6c 100644 --- a/tests/gui/alibaba-intl-token-plan.test.ts +++ b/tests/gui/alibaba-intl-token-plan.test.ts @@ -179,7 +179,7 @@ describe("alibaba-token-plan-intl registry entry", () => { // entitled from its 260917 first listing, probed callable on a Personal key). const cnModels = PROVIDER_REGISTRY.find(e => e.id === "alibaba-token-plan")!.models; expect(cnModels).toEqual([ - "qwen3.8-max", "qwen3.8-flash", "qwen3.7-max", "qwen3.7-plus", "qwen3.6-flash", + "qwen4-max", "qwen3.8-max", "qwen3.8-flash", "qwen3.7-max", "qwen3.7-plus", "qwen3.6-flash", "deepseek-v4-pro", "deepseek-v4-pro-0813", "deepseek-v4-flash-0731", "deepseek-v4.1-flash", "deepseek-v4.1-flash-1017", "glm-5.2", "glm-5.3", ]); // The 260910 DeepSeek rename row is wired: vision-capable, effort ladder, and the diff --git a/tests/providers/alibaba-token-plan-responses-optin.test.ts b/tests/providers/alibaba-token-plan-responses-optin.test.ts index 17d240189f4..0e191e74a64 100644 --- a/tests/providers/alibaba-token-plan-responses-optin.test.ts +++ b/tests/providers/alibaba-token-plan-responses-optin.test.ts @@ -138,7 +138,7 @@ describe("a Responses default flip must carry Responses-side reasoning preservat expect(ALIBABA_TOKEN_PLAN_PRESERVE_REASONING).toContain(model); } expect(getProviderRegistryEntry("alibaba-token-plan")!.preserveReasoningContentModels) - .toEqual(ALIBABA_TOKEN_PLAN_PRESERVE_REASONING); + .toEqual([...ALIBABA_TOKEN_PLAN_PRESERVE_REASONING, "qwen4-max"]); }); // The guard, not a restatement of the case above: preserveReasoningContentModels is read by the diff --git a/tests/providers/gpt61-terra-provider-rows.test.ts b/tests/providers/gpt61-terra-provider-rows.test.ts index 9e4b7bb2b79..dbdf1b3ae56 100644 --- a/tests/providers/gpt61-terra-provider-rows.test.ts +++ b/tests/providers/gpt61-terra-provider-rows.test.ts @@ -104,7 +104,7 @@ describe("GPT-6.1 Terra provider rows", () => { } expect(getProviderRegistryEntry("cursor")!.models).not.toContain(TERRA); expect(getProviderRegistryEntry("openai-apikey")!.defaultModel).toBe("gpt-5.5"); - expect(getProviderRegistryEntry("github-copilot")!.defaultModel).toBe("gpt-4o"); + expect(getProviderRegistryEntry("github-copilot")!.defaultModel).toBe("gpt-5.3-codex"); }); }); diff --git a/tests/providers/model-roster-seed-repair.test.ts b/tests/providers/model-roster-seed-repair.test.ts index 3fb64800d42..9976f2a0ec1 100644 --- a/tests/providers/model-roster-seed-repair.test.ts +++ b/tests/providers/model-roster-seed-repair.test.ts @@ -352,7 +352,7 @@ describe.each([ expect(projectStaleModelRosters(config).changed).toBe(true); const added = entry.to.filter(id => !before.includes(id)); expect(row.modelMaxOutputTokens).toEqual({ - "qwen3.8-max": 4_096, ...Object.fromEntries(added.map(id => [id, ALIBABA_TOKEN_PLAN_MAX_OUTPUT_TOKENS[id]])), + "qwen3.8-max": 4_096, ...Object.fromEntries(added.map(id => [id, entry.maxOutputTokens![id]])), }); expect(routedMaxOutputTokens("custom-token-plan", row, { id: "deepseek-v4.1-flash-1017" } as never)).toBe(393_216); const kept = makeConfig([...before]); diff --git a/tests/providers/provider-registry-parity.test.ts b/tests/providers/provider-registry-parity.test.ts index 47dd6aea191..0a730516b16 100644 --- a/tests/providers/provider-registry-parity.test.ts +++ b/tests/providers/provider-registry-parity.test.ts @@ -549,7 +549,7 @@ describe("provider registry parity", () => { defaultModel: "qwen3.8-max", liveModels: false, models: [ - "qwen3.8-max", "qwen3.8-flash", "qwen3.7-max", "qwen3.7-plus", "qwen3.6-flash", + "qwen4-max", "qwen3.8-max", "qwen3.8-flash", "qwen3.7-max", "qwen3.7-plus", "qwen3.6-flash", "deepseek-v4-pro", "deepseek-v4-pro-0813", "deepseek-v4-flash-0731", "deepseek-v4.1-flash", "deepseek-v4.1-flash-1017", "glm-5.2", "glm-5.3", ], modelInputModalities: { @@ -577,7 +577,7 @@ describe("provider registry parity", () => { preserveReasoningContentModels: expect.arrayContaining(["qwen3.8-max", "qwen3.7-max", "qwen3.7-plus"]), }); expect(PROVIDER_REGISTRY.find(entry => entry.id === "alibaba-token-plan")?.directReasoningEffortModels) - .toEqual(["qwen3.8-max", "qwen3.8-flash"]); + .toEqual(["qwen3.8-max", "qwen3.8-flash", "qwen4-max"]); expect(KEY_LOGIN_PROVIDERS["alibaba-token-plan"].thinkingBudgetModels) .not.toContain("qwen3.8-max"); expect(KEY_LOGIN_PROVIDERS["alibaba-token-plan"].thinkingBudgetModels) @@ -664,7 +664,7 @@ describe("provider registry parity", () => { .map(entry => entry.id); // The 5.3 family carries the number its own catalog reports, 1_048_576, which is what the // domestic Responses row already used. 5.2 keeps the round figure it was seeded with. - expect(zai?.modelContextWindows).toEqual({ "glm-5.3": 1_048_576, "glm-5.3[1m]": 1_048_576, "glm-5.3-flash": 1_048_576, "glm-5.2": 1_000_000, "glm-5.2[1m]": 1_000_000 }); + expect(zai?.modelContextWindows).toEqual({ "glm-5.4": 1_048_576, "glm-5.4[1m]": 1_048_576, "glm-5.3": 1_048_576, "glm-5.3[1m]": 1_048_576, "glm-5.3-flash": 1_048_576, "glm-5.2": 1_000_000, "glm-5.2[1m]": 1_000_000 }); // BUG-R5: glm-5.3-flash is a native VLM (docs.z.ai/guides/vlm/glm-5.3-flash), so it // must never sit in noVisionModels - that list routes a model's images through the // proxy's vision sidecar, which hands the model a text description of a picture it @@ -707,8 +707,8 @@ describe("provider registry parity", () => { // no default effort and no output cap - and this assertion pinned that gap in // place rather than catching it, because it was written from the incomplete // state instead of from the family definition. - expect(zai?.modelDefaultReasoningEfforts).toEqual({ "glm-5.3": "max", "glm-5.3[1m]": "max", "glm-5.3-flash": "max" }); - expect(zai?.modelMaxOutputTokens).toEqual({ "glm-5.3": 131_072, "glm-5.3[1m]": 131_072, "glm-5.3-flash": 131_072 }); + expect(zai?.modelDefaultReasoningEfforts).toEqual({ "glm-5.4": "max", "glm-5.4[1m]": "max", "glm-5.3": "max", "glm-5.3[1m]": "max", "glm-5.3-flash": "max" }); + expect(zai?.modelMaxOutputTokens).toEqual({ "glm-5.4": 131_072, "glm-5.4[1m]": 131_072, "glm-5.3": 131_072, "glm-5.3[1m]": 131_072, "glm-5.3-flash": 131_072 }); // Every 5.3 row carries the same three-tier ladder. Asserted per member rather // than as one object literal so adding a member cannot quietly skip it. for (const id of ["glm-5.3", "glm-5.3[1m]", "glm-5.3-flash"]) { @@ -789,7 +789,7 @@ describe("provider registry parity", () => { baseUrl: "https://open.bigmodel.cn/api/v1", authKind: "key", defaultModel: "glm-5.3", - models: ["glm-5.3", "glm-5.3-flash", "glm-5-turbo"], + models: ["glm-5.4", "glm-5.3", "glm-5.3-flash", "glm-5-turbo"], liveModels: false, preserveCustomDestination: true, preserveResponsesReasoningContent: true, @@ -800,13 +800,13 @@ describe("provider registry parity", () => { // Pinned separately from the global VLM rule above so that copying glm-5.3's ["text"] onto // Flash fails here, naming this preset, rather than only in a loop over every provider. const upstreamModalities = { - "glm-5.3": ["text"], "glm-5.3-flash": ["text", "image"], "glm-5-turbo": ["text"], + "glm-5.4": ["text", "image"], "glm-5.3": ["text"], "glm-5.3-flash": ["text", "image"], "glm-5-turbo": ["text"], }; expect(registry.modelInputModalities).toEqual(upstreamModalities); expect(registry.modelInputModalities?.["glm-5.3-flash"]).toContain("image"); expect(registry.noVisionModels ?? []).not.toContain("glm-5.3-flash"); expect(KEY_LOGIN_PROVIDERS[id]).toMatchObject({ - models: ["glm-5.3", "glm-5.3-flash", "glm-5-turbo"], liveModels: false, apiKeyValidation: "unknown", + models: ["glm-5.4", "glm-5.3", "glm-5.3-flash", "glm-5-turbo"], liveModels: false, apiKeyValidation: "unknown", }); const provider = providerConfigSeed(registry); enrichProviderFromRegistry(id, provider); @@ -821,6 +821,8 @@ describe("provider registry parity", () => { // alike below, and this assertion is what keeps the reason for them different. expect(provider.modelInputModalities).toEqual(upstreamModalities); expect(models).toMatchObject([ + { id: "glm-5.4", contextWindow: 1_048_576, reasoningEfforts: ["low", "high", "max"], + defaultReasoningEffort: "max", supportsReasoningSummaries: true, inputModalities: ["text", "image"] }, { id: "glm-5.3", contextWindow: 1_048_576, reasoningEfforts: ["low", "high", "max"], defaultReasoningEffort: "max", supportsReasoningSummaries: true, inputModalities: ["text", "image"] }, { id: "glm-5.3-flash", contextWindow: 1_048_576, reasoningEfforts: ["low", "high", "max"], @@ -830,6 +832,7 @@ describe("provider registry parity", () => { ]); const entries = buildCatalogEntries(nativeTemplate(), [], models); for (const [modelId, window, efforts] of [ + ["glm-5.4", 1_048_576, ["low", "high", "max", "ultra"]], ["glm-5.3", 1_048_576, ["low", "high", "max", "ultra"]], ["glm-5.3-flash", 1_048_576, ["low", "high", "max", "ultra"]], ["glm-5-turbo", 204_800, []], diff --git a/tests/providers/registry-default-in-seed.test.ts b/tests/providers/registry-default-in-seed.test.ts new file mode 100644 index 00000000000..54f89baab39 --- /dev/null +++ b/tests/providers/registry-default-in-seed.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, test } from "bun:test"; +import { PROVIDER_REGISTRY } from "../../src/providers/registry"; + +// A preset that ships both a static seed and a default must default to a model it seeds. +// When a vendor retires a model, the seed row is the one people delete; a defaultModel left +// pointing at the removed id then hands every fresh install a dead first request. Presets +// without a seed (live-only, local) or without a default are out of scope by construction. +const SEEDED_WITH_DEFAULT = PROVIDER_REGISTRY + .filter(entry => entry.defaultModel && (entry.models?.length ?? 0) > 0) + .map(entry => [entry.id, entry.defaultModel!, entry.models!] as const); + +describe("registry defaultModel", () => { + test("covers a meaningful share of the registry", () => { + expect(SEEDED_WITH_DEFAULT.length).toBeGreaterThan(40); + }); + + test.each(SEEDED_WITH_DEFAULT)("%s defaults to %s, which its seed lists", (_id, defaultModel, models) => { + expect(models).toContain(defaultModel); + }); +}); diff --git a/tests/providers/vendor-catalog-refresh.test.ts b/tests/providers/vendor-catalog-refresh.test.ts new file mode 100644 index 00000000000..d1ed614773f --- /dev/null +++ b/tests/providers/vendor-catalog-refresh.test.ts @@ -0,0 +1,238 @@ +import { describe, expect, test } from "bun:test"; +import { resolveCursorSelection } from "../../src/adapters/cursor/catalog"; +import { CURSOR_STATIC_MODELS, cursorModelContextWindows, cursorModelIds, cursorModelReasoningEfforts } from "../../src/adapters/cursor/discovery"; +import { projectStartupConfigRepairs } from "../../src/providers/model-rename-startup"; +import { getProviderRegistryEntry } from "../../src/providers/registry"; +import { findExpectedPriceOverlay } from "../../src/usage/expected-prices"; +import type { OcxConfig } from "../../src/types"; + +// Vendor catalog refresh, 2026-11-26. Each block pins one provider family to the vendor page it +// was read from, so a later edit that drifts from the source has to change a cited assertion. + +describe("Google Gemini API preset (ai.google.dev models, deprecations and pricing, 2026-11-26)", () => { + const google = getProviderRegistryEntry("google")!; + + test("defaults to the replacement Google names for the retired 3.5 Flash endpoint", () => { + // gemini-3.5-flash is no longer offered in AI Studio; its endpoint routes to gemini-3.6-flash. + expect(google.defaultModel).toBe("gemini-3.6-flash"); + }); + + test("seeds every GA Gemini 4 model and drops the two redirected Flash ids from the picker", () => { + for (const id of ["gemini-4-neon", "gemini-4-hydrogen", "gemini-4-carbon", "gemini-4-argon"]) { + expect(google.models).toContain(id); + expect(google.modelContextWindows?.[id]).toBe(1_048_576); + expect(google.modelInputModalities?.[id]).toEqual(["text", "image"]); + expect(google.modelReasoningEfforts?.[id]?.length).toBeGreaterThan(0); + } + expect(google.models).not.toContain("gemini-3.5-flash"); + expect(google.models).not.toContain("gemini-3.7-flash"); + // Saved selections of the redirected ids keep their metadata. + expect(google.modelContextWindows?.["gemini-3.5-flash"]).toBeDefined(); + expect(google.modelContextWindows?.["gemini-3.7-flash"]).toBeDefined(); + }); + + test("prices Gemini 4 Argon and Carbon at the durable list rate, not the introductory one", () => { + const list = { input: 4, output: 20, cacheRead: 0.2, cacheWrite: 0 }; + for (const [provider, modelId] of [ + ["google", "gemini-4-argon"], + ["google", "gemini-4-carbon"], + ["google-antigravity", "gemini-4-argon"], + ["google-antigravity", "gemini-4-argon-low"], + ["google-antigravity", "gemini-4-argon-medium"], + ["google-antigravity", "gemini-4-argon-high"], + ] as const) { + const row = findExpectedPriceOverlay(provider, modelId); + expect(row?.cost4).toEqual(list); + expect(row?.source).toContain("through 2026-11-30"); + } + }); +}); + +describe("GitHub Copilot cold-start seed (docs.github.com supported-models, 2026-11-26)", () => { + const copilot = getProviderRegistryEntry("github-copilot")!; + + test("defaults to the long-term support model GitHub falls back to", () => { + expect(copilot.defaultModel).toBe("gpt-5.3-codex"); + }); + + test("drops ids GitHub lists as retired or no longer supports", () => { + for (const retired of [ + "gpt-4o", "gpt-4.1", "gpt-4.1-mini", "claude-sonnet-4", "gemini-2.5-pro", + "gpt-5-mini", "gpt-5.4", "gpt-5.4-mini", "gpt-5.5", "gpt-5.6-terra", + ]) { + expect(copilot.models).not.toContain(retired); + } + for (const ga of ["gpt-5.3-codex", "gpt-5.6-sol", "gpt-5.6-luna", "gpt-6-sol", "gpt-6-luna", "gpt-6.1-sol", "gpt-6.1-terra", "gpt-6.2-sol", "gpt-6.2-astra"]) { + expect(copilot.models).toContain(ga); + } + }); +}); + +describe("GLM-5.4 on the Z.ai / BigModel Coding Plan (docs.z.ai glm-5.4 + devpack latest-model, docs.bigmodel.cn latest-model, 2026-11-26)", () => { + const rows = { + zai: { ids: ["glm-5.4", "glm-5.4[1m]"], context: 1_048_576 }, + "zhipu-bigmodel-coding": { ids: ["glm-5.4", "glm-5.4[1m]"], context: 1_000_000 }, + "zhipu-bigmodel-responses": { ids: ["glm-5.4"], context: 1_048_576 }, + } as const; + + test.each(Object.entries(rows))("%s seeds GLM-5.4 with 1M context, native vision and the low/high/max fold", (id, { ids, context }) => { + const row = getProviderRegistryEntry(id)!; + expect(row.defaultModel).toBe("glm-5.3"); + for (const model of ids) { + expect(row.models).toContain(model); + expect(row.modelContextWindows?.[model]).toBe(context); + // Upstream input modality: video / image / text / file. Never through the vision sidecar. + expect(row.modelInputModalities?.[model]).toEqual(["text", "image"]); + expect(row.noVisionModels ?? []).not.toContain(model); + expect(row.modelReasoningEfforts?.[model]).toEqual(["low", "high", "max"]); + expect(row.modelDefaultReasoningEfforts?.[model]).toBe("max"); + expect(row.modelMaxOutputTokens?.[model]).toBe(131_072); + } + }); + + test("the Z.ai row caps GLM-5.4 output at the documented 128K", () => { + const zai = getProviderRegistryEntry("zai")!; + expect(zai.modelMaxOutputTokens?.["glm-5.4"]).toBe(131_072); + expect(zai.modelMaxOutputTokens?.["glm-5.4[1m]"]).toBe(131_072); + }); + + test("pay-as-you-go BigModel stays without GLM-5.4 until the Model API ships", () => { + expect(getProviderRegistryEntry("zhipu-bigmodel")!.models).not.toContain("glm-5.4"); + }); +}); + +describe("qwen4-max on the Alibaba Token Plan, Beijing only (help.aliyun.com token-plan-personal-quick-start + qwen4-max model page, 2026-11-26)", () => { + const beijing = getProviderRegistryEntry("alibaba-token-plan")!; + const intl = getProviderRegistryEntry("alibaba-token-plan-intl")!; + + test("Beijing seeds qwen4-max with its documented window, output, vision and direct effort ladder", () => { + expect(beijing.defaultModel).toBe("qwen3.8-max"); + expect(beijing.models).toContain("qwen4-max"); + expect(beijing.modelContextWindows?.["qwen4-max"]).toBe(1_000_000); + expect(beijing.modelMaxOutputTokens?.["qwen4-max"]).toBe(131_072); + expect(beijing.modelInputModalities?.["qwen4-max"]).toEqual(["text", "image"]); + expect(beijing.noVisionModels ?? []).not.toContain("qwen4-max"); + // reasoning_effort low / high / xhigh, default high (minimal->low, medium->high, max->xhigh). + expect(beijing.modelReasoningEfforts?.["qwen4-max"]).toEqual(["low", "high", "xhigh"]); + expect(beijing.modelDefaultReasoningEfforts?.["qwen4-max"]).toBe("high"); + expect(beijing.directReasoningEffortModels).toContain("qwen4-max"); + expect(beijing.thinkingBudgetModels ?? []).not.toContain("qwen4-max"); + expect(beijing.preserveReasoningContentModels).toContain("qwen4-max"); + }); + + test("the International Team plan carries no qwen4-max row or metadata", () => { + expect(intl.models).not.toContain("qwen4-max"); + for (const map of [intl.modelContextWindows, intl.modelMaxOutputTokens, intl.modelInputModalities, intl.modelReasoningEfforts, intl.modelDefaultReasoningEfforts]) { + expect(map?.["qwen4-max"]).toBeUndefined(); + } + expect(intl.directReasoningEffortModels ?? []).not.toContain("qwen4-max"); + expect(intl.preserveReasoningContentModels ?? []).not.toContain("qwen4-max"); + }); +}); + +describe("DeepSeek first-party seed (api-docs.deepseek.com create-chat-completion + updates, 2026-11-26)", () => { + const deepseek = getProviderRegistryEntry("deepseek")!; + + test("seeds only ids the API reference still accepts, led by the default", () => { + // The model enum is deepseek-flash | deepseek-v4-pro; deepseek-chat / deepseek-reasoner were + // discontinued on 2026-07-24. deepseek-v4-flash and its vision preview are documented as + // accepted legacy names served by V4.1 Flash, so they stay. + expect(deepseek.defaultModel).toBe("deepseek-flash"); + expect(deepseek.models?.[0]).toBe("deepseek-flash"); + expect(deepseek.models).not.toContain("deepseek-chat"); + expect(deepseek.models).not.toContain("deepseek-reasoner"); + expect(deepseek.models).toEqual(["deepseek-flash", "deepseek-v4-flash", "deepseek-v4-pro", "deepseek-v4-flash-vision-exp"]); + }); +}); + +describe("OpenRouter seed (openrouter.ai/api/v1/models, 2026-11-26)", () => { + test("seeds only OpenAI slugs OpenRouter's public catalog lists", () => { + const openrouter = getProviderRegistryEntry("openrouter")!; + // OpenAI documents bare gpt-5.6 as an alias of gpt-5.6-sol; OpenRouter lists only the tiers. + expect(openrouter.models).not.toContain("openai/gpt-5.6"); + for (const id of ["openai/gpt-5.6-sol", "openai/gpt-5.6-terra", "openai/gpt-5.6-luna", "openai/gpt-6.2-sol", "openai/gpt-6.2-astra"]) { + expect(openrouter.models).toContain(id); + } + }); +}); + +describe("Cursor fallback seed (cursor.com/docs/models/gemini-4-neon, 2026-11-26)", () => { + test("seeds gemini-4-neon as a preemptive cold-start row shaped like Hydrogen", () => { + const cursor = getProviderRegistryEntry("cursor")!; + expect(cursorModelIds(CURSOR_STATIC_MODELS)).toContain("gemini-4-neon"); + expect(cursor.models).toContain("gemini-4-neon"); + // Cursor's page shows the 200k default window and the 1M maximum; the row advertises the maximum, + // as the Hydrogen row does for the identical pair. + expect(cursorModelContextWindows(CURSOR_STATIC_MODELS)["gemini-4-neon"]).toBe(1_048_576); + expect(cursorModelReasoningEfforts(CURSOR_STATIC_MODELS)["gemini-4-neon"]).toEqual(["low", "medium", "high", "xhigh"]); + expect(resolveCursorSelection("gemini-4-neon", "xhigh").wireId).toBe("gemini-4-neon-xhigh"); + }); +}); + +describe("saved static rosters follow the refreshed seeds without losing an id the operator could have selected", () => { + type Row = Record; + const refresh = (provider: string, row: Row) => { + const config = { providers: { [provider]: row } } as unknown as OcxConfig; + const first = projectStartupConfigRepairs(config); + const again = projectStartupConfigRepairs(structuredClone(first.config)); + return { changed: first.changed, row: first.config.providers![provider]! as Row, idempotent: !again.changed }; + }; + + test.each(["deepseek-chat", "deepseek-reasoner", "deepseek-flash"])("DeepSeek's historical seed keeps %s as default and in the list", defaultModel => { + const before = ["deepseek-chat", "deepseek-reasoner", "deepseek-flash", "deepseek-v4-flash", "deepseek-v4-flash-vision-exp"]; + const { changed, row, idempotent } = refresh("deepseek", { adapter: "openai-chat", baseUrl: "https://api.deepseek.com", models: [...before], liveModels: false, defaultModel }); + expect(changed).toBe(true); + expect(idempotent).toBe(true); + expect(row.defaultModel).toBe(defaultModel); + for (const id of [...before, "deepseek-v4-pro"]) expect(row.models).toContain(id); + }); + + test("the Gemini API seed gains Gemini 4 and keeps the redirected Flash ids a saved default may name", () => { + const before = ["gemini-4-argon", "gemini-3.8-flash", "gemini-3.6-flash", "gemini-3.5-flash", "gemini-3.5-flash-lite", "gemini-3.1-pro-preview", "gemini-3.7-flash"]; + const { changed, row, idempotent } = refresh("google", { + adapter: "google", baseUrl: "https://generativelanguage.googleapis.com", models: [...before], defaultModel: "gemini-3.5-flash", + modelContextWindows: {}, modelDefaultReasoningEfforts: {}, + }); + expect(changed).toBe(true); + expect(idempotent).toBe(true); + expect(row.defaultModel).toBe("gemini-3.5-flash"); + for (const id of [...before, "gemini-4-neon", "gemini-4-hydrogen", "gemini-4-carbon"]) expect(row.models).toContain(id); + expect((row.modelContextWindows as Record)["gemini-4-neon"]).toBe(1_048_576); + expect((row.modelDefaultReasoningEfforts as Record)["gemini-4-hydrogen"]).toBe("high"); + }); + + const glmBefore = ["glm-5.3", "glm-5.3[1m]", "glm-5.3-flash", "glm-5.2", "glm-5.2[1m]", "glm-5.1", "glm-5", "glm-4.6"]; + test.each([ + ["zai", "https://api.z.ai", "openai-responses", glmBefore, ["glm-5.4", "glm-5.4[1m]"], 1_048_576], + ["zhipu-bigmodel-coding", "https://open.bigmodel.cn/api/coding/paas/v4", "openai-chat", glmBefore, ["glm-5.4", "glm-5.4[1m]"], 1_000_000], + ["zhipu-bigmodel-responses", "https://open.bigmodel.cn/api/v1", "openai-responses", ["glm-5.3", "glm-5.3-flash", "glm-5-turbo"], ["glm-5.4"], 1_048_576], + ] as const)("%s at %s gains GLM-5.4 from its previous seed", (provider, baseUrl, adapter, before, added, window) => { + const { changed, row, idempotent } = refresh(provider, { + adapter, baseUrl, models: [...before], defaultModel: "glm-5.3", + modelContextWindows: {}, modelMaxOutputTokens: {}, modelDefaultReasoningEfforts: {}, + }); + expect(changed).toBe(true); + expect(idempotent).toBe(true); + expect(row.models).toEqual(getProviderRegistryEntry(provider)!.models); + for (const id of added) { + expect((row.modelContextWindows as Record)[id]).toBe(window); + expect((row.modelMaxOutputTokens as Record)[id]).toBe(131_072); + expect((row.modelDefaultReasoningEfforts as Record)[id]).toBe("max"); + } + }); + + test("an edited list or a custom destination keeps its roster", () => { + expect(refresh("zhipu-bigmodel-coding", { adapter: "openai-chat", baseUrl: "https://open.bigmodel.cn/api/coding/paas/v4", models: [...glmBefore, "custom"] }).changed).toBe(false); + expect(refresh("zai", { adapter: "openai-responses", baseUrl: "https://gateway.example/v1", models: [...glmBefore] }).changed).toBe(false); + }); + + test("both BigModel Coding Plan rows declare GLM-5.4's 128K output cap and max default", () => { + for (const id of ["zhipu-bigmodel-coding", "zhipu-bigmodel-responses"]) { + const row = getProviderRegistryEntry(id)!; + for (const model of row.models!.filter(m => m.startsWith("glm-5.4"))) { + expect(row.modelMaxOutputTokens?.[model]).toBe(131_072); + expect(row.modelDefaultReasoningEfforts?.[model]).toBe("max"); + } + } + }); +}); From 2d5fc5baf6885947c4399c4b4b880851a46b612e Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 26 Nov 2026 03:35:47 +0900 Subject: [PATCH 58/60] feat(audio): relay public GPT-Live sessions for API-key providers (#9142) * fix(audio): judge unnamed external live requests like the native path The native voice path refuses a model-scoped key when a request names no model. The external path judged the same requests against the default live model. Both now treat a call-create session without a model, /v1/realtime/calls without a session and a Realtime standalone socket without a model query as unnamed destinations. * fix(audio): treat a blank live session model as unnamed; cover unnamed binds and rejoins * feat(audio): relay public GPT-Live sessions for API-key providers POST /v1/live/sessions, WS /v1/live/sessions and WS /v1/live/sessions/{id}/attach for external audio keys on an OpenAI API-key provider. SIP transport is refused, a ChatGPT account is never substituted, and session ids are replaced by aliases bound to the creating key. * docs(audio): document GPT-Live sessions; register their tests * fix(audio): keep GPT-Live session aliases, sockets and answers on their own contract A session attach opens only a session alias and other routes refuse one; session sockets connect to the selected API-key provider's base instead of the sideband override; a session answer must carry a WebRTC transport with an SDP answer before it is bound. --- devlog/_plan/261126_live_sessions/000_plan.md | 26 ++ .../docs/es/reference/proxy-formats.md | 10 + .../content/docs/reference/proxy-formats.md | 17 + .../test-layout/layout-server-inbound.json | 1 + src/server/audio-live-sessions.ts | 141 ++++++++ src/server/audio-live.ts | 29 +- src/server/inbound-body-admission.ts | 1 + src/server/index.ts | 3 + src/server/index/serve-options.ts | 30 ++ src/server/live-call-bindings.ts | 2 +- src/server/live.ts | 16 +- structure/data-planes/inbound-compat.md | 3 +- tests/fixtures/test-layout-expected.json | 1 + tests/server/audio-live-sessions.test.ts | 312 ++++++++++++++++++ 14 files changed, 586 insertions(+), 6 deletions(-) create mode 100644 devlog/_plan/261126_live_sessions/000_plan.md create mode 100644 src/server/audio-live-sessions.ts create mode 100644 tests/server/audio-live-sessions.test.ts diff --git a/devlog/_plan/261126_live_sessions/000_plan.md b/devlog/_plan/261126_live_sessions/000_plan.md new file mode 100644 index 00000000000..c58b8a67dae --- /dev/null +++ b/devlog/_plan/261126_live_sessions/000_plan.md @@ -0,0 +1,26 @@ +# Public GPT-Live sessions (/v1/live/sessions) + +The coordinator chose to build this in Lane L and leave it unmerged (decision c1786517, 2026-11-26). It adds new public endpoints and an outbound credential route, so it needs maintainer sign-off before it can merge. + +## Why + +OpenAI's public GPT-Live API, read 2026-11-26, creates a WebRTC session with `POST /v1/live/sessions`. The request body is JSON `{ session: { model, ... }, transport: { type: "webrtc", sdp } }`, and the answer is `201 { session: { id }, transport: { type, sdp } }`. A WebSocket session opens `wss://api.openai.com/v1/live/sessions` and sends `session.start` first. A server-side control connection attaches with `wss://api.openai.com/v1/live/sessions/{id}/attach`. The public models are `gpt-live-1` and `gpt-live-1.1`, and the default voice is `marin`. +Sources: developers.openai.com/api/reference/resources/live/methods/create.md, guides/voice-webrtc.md, guides/voice-websockets.md, guides/voice-server-controls.md. + +The existing OpenCodex `/v1/live` endpoint mirrors Codex's Frameless wire, so official SDK clients pointed at OpenCodex currently get 404. Codex itself does not use `/v1/live/sessions`. + +## Change + +| File | Change | +| --- | --- | +| src/server/audio-live-sessions.ts (new) | handles `POST /v1/live/sessions` for external audio keys: bounded JSON (1 MiB), `session.model` required, WebRTC transport with an SDP offer required, SIP refused. Uses the configured OpenAI API-key provider only, so a ChatGPT account is never substituted. The key's model scope is judged on `session.model`. Relays to `{provider base}/live/sessions` with the provider credential and the documented client headers (including `OpenAI-Safety-Identifier`), with manual redirects and a capped answer. The upstream session id is replaced by an `rtc_ocx_` alias bound to the creating key | +| src/server/live.ts | target styles `live-session-start` and `live-session` (attach), with the upstream WebSocket URLs `/live/sessions` and `/live/sessions/{id}/attach`. The native resolver never receives them | +| src/server/audio-live.ts | external sockets for those targets use the API-key provider only. A fresh session socket names its model in band, so it is an unnamed destination (stacked on the scope-alignment PR). An attach is judged on the model recorded for its session | +| src/server/live-call-bindings.ts | join style `live-session` | +| src/server/index/serve-options.ts, src/server/index.ts, src/server/inbound-body-admission.ts | route the POST, refuse requests without an external audio key (401), add the loopback route allowance, and list the path in the ungated loopback route set | +| tests/server/audio-live-sessions.test.ts (new) | fake HTTP and local WebSocket upstreams: create and alias, request validation and SIP refusal, no ChatGPT substitution, scope, native refusal, session socket, attach only by the creating key | + +## Checks + +The 8 new tests fail on the previous source and pass here. Also run: typecheck, the focused audio and live suites, structure:check, privacy:scan, and the docs, test-layout and file-size guards. NOT RUN: any call to OpenAI's GPT-Live API. + diff --git a/docs-site/src/content/docs/es/reference/proxy-formats.md b/docs-site/src/content/docs/es/reference/proxy-formats.md index b3f40cc83fe..4687b32c87e 100644 --- a/docs-site/src/content/docs/es/reference/proxy-formats.md +++ b/docs-site/src/content/docs/es/reference/proxy-formats.md @@ -506,6 +506,16 @@ Los enlaces de llamadas duran 30 minutos, están limitados a 1024 entradas por s +### Sesiones GPT-Live + +OpenCodex también retransmite la API pública de sesiones GPT-Live de OpenAI para claves externas, solo a través de un proveedor de claves OpenAI API habilitado. Nunca se usa una cuenta ChatGPT para ello, y una solicitud sin ese proveedor recibe 400. + +- `POST /v1/live/sessions` acepta JSON `{ "session": { "model": ... }, "transport": { "type": "webrtc", "sdp": ... } }` (como máximo 1 MiB) y responde como la API, `201 { "session": { "id" }, "transport": { "type", "sdp" } }`. `session.model` es obligatorio y una clave limitada a modelos se evalúa con él. El transporte SIP se rechaza. +- El `session.id` devuelto es un alias de OpenCodex vinculado a la clave que lo creó. Solo esa clave puede abrir `WS /v1/live/sessions/{id}/attach`, que llega a la conexión de control del servidor de la sesión. +- `WS /v1/live/sessions` abre una sesión cuyo modelo llega después en `session.start`, por lo que una clave limitada a una lista de modelos no puede abrirla. + +`OpenAI-Safety-Identifier` se reenvía cuando el cliente lo envía. OpenCodex no transporta los medios WebRTC; el cliente se conecta a OpenAI con la respuesta SDP devuelta. + ### Compatibilidad nativa con Codex Las personas que llaman en modo clave nativo API en el oyente local de confianza pueden usar la credencial exacta configurada para el nivel canónico OpenAI API. Otros valores de soporte presentados requieren una clave proxy registrada o un par de token/cuenta ChatGPT explícito, coincidente; un prefijo de clave arbitraria no es prueba de credenciales nativas. Las llamadas nativas locales de confianza sin credenciales conservan su comportamiento existente. diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index 60ec89ce1b8..83968a30c8c 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -953,6 +953,23 @@ directly over WebRTC and is not proxied. The proxy never executes delegation requests. OpenAI account availability is established by the actual upstream response, not by the presence of a model name in the dashboard. +### GPT-Live sessions + +OpenCodex also relays OpenAI's public GPT-Live session API for external keys, through +an enabled OpenAI API-key provider only. A ChatGPT account is never used for it, and a +request without that provider receives 400. + +- `POST /v1/live/sessions` takes JSON `{ "session": { "model": ... }, "transport": { "type": "webrtc", "sdp": ... } }` + (at most 1 MiB) and answers like the API, `201 { "session": { "id" }, "transport": { "type", "sdp" } }`. + `session.model` is required, and a key scoped to models is judged on it. SIP transport is refused. +- The returned `session.id` is an OpenCodex alias bound to the creating key. Only that key can open + `WS /v1/live/sessions/{id}/attach`, which reaches the session's server-side control connection. +- `WS /v1/live/sessions` opens a session whose model arrives later in `session.start`, so a key + restricted to a model list cannot open it. + +`OpenAI-Safety-Identifier` is forwarded when the client sends it. OpenCodex does not carry the +WebRTC media; the client connects to OpenAI with the returned SDP answer. + ### Native Codex compatibility Native API-key-mode callers on the trusted local listener may use the exact diff --git a/scripts/test-layout/layout-server-inbound.json b/scripts/test-layout/layout-server-inbound.json index 56c2342baca..2f80fe779bd 100644 --- a/scripts/test-layout/layout-server-inbound.json +++ b/scripts/test-layout/layout-server-inbound.json @@ -1,4 +1,5 @@ { + "audio-live-sessions.test.ts": "server", "video-openai-client.test.ts": "videos", "video-openai-wire-bridge.test.ts": "videos", "server-videos.test.ts": "server", diff --git a/src/server/audio-live-sessions.ts b/src/server/audio-live-sessions.ts new file mode 100644 index 00000000000..36ebf6e6187 --- /dev/null +++ b/src/server/audio-live-sessions.ts @@ -0,0 +1,141 @@ +/** + * Public GPT-Live session creation (`POST /v1/live/sessions`) for external audio keys. + * + * OpenAI's GPT-Live API creates a WebRTC session with JSON `{ session, transport }` and answers + * `201 { session: { id }, transport: { type, sdp } }` (developers.openai.com/api/reference/resources/live). + * Only an OpenAI API-key provider serves it: no documented ChatGPT subscription endpoint exists, so a + * ChatGPT account is never substituted. SIP transport places phone calls with trunk credentials and is + * refused. The returned session id is replaced by an alias bound to the creating key, so only that key + * can attach (`WS /v1/live/sessions/{id}/attach`). + */ +import { createHash } from "node:crypto"; +import { formatErrorResponse } from "../bridge"; +import { cancelBodyOnAbort, clearableDeadline } from "../lib/abort"; +import type { AdmissionLease } from "../lib/admission"; +import { selectOpenAiImagesProvider } from "../providers/openai-sidecar"; +import type { OcxConfig } from "../types"; +import type { AudioClient } from "./audio-client"; +import { resolveAudioUpstream, type AudioUpstream } from "./audio-upstream"; +import { registerTurn, unregisterTurn } from "./lifecycle"; +import { LIVE_CLIENT_PROTOCOL_HEADERS, LIVE_RESPONSE_MAX_BYTES, readBodyCapped } from "./live"; +import type { LiveCallBindings } from "./live-call-bindings"; +import type { RequestLogContext } from "./request-log"; + +export const LIVE_SESSION_REQUEST_MAX_BYTES = 1024 * 1024; +const LIVE_SESSION_TIMEOUT_MS = 120_000; +const SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/; +/** Client headers the public GPT-Live API documents, relayed only when the client sent them. */ +export const LIVE_SESSION_CLIENT_HEADERS = [...LIVE_CLIENT_PROTOCOL_HEADERS, "openai-safety-identifier"] as const; + +type JsonObject = Record; + +function isObject(value: unknown): value is JsonObject { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function invalid(message: string, status = 400): Response { + return formatErrorResponse(status, "invalid_request_error", message); +} + +/** The API-key provider a GPT-Live session must use, or the refusal when none is configured. */ +export function liveSessionProviderName(config: OcxConfig): string | Response { + return selectOpenAiImagesProvider(config).keyed?.providerName + ?? invalid("GPT-Live sessions require an OpenAI API-key provider"); +} + +/** Headers for a GPT-Live upstream: the documented client headers, then the provider credential. */ +export function liveSessionHeaders(client: AudioClient, relay: AudioUpstream): Headers { + const headers = new Headers(); + for (const name of LIVE_SESSION_CLIENT_HEADERS) { + const value = client.headers.get(name); + if (value) headers.set(name, value); + } + for (const [name, value] of Object.entries(relay.headers)) headers.set(name, value); + return headers; +} + +async function parseSessionRequest(req: Request, signal: AbortSignal): Promise { + if (!(req.headers.get("content-type") ?? "").toLowerCase().includes("application/json")) { + return invalid("GPT-Live session creation expects application/json"); + } + const body = await readBodyCapped(req.body, LIVE_SESSION_REQUEST_MAX_BYTES, () => "too large", signal); + if (body instanceof Response) return invalid("GPT-Live session request exceeds 1 MiB", 413); + let payload: unknown; + try { payload = JSON.parse(new TextDecoder().decode(body)); } catch { return invalid("Malformed GPT-Live session request"); } + if (!isObject(payload) || !isObject(payload.session) || !isObject(payload.transport)) { + return invalid("GPT-Live session creation requires session and transport objects"); + } + const model = payload.session.model; + if (typeof model !== "string" || !model.trim()) return invalid("GPT-Live session.model is required"); + if (payload.transport.type === "sip") return invalid("SIP transport is not supported by OpenCodex"); + if (payload.transport.type !== "webrtc" || typeof payload.transport.sdp !== "string" || !payload.transport.sdp.trim()) { + return invalid("GPT-Live session creation requires a WebRTC transport with an SDP offer"); + } + return payload; +} + +export async function handleLiveSessionCreate( + req: Request, config: OcxConfig, log: RequestLogContext, + options: { client: AudioClient; lease: AdmissionLease; bindings: LiveCallBindings }, +): Promise { + const controller = new AbortController(); + registerTurn(controller, options.lease); + const deadline = clearableDeadline(LIVE_SESSION_TIMEOUT_MS, AbortSignal.any([req.signal, controller.signal])); + let relay: AudioUpstream | undefined; + let outcome: number | "timeout" | "connect_error" | undefined; + try { + const payload = await parseSessionRequest(req, deadline.signal); + if (payload instanceof Response) return payload; + const providerName = liveSessionProviderName(config); + if (providerName instanceof Response) return providerName; + if (!options.bindings.hasCapacity()) return formatErrorResponse(503, "server_busy", "Live call capacity reached"); + const model = (payload.session as JsonObject).model as string; + const resolved = await resolveAudioUpstream(options.client.headers, config, log, { + admission: options.client.admission, model, lease: options.lease, providerName, signal: deadline.signal, + }); + if (resolved instanceof Response) return resolved; + relay = resolved; + if (!relay.keyed) return invalid("GPT-Live sessions require an OpenAI API-key provider"); + const headers = liveSessionHeaders(options.client, relay); + headers.set("content-type", "application/json"); + const upstream = await fetch(`${relay.providerBaseUrl.replace(/\/+$/, "")}/live/sessions`, { + method: "POST", headers, body: JSON.stringify(payload), signal: deadline.signal, redirect: "manual", + }); + outcome = upstream.status; + const detach = cancelBodyOnAbort(upstream.body, deadline.signal); + let raw: ArrayBuffer | Response; + try { raw = await readBodyCapped(upstream.body, LIVE_RESPONSE_MAX_BYTES, () => "GPT-Live answer too large", deadline.signal); } + finally { detach(); } + if (raw instanceof Response) return raw; + if (!upstream.ok) { + return formatErrorResponse(upstream.status >= 400 && upstream.status <= 599 ? upstream.status : 502, "upstream_error", `GPT-Live upstream returned HTTP ${upstream.status}`); + } + let answer: unknown; + try { answer = JSON.parse(new TextDecoder().decode(raw)); } catch { answer = undefined; } + const sessionId = isObject(answer) && isObject(answer.session) ? answer.session.id : undefined; + const transport = isObject(answer) ? answer.transport : undefined; + if (typeof sessionId !== "string" || !SESSION_ID.test(sessionId) || !isObject(transport) + || transport.type !== "webrtc" || typeof transport.sdp !== "string" || !transport.sdp.trim()) { + return formatErrorResponse(502, "upstream_error", "GPT-Live upstream returned an invalid session answer"); + } + const alias = options.bindings.create({ + owner: options.client.owner, upstreamCallId: sessionId, joinStyle: "live-session", + providerName: relay.providerName, model, + keyedCredentialDigest: createHash("sha256").update(new Headers(relay.headers).get("authorization") ?? "").digest("hex"), + callerOwned: false, + }); + if (!alias) return formatErrorResponse(503, "server_busy", "Live call could not be registered"); + return Response.json({ ...(answer as JsonObject), session: { ...((answer as JsonObject).session as JsonObject), id: alias } }, { status: upstream.status }); + } catch { + if (req.signal.aborted || controller.signal.aborted) { + outcome = undefined; + return formatErrorResponse(req.signal.aborted ? 499 : 503, "client_closed_request", "GPT-Live session creation canceled"); + } + outcome = deadline.didExpire() ? "timeout" : "connect_error"; + return formatErrorResponse(deadline.didExpire() ? 504 : 502, "upstream_error", deadline.didExpire() ? "GPT-Live session creation timed out" : "GPT-Live upstream connection failed"); + } finally { + try { if (outcome !== undefined) relay?.recordOutcome?.(outcome); } + finally { relay?.release(); deadline.clear(); unregisterTurn(controller); } + } +} + diff --git a/src/server/audio-live.ts b/src/server/audio-live.ts index bb3a7fb2e08..0c4afcb6c4d 100644 --- a/src/server/audio-live.ts +++ b/src/server/audio-live.ts @@ -18,6 +18,7 @@ import { type LiveSidebandTarget, } from "./live"; import { LIVE_CALL_TTL_MS, LiveCallBindings, upstreamLiveCallId } from "./live-call-bindings"; +import { liveSessionHeaders, liveSessionProviderName } from "./audio-live-sessions"; import type { RequestLogContext } from "./request-log"; function protocolHeaders(client: AudioClient, relay: AudioUpstream, frameless: boolean): Headers { @@ -159,6 +160,11 @@ export async function resolveExternalLiveSocket( ): Promise { const binding = "callId" in target ? options.bindings.get(target.callId, client.owner) : undefined; if ("callId" in target && !binding) return formatErrorResponse(404, "not_found", "Live call is unavailable for this key"); + // A GPT-Live session alias opens only on the session attach route, and that route opens only session + // aliases: each binding keeps the destination rules of the endpoint that created it. + if (binding && (target.style === "live-session") !== (binding.joinStyle === "live-session")) { + return formatErrorResponse(404, "not_found", "Live call is unavailable for this key"); + } if (binding?.callerOwned && !captureExplicitOpenAiCallerAuth(client.headers, config)) { return formatErrorResponse(401, "authentication_error", "Live call requires its original caller account"); } @@ -174,13 +180,27 @@ export async function resolveExternalLiveSocket( // own query. When neither names one, the destination is unnamed and judged as // such, never as the default. const model = binding ? binding.model : liveSidebandModel(upstreamTarget); + // A GPT-Live session socket names its model in session.start, so a fresh one is unnamed here, + // and it is served only by the configured API-key provider. + const liveSession = upstreamTarget.style === "live-session" || upstreamTarget.style === "live-session-start"; + let sessionProvider: string | undefined; + if (liveSession && !binding) { + const provider = liveSessionProviderName(config); + if (provider instanceof Response) return provider; + sessionProvider = provider; + } const relay = await resolveAudioUpstream(client.headers, config, log, { admission: client.admission, model, lease: options.lease, signal: options.signal, - ...(binding ? { exactAccountId: binding.accountId, providerName: binding.providerName } : {}), + ...(binding ? { exactAccountId: binding.accountId, providerName: binding.providerName } + : sessionProvider ? { providerName: sessionProvider } : {}), }); if (relay instanceof Response) return relay; try { + if (liveSession && !relay.keyed) { + relay.release(); + return formatErrorResponse(400, "invalid_request_error", "GPT-Live sessions require an OpenAI API-key provider"); + } if (binding && (relay.providerName !== binding.providerName || (new Headers(relay.headers).get("chatgpt-account-id") ?? undefined) !== binding.chatgptAccountId || (binding.keyedCredentialDigest !== undefined @@ -190,8 +210,11 @@ export async function resolveExternalLiveSocket( } return { authContext: relay.authContext, - headers: Object.fromEntries(protocolHeaders(client, relay, frameless)), - upstreamWsUrl: buildLiveSidebandUpstreamWsUrl(upstreamTarget, binding ? binding.sidebandBaseUrl : config.experimentalRealtimeWsBaseUrl), + headers: Object.fromEntries(liveSession ? liveSessionHeaders(client, relay) : protocolHeaders(client, relay, frameless)), + // A session socket carries the API-key credential, so it goes where session creation posts: + // the selected provider's own base, never the Codex sideband override. + upstreamWsUrl: buildLiveSidebandUpstreamWsUrl(upstreamTarget, liveSession ? relay.providerBaseUrl + : binding ? binding.sidebandBaseUrl : config.experimentalRealtimeWsBaseUrl), maxSessionMs: LIVE_CALL_TTL_MS, finish: finishAudioUpstream(relay), }; diff --git a/src/server/inbound-body-admission.ts b/src/server/inbound-body-admission.ts index da84fd5f434..11fbbf3a181 100644 --- a/src/server/inbound-body-admission.ts +++ b/src/server/inbound-body-admission.ts @@ -43,6 +43,7 @@ export const UNGATED_LOOPBACK_ROUTES: ReadonlySet = new Set([ "/v1/realtime", "/v1/realtime/calls", "/v1/live", + "/v1/live/sessions", ]); export class InboundBodyCapacityError extends Error { diff --git a/src/server/index.ts b/src/server/index.ts index 7d4fb2c0d19..4c35abbeea3 100644 --- a/src/server/index.ts +++ b/src/server/index.ts @@ -444,6 +444,9 @@ function startServerWithSpendLedgerOwner(port: number | undefined, deps: StartSe const isWebSocketUpgrade = req.headers.get("upgrade")?.toLowerCase() === "websocket"; if (path === "/v1/realtime") return isWebSocketUpgrade; if (path === "/v1/live") return isWebSocketUpgrade || req.method === "POST"; + // Public GPT-Live sessions: external audio keys only, checked again at the handler. + if (path === "/v1/live/sessions") return isWebSocketUpgrade || req.method === "POST"; + if (/^\/v1\/live\/sessions\/[^/]+\/attach\/?$/.test(path)) return isWebSocketUpgrade; if (path === "/v1/realtime/calls") return req.method === "POST"; if (/^\/v1\/(?:live|realtime\/calls)\/[^/]+\/?$/.test(path)) return isWebSocketUpgrade; return false; diff --git a/src/server/index/serve-options.ts b/src/server/index/serve-options.ts index 8d4c4fecc66..3532f54a13b 100644 --- a/src/server/index/serve-options.ts +++ b/src/server/index/serve-options.ts @@ -142,6 +142,7 @@ import { resolveLiveSidebandUpgrade, } from "../live"; import { handleAudioTranscriptions } from "../audio-transcriptions"; +import { handleLiveSessionCreate } from "../audio-live-sessions"; import { resolveAudioAdmission, TRANSCRIPTION_MODEL, @@ -1635,6 +1636,32 @@ export function createServeOptions(ctx: ServeOptionsContext) { } // ChatGPT / Codex App voice (GPT‑Live / Frameless Bidi) + OpenAI Realtime call-create. + // Public GPT-Live session creation: an external audio key on an API-key provider only. + if (req.method === "POST" && url.pathname === "/v1/live/sessions") { + disableResponsesRequestTimeout(req, requestServer); + if (isDraining()) return drainingResponse(req, policy); + const audioClient = resolveAudioClient(req, config, true, admissionOptions); + if (!audioClient || audioClient instanceof Response) { + return withCors(audioClient ?? formatErrorResponse(401, "authentication_error", "opencodex API key required"), req, policy); + } + if (!isAllowedRequestOrigin(req, policy)) { + return withCors(formatErrorResponse(403, "origin_rejected", "cross-origin data-plane request blocked"), req, policy); + } + const start = Date.now(); + const requestId = nextRequestLogId(start); + const logCtx: RequestLogContext = { + model: "gpt-live", + provider: "unknown", + ...requestMetricsLogContext, client: classifyUsageClient(req.headers), + ...admissionFields(audioClient.admission), + }; + return runAdmittedHttpTurn(req, policy, async turnAdmissionLease => { + const response = await handleLiveSessionCreate(req, config, logCtx, { client: audioClient, lease: turnAdmissionLease, bindings: liveCallBindings }); + addFinalRequestLog(requestId, start, logCtx, response.status, response.status === 499 ? { closeReason: "client_cancel" } : undefined); + return withCors(response, req, policy); + }, { requestId, start, logCtx }); + } + // Clients hit either /v1/live (Frameless App) or /v1/realtime/calls (codex RealtimeCallClient / // public Realtime API). Sideband WS joins are handled just below. if ( @@ -1695,6 +1722,9 @@ export function createServeOptions(ctx: ServeOptionsContext) { && liveSidebandTarget.callId.startsWith(EXTERNAL_CALL_PREFIX)) { return withCors(formatErrorResponse(401, "authentication_error", "Live call requires its creator API key"), req, policy); } + if (!audioClient && (liveSidebandTarget?.style === "live-session-start" || liveSidebandTarget?.style === "live-session")) { + return withCors(formatErrorResponse(401, "authentication_error", "opencodex API key required"), req, policy); + } const admission = audioClient?.admission ?? resolveApiAuth(req, policy); if (!admission) return withCors(formatErrorResponse(401, "authentication_error", "opencodex API key required"), req, policy); if (!isAllowedRequestOrigin(req, policy)) { diff --git a/src/server/live-call-bindings.ts b/src/server/live-call-bindings.ts index d7400f5e913..691adfab12c 100644 --- a/src/server/live-call-bindings.ts +++ b/src/server/live-call-bindings.ts @@ -7,7 +7,7 @@ const MAX_CALL_BINDINGS = 1024; export interface LiveCallBinding { owner: string; upstreamCallId: string; - joinStyle: "frameless-path" | "realtime-query"; + joinStyle: "frameless-path" | "realtime-query" | "live-session"; providerName: string; /** * The model this call settled on when it was created. A join names no model diff --git a/src/server/live.ts b/src/server/live.ts index cfabc11d239..a870a411488 100644 --- a/src/server/live.ts +++ b/src/server/live.ts @@ -314,7 +314,10 @@ export type LiveSidebandTarget = | { style: "realtime-calls-path"; callId: string } | { style: "realtime-query"; callId: string } | { style: "realtime-standalone"; query: string } - | { style: "frameless-standalone"; query: string }; + | { style: "frameless-standalone"; query: string } + // Public GPT-Live (`/v1/live/sessions`): served only to external audio keys on an API-key provider. + | { style: "live-session-start" } + | { style: "live-session"; callId: string }; export type LiveRelayTarget = { headers: Record; @@ -353,6 +356,13 @@ function httpsToWss(httpUrl: string): string { } export function parseLiveSidebandTarget(pathname: string, searchParams: URLSearchParams, rawQuery = ""): LiveSidebandTarget | null { + // Before the Frameless call-id form, which would otherwise read "sessions" as a call id. + if (pathname === "/v1/live/sessions" || pathname === "/v1/live/sessions/") return { style: "live-session-start" }; + const sessionMatch = pathname.match(/^\/v1\/live\/sessions\/([^/]+)\/attach\/?$/); + if (sessionMatch) { + const callId = decodeLiveCallId(sessionMatch[1]!); + return callId ? { style: "live-session", callId } : null; + } const liveMatch = pathname.match(/^\/v1\/live\/([^/]+)\/?$/); if (liveMatch) { const callId = decodeLiveCallId(liveMatch[1]!); @@ -479,6 +489,10 @@ export function buildLiveSidebandUpstreamWsUrl( if (target.style === "realtime-calls-path") { return httpsToWss(`${sidebandRoot}/realtime/calls/${target.callId}`); } + if (target.style === "live-session-start") return httpsToWss(`${sidebandRoot}/live/sessions`); + if (target.style === "live-session") { + return httpsToWss(`${sidebandRoot}/live/sessions/${encodeURIComponent(target.callId)}/attach`); + } return httpsToWss( `${sidebandRoot}/realtime?intent=quicksilver&call_id=${encodeURIComponent(target.callId)}`, ); diff --git a/structure/data-planes/inbound-compat.md b/structure/data-planes/inbound-compat.md index fee5a9164f8..7503398f5a1 100644 --- a/structure/data-planes/inbound-compat.md +++ b/structure/data-planes/inbound-compat.md @@ -74,7 +74,8 @@ Expired aliases never fall through to native joins. Reconnect resolves the recor freshly; keyed provider replacement fails unless its credential digest still matches. The registry is per server, holds at most 1024 entries for 30 minutes and is cleared on shutdown. It does not proxy WebRTC media or execute delegation requests. Frameless defaults to Codex's gpt-live-1.1-codex (`resolveLiveAudioModel` in `src/server/audio-upstream.ts`); gpt-live-1 and gpt-live-1.1 alias the -codex models for call-create sessions and Frameless standalone sockets, and the resolved name is the one a key scope judges and the binding records; Realtime standalone queries pass unchanged. -Only a session the proxy synthesizes gets a voice, chosen after the upstream resolves: marin for a keyed API relay, cove for ChatGPT, matching openai/codex. Dictation and Frameless event formats remain +Only a session the proxy synthesizes gets a voice, chosen after the upstream resolves: marin for a keyed API relay, cove for ChatGPT, matching openai/codex. +`src/server/audio-live-sessions.ts` relays the public GPT-Live session API (`POST /v1/live/sessions`, `WS /v1/live/sessions`, `WS /v1/live/sessions//attach`) only to the API-key provider, refuses SIP, judges scope on `session.model` (a fresh socket is unnamed), and binds the returned id to the creating key; `tests/server/audio-live-sessions.test.ts`. Dictation and Frameless event formats remain separate. Coverage lives in `tests/server/audio-client.test.ts`, `tests/server/audio-dictation.test.ts` and `tests/server/live-call-bindings.test.ts`. diff --git a/tests/fixtures/test-layout-expected.json b/tests/fixtures/test-layout-expected.json index 29963e66760..17881aa720b 100644 --- a/tests/fixtures/test-layout-expected.json +++ b/tests/fixtures/test-layout-expected.json @@ -433,6 +433,7 @@ "aside-profile-sync-owner.test.ts": "clients", "pi-sync-owner.test.ts": "clients", "aside-profiles-routes.test.ts": "server", "aside-profiles.test.ts": "clients", "assert-mergeable-review.test.ts": "ci-workflows", "test-git-isolation.test.ts": "ci-workflows", "test-network-egress-guard.test.ts": "ci-workflows", "audio-client.test.ts": "server", "audio-dictation.test.ts": "server", + "audio-live-sessions.test.ts": "server", "audio-transcriptions.test.ts": "server", "auto-compact-budget.test.ts": "providers", "autostart-health.test.ts": "service", "azure-adapter.test.ts": "providers", "azure-model-router-tool-schema.test.ts": "providers", "claude-chat-gateway-tool-schema.test.ts": "providers", "bare-echo-alias.test.ts": "responses", diff --git a/tests/server/audio-live-sessions.test.ts b/tests/server/audio-live-sessions.test.ts new file mode 100644 index 00000000000..164e47e8a2d --- /dev/null +++ b/tests/server/audio-live-sessions.test.ts @@ -0,0 +1,312 @@ +/** + * Public GPT-Live sessions (`/v1/live/sessions`) for external audio keys on an OpenAI API-key + * provider. Upstream HTTP and WebSocket peers are local fixtures; nothing reaches OpenAI. + */ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { saveCodexAccountCredential } from "../../src/codex/account-store"; +import { clearAccountQuota } from "../../src/codex/auth-api"; +import { clearCodexUpstreamHealth, clearThreadAccountMap } from "../../src/codex/routing"; +import { saveConfig } from "../../src/config"; +import { startServer } from "../../src/server"; +import { resetLifecycleDrainStateForTests, tryAdmitTurn } from "../../src/server/lifecycle"; +import { resolveAudioClient } from "../../src/server/audio-client"; +import { handleLiveSessionCreate } from "../../src/server/audio-live-sessions"; +import { LIVE_RESPONSE_MAX_BYTES } from "../../src/server/live"; +import { LiveCallBindings } from "../../src/server/live-call-bindings"; +import type { OcxConfig } from "../../src/types"; +import { fakeChatGptJwt } from "../helpers/fake-chatgpt-jwt"; +import { installIsolatedCodexHome, type IsolatedCodexHome } from "../helpers/isolated-codex-home"; +import { removeTreeWithRetry } from "../helpers/remove-tree"; + +const KEY = "ocx_data_live_sessions_fixture"; +const OTHER_KEY = "ocx_data_live_sessions_other"; +const SCOPED_KEY = "ocx_data_live_sessions_scoped"; +const UPSTREAM_KEY = "fixture-upstream-key"; +const fetchOriginal = globalThis.fetch; +const previousHome = process.env.OPENCODEX_HOME; +const previousToken = process.env.OPENCODEX_API_AUTH_TOKEN; +let home: string; +let codex: IsolatedCodexHome; +let fixture: ReturnType | undefined; +const clients = new Set(); + +const offer = { session: { model: "gpt-live-1.1", instructions: "Be concise." }, transport: { type: "webrtc", sdp: "v=0\r\n" } }; + +function keyedConfig(): OcxConfig { + return { + port: 0, hostname: "127.0.0.1", defaultProvider: "openai-apikey", openaiProviderTierVersion: 2, + providers: { "openai-apikey": { adapter: "openai-responses", baseUrl: "https://api.openai.com/v1", apiKey: UPSTREAM_KEY, authMode: "key" } }, + apiKeys: [ + { id: "one", name: "one", key: KEY, createdAt: "2026-11-26T00:00:00Z" }, + { id: "two", name: "two", key: OTHER_KEY, createdAt: "2026-11-26T00:00:00Z" }, + { id: "scoped", name: "scoped", key: SCOPED_KEY, createdAt: "2026-11-26T00:00:00Z", allowedModels: ["gpt-live-1.1"] }, + ], + } as OcxConfig; +} + +const sessionAnswer = () => Response.json({ session: { id: "live_fixture_1" }, transport: { type: "webrtc", sdp: "v=0 answer\r\n" } }, { status: 201 }); + +function createFixture(options: { answer?: (req: Request) => Response | Promise } = {}) { + const creates: Request[] = []; + const handshakes: Array<{ url: string; headers: Headers }> = []; + const upstream = Bun.serve({ + port: 0, + fetch(req, server) { + if (server.upgrade(req, { data: {} })) return; + return new Response("not found", { status: 404 }); + }, + websocket: { message(ws, raw) { ws.send(String(raw)); } }, + }); + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const req = new Request(input, init); + if (["api.openai.com", "chatgpt.com"].includes(new URL(req.url).hostname)) { + if (new URL(req.url).pathname === "/v1/live/sessions") { + creates.push(req.clone()); + return (options.answer ?? sessionAnswer)(req); + } + // Frameless call-create on either upstream, so a call alias exists beside the session aliases. + if (new URL(req.url).pathname === "/v1/live" || new URL(req.url).pathname.endsWith("/realtime/calls")) { + return new Response("v=0\r\n", { status: 201, headers: { "content-type": "application/sdp", location: "https://api.openai.com/v1/live/rtc_frameless_fixture" } }); + } + return Response.json({}); + } + return fetchOriginal(input, init); + }) as typeof fetch; + const server = startServer(0, { + liveSidebandWebSocketFactory(url, headers) { + handshakes.push({ url, headers: new Headers(headers) }); + const local = new URL("/socket", upstream.url); local.protocol = "ws:"; + return new WebSocket(local, { headers } as unknown as string[]); + }, + }); + return { server, upstream, creates, handshakes }; +} + +function create(body: unknown = offer, key = KEY, extra: Record = {}): Promise { + return fetchOriginal(new URL("/v1/live/sessions", fixture!.server.url), { + method: "POST", headers: { authorization: `Bearer ${key}`, "content-type": "application/json", ...extra }, body: JSON.stringify(body), + }); +} + +function socket(path: string, key = KEY): WebSocket { + const url = new URL(path, fixture!.server.url); url.protocol = "ws:"; + const ws = new WebSocket(url, { headers: { authorization: `Bearer ${key}` } } as unknown as string[]); + clients.add(ws); + return ws; +} + +function echo(ws: WebSocket, message: string): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { ws.close(); reject(new Error("Fixture socket timed out")); }, 10000); + ws.addEventListener("message", event => { clearTimeout(timer); resolve(String(event.data)); }, { once: true }); + ws.addEventListener("error", () => { clearTimeout(timer); reject(new Error("Fixture socket failed")); }, { once: true }); + if (ws.readyState === WebSocket.OPEN) ws.send(message); else ws.addEventListener("open", () => ws.send(message), { once: true }); + }); +} + +async function upgradeStatus(path: string, key?: string): Promise { + const response = await fetchOriginal(new URL(path, fixture!.server.url), { headers: { + upgrade: "websocket", connection: "upgrade", "sec-websocket-key": "MDEyMzQ1Njc4OWFiY2RlZg==", "sec-websocket-version": "13", + ...(key ? { authorization: `Bearer ${key}` } : {}), + } }); + await response.text(); + return response.status; +} + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), "ocx-live-sessions-")); + process.env.OPENCODEX_HOME = home; + delete process.env.OPENCODEX_API_AUTH_TOKEN; + codex = installIsolatedCodexHome("ocx-live-sessions-codex-"); + resetLifecycleDrainStateForTests(); clearAccountQuota(); clearCodexUpstreamHealth(); clearThreadAccountMap(); + saveConfig(keyedConfig()); +}); + +afterEach(async () => { + for (const ws of clients) ws.close(); + clients.clear(); + if (fixture) await Promise.all([fixture.server.stop(true), fixture.upstream.stop(true)]); + fixture = undefined; + globalThis.fetch = fetchOriginal; + resetLifecycleDrainStateForTests(); clearAccountQuota(); clearCodexUpstreamHealth(); clearThreadAccountMap(); + codex.restore(); removeTreeWithRetry(home); + if (previousHome === undefined) delete process.env.OPENCODEX_HOME; else process.env.OPENCODEX_HOME = previousHome; + if (previousToken === undefined) delete process.env.OPENCODEX_API_AUTH_TOKEN; else process.env.OPENCODEX_API_AUTH_TOKEN = previousToken; +}); + +describe("GPT-Live session creation", () => { + test("relays the session to the API-key provider and answers with a key-bound alias", async () => { + fixture = createFixture(); + const response = await create(offer, KEY, { "openai-safety-identifier": "hashed-user" }); + expect(response.status).toBe(201); + const answer = await response.json() as { session: { id: string }; transport: unknown }; + expect(answer.session.id).toStartWith("rtc_ocx_"); + expect(answer.transport).toEqual({ type: "webrtc", sdp: "v=0 answer\r\n" }); + const upstream = fixture.creates[0]!; + expect(upstream.url).toBe("https://api.openai.com/v1/live/sessions"); + expect(upstream.headers.get("authorization")).toBe(`Bearer ${UPSTREAM_KEY}`); + expect(upstream.headers.get("openai-safety-identifier")).toBe("hashed-user"); + expect(upstream.headers.get("x-opencodex-api-key")).toBeNull(); + expect(await upstream.json()).toEqual(offer); + }); + + test("malformed requests, SIP and missing models are refused before any upstream call", async () => { + fixture = createFixture(); + const bodies: unknown[] = [ + { transport: offer.transport }, + { session: { instructions: "x" }, transport: offer.transport }, + { session: offer.session, transport: { type: "sip", destination: "+14155550123" } }, + { session: offer.session, transport: { type: "webrtc", sdp: "" } }, + [], + ]; + for (const body of bodies) expect((await create(body)).status).toBe(400); + expect(fixture.creates).toHaveLength(0); + }); + + test("a ChatGPT account is never substituted for the API-key provider", async () => { + saveConfig({ + port: 0, hostname: "127.0.0.1", defaultProvider: "openai", openaiProviderTierVersion: 2, + providers: { openai: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward", codexAccountMode: "pool" } }, + codexAccounts: [{ id: "pool-a", email: "a@example.test", isMain: false, chatgptAccountId: "acct-a" }], + apiKeys: [{ id: "one", name: "one", key: KEY, createdAt: "2026-11-26T00:00:00Z" }], + } as OcxConfig); + saveCodexAccountCredential("pool-a", { accessToken: fakeChatGptJwt({ chatgpt_account_id: "acct-a" }), refreshToken: "fixture-refresh", expiresAt: Date.now() + 3600000, chatgptAccountId: "acct-a" }); + fixture = createFixture(); + const response = await create(); + expect(response.status).toBe(400); + expect(await response.text()).toContain("API-key provider"); + expect(await upgradeStatus("/v1/live/sessions", KEY)).toBe(400); + expect(fixture.creates).toHaveLength(0); + expect(fixture.handshakes).toHaveLength(0); + }); + + test("a model-scoped key is judged on the session model", async () => { + fixture = createFixture(); + expect((await create({ ...offer, session: { ...offer.session, model: "gpt-live-1" } }, SCOPED_KEY)).status).toBe(403); + expect((await create(offer, SCOPED_KEY)).status).toBe(201); + }); + + test("the native path without an audio key cannot create or open sessions", async () => { + fixture = createFixture(); + const response = await fetchOriginal(new URL("/v1/live/sessions", fixture.server.url), { + method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(offer), + }); + expect(response.status).toBe(401); + expect(await upgradeStatus("/v1/live/sessions")).toBe(401); + expect(await upgradeStatus("/v1/live/sessions/rtc_ocx_missing/attach")).toBe(401); + expect(fixture.creates).toHaveLength(0); + expect(fixture.handshakes).toHaveLength(0); + }); +}); + +describe("GPT-Live session sockets", () => { + test("a session socket opens on the API-key provider without a query", async () => { + fixture = createFixture(); + expect(await echo(socket("/v1/live/sessions"), "start-echo")).toBe("start-echo"); + expect(fixture.handshakes[0]!.url).toBe("wss://api.openai.com/v1/live/sessions"); + expect(fixture.handshakes[0]!.headers.get("authorization")).toBe(`Bearer ${UPSTREAM_KEY}`); + expect(fixture.handshakes[0]!.headers.get("openai-alpha")).toBeNull(); + }); + + test("a model-scoped key cannot open a session socket that names its model in-band", async () => { + fixture = createFixture(); + expect(await upgradeStatus("/v1/live/sessions", SCOPED_KEY)).toBe(403); + expect(fixture.handshakes).toHaveLength(0); + }); + + test("only the creating key can attach to a session it created", async () => { + fixture = createFixture(); + const created = await create(); + const alias = (await created.json() as { session: { id: string } }).session.id; + expect(await upgradeStatus(`/v1/live/sessions/${alias}/attach`, OTHER_KEY)).toBe(404); + expect(fixture.handshakes).toHaveLength(0); + expect(await echo(socket(`/v1/live/sessions/${alias}/attach`), "attach-echo")).toBe("attach-echo"); + expect(fixture.handshakes[0]!.url).toBe("wss://api.openai.com/v1/live/sessions/live_fixture_1/attach"); + }); +}); + + +describe("GPT-Live session boundaries", () => { + test("a ChatGPT call alias never opens the session attach route, nor a session alias the call route", async () => { + saveConfig({ + ...keyedConfig(), defaultProvider: "openai", + providers: { + openai: { adapter: "openai-responses", baseUrl: "https://chatgpt.com/backend-api/codex", authMode: "forward", codexAccountMode: "pool" }, + ...keyedConfig().providers, + }, + codexAccounts: [{ id: "pool-a", email: "a@example.test", isMain: false, chatgptAccountId: "acct-a" }], + } as OcxConfig); + saveCodexAccountCredential("pool-a", { accessToken: fakeChatGptJwt({ chatgpt_account_id: "acct-a" }), refreshToken: "fixture-refresh", expiresAt: Date.now() + 3600000, chatgptAccountId: "acct-a" }); + fixture = createFixture(); + const call = await fetchOriginal(new URL("/v1/live", fixture.server.url), { + method: "POST", headers: { authorization: `Bearer ${KEY}`, "content-type": "application/json" }, body: JSON.stringify({ sdp: "v=0\r\n" }), + }); + expect(call.status).toBe(201); + await call.text(); + const callAlias = call.headers.get("location")!.split("/").at(-1)!; + expect(await upgradeStatus(`/v1/live/sessions/${callAlias}/attach`, KEY)).toBe(404); + const created = await create(); + const sessionAlias = (await created.json() as { session: { id: string } }).session.id; + expect(await upgradeStatus(`/v1/live/${sessionAlias}`, KEY)).toBe(404); + expect(fixture.handshakes).toHaveLength(0); + }); + + test("session sockets reach the API-key provider even when a sideband override is configured", async () => { + saveConfig({ ...keyedConfig(), experimentalRealtimeWsBaseUrl: "wss://sideband.example.test/v1" } as OcxConfig); + fixture = createFixture(); + await echo(socket("/v1/live/sessions"), "start-echo"); + const alias = (await (await create()).json() as { session: { id: string } }).session.id; + await echo(socket(`/v1/live/sessions/${alias}/attach`), "attach-echo"); + expect(fixture.handshakes.map(handshake => handshake.url)).toEqual([ + "wss://api.openai.com/v1/live/sessions", + "wss://api.openai.com/v1/live/sessions/live_fixture_1/attach", + ]); + }); + + test.each([ + ["an empty transport", () => Response.json({ session: { id: "live_fixture_1" }, transport: {} }, { status: 201 })], + ["an empty SDP answer", () => Response.json({ session: { id: "live_fixture_1" }, transport: { type: "webrtc", sdp: " " } }, { status: 201 })], + ["a SIP transport", () => Response.json({ session: { id: "live_fixture_1" }, transport: { type: "sip" } }, { status: 201 })], + ["an invalid session id", () => Response.json({ session: { id: "live 1/../x" }, transport: { type: "webrtc", sdp: "v=0" } }, { status: 201 })], + ["a non-JSON body", () => new Response("v=0", { status: 201 })], + ["a redirect", () => new Response(null, { status: 307, headers: { location: "https://elsewhere.example.test/v1/live/sessions" } })], + ["an oversized answer", () => new Response("x".repeat(LIVE_RESPONSE_MAX_BYTES + 1), { status: 201 })], + ] as const)("%s from upstream is a 502 and binds nothing", async (_label, answer) => { + fixture = createFixture({ answer }); + const response = await create(); + expect(response.status).toBe(502); + await response.text(); + expect(fixture.creates[0]!.redirect).toBe("manual"); + }); + + test("a client cancel aborts the upstream request", async () => { + const config = keyedConfig(); + saveConfig(config); + const started = Promise.withResolvers(); + let aborted = false; + globalThis.fetch = ((_input: RequestInfo | URL, init?: RequestInit) => new Promise((_resolve, reject) => { + started.resolve(); + init?.signal?.addEventListener("abort", () => { aborted = true; reject(init.signal!.reason); }, { once: true }); + })) as typeof fetch; + const controller = new AbortController(); + const req = new Request("http://localhost/v1/live/sessions", { + method: "POST", signal: controller.signal, + headers: { "content-type": "application/json", "x-opencodex-api-key": KEY }, body: JSON.stringify(offer), + }); + const audio = resolveAudioClient(req, config, true); + if (!audio || audio instanceof Response) throw new Error("audio key was not admitted"); + const lease = tryAdmitTurn(); + if (!lease) throw new Error("turn gate refused an idle lease"); + try { + const pending = handleLiveSessionCreate(req, config, { model: "unknown", provider: "unknown" }, { client: audio, lease, bindings: new LiveCallBindings() }); + await started.promise; + controller.abort(); + expect((await pending).status).toBe(499); + expect(aborted).toBe(true); + } finally { lease.release(); } + }); +}); + From 8ef15263e6a4318adc15db83dd054adde07d0ee0 Mon Sep 17 00:00:00 2001 From: JUN Date: Thu, 26 Nov 2026 03:57:11 +0900 Subject: [PATCH 59/60] feat(codex): opt the legacy opencodex provider table into Cyber access programs (#9144) * feat(codex): opt the legacy opencodex provider table into Cyber access programs Codex defaults capabilities.cyber_access_programs to off for any provider id other than openai (openai/codex 708e3e2c70; codex-rs/model-provider-info/src/lib.rs:706-710, capabilities.rs:17 and core/src/cyber_access_program.rs:57,74 @5505daf388). Behind the non-loopback [model_providers.opencodex] table, Codex therefore stopped sending Cyber access-program selections. The table now writes capabilities = { cyber_access_programs = true } inline. A table written before this line is still recognized. ocxProviderTableIdentity treats exactly that capability as absent for retention and for the journal's comparison with the recorded injected table. Comparisons with the user's original value stay exact. The ocx codex credential gate compares with the writer's current block, so it trusts only the new shape until ocx start rewrites the table. * fix(codex): show the provider table's capabilities line in the restore preview Review follow-up: the shared lightweight TOML scanner did not recognize the single-line inline table, so the preview never listed it. It now reads a single-line inline table without nesting as one value. The test drives codexConfigKeyChanges with the writer's own output in both directions and checks that unrelated keys stay masked. * fix(codex): keep quoted inline-table keys visible in the restore preview Review follow-up (CodeRabbit): the inline-table value now admits quoted keys and strings, including strings that contain '#'. * docs(codex): one-time ocx start note when ocx codex stops supplying credentials after upgrade * docs(codex): name ocx sync (or ocx stop then ocx start) as the post-upgrade recovery Review follow-up (CodeRabbit): a bare ocx start beside a running proxy exits before it writes the Codex config, so it cannot rewrite the table. * docs(codex): the post-upgrade table rewrite needs the Codex integration on Review follow-up: while the durable Codex integration setting is off, startup and sync skip Codex config, so neither rewrites the table. --- .../docs/es/guides/codex-integration.md | 5 ++ .../content/docs/guides/codex-integration.md | 11 +++ src/codex/inject/config-toml.ts | 7 ++ src/codex/inject/provider-table.ts | 15 +++- src/codex/journal-config-restore.ts | 17 ++++ src/codex/project-config-warnings.ts | 4 +- src/codex/restore-preview.ts | 2 +- structure/config.md | 5 +- ...x-journal-provider-reserialization.test.ts | 29 +++++++ .../codex-launcher-security.test.ts | 2 + .../codex-provider-table-retention.test.ts | 78 +++++++++++++++++++ 11 files changed, 169 insertions(+), 6 deletions(-) diff --git a/docs-site/src/content/docs/es/guides/codex-integration.md b/docs-site/src/content/docs/es/guides/codex-integration.md index 5b6ac3370de..a9d67a232fa 100644 --- a/docs-site/src/content/docs/es/guides/codex-integration.md +++ b/docs-site/src/content/docs/es/guides/codex-integration.md @@ -189,8 +189,11 @@ wire_api = "responses" requires_openai_auth = true env_key = "OPENCODEX_API_AUTH_TOKEN" # supports_websockets = true # only when config.websockets is true +capabilities = { cyber_access_programs = true } ``` +La línea `capabilities` permite que Codex reenvíe una selección de programa de acceso Cyber a través de esta tabla. Codex desactiva esa capacidad de forma predeterminada para todo identificador de proveedor distinto de su `openai` integrado, y la forma loopback ya usa ese identificador. Las versiones de Codex anteriores al campo lo ignoran. Una tabla escrita por una versión anterior de OpenCodex, sin la línea, sigue reconociéndose en `ocx restore` y en la desinstalación. El lanzador `ocx codex` solo confía en la forma actual: después de actualizar, si `ocx codex` deja de proporcionar credenciales, ejecute `ocx sync` una vez para reescribir la tabla. Esto requiere la integración de Codex activada; mientras está desactivada, OpenCodex deja su configuración de Codex tal como está, y ni `ocx sync` ni un reinicio reescriben la tabla. + Cuando OpenCodex posee enrutamiento, ambos modos escriben `$CODEX_HOME/opencodex.config.toml` como una configuración de referencia/retroceso. En loopback contiene las claves de raíz que puede combinar manualmente si se eliminó la inyección automática; en non-loopback contiene el formulario de proveedor dedicado. El modo de proveedor externo deja este perfil intacto. Al reconstruir ese archivo se conservan las claves simples de la raíz que OpenCodex no administra. Por ejemplo, `stream_idle_timeout_ms` y `stream_max_retries` sobreviven a la siguiente inyección. Cada asignación conservada se copia tal como está escrita, incluidos valores de varias líneas y enteros de 64 bits, y se coloca antes de la primera tabla. No se conservan las claves de tablas ni las claves raíz con puntos, como `a.b = 1`. OpenCodex prevalece en cualquier colisión: reescribe `model_provider`, `model_catalog_json` y `openai_base_url` según el modo de enrutamiento. También elimina una clave raíz cuyo nombre coincide con una tabla que escribirá el perfil, como un `features = { ... }` en línea si el perfil escribe `[features]`. Si el archivo cambia mientras la inyección espera el bloqueo de escritura, la operación termina con un error reintentable y conserva tu edición. @@ -271,6 +274,7 @@ name = "OpenCodex Proxy" base_url = "http://127.0.0.1:10100/v1" wire_api = "responses" requires_openai_auth = true +capabilities = { cyber_access_programs = true } ``` Codex luego posee compactación y almacena un resumen de texto plano portátil en lugar de un nuevo sobre OpenCodeX. La solicitud de compactación sigue enrutando a través de OpenCodeX y puede consumir cuota en el proveedor seleccionado. Las solicitudes de subagentes V2 mantienen su selección de proveedores existente y la contabilidad de cuotas. La compactación del lado del cliente no cambia la entrega de texto sin formato, el paso de tareas encriptadas a través de `allowEncryptedV2AgentTasks` o el comportamiento de recuperación y recuperación configurado. @@ -334,6 +338,7 @@ name = "OpenCodex Proxy" base_url = "http://127.0.0.1:10100/v1" wire_api = "responses" requires_openai_auth = false +capabilities = { cyber_access_programs = true } ``` El escritorio se inicia sin un inicio de sesión y las rutas de cada turno a través del proxy. La configuración sobrevive `ocx start`, reinicio, `ocx sync` y `ocx ensure`; al apagarlo (`--desktop-authless off`) hace que la siguiente sincronización restaure la forma de bucle de retorno predeterminada y `ocx restore` la despoja como cualquier otro enrutamiento inyectado. Qué esperar mientras está encendido: diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md index f1f1544e931..e0f2bd822ec 100644 --- a/docs-site/src/content/docs/guides/codex-integration.md +++ b/docs-site/src/content/docs/guides/codex-integration.md @@ -435,8 +435,17 @@ wire_api = "responses" requires_openai_auth = true env_key = "OPENCODEX_API_AUTH_TOKEN" # supports_websockets = true # only when config.websockets is true +capabilities = { cyber_access_programs = true } ``` +The `capabilities` line lets Codex forward a Cyber access-program selection through this table. Codex +turns that capability off by default for every provider id except its built-in `openai`, and the +loopback form already uses that id. Codex releases that predate the field ignore it. A table written by an +earlier OpenCodex release, without the line, is still recognized by `ocx restore` and uninstall. The +`ocx codex` launcher trusts only the current shape: after upgrading, if `ocx codex` stops supplying +credentials, run `ocx sync` once to rewrite the table. This needs the Codex integration on; while it is off, +OpenCodex leaves your Codex config as it is, and neither `ocx sync` nor a restart rewrites the table. + When OpenCodex owns routing, both modes write `$CODEX_HOME/opencodex.config.toml` as a reference/fallback config. On loopback it contains the root keys you can merge manually if automatic injection was removed; on non-loopback it contains the dedicated provider form. External-provider @@ -610,6 +619,7 @@ name = "OpenCodex Proxy" base_url = "http://127.0.0.1:10100/v1" wire_api = "responses" requires_openai_auth = true +capabilities = { cyber_access_programs = true } ``` Codex then owns compaction and stores a portable plaintext summary rather than a new OpenCodeX @@ -730,6 +740,7 @@ name = "OpenCodex Proxy" base_url = "http://127.0.0.1:10100/v1" wire_api = "responses" requires_openai_auth = false +capabilities = { cyber_access_programs = true } ``` Desktop then starts without a login and routes every turn through the proxy. The setting survives diff --git a/src/codex/inject/config-toml.ts b/src/codex/inject/config-toml.ts index d01ce4ec191..34e9bf97970 100644 --- a/src/codex/inject/config-toml.ts +++ b/src/codex/inject/config-toml.ts @@ -86,6 +86,8 @@ export function applyEol(content: string, eol: "\r\n" | "\n"): string { /** Label Codex shows for the injected provider when the operator has not chosen one. */ export const DEFAULT_CODEX_PROVIDER_DISPLAY_NAME = "OpenCodex Proxy"; +/** The legacy table's Cyber access-program opt-in; see buildProviderTableBlockForTarget. */ +export const OCX_PROVIDER_CAPABILITIES_LINE = "capabilities = { cyber_access_programs = true }"; /** Longest label accepted, matching the display-label policy used for provider names. */ const MAX_CODEX_PROVIDER_DISPLAY_NAME_LENGTH = 128; @@ -175,6 +177,11 @@ export function buildProviderTableBlockForTarget( lines.push(`env_key = ${tomlString(target.tokenEnv)}`); } if (supportsWebsockets) lines.push("supports_websockets = true"); + // Codex defaults explicit Cyber access-program selections to off for any provider id other + // than `openai` (openai/codex 708e3e2c70; codex-rs/model-provider-info/src/lib.rs:706-710 + // @5505daf388). This table is the `opencodex` id, so it opts in. Inline, so the owned span stays + // one table with no child header; Codex releases before this field ignore it. + lines.push(OCX_PROVIDER_CAPABILITIES_LINE); return lines.join("\n") + "\n"; } diff --git a/src/codex/inject/provider-table.ts b/src/codex/inject/provider-table.ts index b7c2a3d4a9f..2b7e72720e2 100644 --- a/src/codex/inject/provider-table.ts +++ b/src/codex/inject/provider-table.ts @@ -7,6 +7,19 @@ function record(value: unknown): Record | null { ? value as Record : null; } +/** + * Identity of an OpenCodex provider table across writer releases. A table written before the Cyber + * capability line and one written after it are the same table: exactly `{ cyber_access_programs: true }` + * compares as if `capabilities` were absent. Any other capabilities value stays significant, so a + * user-edited table is never mistaken for ours. Every other field compares exactly. + */ +export function ocxProviderTableIdentity(provider: Record): Record { + const capabilities = record(provider.capabilities); + if (!capabilities || Object.keys(capabilities).length !== 1 || capabilities.cyber_access_programs !== true) return provider; + const { capabilities: _owned, ...rest } = provider; + return rest; +} + function providerValue(text: string): Record { let parsed: unknown; try { parsed = Bun.TOML.parse(text); } @@ -102,7 +115,7 @@ export function appendOcxProviderTableBlock(content: string, block: string): str const captured = providerValue(block); const existing = extractOcxProviderTableBlock(content); if (existing !== null) { - if (!isDeepStrictEqual(providerValue(existing), captured)) { + if (!isDeepStrictEqual(ocxProviderTableIdentity(providerValue(existing)), ocxProviderTableIdentity(captured))) { throw new Error("Codex restore refused: the native config already defines a different [model_providers.opencodex] table."); } return content; diff --git a/src/codex/journal-config-restore.ts b/src/codex/journal-config-restore.ts index d1a278dfc60..bf269cece35 100644 --- a/src/codex/journal-config-restore.ts +++ b/src/codex/journal-config-restore.ts @@ -3,6 +3,7 @@ import { chmodSync, closeSync, fsyncSync, mkdtempSync, openSync, writeFileSync } import { join } from "node:path"; import { hardenSecretDir, hardenSecretPath } from "../lib/windows-secret-acl"; import { isOcxRoutingMarkerLine } from "./injected-marker"; +import { ocxProviderTableIdentity } from "./inject/provider-table"; import { CODEX_CONFIG_PATH, defaultCodexCatalogPathForConfig, sameCodexCatalogPath } from "./paths"; import { transformManagedSubagentDefaults, type WrittenSubagentDefaults } from "./subagent-defaults"; import { rootAssignmentKey, rootSourceLines, sourceAssignment, sourceText } from "./toml-source-lines"; @@ -170,9 +171,25 @@ function matchesInjectedField(key: string, value: unknown, injected: unknown): b if (key === "model_catalog_json" && typeof value === "string" && value && typeof injected === "string" && injected) { return sameCodexCatalogPath(CODEX_CONFIG_PATH, value, injected); } + if (key === "model_providers.opencodex") { + // A table recorded before the Cyber capability line and one written after it are the same + // injected table. Only this provider is normalized; the enclosing shape compares exactly. + const present = capturedOcxProvider(value), recorded = capturedOcxProvider(injected); + if (present && recorded) return isDeepStrictEqual(ocxProviderTableIdentity(present), ocxProviderTableIdentity(recorded)); + } return isDeepStrictEqual(value, injected); } +/** The provider inside a captured `{ model_providers: { opencodex: … } }` span value, and nothing else. */ +function capturedOcxProvider(value: unknown): Record | null { + const object = (candidate: unknown): Record | null => + candidate !== null && typeof candidate === "object" && !Array.isArray(candidate) ? candidate as Record : null; + const root = object(value); + const providers = object(root?.model_providers); + if (!root || !providers || Object.keys(root).length !== 1 || Object.keys(providers).length !== 1) return null; + return object(providers.opencodex); +} + /** Three-way restore: an edited preference stays; an edited routing field blocks hand-back. */ export function restoreJournalConfigFields(current: string, original: string, journal: Ownership, recoverOwnedEdits = false): string | null { try { diff --git a/src/codex/project-config-warnings.ts b/src/codex/project-config-warnings.ts index 183f76c4e83..3f31b09c6e3 100644 --- a/src/codex/project-config-warnings.ts +++ b/src/codex/project-config-warnings.ts @@ -201,7 +201,9 @@ export function parseTomlDocument(content: string): TomlDocument { current = section; continue; } - const kv = line.match(/^\s*([A-Za-z0-9_.-]+)\s*=\s*("(?:\\.|[^"\\])*"|'[^']*'|[^\s#]+)\s*(?:#.*)?$/); + // A single-line inline table without nesting (the provider table's capabilities line) is one value; + // quoted keys and strings inside it, including ones holding '#', stay part of the value. + const kv = line.match(/^\s*([A-Za-z0-9_.-]+)\s*=\s*("(?:\\.|[^"\\])*"|'[^']*'|\{(?:[^{}#"']|"(?:\\.|[^"\\])*"|'[^']*')*\}|[^\s#]+)\s*(?:#.*)?$/); if (kv) current[kv[1]!] = parseTomlString(kv[2]!); } diff --git a/src/codex/restore-preview.ts b/src/codex/restore-preview.ts index 253d6998556..1214889c652 100644 --- a/src/codex/restore-preview.ts +++ b/src/codex/restore-preview.ts @@ -93,7 +93,7 @@ const SHOWN_LEAF_KEYS = new Set([ "base_url", "name", "wire_api", "env_key", "requires_openai_auth", "query_params", "http_headers", "trust_level", "enabled", "trusted_hash", "model", "model_provider", "model_reasoning_effort", "default_subagent_model", "default_subagent_reasoning_effort", "stream_idle_timeout_ms", - "request_max_retries", "stream_max_retries", "supports_websockets", + "request_max_retries", "stream_max_retries", "supports_websockets", "capabilities", ]); /** diff --git a/structure/config.md b/structure/config.md index 8fe1ae1bbe6..d0a5940c0f4 100644 --- a/structure/config.md +++ b/structure/config.md @@ -181,11 +181,10 @@ base_url = "http://:/v1" wire_api = "responses" requires_openai_auth = true env_key = "OPENCODEX_API_AUTH_TOKEN" +capabilities = { cyber_access_programs = true } ``` -Root TOML keys must be written before the first `[table]`. Re-injection strips the stale form of -both shapes — opencodex blocks, injected root base-url overrides, and stale catalog paths — before -rewriting, so switching between forms leaves no residue. A root context-window override is user-owned. +Root TOML keys must be written before the first `[table]`. Re-injection strips the stale form of both shapes — opencodex blocks, injected root base-url overrides, and stale catalog paths — before rewriting, so switching between forms leaves no residue. A root context-window override is user-owned. The inline `capabilities` line opts the `opencodex` id into Cyber access-program selections, which Codex defaults off for every id except `openai` (openai/codex 708e3e2c70; codex-rs/model-provider-info/src/lib.rs:706-710 @5505daf388). It is inline, so the owned span stays one table without a child header. `ocxProviderTableIdentity` in `src/codex/inject/provider-table.ts` treats exactly `{ cyber_access_programs: true }` as absent. Retention (`appendOcxProviderTableBlock`) and the journal's comparison with the recorded injected table (`matchesInjectedField` in `src/codex/journal-config-restore.ts`) therefore accept a table written before the line. Comparisons with the user's original value stay exact. The `ocx codex` credential gate (`src/cli/codex-launch-auth.ts`) compares with the writer's current block, so it trusts only the new shape (`tests/codex-integration/codex-launcher-security.test.ts`, `tests/codex-integration/codex-provider-table-retention.test.ts`, `tests/codex-integration/codex-journal-provider-reserialization.test.ts`). The `name` field is the only presentation value in that table, and `codexProviderDisplayName` chooses it (default `OpenCodex Proxy`). `resolveCodexProviderDisplayName` in diff --git a/tests/codex-integration/codex-journal-provider-reserialization.test.ts b/tests/codex-integration/codex-journal-provider-reserialization.test.ts index 207bc645310..26b8254595d 100644 --- a/tests/codex-integration/codex-journal-provider-reserialization.test.ts +++ b/tests/codex-integration/codex-journal-provider-reserialization.test.ts @@ -73,3 +73,32 @@ test.each(["inline", "dotted"])("%s provider refusal preserves the actual journa expect(result.retained).toBe(true); } finally { removeTreeWithRetry(root); } }); + +const cyberOriginal = 'model = "native"\n'; +const legacyInjected = 'model_provider = "opencodex"\n[model_providers.opencodex]\nbase_url = "http://127.0.0.1:10100/v1"\nrequires_openai_auth = true\n'; +const cyberInjected = legacyInjected + "capabilities = { cyber_access_programs = true }\n"; +const userTable = '[model_providers.mine]\nbase_url = "https://mine.example/v1"\n'; + +test.each([ + ["an old-shape journal", legacyInjected, cyberInjected], + ["a new-shape journal", cyberInjected, legacyInjected], +])("%s restores the other table shape and keeps an unrelated user edit", (_name, recorded, onDisk) => { + const owned = { injectedConfigFields: captureJournalConfigFields(recorded, {}) }; + const current = onDisk.slice(0, onDisk.indexOf("[")) + userTable + onDisk.slice(onDisk.indexOf("[")); + // `model` is a preference the restore leaves alone; the owned table and root selection go. + expect(restoreJournalConfigFields(current, cyberOriginal, owned)).toBe(userTable); +}); + +test.each([ + ["a changed capability", cyberInjected.replace("= true }", "= false }")], + ["an extra capability", cyberInjected.replace("= true }", '= true, remote_compaction = "v2" }')], + ["a changed base_url", cyberInjected.replace("10100", "10101")], + ["an added env_key", cyberInjected + 'env_key = "OTHER_TOKEN"\n'], + ["a changed auth requirement", cyberInjected.replace("requires_openai_auth = true", "requires_openai_auth = false")], +])("%s against either recorded shape still refuses field restoration", (_name, onDisk) => { + for (const recorded of [legacyInjected, cyberInjected]) { + const owned = { injectedConfigFields: captureJournalConfigFields(recorded, {}) }; + expect(restoreJournalConfigFields(onDisk, cyberOriginal, owned)).toBeNull(); + } +}); + diff --git a/tests/codex-integration/codex-launcher-security.test.ts b/tests/codex-integration/codex-launcher-security.test.ts index a829fdcd8e7..e9908e6ce28 100644 --- a/tests/codex-integration/codex-launcher-security.test.ts +++ b/tests/codex-integration/codex-launcher-security.test.ts @@ -55,6 +55,8 @@ describe("codex launcher credential destination", () => { ["default profile redirects provider", 'profile = "foreign"\n' + local + '\n[profiles.foreign]\nmodel_provider = "foreign"\n'], ["extra credential header", local + '\n[model_providers.opencodex.env_http_headers]\nx-key = "OPENCODEX_API_AUTH_TOKEN"\n'], ["malformed TOML", local + '\nmodel_provider = [\n'], + ["provider table written before the Cyber capability", local.replace("capabilities = { cyber_access_programs = true }\n", "")], + ["changed Cyber capability", local.replace("cyber_access_programs = true", "cyber_access_programs = false")], ]) { test(`does not load a token for ${name}`, () => fixture((_home, codexHome) => { writeFileSync(join(codexHome, "config.toml"), content!); diff --git a/tests/codex-integration/codex-provider-table-retention.test.ts b/tests/codex-integration/codex-provider-table-retention.test.ts index b39067bd3e1..6e8f39c1b4e 100644 --- a/tests/codex-integration/codex-provider-table-retention.test.ts +++ b/tests/codex-integration/codex-provider-table-retention.test.ts @@ -4,6 +4,9 @@ import { spawnSync } from "node:child_process"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { deriveCodexInjectionPlan } from "../../src/codex/inject/plan"; +import { buildProviderTableBlockForTarget } from "../../src/codex/inject/config-toml"; +import { standaloneCodexRoutingTarget } from "../../src/codex/inject/routing-target"; +import { codexConfigKeyChanges, displayCodexConfigKey } from "../../src/codex/restore-preview"; import { OCX_ROUTING_MARKER_LINE, OCX_SECTION_MARKER } from "../../src/codex/injected-marker"; import { repoRoot } from "../helpers/repo-root"; import { removeTreeWithRetry } from "../helpers/remove-tree"; @@ -232,3 +235,78 @@ describe("provider table ownership markers", () => { } }, 2 * SPAWN_BUDGET_MS); }); + +describe("Cyber access-program capability in the legacy table (openai/codex 708e3e2c70)", () => { + // codex-rs/model-provider-info/src/lib.rs:706-710 @5505daf388 defaults cyber_access_programs to off for any + // provider id other than openai, so the legacy table must opt in for Cyber selections to reach the backend. + const target = standaloneCodexRoutingTarget(12199, { port: 12199, hostname: "0.0.0.0" }); + const capability = "capabilities = { cyber_access_programs = true }"; + const oldShape = (block: string) => block.split("\n").filter(line => line !== capability).join("\n"); + const user = '[model_providers.mine]\nbase_url = "https://mine.example/v1"\ncapabilities = { cyber_access_programs = false }\n'; + + test("every writer variant opts in without touching an auth line", () => { + const variants = [ + buildProviderTableBlockForTarget(target), + buildProviderTableBlockForTarget(target, true, "Custom"), + buildProviderTableBlockForTarget({ ...target, desktopAuthless: true }), + buildProviderTableBlockForTarget({ ...target, requiresAdmissionToken: true, tokenEnv: "OPENCODEX_API_AUTH_TOKEN" }), + ]; + for (const block of variants) { + expect(block).toContain(capability); + const provider = (Bun.TOML.parse(block) as { model_providers: { opencodex: Record } }).model_providers.opencodex; + expect(provider.capabilities).toEqual({ cyber_access_programs: true }); + expect(oldShape(block)).not.toContain("capabilities"); + expect(hasOcxProviderTable(block)).toBe(true); + } + }); + + test("restore and retention treat the old and new shapes as the same table", () => { + const fresh = buildProviderTableBlockForTarget(target); + const legacy = oldShape(fresh); + expect(fresh).not.toBe(legacy); + expect(appendOcxProviderTableBlock(user + legacy, fresh)).toBe(user + legacy); + expect(appendOcxProviderTableBlock(user + fresh, legacy)).toBe(user + fresh); + }); + + test("any other capabilities value is still a different table", () => { + const fresh = buildProviderTableBlockForTarget(target); + for (const changed of [ + fresh.replace("cyber_access_programs = true", "cyber_access_programs = false"), + fresh.replace("cyber_access_programs = true", 'cyber_access_programs = true, remote_compaction = "v2"'), + ]) { + expect(() => appendOcxProviderTableBlock(user + changed, fresh)).toThrow("different [model_providers.opencodex] table"); + } + }); + + test("removal takes either shape whole and leaves an unrelated user table byte-identical", () => { + const fresh = buildProviderTableBlockForTarget(target); + for (const block of [fresh, oldShape(fresh)]) { + const content = user + block; + // The blank separator line the writer emits before its marker stays with the surrounding file. + expect(removeOcxSection(content)).toBe(user + "\n"); + expect(hasOcxProviderTable(removeOcxSection(content))).toBe(false); + } + }); + + test("the restore preview lists the capability line the writer emits, in both directions", () => { + const fresh = buildProviderTableBlockForTarget(target); + const userKeys = user + 'secret_named_key = "x"\n'; + const withTable = userKeys + fresh; + const removal = codexConfigKeyChanges(withTable, userKeys); + expect(removal).toContainEqual({ file: "config.toml", key: "model_providers.opencodex.capabilities", change: "remove" }); + const addition = codexConfigKeyChanges(userKeys, withTable); + expect(addition).toContainEqual({ file: "config.toml", key: "model_providers.opencodex.capabilities", change: "add" }); + // The old shape differs only by that key. + expect(codexConfigKeyChanges(userKeys + oldShape(fresh), withTable)) + .toEqual([{ file: "config.toml", key: "model_providers.opencodex.capabilities", change: "add" }]); + // Unrelated user keys stay masked and unchanged. + for (const change of [...removal, ...addition]) expect(change.key).not.toContain("mine"); + expect(displayCodexConfigKey("model_providers.mine.capabilities")).toBe("model_providers.….capabilities"); + // A rewriter that quotes the inline key or a value holding '#' is still one recognized value. + for (const line of ['capabilities = { "cyber_access_programs" = true }', "capabilities = { 'cyber_access_programs' = true, note = \"a#b\" }"]) { + expect(codexConfigKeyChanges(userKeys, userKeys + "[model_providers.opencodex]\n" + line + "\n")) + .toContainEqual({ file: "config.toml", key: "model_providers.opencodex.capabilities", change: "add" }); + } + }); +}); + From dba57f0b32d8cb2bec0c92144ae6aeafb7f2cc99 Mon Sep 17 00:00:00 2001 From: Bernardo Donadio Date: Fri, 27 Nov 2026 21:29:58 -0300 Subject: [PATCH 60/60] Preserve draft Combo target positions Reconcile concurrent saved edits without moving draft target insertions or replacements when the saved target order stays the same. Cover replacement and middle insertion through the editor merge. Signed-off-by: Bernardo Donadio --- docs-site/src/content/docs/guides/combos.md | 2 +- gui/src/components/combo-workspace-merge.ts | 4 +++- gui/tests/combo-workspace-dirty.test.tsx | 14 ++++++++++++++ structure/dashboard-and-usage.md | 2 +- 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index cbd66e20d06..ffb08a4bf21 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -20,7 +20,7 @@ if `provider/model` selectors are new to you. In **Models → Combos**, choose **OpenAI first** or **Claude first** when both subscription and API providers are available. Each preset starts with the selected subscription and its API key, then adds the other subscription and its API key. Drag a target by its handle or use its arrow buttons -to reorder it. The **Fallback preview** identifies the first blocked step and shows the steps +to reorder it. The editor keeps the positions of targets you add or replace when a concurrent saved edit leaves the target order intact. The **Fallback preview** identifies the first blocked step and shows the steps beyond it. The paid-call switch sits below the preview status and starts off for both presets. Use **Subscriptions only** when creating a preset to remove both API targets. Send requests to the saved `combo/openai-first` or `combo/claude-first` to use the route. diff --git a/gui/src/components/combo-workspace-merge.ts b/gui/src/components/combo-workspace-merge.ts index 5c7b7be5507..8b6ad0c331f 100644 --- a/gui/src/components/combo-workspace-merge.ts +++ b/gui/src/components/combo-workspace-merge.ts @@ -63,7 +63,9 @@ function mergeTargets(previous: ComboTarget[], draft: ComboTarget[], remote: Com const remoteReordered = !sameOrder(baselineOrder, theirOrder); const orderConflict = !sameOrder(baselineOrder, myOrder) && remoteReordered && !sameOrder(myOrder, theirOrder); const hasIncomplete = draft.some(target => !target.provider.trim() || !target.model.trim()); - const order = reordered || (hasIncomplete && !remoteReordered) ? [...draft, ...remote] : [...remote, ...draft]; + const hasDraftAddition = [...local.keys()].some(key => !old.has(key)); + const order = reordered || ((hasIncomplete || hasDraftAddition) && !remoteReordered) + ? [...draft, ...remote] : [...remote, ...draft]; const targets: ComboTarget[] = []; for (const item of order) { const key = identity(item); diff --git a/gui/tests/combo-workspace-dirty.test.tsx b/gui/tests/combo-workspace-dirty.test.tsx index 1a697c29e5a..2dd81d94566 100644 --- a/gui/tests/combo-workspace-dirty.test.tsx +++ b/gui/tests/combo-workspace-dirty.test.tsx @@ -550,6 +550,20 @@ test("divergent target reorders conflict while one-sided reorders merge", () => expect(remoteOnly.merged.targets.map(t => t.model)).toEqual(["a", "c", "b"]); }); +test.each([ + { change: "replacement", models: ["x", "b"] }, + { change: "insertion", models: ["a", "x", "b"] }, +])("remote metadata edits preserve a draft target $change in place", ({ models }) => { + const targets = (ids: string[]) => ids.map(model => ({ provider: "openai", model })); + const previous = { ...combos[0]!, targets: targets(["a", "b"]) }; + const draft = { ...previous, targets: targets(models) }; + const remote = { ...previous, displayName: "Remote" }; + const result = mergeComboDraft(previous, draft, remote); + expect(result.conflicts).toEqual([]); + expect(result.merged.displayName).toBe("Remote"); + expect(result.merged.targets.map(target => target.model)).toEqual(models); +}); + test("reconciliation preserves multiple unsaved blank target rows in place", () => { const configured = { provider: "openai", model: "a", clientKey: "saved" }; const blank1 = { provider: "", model: "", clientKey: "new-1" }; diff --git a/structure/dashboard-and-usage.md b/structure/dashboard-and-usage.md index 9028c4560e5..affbc7d8cb8 100644 --- a/structure/dashboard-and-usage.md +++ b/structure/dashboard-and-usage.md @@ -468,7 +468,7 @@ expire within 30 minutes; exhaustion may expire earlier when the runtime predica `gui/src/combo-workspace-data.ts` accepts only this projection for quota-based Save/Create blocking. Missing, invalid or expired evidence is unknown. `gui/src/pages/Combos.tsx` wakes at the rendered expiry, including a deadline crossed before effects run, rechecks activation and visibility, and -refreshes quota with Combo data while preserving drafts. Each successful quota snapshot also +refreshes quota with Combo data while preserving drafts. `gui/src/components/combo-workspace-merge.ts` keeps draft insertions and replacements in place when the saved order of shared targets stays the same. Each successful quota snapshot also advances the observation clock, so a retained older row cannot defer evaluation of a fresh row. Optional Codex transport-hint suppression is scoped to canonical Responses client output;