diff --git a/.env.example b/.env.example new file mode 100644 index 0000000000..f5b5a1ee40 --- /dev/null +++ b/.env.example @@ -0,0 +1,8 @@ +# WebMCP stays local-first by default. +LOCAL_ONLY=true + +# Optional production adapters. Leave empty for deterministic demo mode. +COMFYUI_BASE_URL= +H3_BASE_URL= + +# Never commit real credentials. Keep them in the OS keyring or private .env. diff --git a/README.md b/README.md index 106251a8a4..88001a9d9c 100644 --- a/README.md +++ b/README.md @@ -1,303 +1,73 @@ -

make codex open!

-

Universal provider proxy for OpenAI Codex, Claude Code, Claude Desktop & Grok Build
-Two commands, and every one of them runs any LLM you point it at.

+# PaohupByPaoZa -

- Follow @claudeebum on X - npm version - license - node version -

+แดชบอร์ดพร็อกซีโมเดลในเครื่อง สไตล์แอปเปิล รองรับภาษาไทย +ใช้ได้กับ Codex, Claude Code, Claude Desktop และ Grok Build เหมือนเดิม -```bash -npm install -g @bitkyc08/opencodex -ocx start # proxy + dashboard on localhost:10100 -``` - - - - - - - - - - -
- Claude Code running a routed model through opencodex — the status bar shows gpt-5.6-luna-medium as the active model
- Claude Code, running any model.
The picker is stock Claude Code. The brain behind it isn't.
-
- opencodex demo — running a task in the Codex app on a routed non-OpenAI model
- Codex, running any model.
Pick a provider and go — same workflow, different brain.
-
- Claude Desktop answering as Claude Opus 4.8, then dispatching a GPT-5.6 Sol subagent through opencodex
- Claude Desktop, running any model.
Opus answers, then hands the task to a GPT-5.6 Sol subagent.
-
- Grok Build running GPT-5.6 Sol through opencodex and calling a Kimi K3 subagent
- Grok Build, running any model.
Sol drives the session and calls a Kimi K3 subagent.
-
- -

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

+## Brain Universe + WebMCP -opencodex is a lightweight local proxy that translates Codex's Responses API into whatever your -provider speaks — streaming, tool calls, reasoning tokens, images, in both directions. Use Claude, -Gemini, Grok, GLM, DeepSeek, Kimi, Qwen, Ollama, or any other LLM with Codex, Claude Code, Claude -Desktop, and Grok Build. It can also manage a **ChatGPT account pool** for Codex auth: add accounts, -refresh their quotas in the dashboard, and let new sessions auto-route to the lowest-usage healthy -account while existing threads stay pinned to the account that started them. +เปิด http://127.0.0.1:10100/#brain เพื่อดู projects, tasks, agents, skills, +memory, policies, approvals, Atlas/Universe, WebMCP Tool Inspector และ Agent +Activity -## Quick start +เปิด http://127.0.0.1:10100/#demo สำหรับ Smart Factory challenge scenario -### For humans +WebMCP ใช้ document.modelContext เมื่อ browser รองรับ และซ่อน tools อย่าง +ปลอดภัยเมื่อ API ยังไม่พร้อม Human UI กับ agent tools ใช้ Agent OS API, +policy และ approval gateway ชุดเดียวกัน ดูรายละเอียดที่ +docs/PHASE-15-WEBMCP.md และ docs/WEBMCP-TOOLS.md -```bash -npm install -g @bitkyc08/opencodex # Node 18+; the Bun runtime is bundled automatically -ocx start # or `ocx service` to run it in the background -``` +โปรเจคนี้อยู่ที่: -
-Install from source (latest dev, Bun canary) +`C:\Users\AD PAO\Desktop\paohupbypaoZAZAZA55555` -**macOS / Linux:** +ฐานมาจาก OpenCodex 2.26.0 + อัปเดตจากสาขา `dev` หลังนั้น เป็น PaohupByPaoZa **2.62.0** ฟังก์ชันเดิมครบ +ตั้งค่าเดิมยังอยู่ที่ `~/.opencodex` ดังนั้นผู้ให้บริการ / บัญชี / โมเดลเดิมใช้ต่อได้ทันที -```bash -curl -fsSL https://bun.sh/install | bash && ~/.bun/bin/bun upgrade --canary -git clone https://github.com/lidge-jun/opencodex.git -cd opencodex && ~/.bun/bin/bun install -~/.bun/bin/bun run src/cli/index.ts start -``` +## เปิดใช้งาน -**Windows (PowerShell):** +ปิด `ocx` ตัวเดิมก่อนถ้าพอร์ต 10100 ถูกใช้อยู่ แล้วรัน: ```powershell -irm bun.sh/install.ps1 | iex; bun upgrade --canary -git clone https://github.com/lidge-jun/opencodex.git -cd opencodex; bun install -bun run src/cli/index.ts start -``` - -Source install runs the latest `dev` branch with Bun canary. Memory ownership -patches, runtime GC improvements, and unreleased fixes are available here before -they reach the npm package. - -
- -Open **http://localhost:10100** and configure everything in the web dashboard — add providers -(40+ built-ins, or any OpenAI-compatible endpoint), pick models, manage accounts. `ocx gui` -re-opens the dashboard at any time. -It can also manage a **ChatGPT account pool** for Codex auth. Add multiple ChatGPT / Codex accounts, -refresh their 5h / weekly / 30d quota in the dashboard. Under quota routing, new sessions can use -the lowest-usage healthy account; round-robin and fill-first use their own policies. Existing Codex -threads normally retain affinity to the account that started them, so long SSH, tmux, or -mobile-connected sessions do not jump accounts mid-conversation — but quota re-evaluation, failover, -account exclusion, affinity expiry, or 401/403 and 429 recovery can rebind them. Give the accounts a -selection order when one of them — usually your Codex Desktop login — should only be reached for -once the others are drained. - -### For agents - -```bash -npm install -g @bitkyc08/opencodex -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. - -> **Agents installing or running opencodex:** read -> [`AGENTS_INSTALL.md`](./AGENTS_INSTALL.md). An interactive `ocx start` may ask once whether to -> star this repository — that is the user's decision, never an agent's. The CLI suppresses the -> prompt for agent-driven runs and the API refuses them with `403 agent_consent_required`. - -## Supported platforms - -| OS | Status | Service manager | -|---|---|---| -| macOS (arm64 / x64) | Fully supported | launchd | -| Linux (x64 / arm64) | Fully supported | systemd (user unit) | -| Windows (x64) | Fully supported | Task Scheduler (hidden) / opt-in native service (`--native`, WinSW) | - -Requires [Node](https://nodejs.org) 18+. The Bun runtime is bundled on `npm install` — no separate -Bun install needed, no WSL needed on Windows. If npm blocked the bundled runtime's install scripts, -see the [installation docs](https://opencodex.me/getting-started/installation/). - -## Highlights - -- **Use any LLM with Codex, Claude Code, Claude Desktop, and Grok Build** — 40+ providers out of - the box, each keeping its own native UI. -- **Pool ChatGPT accounts** — thread affinity, quota-aware auto-switching, cooldown and - fail-closed auth handling. - - > **Provider-policy note:** Account pooling is for routing and operational resilience only; it does - > not guarantee protection from provider rate limits, enforcement, suspension, or other account - > actions. OpenCodex does not endorse using additional accounts to circumvent provider limits or - > sharing account credentials between people. You are responsible for complying with each - > provider's current terms. See the - > [Codex Auth account-pool guidance](https://opencodex.me/guides/web-dashboard/#codex-auth-and-account-pools) - > and [OpenAI's current Terms of Use](https://openai.com/policies/terms-of-use/). -- **Combos** — one virtual model id with failover or weighted round-robin across providers. See - the [combo guide](https://opencodex.me/guides/combos/). -- **Sub-agents on any model** — feature routed models in Codex's sub-agent picker, with v1/v2 - surface control and fallback chains. See the - [sub-agent guide](https://opencodex.me/guides/sub-agent-surface/). -- **Log in once, skip the API key** — OAuth for xAI, Anthropic, and Kimi; or forward - `codex login`, paste a key, or use `${ENV_VAR}` references. -- **Web search & vision sidecars** — non-OpenAI models get real web search and image understanding - through a sidecar over your ChatGPT login. -- **See what's happening** — the dashboard shows providers, OAuth status, model selection, and a - live request log with cache token counts. -- **Clean exit, zero residue** — `ocx stop` restores Codex to its original configuration. -- **Bounded memory ownership** — every long-lived cache, ring buffer, and protocol-translation - store has a finite cap, byte budget, or active reconciliation. No unbounded `Map` or `Set` - survives a config reload. - -
-Memory ownership details - -OpenCodex tracks 36 categories of process-retained state. Each has a documented bound: - -- **12 retained stores** (request log, debug rings, image cache, model cache, vision - descriptions, cursor blobs, responses continuation, etc.) are byte-accounted and - evicted by the app-owned memory budget (default 256 MiB). -- **4 observed buffers** (translator accumulators, image/OAuth/Grok tails) are - monitored for in-flight byte pressure without eviction. -- **24 state-store registrations** handle expiry sweeps (60 s interval) and - config-generation reconciliation so stale provider/account keys are removed. -- **Path and fingerprint memos** (workspace metadata, hardened identities, installation - salts, mode-hint capabilities) use insertion-order LRU caps (8–128 entries). -- **Model-cache generation tombstones** are deleted after reconciliation; a global - generation increment prevents stale in-flight discoveries from repopulating removed - providers. -- **Lab event-id deduplication** runs under a ledger lock from disk, with no - process-level RAM index. - -Run `GET /api/system/memory` (with the admin token) to inspect live retained bytes, -eviction counters, and watchdog samples. - -
- -## Model routing - -Target any configured provider and model with the `provider/model` syntax: - -```bash -codex -m "anthropic/claude-opus-5" "Explain this stack trace" -codex -m "google/gemini-3-pro" "Write unit tests for auth.ts" -codex -m "ollama/llama3" "Refactor this function" -``` - -Omit the `provider/` prefix to use the default provider or auto-match by model name pattern. -Provider model ids containing `/` are exposed with inner slashes aliased to `-`; the raw -full-slash form keeps working too. Details: [model routing docs](https://opencodex.me/guides/model-routing/). - -## Providers & adapters - -OpenAI (ChatGPT login or API key), Anthropic, Google Gemini, xAI, Kimi, Azure OpenAI, Ollama -(local + Cloud), Cursor (experimental), and every OpenAI-compatible endpoint — plus DeepSeek, -Groq, OpenRouter, Together, Fireworks, Cerebras, Mistral, Hugging Face, NVIDIA NIM, MiniMax, -Qwen Cloud, SiliconFlow, and more. Full list: `ocx init` or the -[provider docs](https://opencodex.me/guides/providers/). - -## CLI - -```bash -ocx init # interactive setup (writes config, wires Codex, offers the shim) -ocx start [--port 10100] # start the proxy in the foreground -ocx stop # stop + restore native Codex -ocx service [install|start|stop|status|uninstall|remove] # background service -ocx codex-shim install # start the proxy on demand whenever `codex` launches -ocx health [--json] # check immediate proxy liveness -ocx ready [--json] [--wait [--timeout ]] # check post-sync readiness -ocx status # is the proxy running? -ocx gui # open the web dashboard -ocx provider <...> # manage providers (list/add/edit/test/remove) -ocx account <...> # manage ChatGPT accounts & API-key pools -ocx combo <...> # manage failover / round-robin combos -ocx v2 <...> # multi-agent v1/v2 surface controls -ocx update [--tag preview] # update opencodex +cd "C:\Users\AD PAO\Desktop\paohupbypaoZAZAZA55555" +bun install +cd gui; bun install; bun run build; cd .. +bun run src/cli/index.ts start --port 10100 ``` -Unpinned starts may pick another free port if the preferred one is busy; an explicit `--port` -never hops. Full reference: [CLI docs](https://opencodex.me/reference/cli/). - -### Health and readiness +หรือดับเบิลคลิก `start.cmd` -`GET /healthz` reports immediate proxy liveness. The unauthenticated `GET /readyz` endpoint reports -post-sync readiness with the sanitized JSON identity `{service, version, uptime, pid, port, status}`. -It returns `200` when `status` is `ready`; `pending` and terminal `failed` return `503` with -`Retry-After: 1`. +ภาษาเริ่มต้นคือ **ไทย** (เปลี่ยนได้ที่ตัวเลือกภาษาด้านซ้าย) -`ocx ready [--json] [--wait [--timeout ]]` performs one probe by default. `--wait` polls -for up to 45 seconds by default, but exits immediately when it observes terminal `failed`; -`--timeout ` sets a 1–300 second limit, requires `--wait`, and accepts only positive integers. CLI `--json` output is -`{ready, status, pid, port}`, where `status` is `ready`, `pending`, `failed`, or `unreachable`. +ถ้าต้องการให้รันพื้นหลังอัตโนมัติแบบเดิม เปิด PowerShell แบบผู้ดูแลแล้วรัน: -| Exit | Result | -| --- | --- | -| `0` | Ready | -| `1` | Not ready: pending, failed, timeout, or unreachable | -| `64` | Invalid arguments | - -An older proxy without `/readyz` fails closed as `unreachable` with exit 1, while `ocx health` -remains compatible. - -### Autostart: service vs shim - -Use the **service** (`ocx service`) for an always-on proxy that restarts on crash. Use the -**shim** (`ocx codex-shim install`) for lightweight, on-demand startup without a background -daemon. Remove them with `ocx service uninstall` / `ocx codex-shim uninstall`. - -### Uninstall - -```bash -ocx uninstall # stop, remove service/shim, restore native Codex, clean up state -npm uninstall -g @bitkyc08/opencodex +```powershell +cd "C:\Users\AD PAO\Desktop\paohupbypaoZAZAZA55555" +bun run src/cli/index.ts service ``` -## Remote access +แล้วเปิด http://localhost:10100/#dashboard -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/). +คำสั่งที่ใช้ได้ (ชี้มาที่โปรเจคนี้แล้ว): -## Documentation +- `paohup start` +- `paohupbypaoza start` +- `ocx start` (ชื่อเดิม ยังใช้ได้) -The public docs — install, providers, routing, combos, sub-agents, sidecars, integrations, and -the CLI/config/management-API references — are built from [`docs-site/`](./docs-site) and -published to **[opencodex.me](https://opencodex.me/)**. +เช็กสถานะ: `paohup status` -Maintainer source-of-truth notes live under [`structure/`](./structure), contributor setup in -[`CONTRIBUTING.md`](./CONTRIBUTING.md), and security reporting in [`SECURITY.md`](./SECURITY.md). -Report undisclosed vulnerabilities privately through -[GitHub private vulnerability reporting](https://github.com/lidge-jun/opencodex/security/advisories/new), -not a public issue. - -## Development - -Source development requires the `bun` CLI on your `PATH`. This is separate from the published npm -package's bundled Bun runtime, which is used only by installed `ocx` commands. - -```bash -git clone https://github.com/lidge-jun/opencodex.git -cd opencodex -bun install -bun run typecheck -bun run test -``` +## สิ่งที่เปลี่ยน -See **[Contributing](./CONTRIBUTING.md)**. +- ชื่อผลิตภัณฑ์: **PaohupByPaoZa** +- UI สไตล์แอปเปิล (สีฟ้าระบบ, ฟอนต์ระบบ, กระจกฝ้า, มุมโค้ง) +- เพิ่มภาษาไทยในตัวเลือกภาษา (ตรวจจับ `th` อัตโนมัติ) +- พอร์ต / API / header / config เดิมยังเหมือนเดิม เพื่อไม่ให้ client ที่ผูกไว้พัง -## Disclaimer +## พูลบัญชี -opencodex is an independent, community-maintained project and is **not affiliated with or endorsed by OpenAI, Anthropic, or any other provider**. +พูลบัญชี ChatGPT / Codex ใช้เพื่อ routing และความทนทานเท่านั้น ไม่ได้รับประกันว่าจะเลี่ยง rate limit การระงับ หรือมาตรการอื่นของ provider ห้ามใช้เพื่อเลี่ยงข้อจำกัดหรือแชร์บัญชีกัน คนใช้มีหน้าที่ปฏิบัติตาม terms ปัจจุบันของแต่ละเจ้า -Some providers — notably Anthropic (Claude) — may suspend or restrict accounts that route API traffic through third-party proxies. **Use at your own risk (UAYOR).** Before connecting a provider, review its Terms of Service to confirm that proxy-based access is permitted. The opencodex maintainers are not responsible for any account actions taken by upstream providers. +## English -## License +PaohupByPaoZa is a local LLM provider proxy dashboard. Same engine as OpenCodex 2.26.0, new name, Apple-style UI, Thai language. Existing `~/.opencodex` config is reused on purpose. This overlay tracks OpenCodex `dev` as **2.62.0**. -MIT +Account pooling is for routing and operational resilience only; it does not guarantee protection from provider rate limits, enforcement, suspension, or other account actions. PaohupByPaoZa does not endorse using additional accounts to circumvent provider limits or sharing account credentials between people. You are responsible for complying with each provider's current terms. diff --git a/devlog/_plan/260820_bug_pr_backlog_consolidation/090_merge_log.md b/devlog/_plan/260820_bug_pr_backlog_consolidation/090_merge_log.md new file mode 100644 index 0000000000..069025e977 --- /dev/null +++ b/devlog/_plan/260820_bug_pr_backlog_consolidation/090_merge_log.md @@ -0,0 +1,110 @@ +# 090 — Merge log: the bug-PR backlog landing on dev + +Unit: 260820_bug_pr_backlog_consolidation +Work-phases: wp21-wp25. +dev before: `31ee7a683`. dev after: `a584890f8`. + +## The override that was not needed + +All 19 PRs sat at CHANGES_REQUESTED from @Ingwannu with green CI, and the plan was to merge +with admin authority. Three independent read-only lanes read every blocking review first, and +the answer was the same in all three: **the objection was factually current, not stale.** + +The recurring complaint was "this head is N commits behind dev". Measured, it was true +everywhere — 16 to 25 commits, and `dev` had itself advanced to `31ee7a683` while the reviews +were being written. A green check on a stale head validates an integration state that no longer +exists, which is a real merge-readiness defect rather than a formality to wave through. + +So the resolution was to rebase all 19 branches onto current `dev`, not to override. Admin +authority can bypass a gate; it cannot make an untested integration state tested. + +Two reviews named genuine code defects, and both were fixed rather than overridden: + +- **#2166** — `addRequestLog` is exported and bypassed the sanitizer: the reviewer reproduced a + raw 111-character value in the `/api/logs` ring against a sanitized 37-character value on + disk. Fixed at the shared ingress so both surfaces read from one normalized entry, with the + direct-ingress regression the reviewer asked for. +- **#2162** — a prompt mutation writing into the outbound user turn needed its content-shape + boundaries pinned. Added: an already-framed turn stays single, image-only content keeps its + image block behind the preamble, assistant-only block content keeps its tail before the + synthesized `(continue)` turn. + +One more objection dissolved on rebase: #2148 was carrying eight `devlog/_plan/` planning files +inherited from its branch point. The rebase removed them. + +## What landed + +19 PRs, merged bottom-up. Every merge commit verified present in `git log origin/dev`. + +| PR | dev merge commit | Absorbed from | +|---|---|---| +| #2134 | `930840ca4` | maintainer fix | +| #2160 | `114e9e543` | #2067 @waw4303 | +| #2162 | `087c3c368` | #2082 @yzxcj797 | +| #2164 | `31750b094` | #2027 @yzxcj797 | +| #2165 | `41689b374` | #2155 @waw4303 | +| #2166 | `5fbe65570` | #2163 @Ingwannu | +| #2137 | `be12328bc` | issue #2132 | +| #2146 | `aa07bc308` | #2101 @Ingwannu | +| #2138 | `81492fd10` | #2102 @lilinxiong | +| #2140 | `3ad9c7bf4` | #2100 + #2077 @ntdatt812 | +| #2141 | `1cc35c560` | #2056 @Ingwannu | +| #2142 | `52a463dd6` | #2131 @bet4it | +| #2144 | `8c8a66816` | #2105 @lilinxiong | +| #2145 | `83d5ffa3c` | #2040 @Ingwannu | +| #2147 | `7fc50846b` | #2104 @olddonkey | +| #2148 | `86ed9ed83` | #2109 + #2110 @drakonkat | +| #2149 | `17e8e916b` | #2053 @Ingwannu | +| #2150 | `9a7801547` | #2127 @agentHits | +| #2151 | `a584890f8` | #2075 @olddonkey | + +Verification that the rebased content is what actually landed: for each of the six PRs whose +merge recorded a pre-rebase SHA, `git diff --name-only origin/dev -- ` returns **0 differing files**. The merge took the branch content; only +the recorded SHA was the older one. + +## Security surfaces, named rather than merged silently + +`MAINTAINERS.md` reserves auth, credential handling, OAuth, workflows, and release automation +for explicit human review. Seven of the merged PRs touch that surface, and the user's merge +authorization is the human decision of record for each: + +- **#2137 / #2146** — bearer admission and stored-credential substitution; entitlement-gated + model discovery sends the selected account's access token. +- **#2144** — decides whether the shell hook exposing `ANTHROPIC_AUTH_TOKEN` is installed. +- **#2145** — lowers third-party `function_call` output and restores it as a client-executed + private `tool_search_call`. +- **#2147** — OAuth 401 refresh and access-token replay. +- **#2148** — operator-selected destinations for Anthropic/Antigravity OAuth bearers. The + transport gate still rejects public cleartext HTTP; only explicitly opted-in local/private + relays may use it. +- **#2149** — OAuth credential commit ownership under the store lock. + +## Issue closure + +Every issue named by a merged PR is closed: #2133, #2132, #2092, #2047, #1950, #2097, #1886, +#2125, #2074, #1924, plus the superseded contributor PRs. Verified by `gh api` state, not by +assuming GitHub auto-closed them — these PRs targeted `dev`, not `main`, so auto-close does not +fire. + +## Release readiness — not a release + +At `a584890f8`: + +- `bun run test` — 13716 pass / 10 skip / 0 fail across 866 files. +- `bun x tsc --noEmit` — exit 0. +- `bun run privacy:scan` — passed. +- `package.json` version line: **2.27.0** (unchanged by this campaign). + +Changed surfaces: provider registry and transport headers, quota dispatch, routing capability +resolution, the Anthropic/OpenAI-chat/Google adapters, Responses core and compact, OAuth store +and credential commit, request logging and usage persistence, subagent roster management. + +Not done, and deliberately: no `scripts/release.ts`, no npm publish, no tag, no change to +`main` or `preview`. Release execution needs its own authorization. + +## Still open + +**#2054** (@keepitmello) stays open by explicit instruction, carrying the wire-probe request. +**#2167** (@ntdatt812) arrived after this campaign and is untriaged. + diff --git a/devlog/_plan/260820_bug_pr_backlog_consolidation/110_three_bug_issues.md b/devlog/_plan/260820_bug_pr_backlog_consolidation/110_three_bug_issues.md new file mode 100644 index 0000000000..0314f191d1 --- /dev/null +++ b/devlog/_plan/260820_bug_pr_backlog_consolidation/110_three_bug_issues.md @@ -0,0 +1,103 @@ +# 110 — Three open bug issues: #2152, #2157, #2156 + +Unit: 260820_bug_pr_backlog_consolidation +Verification host: `ssh lidge:~/ci-wp3/opencodex`. + +Three issues, three different shapes of answer. Two shipped fixes; one is honestly blocked. + +## #2152 — Windows CI, three groups (PR #2178) + +Three read-only lanes read the three groups. The shape PR #2178 already had was right, and two +of the issue's own premises turned out to be wrong — the fix follows the evidence: + +- **Group 1** is not "the case budget is too small". `A-reduced` failed at 79,978 ms against a + 150 s ceiling, so the outer budget was never the constraint. The real abort came from + `Fixture.request`'s unscaled 10 s `AbortSignal` firing from inside. And `E` does not start + `ocx` at all — it starts two lock helpers, and its holder released after a fixed 3 s wait + that a Windows contender's spawn can outlast. +- **Group 2** is not "an unprivileged Windows user cannot create symlinks". The runner can, so + `canSymlink` was true and the cases ran — then failed on Unix mode semantics that a Windows + directory cannot satisfy. Production already returns `windows_skip` for exactly that reason, + which is what makes the platform guard a correct skip rather than a masked failure. +- **Group 3** needed the crash retry the macOS leg already had. + +### The defect I found in the fix + +Group 3's retry grepped for `panic(thread`. This repository already worked that out and wrote +it down: `devlog/_fin/260731_pr_issue_triage_round/050_windows_ci_flake_rca.md:172` says not to +key on it, because Bun emits **both** `panic(thread 2852)` and `panic(main thread)` for the +same failure, and names `Internal assertion failure` as the stable fingerprint. Probed: + +``` +MATCH panic(thread 3960): Internal assertion failure +MISS panic(main thread): Internal assertion failure +MISS panic(main thread): PANIC: reached unreachable code +``` + +The retry would have failed the shard on roughly half the crashes it exists to absorb, while +looking correct. + +Three copies of that signature list exist — macOS inline, the new Windows inline, and +`is_bun_runtime_crash` — and the workflow comment already said to keep them in sync with +nothing enforcing it. They had drifted. All three now match, and the contract test pins **the +sync itself**, not the literal text, so the same drift cannot recur. RED-proven: restoring the +bad signature fails it with `windows:Internal assertion failure:false`. + +`hasShellCommandHead` was added because the existing exact-whole-line matcher rejected the +`| tee` the retry requires — that is why the Windows step assertion went red — while still +rejecting an echoed or commented-out copy. + +**What no local run can prove:** whether 45 s suffices under real Windows contention, the actual +skip result on the runner, and `PIPESTATUS` under Git Bash. Those need a `workflow_dispatch`, +and a useful proof run must exercise the crash path — a green Windows run shows the suite runs, +not that the retry fires. + +## #2157 — shadow-helper observability (PR #2179) + +The dashboard half of the attribution field #2166 landed. Delivered. + +## #2156 — muse-spark truncation: BLOCKED, deliberately + +PR #2180 was opened claiming to fix this. An adversarial review found the attribution wrong, and +the source agrees: + +- A stall abort emits `response.incomplete` / `upstream_stall_timeout` (`bridge.ts:1371-1396`), + after which the bridge has cancelled upstream, closed, and explicitly discards any late + adapter event (`bridge.ts:837-845`). +- The reporter's error is emitted only after `reader.read()` returns EOF with tool calls still + pending (`openai-chat.ts:1819-1827`), surfacing as `response.failed`. + +Different path, different client frame. The heartbeat **cannot** produce the reported error. + +What the heartbeat does fix is real and worth landing alone: tool-call deltas are buffered, the +bridge arms its watchdog on adapter activity rather than socket activity, so a large argument +payload was indistinguishable from a hung upstream. The `#2156` references were reworded to +"found while investigating", and the closing keyword removed. + +**Second finding, fixed in the same PR.** Making the adapter emit one heartbeat per delta +exposed that `guardTerminalEventStream` retained every nonterminal event in `seen`, which feeds +both the continuation analysis and the rebuilt request. A large argument payload could grow it +without bound wherever `terminalContinuationGuard` is on. The empty-completion guard already +passes heartbeats through unretained; the terminal guard now matches it. + +**Why blocked rather than fixed.** The adapter is reporting truthfully: that stream really did +end. What cannot be determined from here is why it ended for ocx and not for Pi direct. +`hadUsage: false` is suggestive — ocx does send `stream_options.include_usage` — but a provider +may simply ignore that flag, so it is not decisive either way. + +Asked the reporter for the one thing that settles it: redacted raw SSE captures from a +Pi-direct success and an ocx failure for an equivalent request, through socket close, and +whether either carried `finish_reason`, `[DONE]`, or a usage-only final chunk. If ocx's +upstream closes without a terminal frame while Pi's does not, the difference is in what we send +or how we read it and it is ours. If both close identically and Pi is merely more tolerant, the +right answer is the buffered-mode fallback the reporter suggested — and that choice should rest +on their capture, not on a guess. + +## Verification + +At the branch tips, on `ssh lidge`: + +- #2178: `bun test` 13719 pass / 15 skip / 0 fail; `tests/ci-workflows.test.ts` 132 pass / 0 fail. +- #2180: `bun test` 13722 pass / 15 skip / 0 fail; focused trio 112 pass / 0 fail. +- `bun x tsc --noEmit` exit 0 and `bun run privacy:scan` passed on both. + diff --git a/docs-site/src/content/docs/fr/guides/grok-build.md b/docs-site/src/content/docs/fr/guides/grok-build.md index 709542ad31..dbb6a450a0 100644 --- a/docs-site/src/content/docs/fr/guides/grok-build.md +++ b/docs-site/src/content/docs/fr/guides/grok-build.md @@ -3,8 +3,8 @@ title: Grok Build description: Utilisez n’importe quel modèle routé par opencodex depuis la CLI Grok Build de xAI — les modèles sont automatiquement enregistrés dans ~/.grok/config.toml pendant l’exécution du proxy. --- -opencodex expose un point de terminaison compatible OpenAI `POST /v1/chat/completions` (ainsi que `/v1/responses`) sur son -port local, tandis que Grok Build prend en charge les modèles personnalisés hébergés sur des serveurs compatibles OpenAI. Avec +opencodex expose un point de terminaison compatible OpenAI `POST /v1/responses` sur son port local, +tandis que Grok Build prend en charge les modèles personnalisés hébergés sur des serveurs compatibles OpenAI. Avec cette intégration, opencodex enregistre automatiquement l’intégralité de son catalogue visible dans Grok Build : aucune modification manuelle de la configuration n’est nécessaire. @@ -21,7 +21,18 @@ base_url = "http://127.0.0.1:10100/v1" api_backend = "responses" api_key = "opencodex-loopback" name = "OCX gpt-5.6-sol" -# ... one [model.ocx-*] table per visible model ... +extra_headers = { "x-opencodex-grok" = "1" } +context_window = 272000 +supports_reasoning_effort = true +reasoning_effort = "low" + +[[model.ocx-gpt-5-6-sol.reasoning_efforts]] +id = "low" +value = "low" +label = "Low" +description = "Quick, fast implementations" +default = true +# ... autres niveaux de ce modèle, puis une table [model.ocx-*] par modèle visible ... # <<< opencodex managed block <<< ``` @@ -33,7 +44,7 @@ name = "OCX gpt-5.6-sol" - **Supprimé à l’arrêt :** `ocx stop`, `ocx eject`, `ocx uninstall` et l’arrêt normal du démon hors service suppriment le bloc délimité et restaurent votre fichier octet pour octet. Sous un gestionnaire de service, le démontage passe par `ocx stop`/`ocx - uninstall` (les processus en mode service maintiennent intentionnellement le blocage lors des réapparitions). + uninstall` (les processus en mode service conservent intentionnellement le bloc lors des relancements). - **Les alias en conflit** déjà définis dans vos propres tables `[model.*]` sont respectés (opencodex ajoute un suffixe à ses propres entrées) ; un bloc délimité endommagé (marqueur de début sans marqueur de fin) refuse tout changement automatique et demande une réparation manuelle. @@ -51,22 +62,26 @@ grok -m ocx-anthropic-claude-opus-4-8 -p "hello" Les commandes `/effort` et `--effort` de Grok Build ne fonctionnent que pour les modèles dont l’entrée de catalogue annonce une échelle d’effort : la récupération de la liste des modèles lit la réponse brute de `GET /v1/models`, et les entrées doivent contenir `supports_reasoning_effort` ainsi que les choix du menu -`reasoning_efforts`. Pour les entrées de modèles routés, opencodex reflète les niveaux configurés pour le fournisseur +`reasoning_efforts`. Une projection compatible avec Grok de cette échelle est également écrite dans chaque table +`[model.*]` gérée, avec `supports_reasoning_effort`, la valeur par défaut `reasoning_effort` et les lignes +`[[model..reasoning_efforts]]`, afin que le menu soit présent lorsque Grok lit le modèle depuis +`config.toml`. Pour les entrées de modèles routés, opencodex reflète les niveaux configurés pour le fournisseur (`reasoningEfforts` / `modelReasoningEfforts`, et la valeur par défaut de -`modelDefaultReasoningEfforts`) dans cette réponse. Ces métadonnées décrivent l’échelle des modèles routés -configurée dans le proxy ; elles ne prétendent pas que le fournisseur prend nativement en charge ces niveaux. +`modelDefaultReasoningEfforts`). Ces métadonnées décrivent l’échelle des modèles routés configurée dans le proxy ; +elles ne prétendent pas que le fournisseur prend nativement en charge ces niveaux. Les adaptateurs peuvent émuler le raisonnement ou mapper les niveaux sur des champs propres au fournisseur. Les modèles routés qui possèdent une échelle configurée affichent le contrôle de l’effort dans Grok Build comme dans Codex. Ceux dont la liste de niveaux est vide n’affichent aucun contrôle d’effort, conformément au comportement de Codex. Les entrées GPT-5.6 natives sont distinctes : elles conservent et exposent leurs échelles de raisonnement -en amont fixes, et non les métadonnées configurées pour les modèles routés. +en amont fixes, et non les métadonnées configurées pour les modèles routés. Les niveaux Grok valides, notamment +`none` et `minimal`, sont conservés lorsqu’ils sont annoncés. Les niveaux non pris en charge ou en double, +notamment `ultra`, propre à Codex, sont omis du fichier afin que chaque option générée reste sélectionnable. -Grok Build communique avec opencodex au moyen de Chat Completions et envoie `reasoning_effort` lorsque -l’échelle est annoncée. Dans ce cas, le traducteur Chat Completions entrant définit par défaut le champ Responses -`reasoning.summary` sur `auto` ; les traces de raisonnement parviennent donc à Grok sous la forme -`delta.reasoning_content` au lieu d’être masquées. Réglez `include_reasoning: false` (ou -`reasoning.summary: "none"`) si un client souhaite que le modèle réfléchisse sans renvoyer le -tracé. Une valeur explicite de `reasoning.summary` prévaut lorsque les deux options sont présentes. +Grok Build communique avec opencodex au moyen de l’API Responses. Lorsque la route annonce une échelle +de raisonnement, la passerelle Responses transmet `reasoning.summary` telle que configurée, de sorte que +les traces de raisonnement parviennent nativement à Grok sous forme d’éléments de raisonnement Responses. +Réglez `reasoning.summary: "none"` si un client souhaite que le modèle réfléchisse sans renvoyer le +tracé. Une valeur explicite de `reasoning.summary` prévaut sur la valeur par défaut de la route. ## Note d'authentification @@ -74,26 +89,25 @@ Grok Build exige une clé API non vide pour les modèles personnalisés, même s injectées contiennent une valeur fictive (`opencodex-loopback`) ; opencodex ignore les clés d’admission pour les connexions de bouclage, de sorte qu’aucun véritable secret n’est utilisé. -**L’enregistrement automatique est réservé au bouclage.** Lorsque opencodex se lie à un hôte hors bouclage, y compris -les caractères génériques `0.0.0.0` et `::`, qui exposent chaque interface — les requêtes ont besoin de votre réel -jeton d’admission, et un bloc géré ne peut pas en transporter un en toute sécurité. Écrire le jeton littéral -mettez votre secret dans `~/.grok/config.toml` et écrasez tout ce que vous y avez défini lors du prochain -`ocx start`/`ensure`/`restart`. Donc opencodex n’écrit rien du tout dans ce cas (et supprime -tout bloc restant d'une liaison de bouclage précédente), et vous configurez les modèles vous-même -en dehors des marqueurs gérés, où rien de ce que opencodex fait ne peut les écraser. Voir -[Recette manuelle](#recette-manuelle-sans-enregistrement-automatique) pour le tableau exact et réglez les deux -`base_url` (un hôte réellement accessible à partir de l'endroit où vous exécutez `grok`) et `api_key` -(votre `OPENCODEX_API_AUTH_TOKEN`). - -Ne remplacez pas `api_key` par `env_key` ici. Sans `model_provider` défini, un `env_key` -qui ne parvient pas à résoudre n'arrête pas la demande — Grok passe à votre xAI session -et l'envoie à n'importe quel `base_url` nom d'entrée, ce qui pour un LAN déploiement est un -texte en clair HTTP point de terminaison qui n'est pas xAI. - -Le modèle injecté `api_key` se trouve en premier dans la chaîne d'informations d'identification de Grok pour ces modèles, -donc les tours contre opencodex n'ont pas besoin de connexion Grok supplémentaire. Gardez votre `grok login` / -`XAI_API_KEY` configuration pour les modèles Grok natifs et toutes les fonctionnalités de harnais qui contactent xAI -directement. +**L’enregistrement automatique est réservé au bouclage.** Lorsque opencodex écoute sur une adresse qui n’est pas +de bouclage — y compris les caractères génériques `0.0.0.0` et `::`, qui exposent toutes les interfaces — les +requêtes doivent présenter votre véritable jeton d’admission, qu’un bloc géré ne peut pas transporter en toute +sécurité. Inscrire ce jeton en clair stockerait votre secret dans `~/.grok/config.toml` et écraserait toute valeur +que vous y auriez définie lors du prochain `ocx start`/`ensure`/`restart`. Dans ce cas, opencodex n’écrit donc rien +(et supprime tout bloc laissé par une ancienne liaison de bouclage) ; vous configurez vous-même les modèles en +dehors des marqueurs gérés, où aucune opération opencodex ne peut les écraser. Consultez la +[recette manuelle](#recette-manuelle-sans-enregistrement-automatique) pour obtenir la table exacte, puis définissez +`base_url` (une adresse réellement accessible depuis l’endroit où vous exécutez `grok`) et `api_key` (votre +`OPENCODEX_API_AUTH_TOKEN`). + +Ne remplacez pas `api_key` par `env_key` ici. En l’absence de `model_provider`, un `env_key` qui ne peut pas être +résolu n’interrompt pas la requête : Grok utilise alors votre jeton de session xAI et l’envoie à l’adresse +`base_url` indiquée par l’entrée. Pour un déploiement sur le réseau local, cette adresse est un point de terminaison +HTTP en clair qui n’appartient pas à xAI. + +La valeur `api_key` injectée pour chaque modèle se trouve en tête de la chaîne d’identifiants de Grok. Les requêtes +adressées à opencodex ne nécessitent donc aucune connexion Grok supplémentaire. Conservez votre configuration +habituelle `grok login` / `XAI_API_KEY` pour les modèles Grok natifs et les fonctions qui contactent directement xAI. ## Recette manuelle (sans enregistrement automatique) @@ -139,9 +153,10 @@ l'identifiant `grok-4.5`. Les alias générés évitent entièrement les points prévisibles. Grok Build surveille `~/.grok/config.toml` et recharge la configuration lorsque la table `[model]` change réellement (temporisation d’environ une seconde, avec comparaison du contenu) ; un bloc actualisé atteint une session ouverte sans redémarrage. Pour confirmer ce que Grok a analysé, - run `grok inspect` : il répertorie les sources de configuration qu'il a chargées et avertit de tout champ qu'il a chargé - rejeté. Il n'imprime pas la liste des modèles résolus. Notez qu’une seule erreur TOML - invalide *l'intégralité* de la couche de configuration utilisateur, c'est pourquoi opencodex écrit le fichier - atomiquement - Grok ne voit jamais une configuration à moitié écrite. + exécutez `grok inspect` : il répertorie les sources de configuration chargées et signale les champs + rejetés. Il n'affiche pas la liste des modèles résolus. La version actuelle de Grok Build signale et + ignore les champs de modèle invalides tout en conservant le reste de l'entrée. Une erreur de syntaxe + TOML empêche toujours le chargement du fichier. opencodex écrit de manière atomique, de sorte que + Grok observe un document complet à chaque rechargement. - **Mises à jour du catalogue :** le bloc délimité reflète le catalogue au moment de l’injection. Après l’ajout de fournisseurs ou de modèles, exécutez `ocx ensure` (ou redémarrez le proxy) pour l’actualiser. diff --git a/docs-site/src/content/docs/fr/guides/providers.md b/docs-site/src/content/docs/fr/guides/providers.md index 59381edd60..4287198fc8 100644 --- a/docs-site/src/content/docs/fr/guides/providers.md +++ b/docs-site/src/content/docs/fr/guides/providers.md @@ -120,7 +120,7 @@ ocx logout | `kimi` | `openai-chat` | `https://api.kimi.com/coding/v1` | Modèles de programmation Kimi K2.7/K2.6/K2.5. | | `nous` | `openai-chat` | `https://inference-api.nousresearch.com/v1` | Passerelle d'abonnement Nous Research (le même service en amont que celui utilisé par Hermes Agent). Connexion par autorisation d'appareil auprès de `portal.nousresearch.com` ; le jeton d'accès est le JWT d'inférence envoyé avec chaque requête. Le catalogue mixte de modèles payants et `:free` (`tencent/hy3:free`, `stepfun/step-3.7-flash:free`, ...) est découvert en direct pour le compte connecté. Les jetons d'actualisation sont à usage unique et renouvelés à chaque actualisation. | | `kiro` | `kiro` | `https://runtime.us-east-1.kiro.dev` | La connexion initiale importe la session de l'installation locale de `kiro-cli`, déjà authentifiée (sous Unix, installez avec `curl -fsSL https://cli.kiro.dev/install` | `bash`; sous Windows PowerShell, utilisez `irm 'https://cli.kiro.dev/install.ps1'` | `iex`; puis exécutez `kiro-cli login`). **Ajouter un compte** déconnecte `kiro-cli`, lance une nouvelle connexion dans le navigateur qui change le compte utilisé par `kiro-cli`, puis enregistre les métadonnées propres au profil. Les comptes OpenCodex existants sont préservés ; une annulation ou un échec restaure la session `kiro-cli` précédente. | -| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | Google OAuth avec le protocole Cloud Code Assist. La découverte en direct utilise le point de terminaison CCA authentifié `v1internal:fetchAvailableModels` et publie les modèles d'agent accessibles au compte connecté ; le catalogue maintenu reste la solution de repli. | +| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | Google OAuth avec le protocole Cloud Code Assist. La découverte en direct utilise le point de terminaison CCA authentifié `v1internal:fetchAvailableModels` et publie les modèles d'agent accessibles au compte connecté ; le catalogue maintenu reste la solution de repli. Le quota est sondé via `retrieveUserQuota` et `retrieveUserQuotaSummary` (délai de 8 secondes). Les requêtes de chat et d'adaptateur CCA utilisent SSE (`v1internal:streamGenerateContent?alt=sse`) et mettent ce flux en mémoire tampon pour les appels unitaires. La génération d'images intégrée utilise le point de terminaison unitaire distinct `v1internal:generateContent`. L'adaptateur réessaie le pair daily/production en cas d'échec de transport, de 404 ou d'indisponibilité sur le premier hôte. | | `cursor` | `cursor` | `https://api2.cursor.sh` | Connexion PKCE expérimentale, transport HTTP/2 en direct et découverte de modèles filtrés par compte. | | `github-copilot` | `openai-chat` | `https://api.githubcopilot.com` | Expérimental. Flux d'appareil GitHub et échange `copilot_internal` (client OAuth de VS Code). Nécessite un abonnement Copilot actif ; il ne s'agit pas d'une API tierce officielle. | diff --git a/docs-site/src/content/docs/fr/reference/configuration/providers.md b/docs-site/src/content/docs/fr/reference/configuration/providers.md index edf41cccc0..9cc6e0f0a6 100644 --- a/docs-site/src/content/docs/fr/reference/configuration/providers.md +++ b/docs-site/src/content/docs/fr/reference/configuration/providers.md @@ -283,6 +283,13 @@ les paramètres de modèle propres à Cursor : Les variantes explicites envoient le modèle `default` de Cursor avec son paramètre `optimization`, ce qui préserve la sélection à chaque requête. Elles restent disponibles lorsque la découverte en direct omet `default`. +### Vision + +La vision native Cursor utilise `SelectedImage` (plafond JPEG souple + `blobIdWithData`) pour les modèles +qui voient les images nativement — Claude, Gemini, GPT, Kimi et Grok notamment — à partir des images +`data:` du tour actif uniquement. Auto, la famille Composer et GLM (`glm-5.2`, `glm-5.3`) restent +sur la liste curatée `noVisionModels` et passent par le sidecar de description d'images. + Les outils locaux pilotés par le serveur Cursor sont désactivés par défaut. Codex continue d'utiliser ses propres outils tels que `apply_patch` et `exec_command` avec sa propre politique d'approbation et de bac à sable : diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md index 1485d49b2c..ea3d0cda09 100644 --- a/docs-site/src/content/docs/guides/codex-integration.md +++ b/docs-site/src/content/docs/guides/codex-integration.md @@ -55,6 +55,12 @@ Standalone `/images/generations` calls never enter that bridge. `openai-responses` provider whose endpoint implements the OpenAI Images API. Explicit selection fails closed and never falls back to a different paid upstream. Registry-managed provider ids are not accepted here; omit `images.provider` to use the built-in OpenAI tiers. +- **xAI Imagine (Grok OAuth) relay:** when `images.bridgeEnabled` is `true` and an `xai` provider + has a usable Grok CLI OAuth token (`ocx login xai`) or API key, `/v1/images/generations` and + `/v1/images/edits` are sent to `https://api.x.ai/v1` with that token. ChatGPT credentials are + not forwarded. The relay maps Codex `size` / `aspect_ratio` onto xAI's Imagine body and returns + the same `{created, data:[{b64_json}]}` shape. This is independent of the Responses Image + Bridge loop (which remains API-key-only). - **Google Antigravity (CCA) fallback:** when neither an OpenAI forward candidate nor a keyed provider is configured, `/v1/images/generations` (not `/images/edits`) falls back to the Antigravity **Cloud Code Assist** endpoint using the `gemini-3.1-flash-image` model. The fallback diff --git a/docs-site/src/content/docs/guides/grok-build.md b/docs-site/src/content/docs/guides/grok-build.md index f1192b73e2..f331f608d2 100644 --- a/docs-site/src/content/docs/guides/grok-build.md +++ b/docs-site/src/content/docs/guides/grok-build.md @@ -21,7 +21,18 @@ base_url = "http://127.0.0.1:10100/v1" api_backend = "responses" api_key = "opencodex-loopback" name = "OCX gpt-5.6-sol" -# ... one [model.ocx-*] table per visible model ... +extra_headers = { "x-opencodex-grok" = "1" } +context_window = 272000 +supports_reasoning_effort = true +reasoning_effort = "low" + +[[model.ocx-gpt-5-6-sol.reasoning_efforts]] +id = "low" +value = "low" +label = "Low" +description = "Quick, fast implementations" +default = true +# ... remaining rungs for this model, then one [model.ocx-*] table per visible model ... # <<< opencodex managed block <<< ``` @@ -51,15 +62,22 @@ grok -m ocx-anthropic-claude-opus-4-8 -p "hello" Grok Build's `/effort` (and `--effort`) only works for models whose catalog entry advertises the ladder: its model list fetch reads the raw `GET /v1/models` response, and entries there must carry `supports_reasoning_effort` plus `reasoning_efforts` menu -options. For routed model entries, opencodex mirrors the configured provider tiers -(`reasoningEfforts` / `modelReasoningEfforts`, and the default from -`modelDefaultReasoningEfforts`) onto that response. This metadata describes the -proxy-configured routed ladder — it does not claim native upstream reasoning support, -and adapters may emulate reasoning or map levels onto provider-specific fields. Routed -models with a configured ladder show the effort control in Grok Build just like they do -in Codex. Models with an empty tier list keep no effort control, matching Codex -behavior. Native GPT-5.6 entries are separate: they preserve and expose their pinned -upstream reasoning ladders rather than provider-configured routed metadata. +options. A Grok-compatible projection of that ladder is written into each managed +`[model.*]` table +(`supports_reasoning_effort`, default `reasoning_effort`, and +`[[model..reasoning_efforts]]` picker rows) so the menu is present when Grok +reads the model from `config.toml`. For routed model entries, opencodex mirrors the +configured provider tiers (`reasoningEfforts` / `modelReasoningEfforts`, and the default +from `modelDefaultReasoningEfforts`). This metadata describes the proxy-configured +routed ladder. Adapters may emulate reasoning or map levels onto provider-specific +fields. Routed models with a configured ladder show the effort control in Grok Build +just like they do in Codex. +Models with an empty tier list keep no effort control, matching Codex behavior. Native +GPT-5.6 entries are separate: they preserve and expose their pinned upstream reasoning +ladders rather than provider-configured routed metadata. Valid Grok rungs, including +`none` and `minimal`, are preserved when advertised. Unsupported or duplicate rungs, +including Codex-only `ultra`, are omitted from the file, keeping every emitted picker +option selectable. Grok Build talks to opencodex over the Responses API. When the route advertises a reasoning ladder, the Responses passthrough forwards `reasoning.summary` as configured, so thinking @@ -139,8 +157,9 @@ the id `grok-4.5`. Generated aliases avoid dots entirely for this reason. `[model]` table actually changes (roughly a one-second debounce, compared by content), so a refreshed block reaches an open session without a restart. To confirm what Grok parsed, run `grok inspect`: it lists the config sources it loaded and warns about any field it - rejected. It does not print the resolved model list. Note that a single TOML error - invalidates the *entire* user config layer, which is why opencodex writes the file - atomically — Grok never sees a half-written config. + rejected. It does not print the resolved model list. Current Grok Build reports and skips + invalid model fields while retaining the rest of the model entry. A TOML syntax error still + prevents the file from loading. opencodex writes atomically, so Grok observes a complete + document on every reload. - **Catalog updates:** the fenced block reflects the catalog at injection time. After adding providers or models, run `ocx ensure` (or restart the proxy) to refresh it. diff --git a/docs-site/src/content/docs/guides/image-bridge.md b/docs-site/src/content/docs/guides/image-bridge.md index 6606fee55b..ca513a0d2a 100644 --- a/docs-site/src/content/docs/guides/image-bridge.md +++ b/docs-site/src/content/docs/guides/image-bridge.md @@ -14,10 +14,12 @@ xAI Grok Imagine, so the model you're actually chatting with can still generate - **Enable the bridge** by setting `images.bridgeEnabled: true` in your config (it is off by default to avoid unexpected xAI charges — see [Configuration](#configuration) below). -- An `xai` provider entry with an **API key**. The bridge pins fulfillment to the registry xAI - Images endpoint (`https://api.x.ai/v1`); any configured `baseUrl` override is ignored for image - calls. OAuth / `ocx login xai` alone does **not** arm the bridge (the Grok CLI OAuth transport is - chat-oriented and is not used for `/images/*`). +- An `xai` provider entry with an **API key**. The Responses Image Bridge pins fulfillment to the + registry xAI Images endpoint (`https://api.x.ai/v1`); any configured `baseUrl` override is + ignored for image calls. OAuth / `ocx login xai` alone does **not** arm this sidecar loop. + The same `bridgeEnabled` flag does arm the separate Codex `/v1/images` relay so the built-in + `image_gen` client can call Imagine with the Grok CLI grant — see + [Built-in image generation](/guides/codex-integration/#built-in-image-generation-image_gen). ```json { diff --git a/docs-site/src/content/docs/guides/providers.md b/docs-site/src/content/docs/guides/providers.md index e1451dcfbd..192bd56ea8 100644 --- a/docs-site/src/content/docs/guides/providers.md +++ b/docs-site/src/content/docs/guides/providers.md @@ -110,12 +110,12 @@ ocx logout | Provider | Adapter | Base URL | Notes | | --- | --- | --- | --- | -| `xai` | `openai-chat` | `https://api.x.ai/v1` | Live-first Grok catalog; `grok-4.5` is the fallback default. | +| `xai` | `openai-chat` | `https://cli-chat-proxy.grok.com/v1` | OAuth uses the separate Grok CLI subscription gateway. The API-key override uses `https://api.x.ai/v1` and may inject Priority Processing. Live-first Grok catalog; `grok-4.5` is the fallback default. | | `anthropic` | `anthropic` | `https://api.anthropic.com` | Claude models; live model list fetched from `/v1/models`. | | `kimi` | `openai-chat` | `https://api.kimi.com/coding/v1` | Kimi K2.7/K2.6/K2.5 coding models. | | `nous` | `openai-chat` | `https://inference-api.nousresearch.com/v1` | Nous Research subscription gateway (same backend Hermes Agent uses). Device-grant login against `portal.nousresearch.com`; the access token is the per-request inference JWT. Mixed paid + `:free` model catalog (`tencent/hy3:free`, `stepfun/step-3.7-flash:free`, ...) discovered live from the signed-in account. Refresh tokens are single-use and rotated on every refresh. | | `kiro` | `kiro` | `https://runtime.us-east-1.kiro.dev` | Initial login imports the installed, signed-in `kiro-cli` session (on Unix, install with `curl -fsSL https://cli.kiro.dev/install` | `bash`; on Windows PowerShell, use `irm 'https://cli.kiro.dev/install.ps1'` | `iex`; then run `kiro-cli login`). **Add account** logs `kiro-cli` out, starts a fresh browser login that switches the account used by `kiro-cli`, and stores account-scoped profile metadata. Existing OpenCodex accounts are preserved, and cancellation or failure restores the previous `kiro-cli` session. | -| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | Google OAuth over the Cloud Code Assist wire. Live discovery uses CCA's authenticated `v1internal:fetchAvailableModels` endpoint and publishes the agent models available to the signed-in account; the maintained catalog remains the fallback. | +| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | Google OAuth over the Cloud Code Assist wire. Live discovery uses CCA's authenticated `v1internal:fetchAvailableModels` endpoint and publishes the agent models available to the signed-in account; the maintained catalog remains the fallback. Quota is probed live via `retrieveUserQuota` and `retrieveUserQuotaSummary` (8-second timeout). CCA chat/adapter requests use SSE (`v1internal:streamGenerateContent?alt=sse`) and buffer that stream for unary callers. Built-in image generation uses the separate unary `v1internal:generateContent` endpoint. The adapter retries its maintained daily/production peer at most once after a first-host transport failure, empty stream, 404, or `UNAVAILABLE`; authentication, geoblock, invalid-request, and exhausted-quota responses do not trigger host failover. | | `cursor` | `cursor` | `https://api2.cursor.sh` | Experimental PKCE login, live HTTP/2 transport with an opt-in HTTP/1.1 compatibility path, and account-filtered model discovery. | | `github-copilot` | `openai-chat` | `https://api.githubcopilot.com` | Experimental. GitHub device flow + `copilot_internal` exchange (VS Code OAuth client). Requires an active Copilot subscription; not an official third-party API. | diff --git a/docs-site/src/content/docs/ja/guides/grok-build.md b/docs-site/src/content/docs/ja/guides/grok-build.md index e68af728ef..be8a60c43d 100644 --- a/docs-site/src/content/docs/ja/guides/grok-build.md +++ b/docs-site/src/content/docs/ja/guides/grok-build.md @@ -3,7 +3,7 @@ title: グロクビルド description: xAI の Grok Build CLI から opencodex でルーティングされたモデルを使用します。モデルはプロキシの実行中に ~/.grok/config.toml に自動登録されます。 --- -opencodex はローカル ポート上で OpenAI 互換の `POST /v1/chat/completions` (および `/v1/responses`) を提供し、Grok Build は OpenAI 互換サーバーに対するカスタム モデルをサポートします。この統合により、opencodex は表示されているカタログ全体を Grok Build に自動的に登録します。手動による構成編集は必要ありません。 +opencodex はローカル ポート上で OpenAI 互換の `POST /v1/responses` を提供し、Grok Build は OpenAI 互換サーバーに対するカスタム モデルをサポートします。この統合により、opencodex は表示されているカタログ全体を Grok Build に自動的に登録します。手動による構成編集は必要ありません。 ## 自動登録 @@ -17,7 +17,18 @@ base_url = "http://127.0.0.1:10100/v1" api_backend = "responses" api_key = "opencodex-loopback" name = "OCX gpt-5.6-sol" -# ... one [model.ocx-*] table per visible model ... +extra_headers = { "x-opencodex-grok" = "1" } +context_window = 272000 +supports_reasoning_effort = true +reasoning_effort = "low" + +[[model.ocx-gpt-5-6-sol.reasoning_efforts]] +id = "low" +value = "low" +label = "Low" +description = "Quick, fast implementations" +default = true +# ... remaining rungs for this model, then one [model.ocx-*] table per visible model ... # <<< opencodex managed block <<< ``` @@ -38,6 +49,32 @@ grok -m ocx-anthropic-claude-opus-4-8 -p "hello" # or in the TUI: /model ocx-anthropic-claude-opus-4-8 ``` +## 推論 effort + +Grok Build の `/effort`(および `--effort`)は、カタログ項目がラダーを公開している +モデルで動作します。モデル一覧は生の `GET /v1/models` 応答を読み、その項目には +`supports_reasoning_effort` と `reasoning_efforts` のメニュー選択肢が必要です。ラダーを +Grok 互換に投影した内容が、管理対象の各 `[model.*]` テーブルにも +`supports_reasoning_effort`、既定の +`reasoning_effort`、`[[model..reasoning_efforts]]` の各行として書き込まれます。 +ルーティングされたモデルでは、opencodex が設定済みのプロバイダー階層 +(`reasoningEfforts` / `modelReasoningEfforts` と +`modelDefaultReasoningEfforts` の既定値)を反映します。このメタデータはプロキシで +設定されたラダーを表し、アダプターは推論をエミュレートしたり、レベルを +プロバイダー固有のフィールドへ変換したりできます。空の階層リストでは effort +コントロールを表示しません。ネイティブ GPT-5.6 項目は、固定された上流の推論 +ラダーを保持します。モデルが公開する有効な Grok 段階(`none` と `minimal` を含む)は +保持されます。Codex 固有の `ultra` を含む、未対応または重複する段階はファイルから +除外され、出力された選択肢はすべて実行できます。 + +Grok Build は Chat Completions 経由で opencodex と通信し、ラダーが公開されている +場合は `reasoning_effort` を送ります。Chat Completions の入力変換は、この場合に +内部 Responses の `reasoning.summary` を `auto` に設定するため、推論トレースは +`delta.reasoning_content` として Grok に届きます。トレースを返さずにモデルに +推論させるクライアントは、`include_reasoning: false`(または +`reasoning.summary: "none"`)を設定できます。両方が指定された場合は、明示的な +`reasoning.summary` が優先されます。 + ## 認証メモ Grok Build では、ループバックでもカスタム モデルに対して空ではない API キーが必要です。挿入されたエントリにはプレースホルダー (`opencodex-loopback`) が含まれます。opencodex はループバック接続のアドミッション キーを無視するため、実際の秘密は関係しません。 @@ -78,6 +115,6 @@ api_key = "your-OPENCODEX_API_AUTH_TOKEN" - **サービスでインストールされた `ocx restart`:** 実行中のプロキシが再起動の認可とドレインの調整を担当し、古いプロセスの終了後はインストール済みのサービス マネージャーが置換プロセスを起動します。サービス監視は維持されます。ループバックの自動登録を使用している場合に限り、マネージド ブロックもハンドオフ中に維持されます。非ループバック構成では Grok 設定を手動管理します。同じポートで、別の ID 検証済みプロセスが正常になったことを確認した場合にのみ成功します。 - **構成読み取りタイミング:** 最初に opencodex を起動し、その後 `grok` を起動します。 -予測可能な結果。 Grok Build は `~/.grok/config.toml` を監視し、`[model]` テーブルが実際に変更されると (内容で比較すると約 1 秒のデバウンス) 再ロードするため、更新されたブロックは再起動せずに開いているセッションに到達します。 Grok が解析した内容を確認するには、`grok inspect` を実行します。ロードされた設定ソースがリストされ、拒否されたフィールドについて警告が表示されます。解決されたモデルのリストは出力されません。単一の TOML エラーがユーザー設定レイヤー「全体」を無効にすることに注意してください。これが、opencodex がファイルをアトミックに書き込む理由です。Grok は書きかけの設定を決して認識しません。 +予測可能な結果。 Grok Build は `~/.grok/config.toml` を監視し、`[model]` テーブルが実際に変更されると (内容で比較すると約 1 秒のデバウンス) 再ロードするため、更新されたブロックは再起動せずに開いているセッションに到達します。 Grok が解析した内容を確認するには、`grok inspect` を実行します。ロードされた設定ソースがリストされ、拒否されたフィールドについて警告が表示されます。解決されたモデルのリストは出力されません。現在の Grok Build は無効なモデルフィールドを警告してスキップし、残りのモデル項目を保持します。TOML 構文エラーがあるとファイルは読み込まれません。opencodex はファイルをアトミックに書き込むため、Grok は再読み込みのたびに完全な文書を認識します。 - **カタログの更新:** フェンスで囲まれたブロックには、射出時のカタログが反映されます。後 プロバイダーまたはモデルを追加するには、`ocx ensure` を実行して (またはプロキシを再起動して) 更新します。 diff --git a/docs-site/src/content/docs/ja/guides/providers.md b/docs-site/src/content/docs/ja/guides/providers.md index 81a19e5e5b..da28e655d2 100644 --- a/docs-site/src/content/docs/ja/guides/providers.md +++ b/docs-site/src/content/docs/ja/guides/providers.md @@ -105,12 +105,12 @@ ocx logout | プロバイダー | アダプター | ベース URL | 備考 | | --- | --- | --- | --- | -| `xai` | `openai-chat` | `https://api.x.ai/v1` | ライブ一覧を優先し、フォールバックのデフォルトモデルは `grok-4.5`。 | +| `xai` | `openai-chat` | `https://cli-chat-proxy.grok.com/v1` | OAuth は独立した Grok CLI サブスクリプションゲートウェイを使用します。API キーのオーバーライドは `https://api.x.ai/v1` を使用し、Priority Processing を注入する場合があります。ライブ一覧を優先し、フォールバックのデフォルトモデルは `grok-4.5`。 | | `anthropic` | `anthropic` | `https://api.anthropic.com` | Claude モデル; ライブモデル一覧は `/v1/models` から取得。 | | `kimi` | `openai-chat` | `https://api.kimi.com/coding/v1` | Kimi K2.7/K2.6/K2.5 コーディングモデル。 | | `nous` | `openai-chat` | `https://inference-api.nousresearch.com/v1` | Nous Research サブスクリプションゲートウェイ(Hermes Agent と同じバックエンド)。`portal.nousresearch.com` へのデバイスグラントログイン; access トークンはリクエストごとの inference JWT。有料 + `:free` モデルの混在カタログ(`tencent/hy3:free`、`stepfun/step-3.7-flash:free` など)はサインイン中のアカウントからライブ探索されます。Refresh トークンは単回使用で、更新のたびにローテーションされます。 | | `kiro` | `kiro` | `https://runtime.us-east-1.kiro.dev` | 初回ログインは、インストール済みでサインインした `kiro-cli` セッションを取り込みます(Unix では `curl -fsSL https://cli.kiro.dev/install` | `bash`、Windows PowerShell では `irm 'https://cli.kiro.dev/install.ps1'` | `iex` でインストールしてから `kiro-cli login` を実行)。**アカウントを追加**は `kiro-cli` をログアウトして新しいブラウザログインを開始し、`kiro-cli` 自体のアカウントを切り替えてアカウント別プロファイルメタデータを保存します。既存の OpenCodex アカウントは保持され、キャンセルまたは失敗時には以前の `kiro-cli` セッションが復元されます。 | -| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | Google OAuth を Cloud Code Assist wire で使用。ライブ探索は認証済みの CCA `v1internal:fetchAvailableModels` エンドポイントを使用し、ログイン中のアカウントで利用可能な agent モデルのみを公開します。管理されたカタログはフォールバックとして残ります。 | +| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | Google OAuth を Cloud Code Assist wire で使用。ライブ探索は認証済みの CCA `v1internal:fetchAvailableModels` エンドポイントを使用し、ログイン中のアカウントで利用可能な agent モデルのみを公開します。管理されたカタログはフォールバックとして残ります。Quota は `retrieveUserQuota` と `retrieveUserQuotaSummary`(8 秒タイムアウト)で取得します。CCA のチャット/アダプター リクエストは SSE(`v1internal:streamGenerateContent?alt=sse`)を使用し、単項呼び出しではそのストリームをバッファリングします。組み込み画像生成は別の単項 `v1internal:generateContent` エンドポイントを使用します。アダプターは最初のホストでの transport、404、unavailable の失敗時に daily/production peer を再試行します。 | | `cursor` | `cursor` | `https://api2.cursor.sh` | 実験的 PKCE ログイン、HTTP/2 トランスポート、アカウント別モデル探索をサポート。 | | `github-copilot` | `openai-chat` | `https://api.githubcopilot.com` | 実験的。GitHub デバイスフロー + `copilot_internal` 交換(VS Code OAuth クライアント)。有効な Copilot サブスクリプションが必要で、公式のサードパーティ API ではありません。 | diff --git a/docs-site/src/content/docs/ko/guides/grok-build.md b/docs-site/src/content/docs/ko/guides/grok-build.md index 1f6b09ecca..c2bbe3633f 100644 --- a/docs-site/src/content/docs/ko/guides/grok-build.md +++ b/docs-site/src/content/docs/ko/guides/grok-build.md @@ -3,7 +3,7 @@ title: Grok Build 안내 description: xAI의 Grok Build CLI에서 opencodex로 라우팅되는 모든 모델을 사용합니다. 프로세스가 실행되는 동안 모델은 `~/.grok/config.toml`에 자동 등록됩니다. --- -opencodex는 로컬 포트에서 OpenAI 호환 `POST /v1/chat/completions`(및 `/v1/responses`)를 제공합니다. Grok Build는 OpenAI 호환 서버를 상대로 사용자 정의 모델을 지원합니다. 이 통합은 opencodex가 노출하는 전체 카탈로그를 Grok Build에 자동 등록합니다. 수동으로 설정 파일을 편집할 필요가 없습니다. +opencodex는 로컬 포트에서 OpenAI 호환 `POST /v1/responses`를 제공합니다. Grok Build는 OpenAI 호환 서버를 상대로 사용자 정의 모델을 지원합니다. 이 통합은 opencodex가 노출하는 전체 카탈로그를 Grok Build에 자동 등록합니다. 수동으로 설정 파일을 편집할 필요가 없습니다. ## 자동 등록 @@ -17,7 +17,18 @@ base_url = "http://127.0.0.1:10100/v1" api_backend = "responses" api_key = "opencodex-loopback" name = "OCX gpt-5.6-sol" -# ... one [model.ocx-*] table per visible model ... +extra_headers = { "x-opencodex-grok" = "1" } +context_window = 272000 +supports_reasoning_effort = true +reasoning_effort = "low" + +[[model.ocx-gpt-5-6-sol.reasoning_efforts]] +id = "low" +value = "low" +label = "Low" +description = "Quick, fast implementations" +default = true +# ... remaining rungs for this model, then one [model.ocx-*] table per visible model ... # <<< opencodex managed block <<< ``` @@ -34,6 +45,31 @@ grok -m ocx-anthropic-claude-opus-4-8 -p "hello" # or in the TUI: /model ocx-anthropic-claude-opus-4-8 ``` +## 추론 강도 + +Grok Build의 `/effort`(및 `--effort`)는 카탈로그 항목이 추론 단계 목록을 제공하는 +모델에서 동작합니다. 모델 목록은 원시 `GET /v1/models` 응답을 읽으며, 항목에는 +`supports_reasoning_effort`와 `reasoning_efforts` 메뉴 선택지가 있어야 합니다. 단계 목록을 +Grok 호환 형태로 투영한 결과가 각 관리형 `[model.*]` 테이블에도 +`supports_reasoning_effort`, 기본 +`reasoning_effort`, `[[model..reasoning_efforts]]` 선택 행으로 기록됩니다. +라우팅 모델의 경우 opencodex는 설정된 공급자 단계(`reasoningEfforts` / +`modelReasoningEfforts`와 `modelDefaultReasoningEfforts`의 기본값)를 반영합니다. 이 +메타데이터는 프록시에 설정된 라우팅 단계를 설명하며, 어댑터는 추론을 에뮬레이션하거나 +단계를 공급자 전용 필드로 매핑할 수 있습니다. 단계 목록이 비어 있는 모델은 effort +컨트롤을 표시하지 않습니다. 네이티브 GPT-5.6 항목은 고정된 업스트림 추론 단계를 +유지합니다. 모델이 제공하는 유효한 Grok 단계는 `none`과 `minimal`을 포함해 유지됩니다. +Codex 전용 `ultra`를 포함해 지원되지 않거나 중복된 단계는 파일에서 제외되어 기록된 +모든 선택지는 실행 가능합니다. + +Grok Build는 Chat Completions를 통해 opencodex와 통신하고 단계 목록이 제공되면 +`reasoning_effort`를 보냅니다. 이 경우 Chat Completions 입력 변환기는 내부 Responses의 +`reasoning.summary` 기본값을 `auto`로 설정하므로 추론 트레이스가 +`delta.reasoning_content`로 Grok에 전달됩니다. 모델은 추론하되 트레이스를 반환하지 +않도록 하려는 클라이언트는 `include_reasoning: false`(또는 +`reasoning.summary: "none"`)를 설정할 수 있습니다. 두 값이 함께 있으면 명시적인 +`reasoning.summary`가 우선합니다. + ## 인증 참고 Grok Build는 루프백에서도 사용자 정의 모델에 비어 있지 않은 API 키를 요구합니다. 주입되는 항목에는 자리표시자(`opencodex-loopback`)가 들어갑니다. opencodex는 루프백 연결의 admission key를 무시하므로 실제 비밀값은 들어가지 않습니다. @@ -73,5 +109,5 @@ api_key = "your-OPENCODEX_API_AUTH_TOKEN" ## 알려진 제한 - **서비스 설치된 `ocx restart`:** 실행 중인 프록시는 재시작 권한 확인과 드레인 조정을 담당하고, 기존 프로세스가 종료된 뒤 설치된 서비스 관리자가 교체 프로세스를 시작합니다. 서비스 감독은 그대로 유지됩니다. 루프백 자동 등록을 사용하는 경우에만 관리 블록도 핸드오프 동안 유지되며, 비루프백 배포에서는 Grok 설정을 수동으로 관리합니다. 같은 포트에서 신원이 확인된 다른 프로세스가 정상 상태가 된 뒤에만 명령이 성공합니다. -- **설정 읽기 시점:** 가장 예측 가능한 결과를 얻으려면 opencodex를 먼저 시작하고 그다음 `grok`를 실행합니다. Grok Build는 `~/.grok/config.toml`을 감시하다가 `[model]` 테이블이 실제로 바뀔 때 다시 불러옵니다(내용을 기준으로 비교하는 약 1초 디바운스). 그래서 새로 고친 블록은 재시작 없이 열린 세션에도 들어갑니다. Grok가 무엇을 파싱했는지 확인하려면 `grok inspect`를 실행합니다. 이 명령은 로드한 설정 원본을 나열하고 거부한 필드가 있으면 경고합니다. 해석된 모델 목록은 출력하지 않습니다. TOML 오류 하나만으로도 사용자 설정 레이어 전체가 무효가 되므로, opencodex가 파일을 원자적으로 쓰는 이유도 여기에 있습니다. Grok는 절반만 써진 설정을 보지 않습니다. +- **설정 읽기 시점:** 가장 예측 가능한 결과를 얻으려면 opencodex를 먼저 시작하고 그다음 `grok`를 실행합니다. Grok Build는 `~/.grok/config.toml`을 감시하다가 `[model]` 테이블이 실제로 바뀔 때 다시 불러옵니다(내용을 기준으로 비교하는 약 1초 디바운스). 그래서 새로 고친 블록은 재시작 없이 열린 세션에도 들어갑니다. Grok가 무엇을 파싱했는지 확인하려면 `grok inspect`를 실행합니다. 이 명령은 로드한 설정 원본을 나열하고 거부한 필드가 있으면 경고합니다. 해석된 모델 목록은 출력하지 않습니다. 현재 Grok Build는 잘못된 모델 필드를 경고와 함께 건너뛰고 나머지 모델 항목을 유지합니다. TOML 구문 오류가 있으면 파일을 불러올 수 없습니다. opencodex는 파일을 원자적으로 기록하므로 Grok는 다시 읽을 때마다 완전한 문서를 봅니다. - **카탈로그 업데이트:** 펜스 블록은 주입 시점의 카탈로그를 반영합니다. 공급자나 모델을 추가한 뒤에는 `ocx ensure`를 실행하거나 프록시를 재시작해 갱신합니다. diff --git a/docs-site/src/content/docs/ko/guides/providers.md b/docs-site/src/content/docs/ko/guides/providers.md index 4f57dab7cc..2a30c24f98 100644 --- a/docs-site/src/content/docs/ko/guides/providers.md +++ b/docs-site/src/content/docs/ko/guides/providers.md @@ -104,12 +104,12 @@ ocx logout | 프로바이더 | 어댑터 | 베이스 URL | 비고 | | --- | --- | --- | --- | -| `xai` | `openai-chat` | `https://api.x.ai/v1` | 실시간 목록을 우선 사용하며, 폴백 기본 모델은 `grok-4.5`입니다. | +| `xai` | `openai-chat` | `https://cli-chat-proxy.grok.com/v1` | OAuth는 별도의 Grok CLI 구독 게이트웨이를 사용합니다. API 키 오버라이드는 `https://api.x.ai/v1`을 사용하며 Priority Processing을 주입할 수 있습니다. 실시간 목록을 우선 사용하며, 폴백 기본 모델은 `grok-4.5`입니다. | | `anthropic` | `anthropic` | `https://api.anthropic.com` | Claude 모델; 실시간 모델 목록은 `/v1/models`에서 가져옵니다. | | `kimi` | `openai-chat` | `https://api.kimi.com/coding/v1` | Kimi K2.7/K2.6/K2.5 코딩 모델. | | `nous` | `openai-chat` | `https://inference-api.nousresearch.com/v1` | Nous Research 구독 게이트웨이(Hermes Agent와 동일한 백엔드). `portal.nousresearch.com`에 대한 디바이스 그랜트 로그인; access 토큰은 요청별 inference JWT. 유료 + `:free` 모델 혼합 카탈로그(`tencent/hy3:free`, `stepfun/step-3.7-flash:free` 등)는 로그인한 계정에서 실시간으로 발견됩니다. Refresh 토큰은 단회 사용이며, 갱신할 때마다 회전됩니다. | | `kiro` | `kiro` | `https://runtime.us-east-1.kiro.dev` | 최초 로그인은 설치하고 로그인한 `kiro-cli` 세션을 가져옵니다(Unix에서는 `curl -fsSL https://cli.kiro.dev/install` | `bash`, Windows PowerShell에서는 `irm 'https://cli.kiro.dev/install.ps1'` | `iex`로 설치한 뒤 `kiro-cli login` 실행). **계정 추가**는 `kiro-cli`에서 로그아웃한 뒤 새 브라우저 로그인을 시작하여 `kiro-cli` 자체의 계정을 전환하고, 계정별 프로필 메타데이터를 저장합니다. 기존 OpenCodex 계정은 유지되며, 취소되거나 실패하면 이전 `kiro-cli` 세션을 복원합니다. | -| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | Google OAuth를 Cloud Code Assist wire로 사용합니다. 실시간 탐색은 인증된 CCA `v1internal:fetchAvailableModels` 엔드포인트를 사용하며 로그인한 계정에서 사용할 수 있는 agent 모델만 게시합니다. 유지 관리되는 카탈로그는 폴백으로 남습니다. | +| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | Google OAuth를 Cloud Code Assist wire로 사용합니다. 실시간 탐색은 인증된 CCA `v1internal:fetchAvailableModels` 엔드포인트를 사용하며 로그인한 계정에서 사용할 수 있는 agent 모델만 게시합니다. 유지 관리되는 카탈로그는 폴백으로 남습니다. Quota는 `retrieveUserQuota` 및 `retrieveUserQuotaSummary` RPC(8초 시간 제한)로 조회합니다. CCA 채팅/어댑터 요청은 SSE(`v1internal:streamGenerateContent?alt=sse`)를 사용하고 단항 호출에는 해당 스트림을 버퍼링합니다. 내장 이미지 생성은 별도의 단항 `v1internal:generateContent` 엔드포인트를 사용합니다. 어댑터는 첫 호스트의 transport/404/unavailable 실패 시 daily/production peer로 한 번 재시도합니다. | | `cursor` | `cursor` | `https://api2.cursor.sh` | 실험적 PKCE 로그인, HTTP/2 전송, 계정별 모델 탐색을 지원합니다. | | `github-copilot` | `openai-chat` | `https://api.githubcopilot.com` | 실험적. GitHub 디바이스 플로우 + `copilot_internal` 교환(VS Code OAuth 클라이언트). 활성 Copilot 구독 필요; 공식 서드파티 API가 아닙니다. | diff --git a/docs-site/src/content/docs/reference/adapters.md b/docs-site/src/content/docs/reference/adapters.md index c97bd7bae4..e11b31055f 100644 --- a/docs-site/src/content/docs/reference/adapters.md +++ b/docs-site/src/content/docs/reference/adapters.md @@ -125,6 +125,10 @@ of the HTTP retry loop. frame, and a buffered response that carries no candidate at all returns `google response contained no candidates`. A root `data: null` keepalive frame is still skipped as padding. +- Tool-call batches are closed by one immediately adjacent user turn containing one ordered + `functionResponse` per representable call. Interrupted histories receive an explicit missing-result marker; + duplicate or standalone results are preserved as marked text (and image siblings) rather than + emitted as invalid unpaired `functionResponse` parts. - **Inline image output:** when the model is one of the explicit image-capable chat IDs (`gemini-3.1-flash-image`, `gemini-2.0-flash-preview-image-generation`, or `gemini-3-pro-image-preview`), the adapter sends `responseModalities: ["TEXT", "IMAGE"]`. diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index a12ed68f3b..efcbf2d346 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -151,6 +151,14 @@ contract; existing configurations see these migration deltas: Explicit capability `false` and Responses caller-tier forwarding retain their existing contracts. +### xAI Priority Processing + +The built-in `xai` preset advertises and injects Fast only when its effective transport uses +`authMode: "key"`. API-key mode targets `https://api.x.ai/v1` through the `openai-chat` adapter and +sends `service_tier: "priority"` through Chat Completions. `ocx login xai` +instead stores OAuth credentials for the separate Grok CLI subscription-gateway flow, so OAuth +remains unclassified: its catalog rows do not advertise Fast and the proxy does not inject a tier. + ### OpenRouter Fast The canonical `https://openrouter.ai/api/v1` preset advertises Fast only for these exact @@ -344,6 +352,13 @@ Cursor-specific model parameters: Explicit variants send Cursor's `default` model with its `optimization` parameter, preserving the selection on every request. They remain available when live discovery omits `default`. +### Vision + +Native Cursor vision uses `SelectedImage` (JPEG soft-cap + `blobIdWithData`) for models that can +see images natively — Claude, Gemini, GPT, Kimi, and Grok among them — using active-turn `data:` +images only. Auto, the Composer family, and GLM (`glm-5.2`, `glm-5.3`) stay on the curated `noVisionModels` +list and use the vision describe sidecar instead. + Cursor server-driven local tools are disabled by default. Codex continues using its own tools such as `apply_patch` and `exec_command` with its own approval and sandbox policy: diff --git a/docs-site/src/content/docs/ru/guides/grok-build.md b/docs-site/src/content/docs/ru/guides/grok-build.md index bd8ac09d7c..234bf7f822 100644 --- a/docs-site/src/content/docs/ru/guides/grok-build.md +++ b/docs-site/src/content/docs/ru/guides/grok-build.md @@ -3,7 +3,7 @@ title: Grok Build description: Используйте любую модель, маршрутизируемую opencodex, из CLI xAI Grok Build — пока прокси работает, модели автоматически регистрируются в ~/.grok/config.toml. --- -opencodex отдаёт OpenAI-совместимый `POST /v1/chat/completions` (и `/v1/responses`) на своём +opencodex отдаёт OpenAI-совместимый `POST /v1/responses` на своём локальном порту, а Grok Build поддерживает custom-модели поверх OpenAI-совместимых серверов. Начиная с этой интеграции, opencodex автоматически регистрирует весь свой видимый каталог в Grok Build — вручную редактировать конфигурацию не нужно. @@ -21,7 +21,18 @@ base_url = "http://127.0.0.1:10100/v1" api_backend = "responses" api_key = "opencodex-loopback" name = "OCX gpt-5.6-sol" -# ... one [model.ocx-*] table per visible model ... +extra_headers = { "x-opencodex-grok" = "1" } +context_window = 272000 +supports_reasoning_effort = true +reasoning_effort = "low" + +[[model.ocx-gpt-5-6-sol.reasoning_efforts]] +id = "low" +value = "low" +label = "Low" +description = "Quick, fast implementations" +default = true +# ... remaining rungs for this model, then one [model.ocx-*] table per visible model ... # <<< opencodex managed block <<< ``` @@ -46,6 +57,30 @@ grok -m ocx-anthropic-claude-opus-4-8 -p "hello" # or in the TUI: /model ocx-anthropic-claude-opus-4-8 ``` +## Уровень рассуждения + +Команда Grok Build `/effort` (и флаг `--effort`) работает для моделей, чья запись в каталоге +публикует шкалу уровней. Список моделей читает исходный ответ `GET /v1/models`; записи в нём +должны содержать `supports_reasoning_effort` и пункты меню `reasoning_efforts`. Совместимая с +Grok проекция этой шкалы записывается в каждую управляемую таблицу `[model.*]` через +`supports_reasoning_effort`, +значение `reasoning_effort` по умолчанию и строки +`[[model..reasoning_efforts]]`. Для маршрутизируемых моделей opencodex отражает +настроенные уровни провайдера (`reasoningEfforts` / `modelReasoningEfforts` и значение по +умолчанию из `modelDefaultReasoningEfforts`). Эти метаданные описывают шкалу прокси; адаптеры +могут эмулировать рассуждение или преобразовывать уровни в поля конкретного провайдера. Модели +с пустым списком уровней не показывают управление effort. Нативные записи GPT-5.6 сохраняют +закреплённые upstream-шкалы. Допустимые уровни Grok, включая `none` и `minimal`, сохраняются, +когда модель их объявляет. Неподдерживаемые или повторяющиеся уровни, в том числе предназначенный +для Codex `ultra`, исключаются из файла; каждый записанный пункт остаётся доступным для выбора. + +Grok Build обращается к opencodex через Chat Completions и отправляет `reasoning_effort`, когда +шкала опубликована. В этом случае входной преобразователь Chat Completions задаёт внутреннему +Responses `reasoning.summary` значение `auto`, поэтому трассировка рассуждений приходит в Grok +как `delta.reasoning_content`. Клиент может оставить рассуждение модели и скрыть трассировку с +помощью `include_reasoning: false` (или `reasoning.summary: "none"`). При наличии обоих +параметров приоритет имеет явно заданный `reasoning.summary`. + ## Замечание об аутентификации Grok Build требует непустой API-ключ для custom-моделей даже на loopback. Внедряемые записи несут @@ -116,8 +151,8 @@ api_key = "your-OPENCODEX_API_AUTH_TOKEN" содержимому), поэтому обновлённый блок доходит до уже открытой сессии без перезапуска. Чтобы проверить, что именно разобрал Grok, выполните `grok inspect`: он перечисляет источники конфигурации и предупреждает о полях, которые отверг. Список разрешённых моделей при этом не - печатается. Учтите, что одна TOML-ошибка делает недействительным *весь* пользовательский слой - конфигурации, поэтому opencodex пишет файл атомарно — Grok никогда не увидит полузаписанный - `config.toml`. + печатается. Текущая версия Grok Build сообщает о недопустимых полях модели, пропускает их и + сохраняет остальные данные записи. Синтаксическая ошибка TOML препятствует загрузке файла. + opencodex пишет файл атомарно, поэтому при каждой перезагрузке Grok видит целый документ. - **Обновления каталога:** fenced-блок отражает каталог на момент внедрения. После добавления провайдеров или моделей выполните `ocx ensure` (или перезапустите прокси), чтобы его обновить. diff --git a/docs-site/src/content/docs/ru/guides/providers.md b/docs-site/src/content/docs/ru/guides/providers.md index 1966d9db63..84e07fb6f6 100644 --- a/docs-site/src/content/docs/ru/guides/providers.md +++ b/docs-site/src/content/docs/ru/guides/providers.md @@ -114,12 +114,12 @@ ocx logout | Провайдер | Адаптер | Базовый URL | Примечания | | --- | --- | --- | --- | -| `xai` | `openai-chat` | `https://api.x.ai/v1` | Каталог Grok загружается в реальном времени; фолбэк по умолчанию — `grok-4.5`. | +| `xai` | `openai-chat` | `https://cli-chat-proxy.grok.com/v1` | OAuth использует отдельный шлюз подписки Grok CLI. Переопределение с API-ключом использует `https://api.x.ai/v1` и может добавлять Priority Processing. Каталог Grok загружается в реальном времени; фолбэк по умолчанию — `grok-4.5`. | | `anthropic` | `anthropic` | `https://api.anthropic.com` | Модели Claude; актуальный список моделей загружается из `/v1/models`. | | `kimi` | `openai-chat` | `https://api.kimi.com/coding/v1` | Модели Kimi K2.7/K2.6/K2.5 для кодинга. | | `nous` | `openai-chat` | `https://inference-api.nousresearch.com/v1` | Шлюз подписки Nous Research (тот же бэкенд, что использует Hermes Agent). Вход по device grant против `portal.nousresearch.com`; access-токен — это JWT для каждого запроса к inference. Смешанный каталог платных + `:free` моделей (`tencent/hy3:free`, `stepfun/step-3.7-flash:free`, …) обнаруживается вживую по авторизованному аккаунту. Refresh-токены одноразовые и ротируются при каждом обновлении. | | `kiro` | `kiro` | `https://runtime.us-east-1.kiro.dev` | Первый вход импортирует существующую сессию после установки Kiro CLI (в Unix: `curl -fsSL https://cli.kiro.dev/install` | `bash`; в Windows PowerShell: `irm 'https://cli.kiro.dev/install.ps1'` | `iex`; затем выполните `kiro-cli login`). **Добавить аккаунт** выполняет выход из `kiro-cli`, запускает новый вход через браузер, переключает аккаунт самого `kiro-cli` и сохраняет метаданные профиля отдельно для каждого аккаунта. Существующие аккаунты OpenCodex сохраняются; при отмене или сбое восстанавливается предыдущая сессия `kiro-cli`. | -| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | Google OAuth поверх протокола Cloud Code Assist. Живое обнаружение использует аутентифицированный CCA-эндпоинт `v1internal:fetchAvailableModels` и публикует только agent-модели, доступные текущему аккаунту; поддерживаемый каталог остаётся резервным вариантом. | +| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | Google OAuth поверх протокола Cloud Code Assist. Живое обнаружение использует аутентифицированный CCA-эндпоинт `v1internal:fetchAvailableModels` и публикует только agent-модели, доступные текущему аккаунту; поддерживаемый каталог остаётся резервным вариантом. Квота запрашивается через `retrieveUserQuota` и `retrieveUserQuotaSummary` (тайм-аут 8 секунд). Запросы чата и адаптера CCA используют SSE (`v1internal:streamGenerateContent?alt=sse`) и буферизуют этот поток для унарных вызовов. Встроенная генерация изображений использует отдельный унарный эндпоинт `v1internal:generateContent`. Адаптер повторяет запрос к daily/production peer при сбое транспорта, 404 или unavailable на первом хосте. | | `cursor` | `cursor` | `https://api2.cursor.sh` | Экспериментальный PKCE-вход, живой транспорт HTTP/2 и обнаружение моделей с фильтрацией по аккаунту. | | `github-copilot` | `openai-chat` | `https://api.githubcopilot.com` | Экспериментально. Device flow GitHub + обмен `copilot_internal` (OAuth-клиент VS Code). Требуется активная подписка Copilot; это не официальный сторонний API. | diff --git a/docs-site/src/content/docs/tr/guides/grok-build.md b/docs-site/src/content/docs/tr/guides/grok-build.md index 94b669874e..932705a9eb 100644 --- a/docs-site/src/content/docs/tr/guides/grok-build.md +++ b/docs-site/src/content/docs/tr/guides/grok-build.md @@ -3,8 +3,7 @@ title: Grok Build description: xAI Grok Build CLI içerisinden opencodex ile yönlendirilen herhangi bir modeli kullanın — proxy çalışırken modeller ~/.grok/config.toml içine otomatik olarak kaydedilir. --- -opencodex, yerel portunda OpenAI uyumlu bir `POST /v1/chat/completions` (ve -`/v1/responses`) sunar ve Grok Build, OpenAI uyumlu sunuculara karşı özel +opencodex, yerel portunda OpenAI uyumlu bir `POST /v1/responses` sunar ve Grok Build, OpenAI uyumlu sunuculara karşı özel modelleri destekler. Bu entegrasyonla başlayarak opencodex, görünür kataloğunun tamamını otomatik olarak Grok Build'e kaydeder — manuel yapılandırma düzenlemesi gerekmez. @@ -22,7 +21,18 @@ base_url = "http://127.0.0.1:10100/v1" api_backend = "responses" api_key = "opencodex-loopback" name = "OCX gpt-5.6-sol" -# ... görünür model başına bir [model.ocx-*] tablosu ... +extra_headers = { "x-opencodex-grok" = "1" } +context_window = 272000 +supports_reasoning_effort = true +reasoning_effort = "low" + +[[model.ocx-gpt-5-6-sol.reasoning_efforts]] +id = "low" +value = "low" +label = "Low" +description = "Quick, fast implementations" +default = true +# ... remaining rungs for this model, then one [model.ocx-*] table per visible model ... # <<< opencodex managed block <<< ``` @@ -55,18 +65,27 @@ grok -m ocx-anthropic-claude-opus-4-8 -p "hello" Grok Build'in `/effort` (ve `--effort`) ayarı yalnızca katalog girdisi merdiveni bildiren modeller için çalışır: model listesi getirme işlemi ham `GET /v1/models` yanıtını okur ve buradaki girdiler `supports_reasoning_effort` artı -`reasoning_efforts` menü seçeneklerini taşımalıdır. Yönlendirilen model -girdileri için opencodex, yapılandırılmış sağlayıcı katmanlarını -(`reasoningEfforts` / `modelReasoningEfforts` ve `modelDefaultReasoningEfforts` -varsayılanı) bu yanıta yansıtır. Bu meta veriler proxy tarafından -yapılandırılmış yönlendirilen merdiveni açıklar — yerel yukarı akış akıl yürütme -desteğini iddia etmez ve adaptörler akıl yürütmeyi taklit edebilir veya -seviyeleri sağlayıcıya özgü alanlarla eşleyebilir. Yapılandırılmış bir merdivene -sahip yönlendirilen modeller, tıpkı Codex'te olduğu gibi Grok Build'de de çaba -denetimini gösterir. Boş bir katman listesine sahip modeller, Codex davranışıyla -eşleşecek şekilde çaba denetimi tutmaz. Yerel GPT-5.6 girdileri ayrıdır: -sağlayıcı tarafından yapılandırılmış yönlendirilen meta veriler yerine -sabitlenmiş yukarı akış akıl yürütme merdivenlerini korur ve ortaya çıkarır. +`reasoning_efforts` menü seçeneklerini taşımalıdır. Merdivenin Grok ile uyumlu +bir izdüşümü, yönetilen her `[model.*]` tablosuna `supports_reasoning_effort`, varsayılan +`reasoning_effort` ve `[[model..reasoning_efforts]]` seçim satırlarıyla +yazılır. Yönlendirilen model girdileri için opencodex, yapılandırılmış sağlayıcı +katmanlarını (`reasoningEfforts` / `modelReasoningEfforts` ve +`modelDefaultReasoningEfforts` varsayılanı) yansıtır. Bu meta veriler proxy +tarafından yapılandırılmış merdiveni açıklar; adaptörler akıl yürütmeyi taklit +edebilir veya seviyeleri sağlayıcıya özgü alanlarla eşleyebilir. Boş bir katman +listesine sahip modeller çaba denetimi göstermez. Yerel GPT-5.6 girdileri, +sabitlenmiş yukarı akış akıl yürütme merdivenlerini korur. Modelin bildirdiği +geçerli Grok katmanları, `none` ve `minimal` dahil olmak üzere korunur. Codex'e özgü +`ultra` dahil desteklenmeyen veya yinelenen katmanlar dosyadan çıkarılır; yazılan her +seçenek seçilebilir durumda kalır. + +Grok Build, opencodex ile Chat Completions üzerinden konuşur ve merdiven +bildirildiğinde `reasoning_effort` gönderir. Bu durumda Chat Completions giriş +dönüştürücüsü, dahili Responses `reasoning.summary` değerini varsayılan olarak +`auto` yapar; böylece akıl yürütme izleri Grok'a `delta.reasoning_content` +olarak ulaşır. Modelin akıl yürütmesini sürdürüp izi gizlemek isteyen bir istemci +`include_reasoning: false` (veya `reasoning.summary: "none"`) ayarlayabilir. Her +iki seçenek de bulunduğunda açıkça belirtilen `reasoning.summary` önceliklidir. ## Kimlik doğrulama notu @@ -153,10 +172,10 @@ adlar bu nedenle noktalardan tamamen kaçınır. oturuma ulaşır. Grok'un neyi ayrıştırdığını doğrulamak için `grok inspect` komutunu çalıştırın: yüklediği yapılandırma kaynaklarını listeler ve reddettiği herhangi bir alan hakkında uyarır. Çözümlenen model listesini - yazdırmaz. Tek bir TOML hatasının *tüm* kullanıcı yapılandırma katmanını - geçersiz kıldığını unutmayın; bu nedenle opencodex dosyayı atomik olarak yazar - — Grok asla yarı yazılmış bir yapılandırma görmez. + yazdırmaz. Güncel Grok Build, geçersiz model alanlarını uyarıyla atlar ve model + girdisinin kalanını korur. Bir TOML sözdizimi hatası dosyanın yüklenmesini + engeller. opencodex dosyayı atomik olarak yazar; Grok her yeniden yüklemede + eksiksiz bir belge görür. - **Katalog güncellemeleri:** çitle çevrili blok, enjeksiyon anındaki kataloğu yansıtır. Sağlayıcılar veya modeller ekledikten sonra yenilemek için `ocx ensure` çalıştırın (veya proxy'yi yeniden başlatın). - diff --git a/docs-site/src/content/docs/tr/guides/providers.md b/docs-site/src/content/docs/tr/guides/providers.md index ee153a0780..23fce9593c 100644 --- a/docs-site/src/content/docs/tr/guides/providers.md +++ b/docs-site/src/content/docs/tr/guides/providers.md @@ -134,7 +134,7 @@ ocx logout | `kimi` | `openai-chat` | `https://api.kimi.com/coding/v1` | Kimi K2.7/K2.6/K2.5 kodlama modelleri. | | `nous` | `openai-chat` | `https://inference-api.nousresearch.com/v1` | Nous Research abonelik ağ geçidi (Hermes Agent'ın kullandığı aynı arka uç). `portal.nousresearch.com`'a karşı cihaz yetkilendirmesi girişi; erişim belirteci istek başına çıkarım JWT'sidir. Oturum açmış hesaptan canlı olarak keşfedilen karışık ücretli + `:free` model kataloğu (`tencent/hy3:free`, `stepfun/step-3.7-flash:free`, ...). Yenileme belirteçleri tek kullanımlıktır ve her yenilemede döndürülür. | | `kiro` | `kiro` | `https://runtime.us-east-1.kiro.dev` | İlk oturum açma, kurulu ve oturum açılmış `kiro-cli` oturumunu içe aktarır (Unix'te `curl -fsSL https://cli.kiro.dev/install` | `bash` ile kurun; Windows PowerShell'de `irm 'https://cli.kiro.dev/install.ps1'` | `iex` kullanın; ardından `kiro-cli login` çalıştırın). **Hesap ekle**, `kiro-cli` oturumunu kapatır, `kiro-cli` tarafından kullanılan hesabı değiştiren yeni bir tarayıcı girişi başlatır ve hesap kapsamlı profil meta verilerini saklar. Mevcut OpenCodex hesapları korunur ve iptal veya başarısızlık önceki `kiro-cli` oturumunu geri yükler. | -| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | Cloud Code Assist hattı üzerinden Google OAuth. Canlı keşif CCA'nın kimlik doğrulamalı `v1internal:fetchAvailableModels` uç noktasını kullanır ve oturum açmış hesap için kullanılabilir olan ajan modellerini yayınlar; sürdürülen katalog geri dönüş olarak kalır. | +| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | Cloud Code Assist hattı üzerinden Google OAuth. Canlı keşif CCA'nın kimlik doğrulamalı `v1internal:fetchAvailableModels` uç noktasını kullanır ve oturum açmış hesap için kullanılabilir olan ajan modellerini yayınlar; sürdürülen katalog geri dönüş olarak kalır. Kota `retrieveUserQuota` ve `retrieveUserQuotaSummary` RPC'leriyle (8 saniyelik zaman aşımı) sorgulanır. CCA sohbet/adaptör istekleri SSE (`v1internal:streamGenerateContent?alt=sse`) kullanır ve tekli çağrılar için bu akışı arabelleğe alır. Yerleşik görüntü oluşturma ayrı tekli `v1internal:generateContent` uç noktasını kullanır. Adaptör, ilk ana bilgisayardaki aktarım/404/unavailable hatasında daily/production peer'ı yeniden dener. | | `cursor` | `cursor` | `https://api2.cursor.sh` | Deneysel PKCE girişi, canlı HTTP/2 aktarımı ve hesap filtreli model keşfi. | | `github-copilot` | `openai-chat` | `https://api.githubcopilot.com` | Deneysel. GitHub cihaz akışı + `copilot_internal` değişimi (VS Code OAuth istemcisi). Aktif bir Copilot aboneliği gerektirir; resmi bir üçüncü taraf API değildir. | diff --git a/docs-site/src/content/docs/zh-cn/guides/grok-build.md b/docs-site/src/content/docs/zh-cn/guides/grok-build.md index 766e8f81b1..c026ecdff1 100644 --- a/docs-site/src/content/docs/zh-cn/guides/grok-build.md +++ b/docs-site/src/content/docs/zh-cn/guides/grok-build.md @@ -3,7 +3,7 @@ title: Grok Build description: 在 xAI 的 Grok Build CLI 中使用任何由 opencodex 路由的模型——在代理运行期间,模型会自动注册到 ~/.grok/config.toml。 --- -opencodex 在本地端口提供一个与 OpenAI 兼容的 `POST /v1/chat/completions`(以及 `/v1/responses`),而 Grok Build 支持针对与 OpenAI 兼容的服务器使用自定义模型。从这次集成开始,opencodex 会将其全部可见目录自动注册到 Grok Build 中,无需手动编辑配置。 +opencodex 在本地端口提供一个与 OpenAI 兼容的 `POST /v1/responses`,而 Grok Build 支持针对与 OpenAI 兼容的服务器使用自定义模型。从这次集成开始,opencodex 会将其全部可见目录自动注册到 Grok Build 中,无需手动编辑配置。 ## 自动注册 @@ -17,7 +17,18 @@ base_url = "http://127.0.0.1:10100/v1" api_backend = "responses" api_key = "opencodex-loopback" name = "OCX gpt-5.6-sol" -# ... one [model.ocx-*] table per visible model ... +extra_headers = { "x-opencodex-grok" = "1" } +context_window = 272000 +supports_reasoning_effort = true +reasoning_effort = "low" + +[[model.ocx-gpt-5-6-sol.reasoning_efforts]] +id = "low" +value = "low" +label = "Low" +description = "Quick, fast implementations" +default = true +# ... remaining rungs for this model, then one [model.ocx-*] table per visible model ... # <<< opencodex managed block <<< ``` @@ -34,6 +45,27 @@ grok -m ocx-anthropic-claude-opus-4-8 -p "hello" # or in the TUI: /model ocx-anthropic-claude-opus-4-8 ``` +## 推理强度 + +Grok Build 的 `/effort`(以及 `--effort`)适用于目录条目声明了推理档位的模型。 +模型列表会读取原始 `GET /v1/models` 响应,其中的条目需要包含 +`supports_reasoning_effort` 和 `reasoning_efforts` 菜单选项。这组档位经过 Grok 兼容投影后 +会写入每个受管理的 `[model.*]` 表,包括 `supports_reasoning_effort`、默认 +`reasoning_effort` 和 `[[model..reasoning_efforts]]` 选择项。对于路由模型, +opencodex 会映射已配置的提供方档位(`reasoningEfforts` / +`modelReasoningEfforts`,以及 `modelDefaultReasoningEfforts` 中的默认值)。这些元数据 +描述代理配置的路由档位;适配器可以模拟推理,或将档位映射到提供方专用字段。档位列表 +为空的模型不会显示 effort 控件。原生 GPT-5.6 条目会保留固定的上游推理档位。 +模型声明的有效 Grok 档位(包括 `none` 和 `minimal`)都会保留。不受支持或重复的档位 +(包括 Codex 专用的 `ultra`)会从文件中省略,从而确保写出的每个选项都可执行。 + +Grok Build 通过 Chat Completions 与 opencodex 通信,并在声明档位时发送 +`reasoning_effort`。在这种情况下,Chat Completions 入站转换器会将内部 Responses 的 +`reasoning.summary` 默认设为 `auto`,因此推理轨迹会以 `delta.reasoning_content` +到达 Grok。需要模型执行推理且不返回轨迹的客户端,可以设置 +`include_reasoning: false`(或 `reasoning.summary: "none"`)。两个选项同时出现时, +显式的 `reasoning.summary` 优先。 + ## 认证说明 即使在 loopback 上,Grok Build 对自定义模型也要求一个非空 API key。注入的条目携带的是占位符(`opencodex-loopback`)——opencodex 会忽略 loopback 连接的接入密钥,因此这里不涉及任何真实机密。 @@ -73,5 +105,5 @@ api_key = "your-OPENCODEX_API_AUTH_TOKEN" ## 已知限制 - **服务安装后的 `ocx restart`:** 运行中的代理负责重启授权和排空协调;旧进程退出后,由已安装的服务管理器启动替换进程。服务监督始终保留。仅在 loopback 自动注册模式下,受管理区块也会在交接期间保留;非 loopback 部署使用手动管理的 Grok 配置。只有确认同一端口上出现另一个经过身份验证且健康的进程后,命令才会成功。 -- **配置读取时机:** 先启动 opencodex,再启动 `grok`,结果最可预测。Grok Build 会监视 `~/.grok/config.toml`,并在 `[model]` 表实际发生变化时重新加载(大约一秒的防抖,按内容比较),因此刷新后的区块可以在无需重启的情况下进入已打开的会话。要确认 Grok 解析到了什么,可以运行 `grok inspect`:它会列出已加载的配置来源,并提示被拒绝的字段,但不会打印最终解析出的模型列表。注意,单个 TOML 错误会使*整个*用户配置层失效,这也是 opencodex 以原子方式写入文件的原因——Grok 不会看到半写入的配置。 +- **配置读取时机:** 先启动 opencodex,再启动 `grok`,结果最可预测。Grok Build 会监视 `~/.grok/config.toml`,并在 `[model]` 表实际发生变化时重新加载(大约一秒的防抖,按内容比较),因此刷新后的区块可以在无需重启的情况下进入已打开的会话。要确认 Grok 解析到了什么,可以运行 `grok inspect`:它会列出已加载的配置来源,并提示被拒绝的字段,但不会打印最终解析出的模型列表。当前 Grok Build 会报告并跳过无效的模型字段,同时保留该模型条目的其余部分。TOML 语法错误仍会阻止文件加载。opencodex 会以原子方式写入文件,因此 Grok 每次重新加载时都会看到完整文档。 - **目录更新:** 有边界线的区块反映的是注入时的目录状态。添加提供方或模型后,运行 `ocx ensure`(或重启代理)以刷新它。 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 4e924458ee..7ff618f09e 100644 --- a/docs-site/src/content/docs/zh-cn/guides/providers.md +++ b/docs-site/src/content/docs/zh-cn/guides/providers.md @@ -95,12 +95,12 @@ ocx logout | 提供商 | Adapter | 基础 URL | 备注 | | --- | --- | --- | --- | -| `xai` | `openai-chat` | `https://api.x.ai/v1` | 优先使用实时 Grok 目录;回退默认模型为 `grok-4.5`。 | +| `xai` | `openai-chat` | `https://cli-chat-proxy.grok.com/v1` | OAuth 使用独立的 Grok CLI 订阅网关。API 密钥覆盖模式使用 `https://api.x.ai/v1`,并可能注入 Priority Processing。优先使用实时 Grok 目录;回退默认模型为 `grok-4.5`。 | | `anthropic` | `anthropic` | `https://api.anthropic.com` | Claude 模型;实时模型列表从 `/v1/models` 获取。 | | `kimi` | `openai-chat` | `https://api.kimi.com/coding/v1` | Kimi K2.7/K2.6/K2.5 编程模型。 | | `nous` | `openai-chat` | `https://inference-api.nousresearch.com/v1` | Nous Research 订阅网关(与 Hermes Agent 使用同一后端)。通过设备授权登录 `portal.nousresearch.com`;access 令牌是每个请求的 inference JWT。付费 + `:free` 模型混合目录(`tencent/hy3:free`、`stepfun/step-3.7-flash:free` 等)会从已登录账户实时发现。Refresh 令牌是单次使用,每次刷新都会轮换。 | | `kiro` | `kiro` | `https://runtime.us-east-1.kiro.dev` | 首次登录会导入已安装并已登录的 Kiro CLI 会话(Unix 使用 `curl -fsSL https://cli.kiro.dev/install` | `bash`;Windows PowerShell 使用 `irm 'https://cli.kiro.dev/install.ps1'` | `iex`;然后运行 `kiro-cli login`)。**添加账户**会先退出 `kiro-cli`,再启动新的浏览器登录,从而切换 `kiro-cli` 自身使用的账户,并保存账户范围的配置文件元数据。现有 OpenCodex 账户会保留;如果取消或失败,则恢复之前的 `kiro-cli` 会话。 | -| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | 通过 Cloud Code Assist 协议使用 Google OAuth。实时发现调用已认证的 CCA `v1internal:fetchAvailableModels` 端点,并仅发布当前登录账户可用的 agent 模型;维护中的目录仍作为回退。 | +| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | 通过 Cloud Code Assist 协议使用 Google OAuth。实时发现调用已认证的 CCA `v1internal:fetchAvailableModels` 端点,并仅发布当前登录账户可用的 agent 模型;维护中的目录仍作为回退。Quota 通过 `retrieveUserQuota` 和 `retrieveUserQuotaSummary` RPC 实时查询(8 秒超时)。CCA 聊天/adapter 请求使用 SSE(`v1internal:streamGenerateContent?alt=sse`),并为单次调用缓冲该流。内置图像生成使用单独的 unary `v1internal:generateContent` 端点。Adapter 在首个主机发生传输失败、空流、404 或 `UNAVAILABLE` 后,至多重试一次其维护的 daily/production peer;认证、地理封锁、无效请求和配额耗尽不会触发主机故障转移。 | | `cursor` | `cursor` | `https://api2.cursor.sh` | 实验性 PKCE 登录、带可选 HTTP/1.1 兼容路径的 HTTP/2 传输,以及按账号筛选的模型发现。 | | `github-copilot` | `openai-chat` | `https://api.githubcopilot.com` | 实验性。GitHub 设备流 + `copilot_internal` 交换(VS Code OAuth 客户端)。需要有效的 Copilot 订阅;不是官方第三方 API。 | diff --git a/docs-site/src/content/docs/zh-tw/guides/grok-build.md b/docs-site/src/content/docs/zh-tw/guides/grok-build.md index 364f92c3fd..af8632247f 100644 --- a/docs-site/src/content/docs/zh-tw/guides/grok-build.md +++ b/docs-site/src/content/docs/zh-tw/guides/grok-build.md @@ -3,7 +3,7 @@ title: Grok Build description: 透過 xAI 的 Grok Build CLI 使用任何由 opencodex 路由的模型——代理程式執行期間會將模型自動註冊到 ~/.grok/config.toml。 --- -opencodex 在本機埠提供 OpenAI 相容的 `POST /v1/chat/completions`(以及 `/v1/responses`),而 Grok Build 支援對 OpenAI 相容伺服器使用自訂模型。從此整合開始,opencodex 會自動將其整個可見目錄註冊到 Grok Build——無需手動編輯設定。 +opencodex 在本機埠提供 OpenAI 相容的 `POST /v1/responses`,而 Grok Build 支援對 OpenAI 相容伺服器使用自訂模型。從此整合開始,opencodex 會自動將其整個可見目錄註冊到 Grok Build——無需手動編輯設定。 ## 自動註冊 @@ -17,7 +17,18 @@ base_url = "http://127.0.0.1:10100/v1" api_backend = "responses" api_key = "opencodex-loopback" name = "OCX gpt-5.6-sol" -# ... one [model.ocx-*] table per visible model ... +extra_headers = { "x-opencodex-grok" = "1" } +context_window = 272000 +supports_reasoning_effort = true +reasoning_effort = "low" + +[[model.ocx-gpt-5-6-sol.reasoning_efforts]] +id = "low" +value = "low" +label = "Low" +description = "Quick, fast implementations" +default = true +# ... remaining rungs for this model, then one [model.ocx-*] table per visible model ... # <<< opencodex managed block <<< ``` @@ -38,13 +49,20 @@ grok -m ocx-anthropic-claude-opus-4-8 -p "hello" Grok Build 的 `/effort`(以及 `--effort`)只對目錄條目宣告了階梯的模型有效:它的模型清單擷取會讀取 原始的 `GET /v1/models` 回應,而該處的條目必須帶有 `supports_reasoning_effort` 以及 -`reasoning_efforts` 選單選項。對已路由的模型條目,opencodex 會把設定的供應商階梯 -(`reasoningEfforts` / `modelReasoningEfforts`,以及 `modelDefaultReasoningEfforts` 的預設值) -映象到該回應上。這份中繼資料描述的是 proxy 設定的路由階梯——它不代表原生產品的 reasoning 支援, -而 adapter 可能模擬 reasoning 或把檔位對映到供應商專用欄位。設定了階梯的路由模型在 Grok Build 中 -會顯示 effort 控制項,就像在 Codex 中一樣。階梯清單為空的模型不會保留 effort 控制項,這也與 -Codex 行為一致。原生 GPT-5.6 條目則分開處理:它們保留並暴露固定於上游的 reasoning 階梯,而不是 -供應商設定的路由中繼資料。 +`reasoning_efforts` 選單選項。這組階梯經 Grok 相容投影後會寫入每個受管理的 `[model.*]` 表格,包括 +`supports_reasoning_effort`、預設 `reasoning_effort`,以及 +`[[model..reasoning_efforts]]` 選項列。對已路由的模型條目,opencodex 會映射設定的 +供應商階梯(`reasoningEfforts` / `modelReasoningEfforts`,以及 +`modelDefaultReasoningEfforts` 的預設值)。這份中繼資料描述 proxy 設定的路由階梯;adapter 可以模擬 +reasoning,或把檔位對映到供應商專用欄位。階梯清單為空的模型不會顯示 effort 控制項。原生 GPT-5.6 +條目會保留固定於上游的 reasoning 階梯。模型宣告的有效 Grok 檔位(包括 `none` 與 `minimal`)都會 +保留。不受支援或重複的檔位(包括 Codex 專用的 `ultra`)會從檔案省略,確保寫出的每個選項都能實際使用。 + +Grok Build 透過 Chat Completions 與 opencodex 通訊,並在條目宣告階梯時送出 +`reasoning_effort`。在這種情況下,Chat Completions 入站轉換器會把內部 Responses 的 +`reasoning.summary` 預設設為 `auto`,因此推理軌跡會以 `delta.reasoning_content` 傳給 Grok。 +需要模型執行推理且不回傳軌跡的用戶端,可以設定 `include_reasoning: false`(或 +`reasoning.summary: "none"`)。兩個選項同時出現時,明確設定的 `reasoning.summary` 優先。 ## 認證注意事項 @@ -84,6 +102,7 @@ api_key = "your-OPENCODEX_API_AUTH_TOKEN" ## 已知限制 -- **以服務安裝的 `ocx restart`:** 當 opencodex 在服務管理員下執行時,`ocx restart` 目前會停止服務並以非受管程序取代——服務持續性(自動重啟、開機啟動)會遺失,直到下次 `ocx service` 設定;若該非受管程序死亡,受管理區塊可能指向已死的代理程式,直到下一次 `ocx start`/`ocx ensure` 重新整理它。 -- **設定讀取時機:** 先啟動 opencodex,再啟動 `grok`,結果最可預期。Grok Build 會監看 `~/.grok/config.toml`,並在 `[model]` 表格實際變更時重新載入(約一秒 debounce,依內容比對),因此重新整理後的區塊可在不重啟的情況下到達開啟中的工作階段。若要確認 Grok 解析了什麼,執行 `grok inspect`:它會列出已載入的設定來源,並對任何被拒絕的欄位發出警告。它不會印出解析後的模型清單。請注意,單一 TOML 錯誤會使*整個*使用者設定層失效,這也是 opencodex 以原子方式寫入檔案的原因——Grok 永遠看不到半寫入的設定。 +- **以服務安裝的 `ocx restart`:** 執行中的代理負責重啟授權與排空協調;舊行程結束後,由已安裝且可用的服務管理員再拉起替換行程。服務監督會維持安裝狀態。在 loopback 自動註冊下,受管理區塊也會在交接期間保留;非 loopback 部署則改用手動管理的 Grok 設定。只有在同一連接埠上確認另一個經過身分驗證且健康的行程後,此命令才會成功。 +- **以服務安裝的 `ocx restart`:** 執行中的代理負責重啟授權與排空協調;舊行程結束後,由已安裝且可用的服務管理員再拉起替換行程。服務監督會維持安裝狀態。在 loopback 自動註冊下,受管理區塊也會在交接期間保留;非 loopback 部署則改用手動管理的 Grok 設定。只有在同一連接埠上確認另一個經過身分驗證且健康的行程後,此命令才會成功。 +- **設定讀取時機:** 先啟動 opencodex,再啟動 `grok`,結果最可預期。Grok Build 會監看 `~/.grok/config.toml`,並在 `[model]` 表格實際變更時重新載入(約一秒 debounce,依內容比對),因此重新整理後的區塊可在不重啟的情況下到達開啟中的工作階段。若要確認 Grok 解析了什麼,執行 `grok inspect`:它會列出已載入的設定來源,並對任何被拒絕的欄位發出警告。它不會印出解析後的模型清單。目前的 Grok Build 會回報並略過無效的模型欄位,同時保留該模型條目的其餘內容。TOML 語法錯誤仍會阻止檔案載入。opencodex 會以原子方式寫入檔案,因此 Grok 每次重新載入時都會看到完整文件。 - **目錄更新:** 圍欄區塊反映注入當下的目錄。新增供應商或模型後,請執行 `ocx ensure`(或重啟代理程式)以重新整理它。 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 ee7d709880..2419bea41b 100644 --- a/docs-site/src/content/docs/zh-tw/guides/providers.md +++ b/docs-site/src/content/docs/zh-tw/guides/providers.md @@ -108,7 +108,7 @@ ocx logout | `kimi` | `openai-chat` | `https://api.kimi.com/coding/v1` | Kimi K2.7/K2.6/K2.5 coding 模型。 | | `nous` | `openai-chat` | `https://inference-api.nousresearch.com/v1` | Nous Research 訂閱 gateway(Hermes Agent 使用相同 backend)。透過 `portal.nousresearch.com` 做 device-grant 登入;access token 是每次請求使用的 inference JWT。混合付費與 `:free` 模型 catalog(`tencent/hy3:free`、`stepfun/step-3.7-flash:free` 等)會從已登入帳號即時探索。Refresh token 為單次使用,每次 refresh 都會輪換。 | | `kiro` | `kiro` | `https://runtime.us-east-1.kiro.dev` | 初次登入會匯入已安裝且已登入的 `kiro-cli` session。Unix 可用 `curl -fsSL https://cli.kiro.dev/install` | `bash` 安裝;Windows PowerShell 使用 `irm 'https://cli.kiro.dev/install.ps1'` | `iex`,再執行 `kiro-cli login`。**Add account** 會先登出 `kiro-cli`、啟動新的 browser login,切換 `kiro-cli` 所使用的帳號並保存 account-scoped profile metadata。既有 OpenCodex 帳號會保留;取消或失敗時會恢復先前的 `kiro-cli` session。 | -| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | 透過 Cloud Code Assist wire 使用 Google OAuth。即時探索使用 CCA 經認證的 `v1internal:fetchAvailableModels` 端點,發布目前登入帳號可用的 agent 模型;維護中的 catalog 作為 fallback。 | +| `google-antigravity` | `google` | `https://daily-cloudcode-pa.googleapis.com` | 透過 Cloud Code Assist wire 使用 Google OAuth。即時探索使用 CCA 經認證的 `v1internal:fetchAvailableModels` 端點,發布目前登入帳號可用的 agent 模型;維護中的 catalog 作為 fallback。Quota 會透過 `retrieveUserQuota` 與 `retrieveUserQuotaSummary` RPC 即時查詢(8 秒逾時)。CCA 聊天/adapter 請求使用 SSE(`v1internal:streamGenerateContent?alt=sse`),並為單次呼叫緩衝該串流。內建圖片生成使用獨立的 unary `v1internal:generateContent` 端點。Adapter 會在第一個主機發生 transport、404 或 unavailable 失敗時重試 daily/production peer。 | | `cursor` | `cursor` | `https://api2.cursor.sh` | 實驗性 PKCE 登入、即時 HTTP/2 transport 與按帳號篩選的模型探索。 | | `github-copilot` | `openai-chat` | `https://api.githubcopilot.com` | 實驗性。GitHub device flow + `copilot_internal` exchange(VS Code OAuth client)。需要有效 Copilot 訂閱;不是官方第三方 API。 | diff --git a/docs/CHALLENGE-CHECKLIST.md b/docs/CHALLENGE-CHECKLIST.md new file mode 100644 index 0000000000..5c856e9b9d --- /dev/null +++ b/docs/CHALLENGE-CHECKLIST.md @@ -0,0 +1,26 @@ +# WebMCP Challenge Checklist + +## Working + +- [x] WebMCP compatibility adapter +- [x] graceful unavailable state +- [x] nine structured P0 tools +- [x] runtime validation +- [x] risk tiers and annotations +- [x] dynamic tool exposure +- [x] audit API and Agent Activity UI +- [x] Approval Center and policy UI +- [x] Brain Atlas and Universe graph +- [x] demo challenge route +- [x] secret redaction +- [x] human-gated write permit +- [x] tests, typecheck, lint, build and privacy scan + +## Before submission + +- [ ] Test in a browser build exposing document.modelContext. +- [ ] Run the North Star workflow from an external browser agent. +- [ ] Configure real ComfyUI or H3, or clearly label demo mode. +- [ ] Deploy a public live URL. +- [ ] Record the three-minute demo video. +- [ ] Freeze features and do final public-repo cleanup. diff --git a/docs/DEMO-SCRIPT.md b/docs/DEMO-SCRIPT.md new file mode 100644 index 0000000000..e67019ab97 --- /dev/null +++ b/docs/DEMO-SCRIPT.md @@ -0,0 +1,35 @@ +# WebMCP Challenge Demo Script + +## 0:00–0:20 + +Show the normal PaohupByPaoZa dashboard and explain that modern apps are +human-first while agents normally guess the interface. + +## 0:20–0:40 + +Open Brain Universe. Show WebMCP readiness, Tool Inspector, Policies, +Atlas/Universe, Agent Activity and Approval Center. + +## 0:40–2:15 + +Open #demo and run the Smart Factory workflow: + +1. Create a stock-video project. +2. Generate five ideas. +3. Create a video prompt. +4. Request a preview render. +5. Review the asset. +6. Generate Adobe Stock metadata. +7. Prepare the export package. + +Show the pending approval and the Agent Activity timeline. + +## 2:15–2:40 + +Grant or reject the pending permit. Show that no high-risk work runs before +approval and policy. + +## 2:40–3:00 + +Close with: One application. One source of truth. Two first-class interfaces: +humans and agents. diff --git a/docs/PHASE-15-WEBMCP.md b/docs/PHASE-15-WEBMCP.md new file mode 100644 index 0000000000..f897e3e461 --- /dev/null +++ b/docs/PHASE-15-WEBMCP.md @@ -0,0 +1,33 @@ +# Phase 15 — PaohupByPaoZa × WebMCP Agent-Native Workspace + +PaohupByPaoZa exposes the same Agent OS capabilities to two first-class +interfaces: + +- Human interface: the existing React dashboard (#brain and #demo). +- Agent interface: WebMCP tools registered through document.modelContext. + +Both paths call the existing /api/agent-os/* application layer. WebMCP handlers +do not duplicate project, task, policy, approval, audit, scanner, or gateway +business logic. + +## Runtime architecture + +Dashboard UI and WebMCP registry both call the Agent OS management API, which +uses the shared services, policy/approval gateway, audit trail, and SQLite +store. + +WebMCP API details are isolated in gui/src/webmcp/capability.ts and +gui/src/webmcp/registry.ts. + +When WebMCP is unavailable, the app remains fully usable and displays +WebMCP unavailable with tools hidden. + +## Demo route + +Open http://127.0.0.1:10100/#demo. + +The deterministic Smart Factory scenario shows project state, pending human +approvals, WebMCP tool activity, and the shared Agent OS audit trail. + +The demo does not upload to Adobe Stock and does not expose arbitrary shell or +filesystem access. diff --git a/docs/WEBMCP-SECURITY.md b/docs/WEBMCP-SECURITY.md new file mode 100644 index 0000000000..73b453f9cd --- /dev/null +++ b/docs/WEBMCP-SECURITY.md @@ -0,0 +1,17 @@ +# WebMCP Security Model + +- No shell, arbitrary commands, unrestricted file writes, deletion, Git push, + or publishing tools are exposed. +- Browser tools call the authenticated Agent OS API. +- Scanner remains read-only, excludes secret-named files and never follows + symlinks. +- Default policy is deny. +- Write-class actions require policy and human approval. +- Write permits are scope-hashed, expiring and single-use. +- Inputs have required-field, length, enum, numeric and traversal checks. +- Audits store hashes and redacted summaries. + +Before public release run: + + bun run privacy:scan + bun audit --audit-level=high diff --git a/docs/WEBMCP-TOOLS.md b/docs/WEBMCP-TOOLS.md new file mode 100644 index 0000000000..4bf0b65e65 --- /dev/null +++ b/docs/WEBMCP-TOOLS.md @@ -0,0 +1,20 @@ +# WebMCP Tools + +| Tool | Risk | Read-only | Shared surface | +|---|---:|---:|---| +| get_workspace_status | R0 | yes | projects, tasks, approvals | +| create_stock_project | R2 | no | project registry | +| generate_stock_ideas | R1 | yes | deterministic demo service | +| generate_video_prompt | R1 | yes | deterministic prompt service | +| start_render_job | R3 | no | task queue and approval reference | +| get_render_status | R0 | yes | task API | +| review_asset | R1 | yes | deterministic review adapter | +| generate_stock_metadata | R1 | yes | deterministic metadata adapter | +| prepare_stock_export | R3 | no | manifest-only export with approval | + +All tools declare JSON input schemas, WebMCP annotations and risk tiers. +Runtime validation rejects missing or oversized values, unsupported enums and +path traversal strings before any service call. + +Every execution posts a safe audit record to /api/agent-os/audit. The server +stores an SHA-256 input digest and a redacted summary, not raw credentials. diff --git a/docs/agent-os/ARCHITECTURE-CURRENT.md b/docs/agent-os/ARCHITECTURE-CURRENT.md new file mode 100644 index 0000000000..f492dcfd0f --- /dev/null +++ b/docs/agent-os/ARCHITECTURE-CURRENT.md @@ -0,0 +1,59 @@ +# PaohupByPaoZa — Current Architecture Map (Phase 00) + +> Generated: 2026-08-29. Describes what exists today, not the Agent OS blueprint. + +## Process model + +One Bun process starts the proxy (src/cli/index.ts start), binds a local HTTP +port (default 10100), and serves: + +- POST /v1/responses — provider translation for Codex clients +- POST /v1/chat/completions — OpenAI-compatible clients +- GET /healthz — health check +- GET /api/* — management API (src/server/management/) +- GET / — GUI dashboard (gui/dist build) + +A Windows tray (src/tray/) and start.cmd/start.ps1 wrap the same entrypoint. + +## Request flow (core path) + +Codex/Claude client → HTTP server → admission/auth boundary → routing +(src/router.ts + src/routing/) → adapter (src/adapters/, per provider wire +format) → provider transport (src/providers/, quota/keys/tiers/failover) → +upstream → response translation back to the client dialect. + +The Compatibility Lab (src/lab/) is opt-in: a user with one provider and no +routing profile never reaches it. The boundary is enforced by import-graph tests, +and activation registers into core-owned slots (passive-route-linker, +provider-slot, optional-shutdown-hooks) rather than importing Lab from core. + +## Dependency direction (as observed) + +cli → server → router → routing + adapters → providers → lib/types +server/management → config + storage (JSON ledgers under ~/.opencodex) +gui → management API over /api/* (no direct backend imports) + +Forbidden direction (enforced by test): router.ts, server/lifecycle.ts, and +server/responses/core.ts must not import or transitively reach src/lab/. + +## Persistence + +- config.json + per-feature JSON/JSONL ledgers in ~/.opencodex (usage, + usage-debug, logs). No SQL database, no ORM, no migration framework. +- src/storage/ runs policy/cleanup/restore jobs over that local data. + +## i18n / GUI + +React app with locale catalogs (en, th, de, fr, ja, ko, ru, tr, zh, zh-TW) in +gui/src/i18n/; this fork's default locale is Thai ("th"), detecting from storage, +then navigator language, then falling back to "th". The local oxlint rule +forbids hardcoded UI strings outside catalogs. + +## Security posture today + +- OAuth token handling with fail-closed admission tests (agent-task-recovery, + auth boundary suites). +- Secrets via @napi-rs/keyring; privacy:scan guards against credential/PII leaks + in the repo. +- Approval/consent rules for agent-owned actions live in AGENTS_INSTALL.md and + are enforced in CLI/server code with dedicated tests. diff --git a/docs/agent-os/BASELINE-AUDIT.md b/docs/agent-os/BASELINE-AUDIT.md new file mode 100644 index 0000000000..a1549c9560 --- /dev/null +++ b/docs/agent-os/BASELINE-AUDIT.md @@ -0,0 +1,81 @@ +# Pao-hubPro — Phase 00 Baseline Audit (PaohupByPaoZa repository) + +> Generated: 2026-08-29 (Asia/Bangkok) — Codex Phase 00 execution +> Scope: read-only audit + baseline checks. No source changes made by this audit. + +## 1. Environment + +- OS: Windows 11 (PowerShell 7 shell) +- Runtime: Bun 1.3.14 (project is Bun-native TypeScript) +- Repo root: C:/Users/AD PAO/Desktop/paohupbypaoZAZAZA55555 +- Git branch: paohupbypaoza (local; origin is lidge-jun/opencodex) + +## 2. Repository identity + +PaohupByPaoZa v2.62.0 — a rebranded, Thai-localized fork of opencodex 2.26.0 +that has absorbed upstream dev updates. It is a local LLM provider proxy with a +React dashboard, serving Codex CLI/App, Claude Code, Claude Desktop, and Grok +Build. User config stays at ~/.opencodex for compatibility. + +CLAUDE.md: UNAVAILABLE (does not exist at repo root; AGENTS.md read instead). + +## 3. Working-tree state (user work preserved) + +- Branch paohupbypaoza with ~37 modified files, none staged. +- Modified areas: Apple-styled GUI (App.tsx, styles.css, new styles-apple.css), + Thai locale (new gui/src/i18n/th.ts, 11 upstream locales adjusted), CLI + branding (doctor/help/init/index), server index, Windows tray/start scripts, + package.json rebrand (bin names paohup/paohupbypaoza retain an opencodex alias). +- Untracked: gui/src/i18n/th.ts, gui/src/styles-apple.css, start.cmd, start.ps1. +- This audit touched none of it. + +## 4. Stack inventory + +| Area | Finding | +|---|---| +| Runtime | Bun-native TypeScript, no separate server compile step | +| Frontend | React + Vite (gui/), packaged output served from gui/dist | +| Database | None. No migrations, no *.prisma, no *.sql anywhere | +| Queue | No persistent task queue. In-process queues only (run-turn-queue.ts, storage policy/cleanup/restore workers) | +| Cache | In-process; config/state are JSON files in ~/.opencodex | +| Auth | Codex/ChatGPT OAuth flows, API keys, @napi-rs/keyring secret storage | +| MCP | @modelcontextprotocol/sdk dependency present | +| Deployment | Local app only (start.cmd/start.ps1, Windows tray); no Docker/Compose | +| Docs | Astro + Starlight docs-site/, structure/ maintainer invariants, devlog/ | + +## 5. Module inventory relevant to the Agent OS blueprint + +- Model routing: src/routing/ (profile, evaluator, health, cost, quota, + capability, trace, analytics, history), src/providers/ (registry, quota, + failover, tiers, discovery), src/adapters/ (openai-chat, openai-responses, + anthropic, google, azure, kiro, cursor, grok/xai, mimo-free, and more), src/combos. +- Optional subsystem: src/lab/ (Compatibility Lab), opt-in, boundary enforced by + tests/core-lab-boundary.test.ts (router.ts, lifecycle.ts, responses/core.ts + must not reach src/lab). +- Server: src/server/ (lifecycle, management API, responses core). +- CLI: src/cli/ (start, doctor, models, init, help). +- Storage jobs: src/storage/ (policy, cleanup, restore, scanner, mutation coordinator). + +## 6. Baseline test report (commands actually run) + +| Check | Result | Evidence | +|---|---|---| +| bun run typecheck | FAIL (pre-existing) | 4 errors, all in src/adapters/google.ts lines 1184-1186, 1229 (TS2367 comparisons). google.ts is untouched by the working tree — upstream defect, not a regression of local work | +| bun run privacy:scan | PASS | exit 0, "Privacy scan passed" | +| bun run test (root, 871 files) | INCONCLUSIVE (environment) | Ran ~38 min (normally ~210 s); Bun 1.3.14 crashed with internal panic (runtime bug, bun.report link emitted). Zero (fail) lines observed before the crash. Classify as pre-existing environment limitation, not a code failure | +| bun test tests/core-lab-boundary.test.ts tests/repo-hygiene.test.ts | PASS 24/24 | exit 0 in 3.57 s | +| gui: bun run lint | FAIL (in-scope uncommitted work) | 1 error: App.tsx:106 hardcoded "PaohupByPaoZa ·" (no-hardcoded-ui-strings) | +| gui: bun test tests | FAIL (root cause identified) | 119 fails; root cause: the rebrand changed detectInitialLocale fallback from "en" to "th" in gui/src/i18n/shared.ts, so tests asserting English UI text time out (e.g. compatibility-lab.test.tsx fails 9/26 in isolation) | + +Pre-existing failures are separated from audit-time failures: nothing in this +audit's run introduced a new failure. The google.ts typecheck errors and the +locale-default test regressions both predate this audit. + +## 7. Risks and constraints + +- Windows-first; tests assume an idle machine (suite timing guard). +- Bun runtime crash under heavy parallel test load is an upstream Bun issue. +- GUI tests are coupled to the default locale; any default-locale change needs a + test-locale pin (e.g. localStorage en) or locale-agnostic assertions. +- No persistent storage engine exists; every future Agent OS phase that needs + durable tasks/workflows must introduce its own storage strategy (Phase 04+). diff --git a/docs/agent-os/GAP-ANALYSIS.md b/docs/agent-os/GAP-ANALYSIS.md new file mode 100644 index 0000000000..2ad4fccd46 --- /dev/null +++ b/docs/agent-os/GAP-ANALYSIS.md @@ -0,0 +1,51 @@ +# Pao-hubPro — Gap Analysis vs Agent OS Blueprint (Phase 00) + +> Generated: 2026-08-29. Compares the Agent OS roadmap (Phases 0-16) against +> what the PaohupByPaoZa repository actually implements today. + +Status legend: NONE = no equivalent found | PARTIAL = some equivalent exists | +STRONG = substantial production-grade equivalent. + +| Phase | Blueprint intent | Repo equivalent today | Status | +|---:|---|---|---| +| 00 | Repository audit & baseline | This audit + docs/agent-os/ deliverables | DONE (this phase) | +| 01 | OpenHarness adapter (runtime boundary) | None. Upstream boundary today is opencodex itself; no OpenHarness seam | NONE | +| 02 | Agent registry (version, lifecycle, policy, health) | IMPLEMENTED: src/agent-os/registry.ts (canonical agents, lifecycle, fail-closed permissions) on top of the existing provider registry | DONE | +| 03 | Pao Commander (goal → task graph orchestration) | None. Proxy routes requests; no orchestration agent | NONE | +| 04 | Persistent task/queue engine | IMPLEMENTED: src/agent-os/tasks.ts (durable SQLite queue, retry/backoff, heartbeat, crash recovery) alongside the existing in-process proxy queues | DONE | +| 05 | Sandbox & security enforcement | IMPLEMENTED (engine): src/agent-os/policy.ts deny-by-default capability policy + approval-required write-class capabilities | DONE (engine) | +| 06 | Model router (providers, fallback, cost, health) | STRONG: routing profiles, evaluator, health, cost, quota, tiers, failover, 10+ adapters | STRONG | +| 07 | Memory OS (scoped, typed, provenance, deletion) | IMPLEMENTED: src/agent-os/memory.ts (scopes, provenance, correction, delete) | DONE | +| 08 | Skill store (versioned, validated skills) | IMPLEMENTED: src/agent-os/skills.ts (versioned records + read-only health pass) | DONE | +| 09 | Workflow engine (durable graphs, approvals) | IMPLEMENTED: src/agent-os/workflow.ts (versioned step graphs on the task queue, approval gates) | DONE | +| 10 | Multi-agent teams (bounded parallel specialists) | IMPLEMENTED: src/agent-os/teams.ts (bounded-parallel dispatch with stored deferred plan) | DONE | +| 11 | Observability & replay | IMPLEMENTED (agent-side): src/agent-os/observability.ts (task timelines + side-effect-aware replay planning); proxy traffic keeps its own ledgers | DONE (agent-side) | +| 12 | Remote nodes (PC/VPS/GPU capacity) | IMPLEMENTED (registry): src/agent-os/remote.ts (register/heartbeat/liveness/capability routing; no dispatch yet) | DONE (registry) | +| 13 | Controlled self-improvement | None | NONE | +| 14 | Marketplace / pack system | None | NONE | +| 15 | Agent OS V1 stable gate / Brain Universe + WebMCP | IMPLEMENTED local vertical slice: scanner, sessions, Atlas/Universe, nine WebMCP tools, audit/activity, approval/policy UI and demo route; embeddings/public deployment remain open | PARTIAL | +| 16 | AI Reviewer Council / second opinion engine | PARTIAL: reviewer results + deterministic aggregation + global search + Ask Pao Brain (read-only); scoped Write Permit gateway is future work | PARTIAL | + +## Reading + +- The repo already covers Phase 06 (model routing) at production depth; any new + Phase 06 work must extend src/routing/ + src/providers/, not start a new router. +- The closest foundations for later phases: src/lab/ (evidence + activation-slot + pattern, reusable for Phase 16 council registration), src/storage/ (job/worker + pattern, reusable for Phase 04 durability), and the management API (reusable + surface for Phase 02 registry and Phase 16 review UI). +- Phases 03/07/08/09/12/13/14/16 have no existing equivalent and must not + silently duplicate or overload the proxy core; each needs its own boundary and + activation seam like the Lab uses today. + +## Baseline constraints for all later phases + +1. Fix the pre-existing google.ts typecheck errors (4) before Phase 01 closes, + since every phase gate includes typecheck. +2. Any default-locale change must pin test locale or update assertions; today the + GUI suite is red against the uncommitted rebrand (119 fails, root cause + documented in BASELINE-AUDIT.md). +3. Full bun run test is unstable on this machine under load (Bun panic); use + focused suites per phase and re-run full suites on an idle machine. +4. No destructive migration exists yet — there is no schema at all; introduce + storage with compatibility notes when Phase 04 lands. diff --git a/docs/agent-os/IMPLEMENTATION-STATUS.md b/docs/agent-os/IMPLEMENTATION-STATUS.md new file mode 100644 index 0000000000..c53f300000 --- /dev/null +++ b/docs/agent-os/IMPLEMENTATION-STATUS.md @@ -0,0 +1,71 @@ +# Agent OS / Brain Universe — Implementation Status + +> Generated: 2026-08-29. Maps the Phase 0-16 roadmap to what is actually +> implemented in this repository, with the test evidence per module. + +## Architecture decision + +Implemented as one opt-in subsystem under `src/agent-os/` (no new app, no new +process, no external database) following the repository rules: Bun-native +TypeScript, storage as a single SQLite file under the existing config dir +(`~/.opencodex/agent-os.sqlite3`, WAL mode), local-first, deny-by-default. +Brain Universe (Phase 15) is exposed over the existing management API as +read-only routes under `/api/agent-os/*`. + +## Module map + +| Phase | Module | What exists | Tests | +|---:|---|---|---| +| 02 | src/agent-os/registry.ts | Agent registry: identity, lifecycle (health/enable), fail-closed default permissions, upsert by id | tests/agent-os-registry.test.ts | +| 04 | src/agent-os/tasks.ts | Persistent task queue: enqueue/claim FIFO, heartbeat, retry with backoff, crash recovery via stale-heartbeat reclaim, cancel | tests/agent-os-tasks.test.ts | +| 05 | src/agent-os/policy.ts | Capability policy: deny-by-default, subject-specific beats global, deny beats allow; write-class capabilities additionally require a granted approval record | tests/agent-os-policy.test.ts | +| 07 | src/agent-os/memory.ts | Memory OS: scopes (global/project/agent/decision/failure/workflow), provenance, correction (update keeps id), delete | tests/agent-os-memory-skills.test.ts | +| 08 | src/agent-os/skills.ts | Skill store: versioned records + read-only health pass (duplicate names, missing files, deprecated) | tests/agent-os-memory-skills.test.ts | +| 09 | src/agent-os/workflow.ts | Workflow engine: durable versioned step graphs driven through the Phase 04 queue; approval gates pause runs; denial cancels | tests/agent-os-workflow.test.ts | +| 10 | src/agent-os/teams.ts | Team runs: bounded-parallel child dispatch (deferred plan stored), rejects unbounded specs | tests/agent-os-teams-observe.test.ts | +| 11 | src/agent-os/observability.ts | Task timelines (event trail) + replay planning: safe only for side-effect-free kinds, never silent re-execution | tests/agent-os-teams-observe.test.ts | +| 12 | src/agent-os/remote.ts | Remote nodes: register/heartbeat, liveness states (online/stale/offline), capability routing to live nodes only | tests/agent-os-teams-observe.test.ts | +| 15 | src/agent-os/brain-scanner.ts | Brain Universe scanner: read-only walk, ignore rules, secret exclusion (never read), size policy, framework/instruction detection, coverage counters, symlink escape blocked | tests/agent-os-brain.test.ts | +| 15 | src/agent-os/brain-sessions.ts | Session indexer: Claude/Codex JSONL -> canonical events, streaming line reader, broken lines counted, byte-offset resume | tests/agent-os-brain.test.ts | +| 15 | src/server/management/agent-os-routes.ts | Observatory HTTP surface: GET-only routes for agents/tasks/skills/memory/nodes/reviews/task-timeline/search/ask; POST/PUT/DELETE rejected 405 | tests/agent-os-routes.test.ts | +| 16 (slice) | src/agent-os/reviews.ts | Reviewer Council results: record + deterministic aggregation (fail dominates, warn -> needs_review) | tests/agent-os-teams-observe.test.ts | +| 16 (slice) | src/agent-os/search.ts, ask.ts | Global metadata search + Ask Pao Brain: deterministic intent routing over local data with source citations; honest fallback, no fabrication | tests/agent-os-teams-observe.test.ts | + +## Test evidence + +``` +bun test tests/agent-os-*.test.ts -> 44 pass / 0 fail (8 files) +bun x tsc --noEmit -> exit 0 +bun run privacy:scan -> pass +``` + +## Security posture (enforced, not just documented) + +- Registry defaults: read=true, write=false, terminal=false, net=false. +- Policy: unknown capability/subject = default_deny; shell.exec/fs.write/ + git.push/deploy require an explicit allow policy AND a granted approval. +- Scanner: no write/rename/delete/execute code paths; secret-named files are + skipped unread; symlinks are never followed; ignore list covers + node_modules/.git/dist/... by default. +- Observatory HTTP: GET only; mutations are impossible over the API by design. +- Ask/search: metadata over the local store only; semantic search honestly + reports as unavailable until a local model seam is added. + +## WebMCP challenge slice + +- Compatibility adapter and dynamic registry live under gui/src/webmcp/. +- Nine P0 tools call the same Agent OS API used by the human UI. +- Audit records use SHA-256 input digests and redacted summaries. +- Brain Universe includes WebMCP status, Tool Inspector and Agent Activity. +- The demo route provides the deterministic Smart Factory scenario. + +## Not yet implemented (honest gaps) + +- Phase 15 pgvector semantic search — intentionally deferred (local-first; needs + a local embedding model seam). +- Real ComfyUI/H3 rendering is not configured; demo tools use deterministic + production-shaped adapters. +- Public deployment and the challenge video are not produced locally. +- Phase 16 full Write-Permit gateway — the approval ledger and policy engine + exist (Phase 05); the scoped SHA-bound write permit flow is Phase 16 work. +- Phase 01 OpenHarness adapter — no OpenHarness integration exists yet. diff --git a/gui/bunfig.toml b/gui/bunfig.toml new file mode 100644 index 0000000000..63915d8f8b --- /dev/null +++ b/gui/bunfig.toml @@ -0,0 +1,8 @@ +# Scope gui test runs and pin the test locale. +# +# The product default locale is Thai (see gui/src/i18n/shared.ts), but most DOM +# tests assert English catalog strings. The preload answers the ocx-lang +# storage read with "en" so UI tests stay locale-deterministic without changing +# product behavior. See gui/tests/preload.ts for the rationale. +[test] +preload = ["./tests/preload.ts"] diff --git a/gui/index.html b/gui/index.html index 0210bc2145..8e66628b7a 100644 --- a/gui/index.html +++ b/gui/index.html @@ -1,11 +1,11 @@ - + - opencodex · proxy dashboard + PaohupByPaoZa