diff --git a/README.md b/README.md index 18ab5e06d03..97474781ae5 100644 --- a/README.md +++ b/README.md @@ -114,6 +114,8 @@ Connect the tool you already use: | Claude Code | With the `claude` CLI installed, run `ocx claude`. It starts the proxy if needed and launches Claude Code through it. | | Claude Desktop | Run `ocx claude desktop`. On a new install it sets up the gateway profile for the whole app; an existing first-party setup is kept, and `ocx claude desktop apply --gateway` switches explicitly. See the [Claude Code guide](https://opencodex.me/guides/claude-code/). Fully quit and reopen Claude Desktop after a switch. | | Grok Build | On a local listener with Grok integration enabled, `ocx start` registers the models when `~/.grok` exists; pick an `ocx-*` model in Grok Build. Remote setups: see the [Grok Build guide](https://opencodex.me/guides/grok-build/). After adding providers, restart the proxy (or run `ocx ensure` when Codex autostart is enabled) to refresh the list. | +| Google Antigravity (desktop) | On the dashboard, open **Route → Antigravity** (also linked from **Route → Clients**), or run `ocx connect antigravity` on the machine where it is installed. | +| agy (CLI) | Use **Route → Antigravity** or run `ocx connect agy` on the machine where it is installed. Reload the indicated shell profile before running `agy`. | | Tools with a managed integration | Use the dashboard **Route** page, or `ocx integration client enable --client `. | | Any other tool | Set a custom OpenAI-compatible base URL of `http://localhost:10100/v1`, or an Anthropic base URL of `http://localhost:10100`. | diff --git a/bin/ocx.mjs b/bin/ocx.mjs index a156f0fc00e..0e78ae3852e 100755 --- a/bin/ocx.mjs +++ b/bin/ocx.mjs @@ -69,7 +69,7 @@ import { } from "../src/update/npm-cache-preflight.mjs"; import { handoffWindowsTrayForUpdate, planWindowsTrayUpdate } from "../src/update/tray-update-plan.mjs"; import { bootRestoreProbe, launcherUsableAfterNpmUpdate, transactionalNpmUpdate as transactionalNpmUpdateSync, transactionalNpmUpdateAsync } from "../src/update/transactional-install.mjs"; -import { manualUpdateFailureGuidance, npmUpdateFailureGuidance } from "../src/update/update-failure-guidance.mjs"; +import { dashboardStopMarker, manualUpdateFailureGuidance, npmUpdateFailureGuidance, takeDashboardStopToken } from "../src/update/update-failure-guidance.mjs"; import { captureCodexCliTransportEnv, CODEX_CLI_TRANSPORT_ENV_KEYS, @@ -84,6 +84,7 @@ import { } from "../src/update/supervised-recovery.mjs"; const PKG = "@bitkyc08/opencodex"; +const dashboardStopToken = takeDashboardStopToken(process.argv, process.platform); const UPDATE_RECOVERY_READY_MS = 30_000; const UPDATE_RECOVERY_POLL_MS = 100; const UPDATE_RECOVERY_SLEEP = new Int32Array(new SharedArrayBuffer(4)); @@ -933,8 +934,10 @@ async function runPackageManagerSelfUpdate(manager, child) { stopAttempted = true; console.log("⏹ Stopping the running proxy before updating..."); if (!homePolicy.authorizeMutation(serviceWasInstalled ? "service" : "runtime")) { releaseUpdateLease(); process.exit(1); } - const stopRes = guardedSpawnSync(homePolicy.authorizeMutation, serviceWasInstalled ? "service" : "runtime", process.execPath, [launcher, "stop"], { - stdio: "inherit", windowsHide: true, env: mutationChildEnvironment(), + const stopArgs = dashboardStopToken ? [launcher, "stop", "--json"] : [launcher, "stop"]; + const stopRes = guardedSpawnSync(homePolicy.authorizeMutation, serviceWasInstalled ? "service" : "runtime", process.execPath, stopArgs, { + stdio: dashboardStopToken ? ["inherit", "pipe", "inherit"] : "inherit", encoding: "utf8", + windowsHide: true, env: mutationChildEnvironment(), }); const stillHasRuntimeState = existsSync(join(configDir(), "ocx.pid")) || existsSync(join(configDir(), "runtime-port.json")); @@ -965,6 +968,8 @@ async function runPackageManagerSelfUpdate(manager, child) { ? `opencodex: could not confirm the proxy on ${bakeHostname}:${bakePort} is stopped; aborting the update. Run 'ocx stop' and retry.` : "opencodex: could not stop the running proxy; aborting the update. Run 'ocx stop' and retry."); releaseUpdateLease(); + const marker = decision.reason === "stop-failed" && dashboardStopMarker(dashboardStopToken, stopRes); + if (marker) console.log("\n" + marker); // Node writes synchronously to the Windows dashboard's pipe. process.exit(1); } if (historyOnlyStop || historyRestoreIncomplete()) { diff --git a/bun.lock b/bun.lock index 01a79ceba9a..95f4837282c 100644 --- a/bun.lock +++ b/bun.lock @@ -26,6 +26,7 @@ "overrides": { "@hono/node-server": "2.1.11", "body-parser": "2.4.0", + "cross-spawn": "7.1.2", "fast-uri": "3.1.9", "hono": "4.13.23", "ip-address": "^10.7.4", @@ -160,7 +161,7 @@ "cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="], - "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], + "cross-spawn": ["cross-spawn@7.1.2", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg=="], "debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="], diff --git a/desktop/src-tauri/Cargo.lock b/desktop/src-tauri/Cargo.lock index ff2111f40f3..9160b3fa0b7 100644 --- a/desktop/src-tauri/Cargo.lock +++ b/desktop/src-tauri/Cargo.lock @@ -2633,7 +2633,7 @@ dependencies = [ [[package]] name = "opencodex-desktop" -version = "2.100.12" +version = "2.100.14" dependencies = [ "base64 0.22.1", "dbus", diff --git a/desktop/src-tauri/Cargo.toml b/desktop/src-tauri/Cargo.toml index 784b7fc197d..ca694b100af 100644 --- a/desktop/src-tauri/Cargo.toml +++ b/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "opencodex-desktop" -version = "2.100.12" +version = "2.100.14" description = "OpenCodex desktop shell" authors = ["OpenCodex contributors"] license = "MIT" diff --git a/desktop/src-tauri/tauri.conf.json b/desktop/src-tauri/tauri.conf.json index 78b00373118..2576fcad669 100644 --- a/desktop/src-tauri/tauri.conf.json +++ b/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "OpenCodex", - "version": "2.100.12", + "version": "2.100.14", "identifier": "com.opencodex.desktop", "build": { "frontendDist": "../ui", diff --git a/devlog/_plan/261201_grok_build_integration/000_plan.md b/devlog/_plan/261201_grok_build_integration/000_plan.md new file mode 100644 index 00000000000..0ae66d77c7c --- /dev/null +++ b/devlog/_plan/261201_grok_build_integration/000_plan.md @@ -0,0 +1,74 @@ +# Grok Build (`3.32.24` Desktop / `2.0.6` CLI) integration & quota routing notes + +Date: 2026-12-01. Branch `docs/261201-grok-build-integration`, base `origin/dev` `740109d34e`. + +## Context + +Cursor's desktop application and CLI have converged into **Grok Build**: + +- **Desktop app (`Grok Build.app` `3.32.24`):** In-place display rebrand over the existing Cursor desktop app identity, keeping existing local data directory compatibility while introducing `grok-build` CLI shims alongside `cursor`. +- **Unified CLI (`grok 2.0.6 [unified]`, public `1.0.97`):** Unified channel serving `grok`, `agent`, `cursor-agent`, and `cursor agent` through a shared unified agent-host runtime. +- **Open-source repository (`xai-org/grok-build`):** Public `main` remains at `1.0.45` (`2026-09-29`), while the shipped `2.0.x [unified]` CLI has moved to the unified agent-host architecture rather than the legacy standalone execution loop. + +## Subscription & quota routing behavior + +### 1. Account states and quota pools + +| Account state | Quota / billing model | Notes | +|---|---|---| +| **Unmerged Cursor subscription** (`Pro`, `Pro+`, `Ultra`, `Express`, `Enterprise`) | Split buckets: **Cursor Models** (Auto, Cursor Grok, Composer) + **Other Models** (named third-party models) | Usage beyond Cursor Models limits spills over to Other Models quota or on-demand spend (`Express` is restricted to Cursor Models). | +| **Unified subscription** (`Plus`, `Premium`, `Super`, `Ultra`) | **Single unified pool** (`total` usage) + prepaid credits + banked usage resets | Replaces the split Cursor Models / Other Models buckets once account unification is completed. | +| **Unmerged Grok / SuperGrok subscription** | Legacy xAI CLI proxy quota + `grok.com` reset credits until unified | Signing in with an unmerged SuperGrok / X Premium+ account on the unified CLI prompts the user either to unify accounts or to keep using the legacy `1.0.x` CLI until unified. | + +### 2. Dual-subscription users (unmerged Cursor + Grok) + +Before account unification, neither the desktop app nor the unified CLI combines or alternates between two separate subscriptions automatically — only the currently signed-in account is billed: + +- **`Grok Build.app`:** Uses Cursor sign-in and deducts exclusively from the **Cursor** subscription pool (showing a merge prompt to settle duplicate Cursor billing). +- **Unified CLI (`grok 2.0.6`):** + - Signing in with Cursor deducts exclusively from the **Cursor** subscription pool. + - Signing in with an unmerged Grok account prompts account unification or switching back to the legacy `1.0.x` CLI to spend the standalone Grok subscription. +- **OpenCodex upstream providers:** + - `cursor` provider (`src/oauth/cursor.ts`, `src/adapters/cursor.ts`) deducts from the **Cursor** subscription pool. + - `xai` provider (`src/providers/xai-transport.ts`, `src/grok/reset-coupons.ts`) routes via `cli-chat-proxy.grok.com/v1` and deducts from the **Grok** subscription pool. + +After completing account unification, existing Cursor balances and standalone plans are settled into a single unified account and shared quota pool. + +## Coexisting Cursor models and OpenCodex custom models + +In both the unified CLI (`2.0.6`) and desktop app (`Grok Build.app` `3.32.24`), the hosted Cursor model catalog and Private Inference (`config.toml` / `private-inference.toml`) are **mutually exclusive by design**: + +- Normal mode loads only the hosted Cursor catalog and does not mix in local `[model_providers.*]` entries from `~/.grok/config.toml`. +- Private Inference mode loads only the configured TOML catalog and intentionally fails closed rather than falling back to hosted Cursor models. + +### Practical options for showing both model sets together + +#### CLI (`grok`) + +1. **OpenCodex as single hub (recommended for one unified picker):** + - Authenticate both `cursor` and `xai` (plus any other providers) inside OpenCodex, and expose `cursor/*` models alongside other models in the `[model_providers.opencodex]` block injected into `~/.grok/config.toml` (`src/grok/inject.ts`). + - Works on legacy `1.0.x` CLI directly, and on `2.0.6` when running through the Private Inference TOML config path. +2. **Dual-binary workflow (zero feature loss):** + - Use unified `grok` (`2.0.6`) for native Cursor models and full agent-host features. + - Keep a separate alias for legacy `1.0.x` CLI when routing through OpenCodex `[model_providers.opencodex]`. + +#### Desktop app (`Grok Build.app` / `Cursor Private Inference.app`) + +1. **Regular `Grok Build.app` + BYOK (`Override OpenAI Base URL` + `Add Custom Model`):** + - Keeping Claude/Gemini BYOK keys off leaves `claude-*` and `gemini-*` on the Cursor subscription while routing custom-added models (and `gpt-*`) through the overridden OpenAI Base URL to OpenCodex. + - **Constraint:** BYOK base URL requests are sent from Cursor's backend rather than from localhost, so `127.0.0.1` will not work; OpenCodex must be reachable over a public HTTPS tunnel (with admission token). +2. **Private Inference (`Cursor Private Inference.app` or `private-inference.toml`) + OpenCodex hub:** + - Supports direct `http://127.0.0.1:10100/v1` loopback without a tunnel. + - When OpenCodex serves `cursor/*`, `xai/*`, and third-party models together, all of them appear in a single picker (Cursor models route through OpenCodex's `cursor` adapter rather than the native cloud agent loop). +3. **Dual-app side-by-side:** + - Run `Grok Build.app` for native Cursor models and `Cursor Private Inference.app` for local loopback OpenCodex models. + +## OpenCodex follow-up backlog + +| Item | Area | Goal | +|---|---|---| +| 1 | `src/integrations/cursor-detect.ts` & `src/cli/integration-cursor.ts` | Detect `Grok Build.app` alongside `Cursor.app` and `Cursor Private Inference.app` without breaking existing installs. | +| 2 | `src/grok/inject.ts` | Verify whether OpenCodex-managed `cursor/*` models are included cleanly in injected `[model.*]` blocks and document `2.0.6` vs legacy `1.0.x` CLI behavior. | +| 3 | `src/oauth/cursor.ts` | Track key-bound / DPoP auth requirements on the `cursor` OAuth path so token refresh stays resilient if enforced upstream. | +| 4 | `src/grok/reset-coupons.ts` | Track unified account banked-reset parity alongside existing `grok.com` reset-credit queries for users who complete account unification. | +| 5 | Live verification (isolated `GROK_HOME`) | Re-verify `xai` provider (`cli-chat-proxy.grok.com/v1`) quota behavior for unified vs unmerged accounts without touching user credentials. | diff --git a/devlog/_plan/261204_start_owner_pid_reuse/000_plan.md b/devlog/_plan/261204_start_owner_pid_reuse/000_plan.md new file mode 100644 index 00000000000..2f2f3cbb4ad --- /dev/null +++ b/devlog/_plan/261204_start_owner_pid_reuse/000_plan.md @@ -0,0 +1,160 @@ +# 261204 Startup refused forever after PID reuse (EPERM) + +Lane ocx-pid-reuse. Base `origin/dev` 981765cbae, branch `fix/start-owner-pid-reuse-eperm`. One PR into `dev`. +Issue #9230 (Windows, svchost) and a Linux report on 2026-12-04 share one root cause. Prior work on this +path: #7851 (owner recheck before journal recovery), #8045, #8552/#8562 (self-PID record and `ownerScope`), +#8697/#8920/#8987 (endpoint uncertainty, Windows bind proof), #9242 (carry of #9231: the `(Check: …)` reason). + +## Incident + +A Linux Remote Link child (Ubuntu 24.04, systemd user service, deb install) refused to start for about a day +after a reboot. systemd restarted it every 5-6 s (restart counter 7,434; 14,926 identical lines in +`service.log`). Codex was pointed at the dead proxy, so every model request hung with no error, while the Home +showed the link as connected. + + Proxy ownership is unverified; startup refused. PID record and recovery journal were preserved. + Retry when the owner can be verified. (Check: pid-probe-failed) + +State: `runtime-port.json` from the pre-reboot proxy naming pid 1777, and a zero-byte `ocx.pid`. After the +reboot 1777 was a thread of a root-owned daemon (`/proc/1777/status`: Tgid 1721, Uid 0; a thread id is not +listed by `readdir(/proc)`, so `ps -p 1777` shows nothing), and `kill(1777, 0)` returned EPERM. Both +loopback families refused the health probe. Restoring the same two files on 2.100.13 reproduced the refusal; +removing them let the proxy start. Any stale record naming a pid or tid that the user cannot signal reproduces +it, on any release up to 2.100.13. + +## Root cause + +`recoverStartJournalAfterOwnerRecheck` (src/cli/start-owner-fence.ts:7-25) refuses on any observation other +than `absent`. `observeProxyLiveness` (src/server/proxy-liveness.ts:666-695) signals each candidate pid with +`kill(pid, 0)`: ESRCH releases it, but any other error, EPERM included, sets `unknown` and **breaks before the +command-line identity check** that a signalable pid gets. Nothing in the loop can change while the foreign +process lives, and a system daemon lives until the next reboot, which recreates the same situation. So the +refusal is permanent, and the record already carried the evidence to clear it: + +- `runtime-port.json` `startTime` (src/cli/index.ts:609, src/client/stop-teardown-owner.ts:75-94) is the + owner's creation identity: `linux::`, `darwin::`, `win32:<.NET ticks>`. +- `ownerScope` (src/config/process-state.ts:46-143) holds host, boot, network and container digests, but is + consulted only for the #8552 self-PID case. + +## Findings + +### Other recorded PIDs (investigation 3a) + +Investigation 3a inventoried every other record and lock that trusts a PID across process lifetimes. Findings +about paths this PR does not change stay out of the tree under the security-notes rule in AGENTS.md; they are +held in maintainer scratch notes and will be written up here once fixed. + +### Startup state machine (3b) + + start -> client journal reconcile -> supervised stay-out check -> early discovery + -> [ownership lease] -> service ownership decision -> observeProxyLiveness + live -> existing owner (stay out / refuse / sibling) + unknown -> REFUSE (endpoint-unverified | pid-probe-failed | pid-identity-unverified | probe-budget-exhausted) + absent -> cross-home discovery (indeterminate -> REFUSE) + -> loopback bind proven and journal owner pid may be live -> REFUSE + -> drop pid file (snapshot-guarded), reconcile journal + -> client fence (same observation) -> publication lease -> bind -> write ocx.pid, runtime-port.json + +Refusals that no later start clears without a person: `pid-probe-failed` for a pid held by another user +(Linux, macOS, Windows), `pid-identity-unverified` for a signalable pid whose command line cannot be read +(kernel threads have an empty one, `hidepid` hides it), and the journal-owner refusal for a reused pid. Endpoint +refusals clear when the listener changes. + +Service managers: systemd `Restart=on-failure`, `RestartSec=5`, no `StartLimit*` +(src/service/systemd.ts:118-133), about 17,000 attempts a day; launchd `KeepAlive` on failure with the default +throttle (src/service/launchd.ts:64-87); the Windows wrapper respawns every ~5 s and the Task Scheduler restart +count never applies to that inner loop (src/service/windows-taskxml.ts:80-143). `service.log` rotates at +20 MiB with two archives (src/service/logging.ts:6,119-161), so disk use is bounded and each line carries an ISO +timestamp. + +### Reported inconsistencies (3c) + +| Report | Cause | Verdict | +|---|---|---| +| `ocx resolve --json` said `absent-proven` while `ocx start` refused | resolve uses `findLiveProxy` and proves only endpoints down (src/cli/resolve.ts:309-331); it never asks the PID question start asks | bug, fixed here | +| `ocx service repair`: "no proxy answered" with no reason | the health report knows only that nothing answered (src/service/health.ts:256-263); the refusal is in `service.log` | bug, fixed here (report the refusal logged during the wait) | +| `ocx status` / `ocx doctor`: "not running", generic advice | status-probes treat every kill error as dead (src/cli/status-probes.ts:116-150, src/lib/process-control.ts:9) and never run the ownership observation | bug, follow-up | +| `ocx link update` / `ocx update --plan`: installer unknown for a deb install | standalone binaries are classified only as desktop or unknown (src/update/orchestrated-entry.ts:53-57,128-145); dpkg ownership is never consulted | bug, follow-up | +| Home shows the child connected while its proxy is down | link state is the SSH forward (src/link/tunnel-state.ts:1-8,155-165); inference readiness is `unknown` (src/link/status-projection.ts:78-104) | UX bug, follow-up | + +### Prior art (3d) + +PostgreSQL `CreateLockFile` (src/backend/utils/init/miscinit.c) treats ESRCH **and EPERM** from `kill(pid, 0)` +as a stale lock, relying on its rule that the data directory and lock file belong to the server's own user; it +also discounts its own, parent and grandparent pids after a reboot. systemd discourages PID files in favour of +supervising the process and, on recent versions, identifies processes by pidfd inode. A pidfd pins a process only +after it is opened, so it cannot vouch for a number written in an earlier lifetime. `flock` held for the process +lifetime is the sound primitive, but every writer must participate and Windows needs its own equivalent. nginx and +redis use their pid files for signalling and do not detect reuse. The process creation time is the portable +incarnation identity: `/proc//stat` field 22 with the boot id on Linux, `kinfo_proc.p_starttime` from the +`kern.proc.pid` sysctl on macOS (no privilege needed; `proc_pidinfo` refuses another user's process, checked on +this Mac), and `GetProcessTimes` or CIM `Win32_Process.CreationDate` on Windows. Sources are in the lane report. + +## Decision: what proves a recorded pid is not our owner + +The question the loop answers per candidate is narrow: is the process now at this pid number the owner the record +describes? ESRCH answers "no" today. The fix adds evidence that answers "no" just as firmly without signalling the +process, and keeps `unknown` whenever that evidence cannot be read. EPERM now leads to the identity check instead +of ending the loop; any other kill error still refuses. + +1. **Creation identity differs from the record's `startTime`** (only for the pid the record names). + Linux: a recorded boot id different from the current one means the owner ran under another kernel lifetime, + so the local process at that number is a different process. Same boot: `/proc//stat` start ticks + differ. macOS: `p_starttime` from `kern.proc.pid` differs. Windows: creation time from the native handle + read, else the CIM process table, differs by more than 1 ms. A pid names one process at a time and a creation + time never changes, so a mismatch is proof; an equal value or an unreadable one proves nothing. +2. **Linux structure.** `/proc//status` Tgid differs from the pid: the number is a thread of another + process, while the owner recorded `process.pid`, a thread-group leader (a zombie leader keeps Tgid = pid). + `/proc//stat` flags carry `PF_KTHREAD`: a kernel thread is never an ocx process. +3. **A readable command line that is not OpenCodex** (the existing rule, now reached after EPERM too). + +All three rules describe the process holding that number *here*, so they apply, and EPERM reaches them, only +when the record's `ownerScope` proves its PID was issued in the PID space this process inspects +(`sameRuntimePidSpace` in src/config/process-state.ts). On macOS and Windows that is the same host. On Linux the +scope now records the PID namespace (`ownerScope.pidNamespace`, a digest of `/proc/self/ns/pid`), which must +match, and within the same boot unless it is the initial namespace: its inode is fixed by the kernel +(PROC_PID_INIT_INO), while other namespace inodes repeat across boots and machines. Within one boot an equal +inode is either the same namespace or one that replaced a namespace already gone with all its processes. + +A network namespace or container layer is not enough, which round-1 review caught: a host-network container shares +the host's network namespace but numbers its own processes, and in a Kubernetes RollingUpdate both pods are PID 1 +in their own PID namespaces, so the new pod's recheck lands on itself and a different start time says nothing +about the old pod, whose listener the endpoint probe cannot see (#8552). Outside a proven PID space every +candidate keeps today's rules exactly (ESRCH, or a readable foreign command line after a successful signal); +EPERM refuses. + +Consequence, and the delivered contract (round-2 review): a record written before this version cannot prove its +PID space and keeps the refusal. `ownerScope` dates from v2.100.3 and `startTime` from v2.100.6; the record in +the incident was written by 2.100.2 and carries neither, so nothing in it says which PID space or boot wrote it, +and accepting it on EPERM would reopen the cross-namespace case. Such a machine gets a refusal that names the two +files to remove, quoted by `ocx service repair` as well. Every start of a fixed version rewrites the record, so +later reboots and PID reuse recover without help. The reporting machine was repaired by hand. An owner running +on another kernel that shares this home is invisible to local evidence of any kind, ESRCH included; the +endpoint probe stays the guard there, as before. + +Unchanged: ESRCH; a live ocx owner (healthz identity); a readable OpenCodex command line with an equal or +unreadable start time; unreadable identity after EPERM (still `pid-probe-failed`); every endpoint rule. + +Windows (#9230): the svchost case is covered when the CIM table reports a creation time for that process, which +standard users normally receive (the command line is the field Windows withholds). This is not yet validated on +a Windows host; a host where neither read works keeps the refusal, the safe outcome. + +## This PR + +| Unit | Change | Proof | +|---|---|---| +| 010 | `src/server/recorded-pid-identity.ts`: the three evidence rules with injected readers; `observeProxyLiveness` uses them, and lets EPERM reach them, only for the recorded PID when `ownerScope` proves the PID space (new `ownerScope.pidNamespace`) | failing-first tests: EPERM + foreign identity released; EPERM + unreadable refused; Linux thread id and kernel thread released; earlier boot released; ESRCH and a live owner unchanged; Windows and macOS creation-time comparison | +| 020 | refusal message names the reason in words and the recovery step | message test | +| 030 | `ocx resolve` runs the same tri-state observation and reports `liveness_unknown` with its reason | resolve test | +| 040 | service start/restart/repair health report prints a startup refusal logged after the command marked the log, before the manager acted | health report test | + +## Follow-ups, in priority order + +1. Other records and locks that trust a PID across lifetimes (investigation 3a): kept in maintainer scratch notes + until fixed. +2. Restart storm: a distinct exit status for an ownership refusal plus systemd `RestartSteps`/`RestartMaxDelaySec` + (ignored on systemd < 254), a launchd throttle and Windows wrapper backoff. +3. `ocx status` and `ocx doctor`: run the ownership observation when the proxy is down and name a refusal. +4. Installer detection for deb/rpm installs (dpkg ownership of the resolved binary) and owner guidance in Home. +5. Home link status: show the child's proxy readiness separately from the tunnel. +6. Windows: validate the CIM creation-time read against a SYSTEM svchost on a real host. diff --git a/devlog/_plan/261204_start_owner_pid_reuse/010_phase2_slices.md b/devlog/_plan/261204_start_owner_pid_reuse/010_phase2_slices.md new file mode 100644 index 00000000000..cb9da3761db --- /dev/null +++ b/devlog/_plan/261204_start_owner_pid_reuse/010_phase2_slices.md @@ -0,0 +1,15 @@ +# 261204 Phase 2: process identity for every recorded owner, and the follow-ups + +Lane ocx-pid-reuse, phase 2. Base `origin/dev` e4d4c077de (#9326). Several small PRs into `dev`, each from fresh +`origin/dev`, each with its own review. Each PR describes what it changes; this file names the slices only. + +| Slice | Branch | Change | +|---|---|---| +| A1 | `fix/pid-owner-incarnation` | Recorded lock and record owners carry the owner's process identity (start time and owner scope) and are released only on positive evidence that the PID now names a different process, never because a signal was refused. | +| A2 | `fix/pid-owner-incarnation-2` | The same rule for the remaining owners, and recovery of a pre-#9326 runtime record left by an earlier boot of the same host. | +| B1 | `fix/service-refusal-backoff` | A start refused for a reason no retry can clear exits with a distinct status that systemd, launchd and the Windows wrapper do not restart in a tight loop. | +| B2+B3 | `fix/status-refusal-deb-installer` | `ocx status` and `ocx doctor` name a standing startup refusal; deb installs are recognised by the updater and Home. | +| B4 | `fix/link-child-proxy-readiness` | Home shows a child's proxy readiness separately from its tunnel. | + +Windows: the creation-time evidence from #9326 is exercised on a real Windows host only by the manual `dev` +dispatch; PR CI runs no Windows jobs. diff --git a/docs-site/src/content/docs/es/guides/chatgpt-desktop.md b/docs-site/src/content/docs/es/guides/chatgpt-desktop.md index 7cde0152166..801523a310c 100644 --- a/docs-site/src/content/docs/es/guides/chatgpt-desktop.md +++ b/docs-site/src/content/docs/es/guides/chatgpt-desktop.md @@ -36,7 +36,7 @@ Si ChatGPT no está instalado (no se encuentra un paquete `com.openai.codex`), ` ## Alcance de la reescritura -Solo se consideran las notificaciones `account/rateLimits/updated` y las respuestas cuyo resultado de nivel superior contiene `rateLimits`, `rateLimitsByLimitId` u `ordinaryUsageAllowed`. Se eliminan los marcadores simples `rate_limit_reached`. Los campos conocidos de bloqueo por cuota (`allowed`, `limit_reached` / `limitReached`, `ordinaryUsageAllowed`) solo pasan al estado permitido cuando hay evidencia de que el bloqueo se debe a la cuota general: se ha eliminado un marcador de ese tipo o una ventana de uso alcanza el 100%. Un campo bloqueado por un motivo que no aparece en los datos recibidos permanece bloqueado. Las restricciones del espacio de trabajo, los créditos, los tipos desconocidos de límite alcanzado y los controles de gasto mantienen cerrado el acceso por uso. +Solo se consideran las notificaciones `account/rateLimits/updated` y las respuestas cuyo resultado de nivel superior contiene `rateLimits`, `rateLimitsByLimitId` u `ordinaryUsageAllowed`. Se eliminan los marcadores simples `rate_limit_reached`. Los campos conocidos de bloqueo por cuota (`allowed`, `limit_reached` / `limitReached`, `ordinaryUsageAllowed`) solo pasan al estado permitido cuando hay evidencia de que el bloqueo se debe a la cuota general: se ha eliminado un marcador de ese tipo o una ventana de uso alcanza el 100%. Un campo bloqueado por un motivo que no aparece en los datos recibidos permanece bloqueado. Las restricciones del espacio de trabajo, los tipos desconocidos de límite alcanzado y los controles de gasto mantienen cerrado el acceso por uso. Con `chatgptDesktop.spendCredits: true`, las variantes de crédito (`workspace_member_credits_depleted`, `workspace_owner_usage_limit_reached`) se abren igual que la cuota general, así que el escritorio puede usar créditos cuando se agota la cuota de la suscripción. OpenAI factura esos créditos y, de forma predeterminada, un compositor limitado por créditos sigue bloqueado. El uso mostrado conserva los datos reales: porcentajes, fechas de restablecimiento, duración de las ventanas, información del plan y otros campos de presentación se mantienen como se recibieron. Los mensajes JSON-RPC ajenos a este caso, la salida anidada de herramientas, los metadatos que bloquean el envío de conversaciones y las líneas malformadas se transmiten sin cambios. Solo se vuelven a serializar las líneas modificadas; los demás bytes conservan su codificación y sus finales de línea originales. La entrada estándar, la salida de errores y el código de salida del binario real mantienen su conexión directa con la aplicación. diff --git a/docs-site/src/content/docs/es/guides/codex-integration.md b/docs-site/src/content/docs/es/guides/codex-integration.md index dc448d22184..93a9451f312 100644 --- a/docs-site/src/content/docs/es/guides/codex-integration.md +++ b/docs-site/src/content/docs/es/guides/codex-integration.md @@ -758,6 +758,13 @@ Cuando opencodex se ejecuta como un [servicio de fondo](/es/reference/cli/lifecy La revista guarda los hashes originales `config.toml` y `opencodex.config.toml` más del estado OpenCodex inyectado. Un diario heredado o una interrupción antes de que se registraran esos hashes no pueden probar que el contenido posterior del archivo pertenezca a OpenCodex. Si cualquiera de los archivos difiere de su original guardado y carece de su propio hash de estado inyectado, la recuperación automática del diario y el error del informe de restauración nativa sin cambiar el archivo o la revista. El original guardado permanece disponible para la comparación; revíselo junto con los archivos actuales antes de elegir una acción de recuperación manual. +Ejecute `ocx doctor` en el host afectado. Su sección **Codex recovery journal** compara cada archivo +con el original e informa si el diario registró su estado inyectado. Por ejemplo, `config.toml` puede +diferir mientras que el perfil estaba ausente en ambos estados. La comparación funciona con el proxy +detenido y no imprime valores de configuración. Si alguno de los archivos no se puede leer de forma segura, +el informe lo nombra. Conserve los archivos actuales y el diario. +Una URL de enrutamiento local por sí sola no puede establecer qué ajustes escribió OpenCodex. + Los archivos que ya son iguales a sus originales guardados se aceptan sin reescribirlos. Un archivo faltante es distinto de un archivo vacío. Los hashes inyectados verificados aún permiten la restauración normal de instantáneas y las ediciones posteriores en configuraciones respaldadas por hash conservan el comportamiento de limpieza de campo propio existente. Sync y `ocx restore back` también rechazan una configuración enrutada existente cuyo diario sin hash no coincide con la línea base previa a la inyección. Esto evita que un nuevo hash de inyección se adhiera a un original más antiguo. Una configuración genuinamente nativa se puede guardar como una nueva línea de base antes de la inyección. El comportamiento explícito de exclusión de proveedores externos no se modifica. diff --git a/docs-site/src/content/docs/es/guides/combos.md b/docs-site/src/content/docs/es/guides/combos.md index 74cd2989ade..e8b7451afc5 100644 --- a/docs-site/src/content/docs/es/guides/combos.md +++ b/docs-site/src/content/docs/es/guides/combos.md @@ -778,6 +778,11 @@ ocx combo remove --yes `set` también acepta `--strategy`, `--sticky`, `--effort`, `--alias`, `--native-alias`, `--allow-metered-targets on|off`, `--cooldown-reprobe on|off`, `--cooldown-reprobe-interval`, `--display-name`, `--description`, `--decision-provider`, `--decision-timeout` y `--rename-from`. Utilice `-` como el valor de `--effort`, `--alias`, `--display-name`, `--description`, `--decision-provider`, o `--decision-timeout` para borrar ese campo. Las dos opciones de decisión solo se aplican cuando la estrategia efectiva es JEV: al indicar `--strategy jev` o al omitir `--strategy` en un combo JEV existente. En un combo existente, `--targets` solo sustituye la lista de destinos; sin `--strategy`, conserva la estrategia guardada y sus ajustes JEV. `--native-alias` requiere un alias de modelo nativo desnudo actualmente soportado y un nombre de visualización no vacío. `create` y `update` son alias para `set`; `delete` es un alias para `remove`; y los mismos subcomandos están disponibles bajo `ocx route combo`. +En los proxies que admiten revisiones de combos, `set` informa de un conflicto si el combo de origen +cambia antes de que se guarde una edición o un cambio de nombre, o si el destino del cambio de nombre +ya está en uso. El comando termina con el código de salida 5. Ejecute `ocx combo list --json` para +revisar los combos actuales antes de volver a intentarlo. + ### API de administración diff --git a/docs-site/src/content/docs/es/guides/integrations.md b/docs-site/src/content/docs/es/guides/integrations.md index a1c9f5d179c..9810ce068f3 100644 --- a/docs-site/src/content/docs/es/guides/integrations.md +++ b/docs-site/src/content/docs/es/guides/integrations.md @@ -746,7 +746,7 @@ La app de escritorio Antigravity de Google (2.15 y posteriores) y la CLI `agy` ( funcionar a través del gateway de OpenCodex. Conéctalas desde el panel o desde una terminal: ```bash -ocx connect antigravity --model # desktop app: ~/.antigravity/settings.json +ocx connect antigravity --model # configure both desktop app settings files ocx connect agy # agy CLI: a marked shell function in your profiles ocx connect antigravity status # or: ocx connect agy status ocx disconnect antigravity # or: ocx disconnect agy @@ -754,6 +754,23 @@ ocx disconnect antigravity # or: ocx disconnect agy Usa `--model` solo con `ocx connect antigravity` para fijar el modelo predeterminado de la app de escritorio. +Antigravity 2.15–2.29 lee únicamente `~/.antigravity/settings.json`. La versión 2.30 y las posteriores +leen únicamente `~/.gemini/config/config.json`. Las actualizaciones de la app dejan la configuración +del gateway en su ruta existente. OpenCodex escribe ambos archivos para instalaciones nuevas, +actualizaciones y cambios a versiones anteriores sin detectar la versión de la app. Comprueba ambos +archivos antes de escribir en cualquiera de ellos. + +El estado muestra primero `~/.gemini/config/config.json` y después `~/.antigravity/settings.json`. +Indica `connected` solo cuando ambos coinciden con el gateway de OpenCodex. Una configuración +incompleta se indica como `drifted`. + +OpenCodex acepta los registros de restauración antiguos de Antigravity de un solo archivo. Al +reconectar, conserva los datos originales de restauración del archivo heredado y añade un registro +para el archivo moderno. +La desconexión comprueba y restaura únicamente los archivos registrados, cada uno de forma independiente. +Los fallos parciales de escritura o restauración conservan los datos de recuperación necesarios para +volver a intentarlo. + Conectar registra lo que reemplazó. Desconectar restaura los bytes originales cuando el archivo no ha cambiado y, en caso contrario, revierte solo las entradas propias de OpenCodex y conserva tus otras ediciones. Antigravity puede restaurar la configuración aunque se reordenen las claves JSON y conserva @@ -764,8 +781,10 @@ Recupera de una copia el bloque completo de `agy`, incluidas las dos líneas de entre ellas, y vuelve a intentar la desconexión o la desinstalación. OpenCodex elimina el bloque entero y conserva los cambios que quedan fuera. También puedes restaurar el perfil original guardado, lo que reemplaza las ediciones posteriores. Un enlace simbólico de un perfil de `agy` debe apuntar a otro perfil compatible -de la misma familia de shells dentro de tu directorio personal. El archivo de configuración de -Antigravity debe resolverse a la ruta exacta `~/.antigravity/settings.json`. Reinicia Antigravity, o +de la misma familia de shells dentro de tu directorio personal. Cada archivo de configuración de +Antigravity debe resolverse a su propia ruta exacta dentro de tu directorio personal canónico. Los +directorios superiores deben resolverse a `.gemini/config` para el archivo moderno y a `.antigravity` +para el archivo heredado. Reinicia Antigravity, o abre una terminal nueva para `agy`, para aplicar un cambio. Al desconectar, `agy` omite los perfiles sin registro de restauración si no se pueden resolver o leer. `ocx uninstall` desconecta los clientes con registros de restauración guardados antes de eliminar la diff --git a/docs-site/src/content/docs/es/reference/cli/lifecycle.md b/docs-site/src/content/docs/es/reference/cli/lifecycle.md index a3d9536b3f0..44740d5ee2e 100644 --- a/docs-site/src/content/docs/es/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/es/reference/cli/lifecycle.md @@ -35,6 +35,8 @@ Asistente de configuración interactiva (`setup` es un alias de `init`). Indica Inicie el servidor proxy (puerto preferido `10100`). Escribe el estado PID / runtime-port y se niega a iniciar una segunda instancia en vivo. Cuando el puerto preferido está ocupado, `start` pregunta al titular quién es y se detiene en cualquier sentido: se niega rotundamente cuando un opencodex responde allí, e informa a un titular no identificado de lo contrario. Nunca mueve al oyente a otro puerto por sí mismo, porque eso dejaría el primer proxy en funcionamiento y volvería a apuntar al Codex en el segundo. Todavía se rechaza un `--port` explícito diferente cuando el proxy en vivo comparte este `OPENCODEX_HOME`, porque tanto la contabilidad de gastos solo observada como forzada escriben el mismo diario. Use un `OPENCODEX_HOME` separado para un hermano independiente; `port: 0` solo pide al sistema operativo el puerto de esa instancia y no separa su estado. Al inicio, sincroniza los modelos de cada proveedor en el catálogo de Codex. Al apagarlo, restaura el Codex nativo, a menos que se haya lanzado como un servicio administrado (`OCX_SERVICE=1`). Un hermano iniciado junto a un proxy en ejecución no hace ninguna de las dos cosas: sirve solicitudes directas solo en su propio puerto, y Codex, Grok y Claude permanecen apuntando al proxy que ya se estaba ejecutando. Con un `OPENCODEX_HOME` separado, el inicio comprueba el registro de entorno de ejecución del hogar predeterminado y administra Grok y Codex destinos de bucle de retorno para un propietario de opencodex en vivo antes de la sincronización. Una casa personalizada sin propietario en vivo todavía se sincroniza normalmente; `ocx sync` y `ocx grok apply` explícitos permanecen disponibles. Detener a ese hermano con `ocx stop` o una señal también deja su configuración sola. Mientras se ejecuta, el proxy también mantiene Codex apuntado a sí mismo: cuando el enrutamiento opencodex en `~/.codex/config.toml` nombra otro puerto local donde no opencodex ha respondido durante aproximadamente 20 segundos (una instancia que lo volvió a apuntar y luego murió, por ejemplo), el proxy vuelve a apuntar Codex en su propio puerto e imprime una advertencia. Codex hilos abiertos mientras tanto, mantenga la dirección muerta hasta que los vuelva a abrir. +Cuando el inicio se rechaza porque no se puede verificar el propietario del proxy, el error indica el motivo. Para los dos motivos de PID (`pid-probe-failed`, `pid-identity-unverified`) también indica la recuperación: si no hay ningún proxy de OpenCodex en ejecución para este directorio, elimina `runtime-port.json` y `ocx.pid` en `$OPENCODEX_HOME` (`~/.opencodex` si no está definido) y vuelve a iniciar. Un registro escrito por una versión actual guarda la hora de creación del proceso propietario y su espacio de nombres de PID, de modo que en macOS, en Windows y en el espacio de nombres de PID del propio host Linux se reconoce un PID que otro proceso reutiliza después (por ejemplo, tras un reinicio) y el inicio continúa por sí solo. El espacio de nombres de PID propio de un contenedor solo se compara dentro de un mismo arranque: tras un reinicio, un PID reutilizado allí solo se reconoce cuando su línea de comandos legible muestra un programa distinto de OpenCodex, y el inicio sigue rechazándose cuando la línea de comandos no se puede leer o el proceso pertenece a otro usuario; elimina los dos archivos una vez, como se indica arriba. Un registro escrito por 2.100.13 o una versión anterior no tiene espacio de nombres de PID: si su PID se reutiliza, el inicio puede seguir rechazándose hasta que elimines los dos archivos una vez, y el siguiente registro usa el formato nuevo. En Windows la hora de creación procede del identificador del proceso, o de CIM cuando no se puede abrir; la CI ejecuta la ruta del identificador en equipos Windows, y la ruta de CIM no se ha comprobado en un equipo real. + `--socks5` (por defecto `127.0.0.1:10808`) guarda `config.proxy` como una URL de SOCKS5 y las rutas de salida HTTP (S) a través de un túnel real SOCKS5. `--socks5-off` borra solo ese proxy SOCKS5 guardado; no elimina un proxy HTTP. El valor sobrevive `ocx update` porque vive en config, no en el paquete instalado. Se puede incluir un nombre de usuario y una contraseña proxy en la URL, pero los registros de inicio los redactan. ```bash @@ -142,6 +144,8 @@ Si otro programa escucha en el puerto después de que terminen los procesos de e La parada solo finaliza la instancia activa. Los desencadenadores de inicio de sesión y desbloqueo de la tarea siguen habilitados, por lo que el proxy volverá a iniciarse en el siguiente inicio de sesión o desbloqueo; usa `ocx service uninstall` para eliminar el servicio. `ocx service stop`, `ocx service uninstall`, `ocx uninstall` y `ocx service install` usan la misma parada verificada: la desinstalación y la instalación rechazan eliminar o reemplazar la tarea si no se puede demostrar que el servicio está detenido, y la instalación también se detiene si otro programa ocupa el puerto. En Windows en Arm aún no se pueden finalizar los envoltorios, por lo que una parada que lo requiera devuelve `evidence-unreadable`; finaliza el envoltorio manualmente y vuelve a intentarlo. +Durante una instalación del Programador de tareas, el tiempo no utilizado del análisis de procesos puede dar a la CLI hasta cuatro segundos para verificar la tarea registrada y detener sus instancias en ejecución dentro del mismo plazo. + Para una adquisición aprobada por el escritorio, `ocx stop --json` también acepta el conjunto completo de `--expect-*` valores suministrados por `ocx resolve --json`. En Windows, esta parada vigilada puede detener una tarea del Programador de tareas solo cuando su definición registrada, el estado de ejecución y el antepasado de la envoltura demuestren que posee el proxy aprobado. Un servicio WinSW debe probar su ruta binaria instalada y la ascendencia PID del servicio. Después de detener cualquiera de los administradores, el CLI señala el proxy aprobado por separado y verifica que la tarea ya no se esté ejecutando, que no sobreviva ningún envoltorio y que se detenga WinSW. Un proceso `wscript.exe`, `cscript.exe` o `cmd.exe` con una línea de comandos ilegible en la cadena de supervisión del proxy aprobado (o sobrevivir bajo el administrador detenido) deja desconocida la propiedad del envoltorio, por lo que el stop vigilado no puede informar el éxito. La evidencia faltante o ilegible bloquea la parada vigilada. ### `ocx restart` @@ -185,6 +189,8 @@ Recuperación explícita para versiones de desarrollo anteriores que volvieron a Este es un reetiquetado amplio y destructivo: cada hilo de mensaje de usuario etiquetado actualmente `opencodex` se cambia a `openai`, `exec` se normaliza a `cli` y se establece el marcador de evento. Eso incluye la historia legítima de proveedores dedicados. Realice una copia de seguridad del estado y ejecútelo solo cuando se pretenda ese alcance completo. +La comprobación previa se detiene antes de reetiquetar y muestra `history_rollout_uninspectable` si el historial de un hilo solo existe en formato `.jsonl.zst`, si el último registro no termina con un salto de línea o si no se puede determinar el formato de los últimos registros al leer hasta 16 MiB. Conserve los archivos existentes. Este comando no reconstruye el índice de conversaciones de la aplicación móvil. + ### `ocx recover-history --ocx-compaction --yes` Repare un hilo que se compactó a través de un proveedor enrutado antes de reanudarlo a través del Codex nativo. El comando lee el subproceso exacto seleccionado por UUID, guarda una copia de seguridad privada de byte por byte y, a continuación, convierte solo el estado de compactación `ocx1:` / `ocx2:` propiedad de OpenCodeX en un resumen sencillo que el Codex nativo puede reproducir. El contenido cifrado nativo y otros hilos se dejan sin cambios. Cierre el subproceso seleccionado antes de ejecutar el comando; un cambio de implementación concurrente hace que la recuperación se detenga sin reemplazar el archivo. @@ -205,6 +211,8 @@ Ambos comandos no aceptan argumentos. Las banderas no soportadas (incluyendo `-- ### `ocx status [--json]` +El estado y `ocx doctor` también comprueban si `ocx start` sería rechazado porque no se puede verificar la propiedad del proxy, con la misma comprobación de solo lectura que ejecuta el inicio, limitada a un segundo: el estado cuando ningún proxy responde a su comprobación de salud, y el doctor cuando no encuentra ningún proxy activo verificado. En ese caso, la línea del proxy y la sugerencia del doctor muestran el texto del error de inicio con su paso de recuperación, y `--json` informa `proxy.startupRefusal: { reason, message }` (en otro caso `null`). Describe el estado actual, no un fallo anterior; una comprobación que solo agota el tiempo no informa nada, y un cliente conectado no se comprueba. + Estado y `ocx doctor` comparan la versión de este CLI con la del proxy en ejecución. Si el CLI es más nuevo, reinicie el proxy utilizando la instalación actual prevista; para un servicio en segundo plano, ejecute `ocx service restart`. En macOS, un sesgo de versión deja la definición de servicio byte-idéntica, por lo que `ocx service repair` no recargaría nada y mantendría el antiguo proceso en servicio. Si el proxy es más nuevo, actualice el CLI o resuelva `PATH` a la instalación prevista. Estos diagnósticos no reparan el servicio ni cambian si se permiten solicitudes. Las cadenas de versión idénticas y los marcadores de posición `unknown` / `0.0.0` suprimen la advertencia, al igual que una versión proxy ausente. El doctor no reporta marcadores de posición como un partido confirmado. Las diferentes cadenas aún producen una advertencia neutral cuando no pueden analizarse estrictamente como SemVer o difieren solo en los metadatos de compilación; ninguno de los lados se llama más antiguo. Las versiones no se recortan y no se normaliza un `v` principal. JSON expone el mismo consejo en `versionSkew`, cuyos campos permanecen `cliVersion`, `proxyVersion`, `skewed` y `warning`. @@ -639,7 +647,7 @@ el código 1 por sí solo no confirma una denegación de acceso; el texto de acc en la eliminación sigue clasificándose como tal. En Windows, la sintaxis es `ocx service install [--native|--scheduler] [--allow-uac]`. -En una instalación nueva con el Programador de tareas, la CLI intenta registrar la tarea con los permisos actuales. Si se deniega el acceso, ejecute `ocx service install --scheduler` desde PowerShell como administrador, o use `ocx service install --scheduler --allow-uac` para que Windows pueda pedir autorización. Sin la opción, ni el registro ni la limpieza tras un fallo abren un aviso de UAC. Si durante la reversión se intenta eliminar la tarea, la CLI indica si sigue registrada cuando puede verificar el resultado. Si la instalación falla, compruebe `ocx service status` antes de volver a intentarla. La opción solo se admite al ejecutar `service install` con el Programador de tareas. La aprobación y el éxito de la instalación siguen dependiendo de Windows. WinSW (`--native`) y `ocx service repair` conservan sus propios mecanismos de elevación. +En una instalación nueva con el Programador de tareas, la CLI intenta registrar la tarea con los permisos actuales. Si se deniega el acceso, ejecute `ocx service install --scheduler` desde PowerShell como administrador, o use `ocx service install --scheduler --allow-uac` para que Windows pueda pedir autorización. Si el Programador de tareas devuelve el mensaje en coreano `오류: 액세스가 거부되었습니다.`, la CLI muestra esas mismas instrucciones. Sin la opción, ni el registro ni la limpieza tras un fallo abren un aviso de UAC. Si durante la reversión se intenta eliminar la tarea, la CLI indica si sigue registrada cuando puede verificar el resultado. Si la instalación falla, compruebe `ocx service status` antes de volver a intentarla. La opción solo se admite al ejecutar `service install` con el Programador de tareas. La aprobación y el éxito de la instalación siguen dependiendo de Windows. WinSW (`--native`) y `ocx service repair` conservan sus propios mecanismos de elevación. Si la tarea de OpenCodex no existe en el Programador de tareas de Windows, se registra sin `/f`. Si reconoce una denegación de acceso, `ocx service install` la comunica sin abrir un aviso de UAC. Al elegir **Instalar** para el Programador de tareas en el panel, se ejecuta `ocx service install --allow-uac`, que permite a la CLI pedir elevación si Windows deniega el registro. @@ -751,13 +759,13 @@ ocx update --plan --json [--tag latest|preview | --version ] ocx update --yes --json [--version ] [--expect-plan ] [--not-after ] ``` -Plan emite un único objeto JSON `ocx.update.plan/1`: `currentVersion`, `targetVersion`, `installer`, `runtimeOwner`, `servingPath`, `cliPath`, `canApply`, el `reason` opcional, `restartRequired`, `planToken`, `updateInFlight` y `mutationBoundMs`. El plan es de solo lectura. Los motivos son `desktop-app-owned`, `source-checkout`, `mise-managed`, `installer-unknown`, `plan-unavailable`, `serving-install-unknown`, `cli-not-serving-install`, `runtime-ownership-refused`, `target-unresolved`, `downgrade-refused` y `up-to-date`. `desktop-app-owned` dirige la actualización a Desktop; una identidad de ejecución incierta provoca rechazo en vez de adivinar. Ejecuta `ocx start` u `ocx stop` para resolver un registro de ejecución obsoleto antes de volver a planificar. +Plan emite un único objeto JSON `ocx.update.plan/1`: `currentVersion`, `targetVersion`, `installer`, `runtimeOwner`, `servingPath`, `cliPath`, `canApply`, el `reason` opcional, `restartRequired`, `planToken`, `updateInFlight` y `mutationBoundMs`. El plan es de solo lectura. Los motivos son `desktop-app-owned`, `source-checkout`, `mise-managed`, `installer-unknown`, `plan-unavailable`, `serving-install-unknown`, `cli-not-serving-install`, `runtime-ownership-refused`, `target-unresolved`, `downgrade-refused` y `up-to-date`. `desktop-app-owned` dirige la actualización a Desktop; una identidad de ejecución incierta provoca rechazo en vez de adivinar. Una CLI que pertenece a un paquete Debian (el paquete de escritorio para Linux instala `/usr/bin/ocx`) planifica como `installer-unknown`; `ocx update` indica en su lugar cómo actualizar el paquete, lo que requiere root (`sudo apt install ./OpenCodex-VERSION-linux-amd64.deb`), y `ocx link update` en un Home informa de una CLI de Child en `/usr/bin/ocx` como la acción del propietario `deb-managed` con ese comando. Ejecuta `ocx start` u `ocx stop` para resolver un registro de ejecución obsoleto antes de volver a planificar. Apply emite un objeto `ocx.update.result/1` con `applied`, `fromVersion`, `toVersion`, `installer`, `restarted`, `healthy`, `rolledBack` y un `error` opcional. Pasa el `planToken` del plan como `--expect-plan` para rechazar con `plan-changed` si cambia la instalación seleccionada o la identidad de ejecución. `--not-after` es un entero positivo y seguro con la hora Unix en milisegundos; después de ese momento se rechaza la modificación con `deadline-passed`. `mutationBoundMs` es 900000 (15 minutos): excederlo informa de un resultado incierto sin terminar una transacción activa. `updateInFlight` sigue siendo true mientras una actualización pueda modificar archivos, incluso si su estado es indeterminado; una sincronización por sí sola no lo activa. Una sincronización simultánea puede rechazar apply con `sync-in-progress`, y otra actualización, con `update-in-flight`. La aplicación orquestada sale con 0 cuando el resultado está verificado o ya estaba actualizado; con 10 ante un rechazo; con 11 cuando la actualización falló pero se verificó que la versión anterior sigue activa (incluido el runtime cuando corresponde); con 12 cuando el resultado no está verificado o sigue en curso; y con 64 por uso no válido. `rolledBack` solo es verdadero si una reversión real del instalador se realizó y se verificó. Un comando de plan emite su plan con código de salida 0; los campos `canApply` y `reason` describen la elegibilidad. -Las instalaciones independientes compiladas, incluido el paquete de escritorio MSI Windows, se actualizan a través de **Buscar actualizaciones...** en OpenCodex Desktop, con `ocx update --desktop` en una instalación de Desktop para Windows (que verifica el MSI publicado con la clave del actualizador de la aplicación, lo instala sin interfaz y reinicia el proxy que sigue sirviendo la versión anterior; consulta la guía de la aplicación de escritorio), o reinstalando el binario independiente desde [GitHub Lanzamientos](https://github.com/lidge-jun/opencodex/releases). `ocx system update check` reporta `installer: "standalone"`, `canUpdate: false` y `reason: "standalone_install"` con esa guía. `ocx update` sin `--desktop` sale sin éxito con la misma pista; no ejecuta una actualización de gestor de paquetes para el ejecutable compilado. Una comprobación de fuente genuina todavía reporta `installer: "source"` y `reason: "source_checkout"`. +Las instalaciones independientes compiladas, incluido el paquete de escritorio MSI Windows, se actualizan a través de **Buscar actualizaciones...** en OpenCodex Desktop, con `ocx update --desktop` en una instalación de Desktop para Windows (que verifica el MSI publicado con la clave del actualizador de la aplicación, lo instala sin interfaz y reinicia el proxy que sigue sirviendo la versión anterior; consulta la guía de la aplicación de escritorio), o reinstalando el binario independiente desde [GitHub Lanzamientos](https://github.com/lidge-jun/opencodex/releases). `ocx system update check` reporta `installer: "standalone"`, `canUpdate: false` y `reason: "standalone_install"` con esa guía. `ocx update` sin `--desktop` sale sin éxito con la misma pista; no ejecuta una actualización de gestor de paquetes para el ejecutable compilado. Una comprobación de fuente genuina todavía reporta `installer: "source"` y `reason: "source_checkout"`. Cuando un paquete Debian es dueño del ejecutable (el `/usr/bin/ocx` del paquete de escritorio para Linux), ambos indican en su lugar la actualización del paquete (arriba). Si el host ya usa un actualizador externo, por ejemplo un temporizador de systemd que despliega y activa versiones del código fuente en `/opt/opencodex/releases/`, diff --git a/docs-site/src/content/docs/es/reference/client-support.md b/docs-site/src/content/docs/es/reference/client-support.md index d35541a45e4..3edf3f3a270 100644 --- a/docs-site/src/content/docs/es/reference/client-support.md +++ b/docs-site/src/content/docs/es/reference/client-support.md @@ -6,11 +6,11 @@ description: "Qué herramientas de programación conecta opencodex, cómo se con -opencodex es una única pasarela local para tus herramientas de programación con IA y tus modelos. Configura algunas herramientas de forma nativa; para las demás, exporta o administra un archivo de configuración que las dirige al proxy local. Esta página se genera a partir de los registros del código, por lo que enumera exactamente lo que ofrece la versión actual. +opencodex es una única pasarela local para tus herramientas de programación con IA y tus modelos. Puede configurar herramientas de forma nativa, exportar o administrar un archivo de configuración o usar un conector de gateway dedicado. Esta página se genera a partir de los registros del código, por lo que enumera exactamente lo que ofrece la versión actual. ## Niveles de compatibilidad -- **implemented**: el cliente figura en el registro. Para las configuraciones exportadas, el protocolo mostrado se lee de la configuración que genera opencodex, y la generación falla si cambia. Un protocolo marcado como *revisado* indica un endpoint determinado mediante una revisión, en lugar de obtenerse de la propia configuración (clientes nativos y clientes que convierten un ajuste en un endpoint concreto); el generador comprueba que el código revisado siga presente. Las filas «Compatible con OpenAI» no afirman que se use un endpoint concreto. +- **implemented**: el cliente figura en el registro. Para las configuraciones exportadas, el protocolo mostrado se lee de la configuración que genera opencodex, y la generación falla si cambia. Un protocolo marcado como *revisado* se obtiene de una revisión del código, no de una inspección automatizada de la configuración; el generador comprueba que el código revisado siga presente. Las filas «Compatible con OpenAI» no afirman que se use un endpoint concreto. - **test-covered**: cumple implemented y enlaza un caso de prueba elegido durante la revisión que ejercita este cliente. El generador solo comprueba que la prueba siga existiendo y esté habilitada; léela para saber qué verifica. - **Verificado en ejecución**: una observación histórica: una persona ejecutó el producto cliente y la versión exactos que se indican con la versión de opencodex mostrada, en el escenario y la fecha señalados, y enlazó la evidencia. No demuestra nada sobre otras versiones o productos. La evidencia se revisa al añadir el resultado; el generador no vuelve a ejecutar la prueba. Un guion significa que no hay ningún resultado registrado. @@ -47,6 +47,15 @@ opencodex es una única pasarela local para tus herramientas de programación co | Gentle Shell | — | JSON | Sí | Chat Completions | test-covered ([prueba](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | Solo escucha local. | | T3 Code | — | JSON | Sí | Anthropic Messages | test-covered ([prueba](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | Solo escucha local. Antes de aplicar los cambios, se ejecuta una comprobación específica del cliente que puede rechazarlos. | +## Clientes de gateway + +Abre **Enrutamiento → Antigravity** en el panel (también hay un enlace en **Enrutamiento → Clientes**) o ejecuta los comandos de abajo. Estos conectores configuran el gateway del cliente; no exportan configuraciones ni usan el flujo de integración mediante archivo administrado. Para agy, vuelve a cargar el perfil de shell indicado antes de ejecutar la CLI. + +| Cliente | Protocolo de entrada | Nivel de compatibilidad | Verificado en ejecución | Configurar en este equipo | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | Compatible con OpenAI (endpoint elegido por el cliente) (revisado) | test-covered ([prueba](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (revisado) | test-covered ([prueba](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## Endpoints de entrada El proxy acepta estos protocolos. Una herramienta que no figure arriba puede conectarse si permite configurar un endpoint personalizado para alguno de ellos. @@ -54,7 +63,9 @@ El proxy acepta estos protocolos. Una herramienta que no figure arriba puede con - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## Mantener esta página actualizada -Esta página se genera mediante `scripts/generate-client-support-matrix.ts` a partir de los registros de exportación, integración administrada e integración nativa. Para añadir un cliente, añade su entrada en `scripts/client-support-matrix/metadata.ts` y ejecuta `bun run docs:clients`; `bun run docs:clients:check` falla mientras la página guardada en el repositorio esté desactualizada. +Esta página se genera mediante `scripts/generate-client-support-matrix.ts` a partir de los registros de exportación, integración administrada, integración nativa y clientes de gateway. Para añadir un cliente, añade su entrada en `scripts/client-support-matrix/metadata.ts` y ejecuta `bun run docs:clients`; `bun run docs:clients:check` falla mientras la página guardada en el repositorio esté desactualizada. diff --git a/docs-site/src/content/docs/es/reference/configuration/providers.md b/docs-site/src/content/docs/es/reference/configuration/providers.md index b77f5f37067..5b3f5af8113 100644 --- a/docs-site/src/content/docs/es/reference/configuration/providers.md +++ b/docs-site/src/content/docs/es/reference/configuration/providers.md @@ -243,7 +243,7 @@ Los proveedores pueden exponer una abreviatura incorporada, como `agy` para `goo | `chatServiceTier?` | `boolean` | Chat-wire en todo el proveedor opt-in para el reenvío de llamadas `service_tier` valores. En una ruta clasificada gobierna valores extranjeros como `flex`, no canónica propiedad de proxy Fast después de la validación de la capacidad; en una ruta no clasificada gobierna cada valor de llamada porque no se ha validado ninguna capacidad Fast. La capacidad del modelo exacto no autoriza el reenvío extranjero. Responses rutas conservan su comportamiento de reenvío de llamadas basado en la capacidad. | | `promptCacheKey?` | `boolean` | Opción de todo el proveedor `openai-chat` para reenviar `prompt_cache_key`. El adaptador reenvía la clave recibida sin inventarla, aunque no siempre procede del cliente: la conversión de Claude Messages obtiene una a partir de `metadata.user_id` o de un grupo de modelo, sistema y herramientas cuando no hay metadatos. Está desactivada por defecto salvo que lo indique el preajuste. Mistral la habilita según su [contrato de caché de instrucciones](https://docs.mistral.ai/studio/conversations/advanced/prompt-caching); un `false` explícito la desactiva. Habilítala solo si el proveedor documenta compatibilidad, porque una pasarela estricta puede rechazar ese campo con HTTP 400. | | `preserveResponsesReasoningContent?` | `boolean` | Por defecto para los proveedores personalizados. En **Proveedores → Configuración**, habilite **Replay razonamiento de texto plano** para un punto final personalizado Responses solo si acepta este historial. Esto envía un razonamiento previo de texto sin formato a ese punto final y puede aumentar el uso de tokens. Mantenga el contenido de razonamiento de texto plano en los elementos de razonamiento Responses reproducidos en lugar de borrarlo, incluida la entrada compacta nativa personalizada v1 (blanking es la regla del backend ChatGPT). Habilitar para aguas arriba cuyo contrato acepta la repetición de razonamiento, como DeepSeek o un Kimi autoalojado en vLLM. Los sobres `ocxr1` con proxy siempre se eliminan. Un proveedor `openai-responses` configurado manualmente sin él registra una advertencia por host la primera vez que se elimina el razonamiento de texto sin formato. `preserveReasoningContentModels` no afecta a este cable. | -| `preserveResponsesInputItemIds?` | `boolean` | Por defecto. Preservar `input[].id` válido cuando `store: false` para relés de lanzador de confianza explícita que requieren identidad de turno. Responses proveedores ordinarios siguen eliminando las identificaciones; xAI La reparación del ID de llamada personalizada permanece activa. | +| `preserveResponsesInputItemIds?` | `boolean` | Por defecto. Preservar `input[].id` válido cuando `store: false` para relés de lanzador de confianza explícita que requieren identidad de turno. Responses proveedores ordinarios siguen eliminando las identificaciones, salvo la de un `web_search_call` alojado, que una pasarela de búsqueda necesita para emparejar la llamada con sus resultados; xAI La reparación del ID de llamada personalizada permanece activa. | | `preserveResponsesMessageMetadata?` | `boolean` | Por defecto. Preservar `internal_chat_message_metadata_passthrough` privado en elementos de entrada para relés de lanzador de confianza explícita, incluidas las solicitudes compactas nativas personalizadas v1. Esto reenvía metadatos privados de turno/sesión a ese destino; no habilite las puertas de enlace ordinarias. | | `dropResponsesReasoningItems?` | `boolean` | Elimine por completo los elementos Responses `reasoning` reproducidos de la entrada de continuación, incluidas las solicitudes compactas nativas v1 personalizadas, en lugar de reenviarlos con contenido en blanco. Esto es con pérdida: resúmenes, identificadores de ítems y `encrypted_content` van con ellos, por lo que no queda ningún ítem de razonamiento del turno anterior en la entrada reenviada. No elimina `previous_response_id`, por lo que un curso arriba que mantiene su propio estado de giro aún puede alcanzarlo. Habilitar solo para un upstream que rechaza la repetición de razonamiento directamente: el preajuste integrado Volcengine Ark Coding Plan lo establece porque las continuaciones de la herramienta validadas respondieron `400 InvalidParameter` de lo contrario. Establezca a `false` en ese proveedor para reenviar los elementos de razonamiento nuevamente. | | `disabled?` | `boolean` | Mantenga el proveedor en el disco, pero excluya el enrutamiento y los listados de modelos/catálogos. | diff --git a/docs-site/src/content/docs/es/reference/configuration/server.md b/docs-site/src/content/docs/es/reference/configuration/server.md index 73986b0254d..a6dd00f248d 100644 --- a/docs-site/src/content/docs/es/reference/configuration/server.md +++ b/docs-site/src/content/docs/es/reference/configuration/server.md @@ -57,7 +57,7 @@ La configuración del servidor controla la forma en que el proxy local escucha, | `resetCreditAutoRedeem?` | `{ enabled?: boolean; leadTimeMinutes?: number }` | desactivado | Activación explícita: canjear el crédito de restablecimiento más pronto de la cuenta principal Codex `leadTimeMinutes` (1–60, por defecto 10) antes de que expire. Cada intento vuelve a leer la lista de crédito ascendente primero y se salta cuando el crédito se ha ido (por ejemplo, canjeado a mano); `redeem_request_id` Es journalizado en `$OPENCODEX_HOME/reset-credit-auto-redeem.json` antes de la llamada, por lo que un bloqueo reproduce la misma solicitud idempotente en lugar de gastar un segundo crédito. Los servidores que comparten este directorio de configuración coordinan las reservas y liquidaciones para que un proceso no reemplace el registro de solicitud de otro. Los registros solo llevan una clave de cuenta hash. | | `syncResumeHistory?` | `boolean` | `true` | Compatibilidad reversible con el historial de Codex App. Los metadatos originales se respaldan y se restauran mediante `ocx stop` / `ocx restore`. | | `spendPoolAliases?` | `Record` | Sin configurar | Mapa explícito de alias históricos de grupos, calculados con sal, a proveedores canónicos. Mantenga esta clave en el nivel superior, fuera de `spend`. Véase [Continuidad histórica de los grupos](#historical-pool-continuity). | -| `shadowCallIntercept?` | `{ enabled?: boolean; model?: string; sourceModels?: string[] }` | desactivado | Redirige llamadas auxiliares reconocidas de Codex al modelo elegido, conservando su esfuerzo de razonamiento. Los prefijos predeterminados son `gpt-6-luna` y `gpt-5.6-luna`. El panel ofrece un interruptor por origen; las generaciones Terra (`gpt-6.1-terra` y `gpt-5.6-terra`) y el antiguo `gpt-5.4-mini` permanecen desactivados hasta seleccionarlos. Debe quedar al menos un origen activo; desactiva el interruptor principal para detener todas las llamadas de sombra. | +| `shadowCallIntercept?` | `{ enabled?: boolean; model?: string; sourceModels?: string[]; followConversation?: Record }` | desactivado | Redirige llamadas auxiliares reconocidas de Codex al modelo elegido, conservando su esfuerzo de razonamiento. Los prefijos predeterminados son `gpt-6-luna` y `gpt-5.6-luna`. El panel ofrece un interruptor por origen; las generaciones Terra (`gpt-6.1-terra` y `gpt-5.6-terra`) y el antiguo `gpt-5.4-mini` permanecen desactivados hasta seleccionarlos. Debe quedar al menos un origen activo; desactiva el interruptor principal para detener todas las llamadas de sombra. | | `memoryModels?` | `{ extract?: { model: string; reasoningEffort?: string }; consolidation?: { model: string; reasoningEffort?: string } }` | desactivado | Enruta las dos fases de memoria de Codex a un modelo elegido, con un esfuerzo de razonamiento opcional por fase. Véase [Enrutamiento de memoria](#memory-routing). | | `webSearchSidecar?` | `OcxWebSearchSidecarConfig` | activado si está disponible | Opciones del asistente de búsqueda web. | | `visionSidecar?` | `OcxVisionSidecarConfig` | activado si está disponible | Opciones del asistente de descripción de imágenes. | @@ -617,6 +617,9 @@ Este comportamiento está habilitado de forma predeterminada. Se conservan el te En **Tablero → Visión de conjunto → Enrutamiento de compactación**, elija un modelo, que activa que se aplica a, un esfuerzo de razonamiento opcional, y si la anulación cubre todos los modelos de origen o sólo fuentes seleccionadas. Para las fuentes seleccionadas, compruebe los modelos individuales o las entradas `provider/*` de todo el proveedor y, a continuación, haga clic en **Guardar**. Seleccione **Usar el modelo de conversación** y guarde para eliminar la anulación. Los cambios se aplican a la siguiente solicitud de compactación sin reiniciar el proxy. +Para personalizar solo los resúmenes que genera OpenCodex, complete **Instrucciones adicionales para el resumen** o configure la cadena `compactionAdditionalInstructions` de nivel superior en `config.json` (hasta 8192 caracteres). +**Mostrar los prompts de compactación integrados** muestra el prompt estándar y la variante de Anthropic que conserva el prefijo de caché. Se aplica a los resúmenes automáticos y manuales generados por OpenCodex, con o sin un modelo de compactación alternativo. No modifica la compactación nativa ni los puntos de control locales creados por el cliente. Si deja el campo vacío o solo con espacios, el prompt original no cambia. El texto adicional se envía al proveedor que genera el resumen; no incluya secretos. + Establecer `compactionRouting` en OpenCodex `config.json` para anular las solicitudes de compactación del modelo Codex. La configuración está desactivada cuando se omite. ```json @@ -729,6 +732,57 @@ Los ids de modelo sin proveedor que coincidan son elegibles para interceptación } ``` + + +### Usar un combo de conmutación por error como objetivo de sombra + +Para que las llamadas auxiliares interceptadas tengan un respaldo, crea un combo `failover` con tu +ruta preferida en primer lugar. Por ejemplo, si tienes configuradas rutas de suscripción de OpenAI y +Anthropic, crea el combo y selecciónalo como objetivo de sombra con el prefijo `combo/`. Sustituye +los ID de modelo por los de tu configuración. + +```sh +ocx combo set title-helpers --strategy failover --targets "openai/gpt-5.6-sol,anthropic/claude-haiku-5-5" --quota-only-fallback on +ocx models shadow set combo/title-helpers --enabled on +``` + +En este ejemplo, el combo solo prueba el siguiente objetivo elegible si se confirma el agotamiento +de cuota o facturación antes de que empiece la salida. Si el proveedor aplica un límite de frecuencia +temporal a una solicitud, el cliente recibe ese error. Si el primer objetivo sigue en enfriamiento por +un límite temporal, el combo devuelve `503 Service Unavailable` sin contactar con ningún objetivo. +Configura `--quota-only-fallback off` en el combo para permitir la conmutación ante otros fallos +reintentables antes de que empiece la salida. + +Consulta [Combos](/es/guides/combos/) para la elegibilidad de los objetivos y el +[consentimiento de fallback medido](/es/guides/combos/#metered-fallback-consent). + +### Seguir al proveedor de la conversación + +`followConversation` asigna un modelo auxiliar a cada id de proveedor. Con este mapa, una llamada +auxiliar interceptada va al modelo asignado al proveedor al que se enrutó el último turno ordinario de la +misma conversación de Codex, identificada por las cabeceras `thread-id` y `session-id`. Un turno +fija el proveedor en cuanto se enruta, así que un turno que luego falla o se cancela también lo cambia. Cada +hilo de subagente guarda su propio registro, así que un turno de un subagente en otro proveedor no cambia +el proveedor que siguen las llamadas auxiliares de su padre. Una +conversación desconocida, un proveedor sin asignación o un modelo asignado que no se resuelve usan +`model` como antes, incluido el rechazo `intercept_target_unavailable`. El registro vive solo en +memoria, guarda como máximo 2048 conversaciones y empieza vacío tras un reinicio. La ruta registra el +motivo `shadow-follow-conversation`. Configúralo con `PUT /api/shadow-call-settings`, +`ocx models shadow set --follow-conversation ` o en la página Modelos. Asignar `openai` a `gpt-6-luna` deja nativas las llamadas auxiliares de esa conversación. + +```json +{ + "shadowCallIntercept": { + "enabled": true, + "model": "gpt-5.5", + "followConversation": { + "anthropic": "anthropic/claude-haiku-5-5", + "openai": "gpt-6-luna" + } + } +} +``` + ### Cuando el objetivo no está disponible diff --git a/docs-site/src/content/docs/es/reference/management-api.md b/docs-site/src/content/docs/es/reference/management-api.md index b7c3c246240..6dad956dd8f 100644 --- a/docs-site/src/content/docs/es/reference/management-api.md +++ b/docs-site/src/content/docs/es/reference/management-api.md @@ -264,7 +264,7 @@ Vea [Codex capas de solicitud](/es/guides/codex-prompt/) para el modelo de capa | `POST /api/update/run` | Comprobar de forma asíncrona una versión nueva e iniciar su actualización, opcionalmente seguida de reinicio | 400 cuerpo inválido; 409 `update_restart_unsupervised` si el proxy se ejecuta dentro de una unidad systemd distinta del servicio de usuario de OpenCodex, o el proceso de actualización no puede salir de su cgroup (con o sin reinicio, porque la actualización detiene primero el proxy); otros estados de conflicto o error del trabajo | | `GET /api/update/status` | Consultar periódicamente un trabajo de actualización por su id | 404 trabajo desconocido | | `GET, PUT /api/sidecar-settings` | Lea o actualice la configuración del modelo/backend del sidecar de la visión y la búsqueda web | 400 forma inválida, backend o límite | -| `GET, PUT /api/shadow-call-settings` | Leer o actualizar la interceptación de llamadas de sombra, incluido `sourceModels`; GET también devuelve el inventario `sourceModelOptions` del entorno | 400 forma o valor inválido, incluidos prefijos vacíos, duplicados, con espacios o proveedor, más de 32 prefijos o más de 128 caracteres por prefijo; los fallos de lista llevan `code: shadow_call_source_invalid` y los conflictos de destino `code: shadow_call_target_invalid` | +| `GET, PUT /api/shadow-call-settings` | Leer o actualizar la interceptación de llamadas de sombra, incluidos `sourceModels` y el mapa proveedor → modelo auxiliar `followConversation` (`null` lo borra); GET también devuelve el inventario `sourceModelOptions` del entorno | 400 forma o valor inválido, incluidos prefijos vacíos, duplicados, con espacios o proveedor, más de 32 prefijos o más de 128 caracteres por prefijo; los fallos de lista llevan `code: shadow_call_source_invalid` y los conflictos de destino `code: shadow_call_target_invalid`, y una entrada `followConversation` inválida `code: shadow_call_follow_invalid` | diff --git a/docs-site/src/content/docs/es/reference/proxy-formats.md b/docs-site/src/content/docs/es/reference/proxy-formats.md index 10e51751879..198731096ac 100644 --- a/docs-site/src/content/docs/es/reference/proxy-formats.md +++ b/docs-site/src/content/docs/es/reference/proxy-formats.md @@ -488,7 +488,7 @@ Los clientes de Gemini, como el SDK google-genai con una URL base personalizada, - `:generateContent` y `:streamGenerateContent`, bajo `/v1beta/models/` o `/v1/models/`, traducen `contents`, `systemInstruction`, imágenes en línea, declaraciones y llamadas de funciones, y `generationConfig`. Las firmas de pensamiento de las partes `functionCall` viajan en ambos sentidos. Con `alt=sse` el flujo es SSE; sin él la respuesta es un único array JSON, como lo envía la API REST de Google. Las herramientas alojadas de Gemini se ignoran. Un `candidateCount` distinto de 1, datos en línea que no son imágenes y partes de archivo se rechazan con 400. - `:countTokens` devuelve `{ "totalTokens": n }` a partir de una estimación local y no envía nada al proveedor. `:embedContent` y `:batchEmbedContents` responden 501. - `POST /v1beta/interactions`, o `POST /v1/interactions`, crea una interacción a partir de `input` (texto, imágenes base64 o pasos que incluyen `function_call` y `function_result`), `system_instruction`, herramientas `function`, `generation_config` y un `response_format` de texto. Un flujo usa los eventos de Interactions `interaction.created`, `step.start`, `step.delta`, `step.stop` e `interaction.completed`. Un turno que termina en llamadas de funciones tiene el estado `requires_action`. Los campos que el proxy no puede respetar se rechazan con 400: `agent`, `background: true`, `webhook_config`, `environment`, `agent_config`, `safety_settings`, herramientas alojadas, contenido de entrada que no sea texto ni imagen, y salida que no sea texto. El proveedor seleccionado aplica su propia política de seguridad. -- `previous_interaction_id` continúa una interacción guardada. El proxy guarda las interacciones solo en memoria, como máximo 24 horas desde la última escritura, y solo la clave que creó una puede leerla, continuarla o borrarla; los llamantes de loopback sin clave comparten un único propietario. La retención no está garantizada: cada clave guarda como máximo 200 interacciones y 16 MiB, el proxy guarda como máximo 1.000 y 64 MiB en total, y el presupuesto de memoria del proxy puede eliminarlas antes. Las claves hacen espacio eliminando únicamente sus propias interacciones más antiguas. Una escritura de loopback sin clave solo hace espacio eliminando turnos anteriores de la conversación que continúa, por lo que las demás conversaciones sin clave se conservan; si eso no basta para respetar el límite compartido o global, el proxy devuelve la respuesta sin guardar la nueva interacción. En el límite global, una clave que no tiene nada propio con lo que hacer espacio recibe igualmente su respuesta sin que la interacción se guarde, y lo mismo ocurre con una interacción mayor que 8 MiB o que el límite de cuerpo de entrada configurado, el que sea menor. Una respuesta no transmitida en flujo indica si se guardó en `x-opencodex-interaction-stored: true|false`. Un reinicio las olvida todas, y un id que falta o caducó responde 404, así que el cliente debe conservar su historial para reenviarlo. Una solicitud con `store: false` no se guarda. `GET /v1beta/interactions/{id}` devuelve una interacción guardada, `DELETE` la elimina y `POST /v1beta/interactions/{id}/cancel` responde 400 porque nada se ejecuta en segundo plano. Ambos alias de Interactions devuelven `Cache-Control: no-store`. +- `previous_interaction_id` continúa una interacción guardada. El proxy guarda las interacciones solo en memoria, como máximo 24 horas desde la última escritura, y solo la clave que creó una puede leerla, continuarla o borrarla; los llamantes de loopback sin clave comparten un único propietario. La retención no está garantizada: cada clave guarda como máximo 200 interacciones y 16 MiB, el proxy guarda como máximo 1.000 y 64 MiB en total, y el presupuesto de memoria del proxy puede eliminarlas antes. Las claves hacen espacio eliminando únicamente sus propias interacciones más antiguas. Una escritura de loopback sin clave solo puede eliminar la interacción indicada por `previous_interaction_id` y los turnos anteriores de esa rama que aún estén guardados. Los identificadores exclusivos de otras ramas y los de otras conversaciones siguen disponibles. Si las interacciones que se pueden eliminar no bastan para respetar ambos límites, el proxy devuelve la respuesta sin guardar la nueva interacción y conserva todas las que siguen vigentes. Esto se aplica a las escrituras con y sin clave. El proxy tampoco guarda una interacción que supere el menor de estos dos límites, 8 MiB o el límite de cuerpo de entrada configurado. Una respuesta no transmitida en flujo indica si se guardó en `x-opencodex-interaction-stored: true|false`. Un reinicio las olvida todas, y un id que falta o caducó responde 404, así que el cliente debe conservar su historial para reenviarlo. Una solicitud con `store: false` no se guarda. `GET /v1beta/interactions/{id}` devuelve una interacción guardada, `DELETE` la elimina y `POST /v1beta/interactions/{id}/cancel` responde 400 porque nada se ejecuta en segundo plano. Ambos alias de Interactions devuelven `Cache-Control: no-store`. ## `POST /v1/live` y banda lateral en tiempo real diff --git a/docs-site/src/content/docs/es/troubleshooting/update-failed.md b/docs-site/src/content/docs/es/troubleshooting/update-failed.md index 05a6e559af3..6c79e803fce 100644 --- a/docs-site/src/content/docs/es/troubleshooting/update-failed.md +++ b/docs-site/src/content/docs/es/troubleshooting/update-failed.md @@ -27,7 +27,8 @@ ocx --version ocx status ``` -El trabajo del panel de control solo registra el estado de salida, ya que la propia salida del instalador puede contener rutas locales. La ejecución de `ocx update` en un terminal muestra el paso que falló y el siguiente paso a tomar. +En instalaciones de Windows con npm o pnpm, el panel puede indicar por qué se detuvo la actualización antes de reemplazar el paquete. El servicio puede informar que se denegó el acceso, que no se pudo leer su estado o el de un proceso, que no se pudo verificar el propietario del proceso de servicio o que faltó tiempo para confirmar la parada. Ejecuta `ocx stop` con la misma cuenta de Windows. Cuando confirme la parada, ejecuta `ocx update`. +Para otros fallos, ejecuta `ocx update` en un terminal para ver los detalles. El panel oculta la salida original del instalador porque puede contener rutas locales. diff --git a/docs-site/src/content/docs/es/troubleshooting/windows-loopback-startup.md b/docs-site/src/content/docs/es/troubleshooting/windows-loopback-startup.md index 699276e8ad8..385f955937c 100644 --- a/docs-site/src/content/docs/es/troubleshooting/windows-loopback-startup.md +++ b/docs-site/src/content/docs/es/troubleshooting/windows-loopback-startup.md @@ -30,6 +30,20 @@ el proxy. Si persiste el conflicto, comprueba qué proceso controla el puerto indicado y vuelve a intentarlo cuando se haya detenido o recuperado. Conserva el registro del PID y el diario de recuperación para la próxima comprobación. +Si al ejecutar `ocx service install --scheduler` se agota el plazo para +consultar la lista de procesos o finalizar la tarea, el mensaje indica cuánto +tiempo se concedió a la operación. Esto puede ocurrir mientras se inicia +Windows PowerShell o mientras Windows comprueba a quién pertenecen los procesos. +Si Windows deniega el acceso, OpenCodex muestra un mensaje distinto. Antes de +cambiar los permisos, comprueba qué operación falló y qué cuenta de Windows +ejecutó el instalador. + +Algunas imágenes de Windows omiten el componente opcional VBScript. En esas +imágenes, una instalación nueva del servicio con el Programador de tareas usa +un lanzador JScript para ejecutar el mismo script del servicio con la ventana +oculta. El servicio se ejecuta con los permisos del usuario que ha iniciado +sesión. Se necesitan Windows Script Host y el motor JScript. + Si el error incluye `pid-probe-failed`, Windows puede haber reutilizado el PID registrado para un proceso que OpenCodex no puede consultar. Un puerto cerrado no demuestra la identidad del proceso. No termines un proceso solo diff --git a/docs-site/src/content/docs/fr/reference/cli/lifecycle.md b/docs-site/src/content/docs/fr/reference/cli/lifecycle.md index 24a67794a74..f3f1805ce77 100644 --- a/docs-site/src/content/docs/fr/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/fr/reference/cli/lifecycle.md @@ -85,6 +85,8 @@ Récupération explicite destinée aux anciennes versions de développement qui Il s'agit d'un réétiquetage large et destructif : chaque fil contenant un message utilisateur et actuellement marqué `opencodex` passe à `openai`, `exec` est normalisé en `cli` et l'indicateur d'événement est activé. L'historique légitime d'un fournisseur dédié est également concerné. Sauvegardez l'état et n'exécutez la commande que si vous souhaitez cette portée complète. +La vérification préalable s’arrête avant le réétiquetage et signale `history_rollout_uninspectable` si l’historique d’un fil n’existe qu’au format `.jsonl.zst`, si le dernier enregistrement ne se termine pas par un saut de ligne ou si la lecture des 16 derniers Mio ne permet pas de déterminer le format des derniers enregistrements. Conservez les fichiers en place. Cette commande ne reconstruit pas l’index des conversations de l’application mobile. + ### `ocx recover-history --ocx-compaction --yes` Réparez l'historique d'une tâche compactée par un fournisseur routé avant de la reprendre avec Codex natif. La commande sélectionne exactement une tâche par UUID, enregistre d'abord une sauvegarde privée octet par octet, puis convertit uniquement l'état de compaction `ocx1:`/`ocx2:` propre à OpenCodeX en résumé ordinaire relisible par Codex natif. Le contenu chiffré natif et les autres tâches restent inchangés. Fermez la tâche sélectionnée avant d'exécuter la commande ; toute modification simultanée du rollout interrompt la récupération sans remplacer le fichier. diff --git a/docs-site/src/content/docs/fr/reference/client-support.md b/docs-site/src/content/docs/fr/reference/client-support.md index c78d42b7da7..2fed2951cfb 100644 --- a/docs-site/src/content/docs/fr/reference/client-support.md +++ b/docs-site/src/content/docs/fr/reference/client-support.md @@ -6,11 +6,11 @@ description: "Les outils de code auxquels opencodex se connecte, la façon dont -opencodex est une passerelle locale unique pour vos outils de code IA et vos modèles. Il configure certains outils nativement ; pour les autres, il exporte ou gère un fichier de configuration qui dirige l’outil vers le proxy local. Cette page est générée à partir des registres du code et reflète donc exactement ce que fournit la version actuelle. +opencodex est une passerelle locale unique pour vos outils de code IA et vos modèles. Il peut configurer un outil nativement, exporter ou gérer un fichier de configuration, ou utiliser un connecteur de passerelle dédié. Cette page est générée à partir des registres du code et reflète donc exactement ce que fournit la version actuelle. ## Niveaux de prise en charge -- **implemented**: le client figure dans le registre. Pour les configurations exportées, le protocole indiqué est lu dans la configuration générée par opencodex, et la génération échoue s’il change. Un protocole marqué *revu* désigne un point de terminaison issu d’une revue plutôt que de la configuration elle-même (clients natifs, et clients qui déduisent un point de terminaison précis d’un réglage) ; le générateur vérifie que le code revu est toujours en place. Les lignes « Compatible OpenAI » n’affirment aucun point de terminaison. +- **implemented**: le client figure dans le registre. Pour les configurations exportées, le protocole indiqué est lu dans la configuration générée par opencodex, et la génération échoue s’il change. Un protocole marqué *revu* est établi par une revue de code, et non par une inspection automatisée de la configuration ; le générateur vérifie que le code revu est toujours en place. Les lignes « Compatible OpenAI » n’affirment aucun point de terminaison. - **test-covered**: implemented, et un cas de test choisi en revue qui exerce ce client est lié. Le générateur vérifie seulement que le test existe toujours et qu’il est actif ; lisez-le pour savoir ce qu’il vérifie. - **Vérifié à l’exécution**: une observation datée : une personne a exécuté le produit et la version du client indiqués avec la version d’opencodex indiquée, pour le scénario décrit, à cette date, et a lié la preuve. Cela ne dit rien des autres versions ou produits. La preuve est revue lors de l’ajout du résultat ; le générateur ne la rejoue pas. Un tiret signifie qu’aucun résultat n’est enregistré. @@ -47,6 +47,15 @@ opencodex est une passerelle locale unique pour vos outils de code IA et vos mod | Gentle Shell | — | JSON | Oui | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | Écoute locale uniquement. | | T3 Code | — | JSON | Oui | Anthropic Messages | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | Écoute locale uniquement. L’application exécute d’abord une vérification propre au client et peut refuser. | +## Clients de passerelle + +Ouvrez **Routage → Antigravity** dans le tableau de bord (également accessible depuis **Routage → Clients**) ou exécutez les commandes ci-dessous. Ces connecteurs configurent la passerelle du client ; ils n’exportent pas de configuration et n’utilisent pas le flux d’intégration de fichiers gérés. Pour agy, rechargez le profil de shell indiqué avant de lancer la CLI. + +| Client | Protocole entrant | Niveau | Vérifié à l’exécution | Configurer sur cette machine | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | Compatible OpenAI (point de terminaison choisi par le client) (revu) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (revu) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## Points de terminaison entrants Le proxy accepte ces protocoles. Un outil absent de la liste peut quand même se connecter s’il permet de définir un point de terminaison personnalisé pour l’un d’eux. @@ -54,7 +63,9 @@ Le proxy accepte ces protocoles. Un outil absent de la liste peut quand même se - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## Tenir cette page à jour -Cette page est générée par `scripts/generate-client-support-matrix.ts` à partir des registres d’export, d’intégration gérée et d’intégration native. Pour ajouter un client, ajoutez son entrée dans `scripts/client-support-matrix/metadata.ts` puis lancez `bun run docs:clients` ; `bun run docs:clients:check` échoue tant que la page validée est obsolète. +Cette page est générée par `scripts/generate-client-support-matrix.ts` à partir des registres d’export, d’intégration gérée, d’intégration native et de clients de passerelle. Pour ajouter un client, ajoutez son entrée dans `scripts/client-support-matrix/metadata.ts` puis lancez `bun run docs:clients` ; `bun run docs:clients:check` échoue tant que la page validée est obsolète. diff --git a/docs-site/src/content/docs/guides/chatgpt-desktop.md b/docs-site/src/content/docs/guides/chatgpt-desktop.md index 8f195bfa829..ea824b0703e 100644 --- a/docs-site/src/content/docs/guides/chatgpt-desktop.md +++ b/docs-site/src/content/docs/guides/chatgpt-desktop.md @@ -51,8 +51,13 @@ are eligible. Plain `rate_limit_reached` markers are cleared; known quota gate flags (`allowed`, `limit_reached` / `limitReached`, `ordinaryUsageAllowed`) are opened only with plain-quota evidence (a cleared plain reached type or a window at 100%). A flag closed for a reason the payload does not show stays closed. Workspace, -credit, unknown reached-type and spend-control -restrictions keep the usage gate closed. +unknown reached-type and spend-control +restrictions keep the usage gate closed. With +`chatgptDesktop.spendCredits: true` the credit variants +(`workspace_member_credits_depleted`, `workspace_owner_usage_limit_reached`) are +lifted like the plain quota, so the desktop can draw on credits when the +subscription quota is exhausted — credits are billed by OpenAI, and the default +keeps a credit-limited composer locked. Displayed usage stays honest: percentages, reset times, window durations, plan information and other display fields stay as received. Unrelated JSON-RPC diff --git a/docs-site/src/content/docs/guides/codex-integration.md b/docs-site/src/content/docs/guides/codex-integration.md index 0e1f2d423d0..c3da2ba6b04 100644 --- a/docs-site/src/content/docs/guides/codex-integration.md +++ b/docs-site/src/content/docs/guides/codex-integration.md @@ -1618,6 +1618,9 @@ and lacks its own injected-state hash, automatic journal recovery and native res without changing either file or the journal. The saved original remains available for comparison; review it alongside the current files before choosing a manual recovery action. +Run `ocx doctor` on the affected host, even with the proxy stopped. **Codex recovery journal** compares each file with its saved original, reports whether its injected hash was recorded, and names unreadable files without printing their contents. +Keep the files and journal. A local routing URL alone cannot establish which settings OpenCodex wrote. + Files already equal to their saved originals are accepted without rewriting them. A missing file is distinct from an empty file. Verified injected hashes still allow normal snapshot restoration, and later edits in hash-backed configurations retain the existing owned-field cleanup behavior. @@ -1627,7 +1630,6 @@ does not match the pre-injection baseline. This prevents a new injection hash fr to an older original. A genuinely native configuration can be saved as a fresh baseline before injection. Explicit external-provider opt-out behavior is unchanged. - ### Sub-agent fallback and V2 compatibility In **Subagents → Delegation settings**, edit the ordered fallback chain and its availability polling interval (5000–600000 ms), then save it separately from the featured roster. A configured target that is no longer advertised remains in the chain until you remove it. The roster and fallback chain are separate settings; this editor does not make the roster replace the fallback policy. diff --git a/docs-site/src/content/docs/guides/combos.md b/docs-site/src/content/docs/guides/combos.md index ffb08a4bf21..c3d58636b7b 100644 --- a/docs-site/src/content/docs/guides/combos.md +++ b/docs-site/src/content/docs/guides/combos.md @@ -1195,6 +1195,11 @@ the target list: without `--strategy` the stored strategy and its JEV settings s model alias and a non-empty display name. `create` and `update` are aliases for `set`; `delete` is an alias for `remove`; and the same subcommands are available under `ocx route combo`. +On proxies that support combo revisions, `set` reports a conflict if the source combo changes +before an edit or rename is saved, or if the rename destination is already in use. +The command exits with code 5. Run `ocx combo list --json` to review the current combos +before retrying. + ### Management API Headless clients use `GET`, `PUT`, and `DELETE` on `/api/combos`. `GET` lists normalized combo diff --git a/docs-site/src/content/docs/guides/integrations.md b/docs-site/src/content/docs/guides/integrations.md index fed917bedfe..93a2d32b3f9 100644 --- a/docs-site/src/content/docs/guides/integrations.md +++ b/docs-site/src/content/docs/guides/integrations.md @@ -1238,7 +1238,7 @@ Google's Antigravity desktop app (2.15 and newer) and the `agy` CLI (1.2.15 and OpenCodex's gateway. Connect from the dashboard, or from a terminal: ```bash -ocx connect antigravity --model # desktop app: ~/.antigravity/settings.json +ocx connect antigravity --model # configure both desktop app settings files ocx connect agy # agy CLI: a marked shell function in your profiles ocx connect antigravity status # or: ocx connect agy status ocx disconnect antigravity # or: ocx disconnect agy @@ -1246,6 +1246,18 @@ ocx disconnect antigravity # or: ocx disconnect agy Use `--model` only with `ocx connect antigravity` to set the desktop app's default model. +Antigravity 2.15–2.29 reads only `~/.antigravity/settings.json`. Version 2.30 and newer reads only +`~/.gemini/config/config.json`. App upgrades leave the gateway configuration at its existing path. +OpenCodex writes both files for fresh installs, upgrades and downgrades without detecting the app +version. It checks both files before writing either one. + +Status lists `~/.gemini/config/config.json` first and `~/.antigravity/settings.json` second. +It reports `connected` only when both match the OpenCodex gateway. Incomplete wiring is `drifted`. + +OpenCodex accepts older single-file Antigravity restore records. Reconnect preserves the original +legacy restore data and adds a record for the modern file. Disconnect checks and restores only recorded files, +restoring each independently. Partial write or restore failures keep the recovery data needed for a retry. + Connect records what it replaced. Disconnect puts the original bytes back when the file is unchanged, and otherwise reverts only OpenCodex's own entries and keeps your other edits. Antigravity can restore settings after JSON keys are reordered and keeps the file and restore record when a managed setting conflicts. @@ -1254,8 +1266,10 @@ retry. If OpenCodex reports `agy-profile-restore-required`, open the shell profi Restore the complete `agy` block from a copy, including both marker lines and the function between them, then retry disconnect or uninstall. OpenCodex removes the whole block and keeps edits outside it. You can also restore the saved original profile, which replaces any later edits. An `agy` profile symlink must resolve -to another supported profile for the same shell family under your home. Antigravity settings must resolve -to the exact `~/.antigravity/settings.json` path. Restart Antigravity, or open a new terminal for `agy`, +to another supported profile for the same shell family under your home. Each Antigravity settings file +must resolve to its own exact path under your canonical home. The parent directories must resolve to +`.gemini/config` for the modern file and `.antigravity` for the legacy file. +Restart Antigravity, or open a new terminal for `agy`, to apply a change. During disconnect, `agy` skips profiles without a restore record if they cannot be resolved or read. `ocx uninstall` disconnects clients with saved restore records before removing configuration. If a client cannot be restored, uninstall stops and keeps its record. diff --git a/docs-site/src/content/docs/ja/reference/cli/lifecycle.md b/docs-site/src/content/docs/ja/reference/cli/lifecycle.md index 88442c08a12..a42d736caa1 100644 --- a/docs-site/src/content/docs/ja/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ja/reference/cli/lifecycle.md @@ -75,6 +75,8 @@ ocx eject back これは広範囲で破壊的な再ラベル付けです。ユーザーメッセージを持ち、現在 `opencodex` とタグ付けされているすべてのスレッドを `openai` に変更し、`exec` を `cli` に正規化してイベントマーカーを設定します。正当な専用プロバイダー履歴も対象です。状態をバックアップし、この全範囲を意図する場合にのみ実行してください。 +スレッドの履歴が `.jsonl.zst` 形式でしか残っていない場合、最後のレコードの末尾に改行がない場合、または末尾から最大 16 MiB を読み取ってもレコードの形式を判定できない場合は、事前チェックで `history_rollout_uninspectable` が表示され、ラベルを変更する前に処理が停止します。既存のファイルはそのままにしてください。このコマンドはモバイルアプリの会話インデックスを再構築しません。 + ### `ocx recover-history --ocx-compaction --yes` ルーティングされたプロバイダーで圧縮されたタスクをネイティブ Codex で再開する前に、その履歴を修復します。このコマンドは UUID で 1 つのタスクだけを選択し、非公開のバイト単位バックアップを保存してから、OpenCodeX 所有の `ocx1:`/`ocx2:` 圧縮状態だけをネイティブ Codex が再生できる通常の要約に変換します。ネイティブの暗号化コンテンツと他のタスクは変更しません。実行前に対象タスクを閉じてください。処理中に rollout が変更された場合、ファイルを置き換えずに修復を中止します。 diff --git a/docs-site/src/content/docs/ja/reference/client-support.md b/docs-site/src/content/docs/ja/reference/client-support.md index fc92aed9064..3dfa580c08f 100644 --- a/docs-site/src/content/docs/ja/reference/client-support.md +++ b/docs-site/src/content/docs/ja/reference/client-support.md @@ -6,11 +6,11 @@ description: "opencodex が接続するコーディングツール、それぞ -opencodex は、AI コーディングツールとモデルをつなぐ 1 つのローカルゲートウェイです。一部のツールはネイティブに設定し、それ以外はローカルプロキシを指す設定ファイルをエクスポートまたは管理します。このページはコードのレジストリから生成されるため、現在のリリースの内容と正確に一致します。 +opencodex は、AI コーディングツールとモデルをつなぐ 1 つのローカルゲートウェイです。ツールをネイティブに設定するほか、設定ファイルをエクスポートまたは管理したり、専用のゲートウェイコネクターを使用したりできます。このページはコードのレジストリから生成されるため、現在のリリースの内容と正確に一致します。 ## サポートレベル -- **implemented**: レジストリに登録されたクライアントです。エクスポートされる設定では、表のプロトコルは opencodex が生成する設定から読み取られ、変わると生成が失敗します。*レビュー済み*は、エンドポイントが設定そのものではなくレビューに基づくことを示します(ネイティブクライアントと、設定を特定のエンドポイントに変換するクライアント)。レビューしたコードが残っているかを生成時に確認します。「OpenAI 互換」の行は特定のエンドポイントを主張しません。 +- **implemented**: レジストリに登録されたクライアントです。エクスポートされる設定では、表のプロトコルは opencodex が生成する設定から読み取られ、変わると生成が失敗します。*レビュー済み*は、設定の自動検査ではなくコードレビューで確認したプロトコルです。レビューしたコードが残っているかを生成時に確認します。「OpenAI 互換」の行は特定のエンドポイントを主張しません。 - **test-covered**: implemented であり、レビューで選んだこのクライアントのテストケースへのリンクがあります。生成時に確認するのはテストが存在し無効化されていないことだけです。何を検証しているかはテストを読んでください。 - **実行確認**: ある時点の観察記録です。表のクライアント製品・バージョンを表の opencodex バージョンで、記載のシナリオにより、その日付に人が実行し、証拠をリンクしました。ほかのバージョンや製品については何も示しません。証拠は結果の追加時にレビューされ、生成時に再実行はされません。ダッシュは記録がないことを示します。 @@ -47,6 +47,15 @@ opencodex は、AI コーディングツールとモデルをつなぐ 1 つの | Gentle Shell | — | JSON | はい | Chat Completions | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | ローカルリスナーのみ。 | | T3 Code | — | JSON | はい | Anthropic Messages | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | ローカルリスナーのみ。適用前にクライアント固有のチェックを実行し、拒否することがあります。 | +## ゲートウェイクライアント + +ダッシュボードで **ルート → Antigravity** を開くか(**ルート → クライアント** からも移動できます)、以下のコマンドを実行します。各コネクターはクライアントのゲートウェイを設定します。設定のエクスポートや管理対象ファイル連携は使用しません。agy CLI を起動する前に、案内されたシェルプロファイルを再読み込みしてください。 + +| クライアント | 受信プロトコル | サポートレベル | 実行確認 | このマシンでセットアップ | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | OpenAI 互換(エンドポイントはクライアントが選択) (レビュー済み) | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (レビュー済み) | test-covered ([テスト](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## 受信エンドポイント プロキシは次のプロトコルを受け付けます。上の表にないツールでも、いずれかのカスタムエンドポイントを設定できれば接続できます。 @@ -54,7 +63,9 @@ opencodex は、AI コーディングツールとモデルをつなぐ 1 つの - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## このページを最新に保つ -このページは `scripts/generate-client-support-matrix.ts` がエクスポート・管理連携・ネイティブ連携のレジストリから生成します。クライアントを追加するには `scripts/client-support-matrix/metadata.ts` にエントリを追加し、`bun run docs:clients` を実行してください。コミット済みのページが古いと `bun run docs:clients:check` が失敗します。 +このページは `scripts/generate-client-support-matrix.ts` がエクスポート・管理連携・ネイティブ連携・ゲートウェイクライアントのレジストリから生成します。クライアントを追加するには `scripts/client-support-matrix/metadata.ts` にエントリを追加し、`bun run docs:clients` を実行してください。コミット済みのページが古いと `bun run docs:clients:check` が失敗します。 diff --git a/docs-site/src/content/docs/ko/reference/cli/lifecycle.md b/docs-site/src/content/docs/ko/reference/cli/lifecycle.md index e06228ebc3f..dc793f3aca0 100644 --- a/docs-site/src/content/docs/ko/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ko/reference/cli/lifecycle.md @@ -118,6 +118,8 @@ ocx eject back thread를 `openai`로 바꾸고, `exec`를 `cli`로 정규화하며 event marker를 설정합니다. 정상적인 dedicated-provider history도 포함됩니다. 상태를 백업하고 이 전체 범위를 의도한 경우에만 실행하세요. +스레드 기록이 `.jsonl.zst`로만 남아 있거나, 마지막 레코드 끝에 줄바꿈이 없거나, 파일 끝에서 최대 16 MiB를 읽어도 마지막 레코드의 형식을 판별할 수 없으면, 사전 검사에서 `history_rollout_uninspectable`을 표시하고 태그를 바꾸기 전에 중단합니다. 기존 파일은 그대로 두세요. 이 명령으로 모바일 앱의 대화 색인을 다시 만들 수는 없습니다. + ### `ocx recover-history --ocx-compaction --yes` 라우팅된 provider를 통해 압축된 작업을 native Codex에서 다시 열기 전에 해당 기록을 복구합니다. 이 명령은 UUID로 정확히 하나의 작업을 선택하고 비공개 바이트 단위 백업을 저장한 뒤, OpenCodeX가 소유한 `ocx1:`/`ocx2:` 압축 상태만 native Codex가 재생할 수 있는 일반 요약으로 변환합니다. native 암호화 콘텐츠와 다른 작업은 변경하지 않습니다. 실행 전에 선택한 작업을 닫으십시오. 처리 중 rollout이 변경되면 파일을 교체하지 않고 복구를 중단합니다. @@ -397,7 +399,7 @@ Windows에서는 `ocx service status`가 Task Scheduler 등록 상태를 ID가 Windows 작업 스케줄러에 새로 설치할 때 CLI는 먼저 현재 권한으로 작업 등록을 시도합니다. 접근이 거부되면 관리자 권한으로 연 PowerShell에서 `ocx service install --scheduler`를 실행하거나, `ocx service install --scheduler --allow-uac`로 Windows가 권한 상승 승인을 요청하도록 허용하세요. 옵션을 생략하면 등록할 때와 설치 실패 후 작업을 정리할 때 모두 UAC 창이 뜨지 않습니다. 롤백 중에 작업 삭제를 시도한 경우, CLI는 결과를 확인할 수 있으면 작업이 여전히 등록되어 있는지 알려줍니다. 설치가 실패하면 재시도 전에 `ocx service status`로 상태를 확인하세요. 이 옵션은 작업 스케줄러를 사용해 `service install`을 명시적으로 실행할 때만 적용됩니다. 권한 상승에는 승인이 필요하며 설치는 여전히 실패할 수 있습니다. -Windows 작업 스케줄러에 OpenCodex 작업이 없으면 `/f` 없이 등록합니다. `ocx service install`은 접근 거부를 확인하면 UAC 창을 띄우지 않고 오류를 알립니다. 대시보드에서 작업 스케줄러 **설치**를 선택하면 `ocx service install --allow-uac`가 실행되어, Windows가 등록을 거부했을 때 CLI가 권한 상승을 요청할 수 있습니다. +Windows 작업 스케줄러에 OpenCodex 작업이 없으면 `/f` 없이 등록합니다. 작업 스케줄러가 `오류: 액세스가 거부되었습니다.`를 반환하면 CLI는 위의 두 가지 설치 방법을 안내합니다. `ocx service install`은 접근 거부를 확인하면 UAC 창을 띄우지 않고 오류를 알립니다. 대시보드에서 작업 스케줄러 **설치**를 선택하면 `ocx service install --allow-uac`가 실행되어, Windows가 등록을 거부했을 때 CLI가 권한 상승을 요청할 수 있습니다. OpenCodex가 `/f`로 자신의 기존 작업을 교체할 때는 실행 중인 프로세스에 관리자 권한이 없음을 확인한 경우 종료 코드 1도 접근 거부로 해석합니다. 대시보드가 별도로 권한 상승을 요청해 재시도하는 동작은 **설치**에만 적용됩니다. **복구**는 복구 절차 안에서 필요한 권한 상승을 요청합니다. diff --git a/docs-site/src/content/docs/ko/reference/client-support.md b/docs-site/src/content/docs/ko/reference/client-support.md index ada4d6c65d5..113ced001c1 100644 --- a/docs-site/src/content/docs/ko/reference/client-support.md +++ b/docs-site/src/content/docs/ko/reference/client-support.md @@ -6,11 +6,11 @@ description: "opencodex가 연결하는 코딩 도구, 각 도구의 연결 방 -opencodex는 AI 코딩 도구와 모델을 잇는 하나의 로컬 게이트웨이입니다. 일부 도구는 직접(네이티브로) 설정하고, 나머지는 로컬 프록시를 가리키는 설정 파일을 내보내거나 관리합니다. 이 페이지는 코드 레지스트리에서 생성되므로 현재 릴리스가 제공하는 내용과 정확히 일치합니다. +opencodex는 AI 코딩 도구와 모델을 잇는 하나의 로컬 게이트웨이입니다. 도구를 네이티브로 설정하거나, 설정 파일을 내보내거나 관리하거나, 전용 게이트웨이 커넥터로 연결합니다. 이 페이지는 코드 레지스트리에서 생성되므로 현재 릴리스가 제공하는 내용과 정확히 일치합니다. ## 지원 수준 -- **implemented**: 레지스트리에 등록된 클라이언트입니다. 내보내는 설정의 경우 표의 프로토콜은 opencodex가 생성하는 설정에서 읽으며, 바뀌면 생성이 실패합니다. *검토됨* 표시는 설정 자체가 아니라 리뷰에서 나온 특정 엔드포인트를 뜻합니다(네이티브 클라이언트, 설정값을 특정 엔드포인트로 바꾸는 클라이언트). 생성기는 리뷰한 코드가 그대로 있는지 확인합니다. 'OpenAI 호환' 행은 엔드포인트를 단정하지 않습니다. +- **implemented**: 레지스트리에 등록된 클라이언트입니다. 내보내는 설정의 경우 표의 프로토콜은 opencodex가 생성하는 설정에서 읽으며, 바뀌면 생성이 실패합니다. *검토됨* 표시는 프로토콜을 설정에서 자동으로 읽은 것이 아니라 코드 검토로 확인했다는 뜻입니다. 생성기는 리뷰한 코드가 그대로 있는지 확인합니다. 'OpenAI 호환' 행은 엔드포인트를 단정하지 않습니다. - **test-covered**: implemented이면서, 리뷰로 고른 이 클라이언트의 테스트 케이스가 링크되어 있습니다. 생성기는 테스트가 존재하고 비활성화되지 않았는지만 확인하므로, 무엇을 검증하는지는 테스트를 직접 읽어 보세요. - **실행 검증**: 특정 시점의 관찰 기록입니다. 표에 적힌 클라이언트 제품·버전을 표에 적힌 opencodex 버전과 함께, 명시한 시나리오로, 그 날짜에 사람이 실행하고 증거를 링크했습니다. 다른 버전이나 제품에 대해서는 아무것도 보장하지 않습니다. 증거는 결과를 추가할 때 리뷰하며, 생성기가 다시 실행하지 않습니다. 대시(—)는 기록된 결과가 없다는 뜻입니다. @@ -47,6 +47,15 @@ opencodex는 AI 코딩 도구와 모델을 잇는 하나의 로컬 게이트웨 | Gentle Shell | — | JSON | 예 | Chat Completions | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | 로컬 리스너 전용. | | T3 Code | — | JSON | 예 | Anthropic Messages | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | 로컬 리스너 전용. 적용 전에 클라이언트별 검사를 실행하며 거부할 수 있습니다. | +## 게이트웨이 클라이언트 + +대시보드에서 **라우트 → Antigravity**를 열거나(**라우트 → 클라이언트**에서도 이동할 수 있음) 아래 명령을 실행하세요. 이 커넥터는 클라이언트의 게이트웨이를 설정하며 설정을 내보내거나 관리형 파일 통합 절차를 사용하지 않아요. agy CLI를 실행하기 전에 안내된 셸 프로필을 다시 불러오세요. + +| 클라이언트 | 수신 프로토콜 | 지원 수준 | 실행 검증 | 이 컴퓨터에서 설정 | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | OpenAI 호환(엔드포인트는 클라이언트가 선택) (검토됨) | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (검토됨) | test-covered ([테스트](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## 수신 엔드포인트 프록시는 아래 프로토콜을 받습니다. 위 목록에 없는 도구도 이 중 하나로 사용자 지정 엔드포인트를 설정할 수 있으면 연결할 수 있습니다. @@ -54,7 +63,9 @@ opencodex는 AI 코딩 도구와 모델을 잇는 하나의 로컬 게이트웨 - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## 이 페이지 최신 상태 유지 -이 페이지는 `scripts/generate-client-support-matrix.ts`가 내보내기·관리형 연동·네이티브 연동 레지스트리로부터 생성합니다. 클라이언트를 추가하려면 `scripts/client-support-matrix/metadata.ts`에 항목을 넣고 `bun run docs:clients`를 실행하세요. 커밋된 페이지가 오래되면 `bun run docs:clients:check`가 실패합니다. +이 페이지는 `scripts/generate-client-support-matrix.ts`가 내보내기·관리형 연동·네이티브 연동·게이트웨이 클라이언트 레지스트리로부터 생성합니다. 클라이언트를 추가하려면 `scripts/client-support-matrix/metadata.ts`에 항목을 넣고 `bun run docs:clients`를 실행하세요. 커밋된 페이지가 오래되면 `bun run docs:clients:check`가 실패합니다. diff --git a/docs-site/src/content/docs/reference/cli/lifecycle.md b/docs-site/src/content/docs/reference/cli/lifecycle.md index bbd9bf76a97..6b152ec1fe5 100644 --- a/docs-site/src/content/docs/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/reference/cli/lifecycle.md @@ -65,6 +65,22 @@ Stopping that sibling with `ocx stop` or a signal leaves their configuration alo If the sibling serves a saved Remote Link, `ocx stop` verifies the running instance and its Link ownership and stops only that process. Unverified Link ownership or conflicting service manager approval leaves the process running and reports an ownership refusal. + +When startup is refused because proxy ownership is unverified, the error names the reason. For the +two PID reasons (`pid-probe-failed`, `pid-identity-unverified`) it also names the recovery: if no +OpenCodex proxy is running for this home, delete `runtime-port.json` and `ocx.pid` in +`$OPENCODEX_HOME` (`~/.opencodex` when it is unset), then start again. A runtime record written by +a current version carries its owner's process creation time and PID namespace, so on macOS, Windows +and a Linux host's own PID namespace a recorded PID that another process reuses later (after a reboot, +for example) is recognised and startup proceeds by itself. A container's own PID namespace is compared +only within one boot: after a reboot, a reused PID there is recognised only when its readable command +line shows a program other than OpenCodex, and startup still refuses when the command line is +unreadable or the process belongs to another user; remove the two files once as above. A record +written by 2.100.13 or earlier has no PID namespace: if its PID is reused, startup can keep refusing +until you remove the two files once, and the record written next uses the new format. On Windows the +creation time comes from the process handle, or from CIM when the handle cannot be opened; CI +exercises the handle path on Windows runners, and the CIM path has not been checked on a real host. + While it runs, the proxy also keeps Codex pointed at itself: when the opencodex routing in `~/.codex/config.toml` names another local port where no opencodex has answered for about 20 seconds (an instance that re-pointed it and @@ -379,6 +395,11 @@ changed to `openai`, `exec` is normalized to `cli`, and the event marker is set. legitimate dedicated-provider history. Back up the state and run it only when that full scope is intended. +Preflight stops before relabeling and reports `history_rollout_uninspectable` if a thread’s history +exists only as `.jsonl.zst`, the last record lacks a terminating newline, or the final records +cannot be classified within the 16 MiB read limit. +Leave the existing files in place. This command does not rebuild the mobile conversation index. + ### `ocx recover-history --ocx-compaction --yes` Repair one thread that was compacted through a routed provider before resuming it through native @@ -423,6 +444,13 @@ restart the proxy using the intended current installation; for a background serv or resolve `PATH` to the intended installation. These diagnostics do not repair the service or change whether requests are allowed. +Status and `ocx doctor` also check whether `ocx start` would be refused because proxy ownership cannot be +verified, the same read-only check the start runs, bounded to one second: status when no proxy answers its +health check, doctor when it finds no verified live proxy. If so, +the proxy line and doctor's hint show the start error's text with its recovery step, and `--json` reports +`proxy.startupRefusal: { reason, message }` (otherwise `null`). It describes the current state, not an earlier +failure; a check that only runs out of time reports nothing, and a connected client is not checked. + If an update restart reports a blank hostname in the runtime record, it leaves the proxy running. Use `ocx status` and `ocx service status` as clues, not proof of ownership or the actual bind. Once ownership is verified, for a service use the owning installation's `ocx service restart`; @@ -922,6 +950,7 @@ On Windows, the install syntax is `ocx service install [--native|--scheduler] [- For a fresh Task Scheduler install, the CLI first tries to register the task with the current permissions. If Windows denies access, run `ocx service install --scheduler` from an administrator PowerShell, or run `ocx service install --scheduler --allow-uac` to allow Windows to ask for elevation. +The CLI also recognizes the Korean Task Scheduler message `오류: 액세스가 거부되었습니다.` and displays the same instructions. The prompt still requires approval and installation can still fail. Without the flag, the CLI opens no UAC prompt for registration or for cleanup if the install fails. When rollback attempts to delete the task, the CLI reports whether it is still registered if it can verify the result. After any failed install, @@ -1419,7 +1448,11 @@ read-only. Reasons are `desktop-app-owned`, `source-checkout`, `mise-managed`, `installer-unknown`, `plan-unavailable`, `serving-install-unknown`, `cli-not-serving-install`, `runtime-ownership-refused`, `target-unresolved`, `downgrade-refused`, and `up-to-date`. `desktop-app-owned` directs updates to the -Desktop app; uncertain serving identity refuses rather than guessing. Run `ocx start` +Desktop app; uncertain serving identity refuses rather than guessing. A CLI that a Debian +package owns (the Linux desktop package installs `/usr/bin/ocx`) plans as `installer-unknown`; +`ocx update` names the package update instead, which needs root +(`sudo apt install ./OpenCodex-VERSION-linux-amd64.deb`), and a Home's `ocx link update` +reports a Child CLI at `/usr/bin/ocx` as the owner action `deb-managed` with that command. Run `ocx start` or `ocx stop` to settle a stale runtime record before planning again. Apply emits one `ocx.update.result/1` object with `applied`, `fromVersion`, @@ -1440,7 +1473,7 @@ and 64 for invalid usage. `rolledBack` is true only when an actual installer rollback and its verification succeeded. A plan command emits its plan with exit 0; the `canApply` and `reason` fields describe eligibility. -Compiled standalone installs, including the Windows MSI Desktop bundle, are updated through **Check for Updates…** in OpenCodex Desktop, by `ocx update --desktop` on a Windows Desktop installation (below), or by reinstalling the standalone binary from [GitHub Releases](https://github.com/lidge-jun/opencodex/releases). `ocx system update check` reports `installer: "standalone"`, `canUpdate: false`, and `reason: "standalone_install"` with that guidance. `ocx update` without `--desktop` exits unsuccessfully with the same hint; it does not run a package-manager update for the compiled executable. A genuine source checkout still reports `installer: "source"` and `reason: "source_checkout"`. +Compiled standalone installs, including the Windows MSI Desktop bundle, are updated through **Check for Updates…** in OpenCodex Desktop, by `ocx update --desktop` on a Windows Desktop installation (below), or by reinstalling the standalone binary from [GitHub Releases](https://github.com/lidge-jun/opencodex/releases). `ocx system update check` reports `installer: "standalone"`, `canUpdate: false`, and `reason: "standalone_install"` with that guidance. `ocx update` without `--desktop` exits unsuccessfully with the same hint; it does not run a package-manager update for the compiled executable. When a Debian package owns the executable (the Linux desktop package's `/usr/bin/ocx`), both name the package update instead (above). A genuine source checkout still reports `installer: "source"` and `reason: "source_checkout"`. If your host already uses an external updater, such as a systemd timer that deploys and switches versioned source trees under `/opt/opencodex/releases/`, set diff --git a/docs-site/src/content/docs/reference/client-support.md b/docs-site/src/content/docs/reference/client-support.md index 80aa83eea3b..3c9a6e243c7 100644 --- a/docs-site/src/content/docs/reference/client-support.md +++ b/docs-site/src/content/docs/reference/client-support.md @@ -6,11 +6,11 @@ description: "Which coding tools opencodex connects to, how each one is wired, a -opencodex is one local gateway for your AI coding tools and models. Some tools it configures natively; for the others it exports or manages a config file that points the tool at the local proxy. This page is generated from the code registries, so it lists exactly what the current release ships. +opencodex is one local gateway for your AI coding tools and models. It can configure tools natively, export or manage a config file, or use a dedicated gateway connector. This page is generated from the code registries, so it lists exactly what the current release ships. ## Support levels -- **implemented**: the client is in the registry. For exported configs, the protocol shown is read from the config opencodex generates, and generation fails if it changes. A protocol marked *curated* names an endpoint that comes from a review instead of the config itself (native clients, and clients that turn a setting into a specific endpoint); the generator checks that the reviewed code is still in place. "OpenAI-compatible" rows make no endpoint claim. +- **implemented**: the client is in the registry. For exported configs, the protocol shown is read from the config opencodex generates, and generation fails if it changes. A protocol marked *curated* comes from a code review rather than automated config inspection; the generator checks that the reviewed code is still in place. "OpenAI-compatible" rows make no endpoint claim. - **test-covered**: implemented, and a test case chosen in review that exercises this client is linked. The generator checks only that the test still exists and is enabled; read it to see what it asserts. - **Runtime verified**: a historical observation: a person ran the exact client product and version shown against the opencodex version shown, for the stated scenario, on that date, and linked the evidence. It says nothing about other versions or products. The evidence is reviewed when a result is added; the generator does not re-run it. A dash means no result is recorded. @@ -47,6 +47,15 @@ opencodex is one local gateway for your AI coding tools and models. Some tools i | Gentle Shell | — | JSON | Yes | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | Local listener only. | | T3 Code | — | JSON | Yes | Anthropic Messages | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | Local listener only. Apply runs a client-specific check first and can refuse. | +## Gateway clients + +Use **Route → Antigravity** on the dashboard (also linked from **Route → Clients**) or run the commands below. These connectors set up the gateway for their respective client; they do not export a config or use the managed file integration workflow. For agy, reload the indicated shell profile before running the CLI. + +| Client | Inbound protocol | Support level | Runtime verified | Set up on this machine | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | OpenAI-compatible (endpoint chosen by the client) (curated) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (curated) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## Inbound endpoints The proxy accepts these protocols. A tool that is not listed above can still connect if it lets you set a custom endpoint for one of them. @@ -54,7 +63,9 @@ The proxy accepts these protocols. A tool that is not listed above can still con - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## Keeping this page current -This page is generated by `scripts/generate-client-support-matrix.ts` from the export, managed-integration and native-integration registries. To add a client, add its entry in `scripts/client-support-matrix/metadata.ts` and run `bun run docs:clients`; `bun run docs:clients:check` fails while the committed page is stale. +This page is generated by `scripts/generate-client-support-matrix.ts` from the export, managed-integration, native-integration and gateway-client registries. To add a client, add its entry in `scripts/client-support-matrix/metadata.ts` and run `bun run docs:clients`; `bun run docs:clients:check` fails while the committed page is stale. diff --git a/docs-site/src/content/docs/reference/configuration/providers.md b/docs-site/src/content/docs/reference/configuration/providers.md index 44ea622dfbf..e143a721b16 100644 --- a/docs-site/src/content/docs/reference/configuration/providers.md +++ b/docs-site/src/content/docs/reference/configuration/providers.md @@ -361,7 +361,7 @@ Providers can expose a built-in shorthand, such as `agy` for `google-antigravity | `chatServiceTier?` | `boolean` | Provider-wide Chat-wire opt-in for forwarding caller `service_tier` values. On a classified route it governs foreign values such as `flex`, not proxy-owned canonical Fast after capability validation; on an unclassified route it governs every caller value because no Fast capability has been validated. Exact model capability does not authorize foreign forwarding. Responses routes retain their capability-based caller forwarding behavior. | | `promptCacheKey?` | `boolean` | Provider-wide `openai-chat` opt-in for forwarding a `prompt_cache_key`. The adapter forwards the key it is given and never invents one, but the key is not always the caller's: Claude Messages translation derives one from `metadata.user_id`, or from a model/system/tools cohort when no metadata is sent. Default off unless declared by the provider preset; Mistral enables it per its [prompt-caching contract](https://docs.mistral.ai/studio/conversations/advanced/prompt-caching), and explicit `false` disables it. Enable only when the upstream documents support, because strict gateways may reject the unknown field with HTTP 400. | | `preserveResponsesReasoningContent?` | `boolean` | Default off for custom providers. In **Providers → Settings**, enable **Replay plaintext reasoning** for a custom Responses endpoint only if it accepts this history. This sends prior plaintext reasoning to that endpoint and may increase token use. Keep plaintext reasoning content on replayed Responses reasoning items instead of blanking it, including custom native v1 compact input (blanking is the ChatGPT backend's rule). Enable for upstreams whose contract accepts reasoning replay, such as DeepSeek or a self-hosted Kimi on vLLM. Proxy-minted `ocxr1` envelopes are always stripped. A hand-configured `openai-responses` provider without it logs one warning per host the first time plaintext reasoning is dropped. `preserveReasoningContentModels` does not affect this wire. | -| `preserveResponsesInputItemIds?` | `boolean` | Default off. Preserve valid `input[].id` when `store: false` for explicitly trusted launcher relays that require turn identity. Ordinary Responses providers keep stripping IDs; xAI custom-call ID repair remains active. | +| `preserveResponsesInputItemIds?` | `boolean` | Default off. Preserve valid `input[].id` when `store: false` for explicitly trusted launcher relays that require turn identity. Ordinary Responses providers keep stripping IDs, except a hosted `web_search_call`'s, which a search gateway needs to pair the call with its results; xAI custom-call ID repair remains active. | | `preserveResponsesMessageMetadata?` | `boolean` | Default off. Preserve private `internal_chat_message_metadata_passthrough` on input items for explicitly trusted launcher relays, including custom native v1 compact requests. This forwards private turn/session metadata to that destination; do not enable for ordinary gateways. | | `dropResponsesReasoningItems?` | `boolean` | Remove replayed Responses `reasoning` items from continuation input entirely, including custom native v1 compact requests, instead of forwarding them with blanked content. This is lossy: summaries, item ids, and `encrypted_content` go with them, so no reasoning item from the previous turn remains in the forwarded input. It does not remove `previous_response_id`, so an upstream holding its own turn state may still reach it. Enable only for an upstream that rejects reasoning replay outright — the built-in Volcengine Ark Coding Plan preset sets it because validated tool continuations answered `400 InvalidParameter` otherwise. Set it to `false` on that provider to forward reasoning items again. | | `disabled?` | `boolean` | Keep the provider on disk but exclude it from routing and model/catalog listings. | diff --git a/docs-site/src/content/docs/reference/configuration/server.md b/docs-site/src/content/docs/reference/configuration/server.md index 480a09c6db3..263b29f6b96 100644 --- a/docs-site/src/content/docs/reference/configuration/server.md +++ b/docs-site/src/content/docs/reference/configuration/server.md @@ -63,7 +63,7 @@ passthrough, including native WebSocket output, retain their existing stop behav | `resetCreditAutoRedeem?` | `{ enabled?: boolean; leadTimeMinutes?: number }` | off | Opt-in: redeem the main Codex account's soonest-expiring reset credit `leadTimeMinutes` (1–60, default 10) before it expires. Every attempt re-reads the upstream credit list first and skips when the credit is gone (for example, redeemed by hand); the `redeem_request_id` is journaled in `$OPENCODEX_HOME/reset-credit-auto-redeem.json` before the call so a crash replays the same idempotent request instead of spending a second credit. Servers sharing this configuration directory coordinate reservations and settlements so one process does not replace another's request record. Logs carry a hashed account key only. | | `syncResumeHistory?` | `boolean` | `true` | Reversible Codex App history compatibility. Original metadata is backed up and restored by `ocx stop` / `ocx restore`. | | `spendPoolAliases?` | `Record` | unset | Explicit historical salted pool-alias to canonical provider mappings. Keep this key at the top level, outside `spend`. See [Historical pool continuity](#historical-pool-continuity). | -| `shadowCallIntercept?` | `{ enabled?: boolean; model?: string; sourceModels?: string[] }` | off | Redirect recognized Codex helper/shadow calls to a chosen model while preserving the request's configured reasoning effort. The default source prefixes are `gpt-6-luna` and `gpt-5.6-luna`. The dashboard exposes one toggle per source and keeps both Terra generations (`gpt-6.1-terra` and `gpt-5.6-terra`) and the retired `gpt-5.4-mini` helper off until selected. At least one source must stay enabled; disable the main switch to stop all shadow calls. | +| `shadowCallIntercept?` | `{ enabled?: boolean; model?: string; sourceModels?: string[]; followConversation?: Record }` | off | Redirect recognized Codex helper/shadow calls to a chosen model while preserving the request's configured reasoning effort. The default source prefixes are `gpt-6-luna` and `gpt-5.6-luna`. The dashboard exposes one toggle per source and keeps both Terra generations (`gpt-6.1-terra` and `gpt-5.6-terra`) and the retired `gpt-5.4-mini` helper off until selected. At least one source must stay enabled; disable the main switch to stop all shadow calls. | | `memoryModels?` | `{ extract?: { model: string; reasoningEffort?: string }; consolidation?: { model: string; reasoningEffort?: string } }` | off | Route Codex's two memory phases to a chosen model, with an optional reasoning effort per phase. See [Memory routing](#memory-routing). | | `webSearchSidecar?` | `OcxWebSearchSidecarConfig` | on when usable | Web-search sidecar options. | | `visionSidecar?` | `OcxVisionSidecarConfig` | on when usable | Image-description sidecar options. | @@ -865,6 +865,15 @@ sources. For selected sources, check individual models or provider-wide `provide then click **Save**. Select **Use conversation model** and save to remove the override. Changes apply to the next compaction request without restarting the proxy. +To customize only the summaries OpenCodex generates, fill in **Additional summary instructions** or +set the top-level `compactionAdditionalInstructions` string in `config.json` (up to 8,192 characters). +**Show built-in compaction prompts** displays the actual standard prompt and the separate +cache-preserving Anthropic variant. These prompts apply only when OpenCodex generates the summary, +whether compaction is automatic or manual and whether or not a model override is set. Native +compaction and client-authored local checkpoint prompts are not changed. Leaving this field blank or whitespace-only +keeps the original prompt exactly. Additional instructions are sent to the summarizing provider, so +do not include secrets. + Set `compactionRouting` in OpenCodex `config.json` to override the model Codex's compaction requests use. The setting is disabled when omitted. @@ -1123,6 +1132,58 @@ subject to configured memory routing. These rules apply to concrete and combo ta } ``` +### Use a failover combo as the shadow target + +To give intercepted helper calls a backup, create a failover combo with your preferred route first. +For example, if you have OpenAI and Anthropic subscription routes configured, create the combo and +select it as the shadow target using the `combo/` prefix. Substitute model IDs from your configuration. + +```sh +ocx combo set title-helpers --strategy failover --targets "openai/gpt-5.6-sol,anthropic/claude-haiku-5-5" --quota-only-fallback on +ocx models shadow set combo/title-helpers --enabled on +``` + +In this example, the combo tries the next eligible target only after confirmed quota or billing +exhaustion before output begins. If the provider temporarily throttles a request, the caller receives +the rate-limit error. If the first target is already cooling down from a temporary throttle, the combo +returns `503 Service Unavailable` without contacting any target. Set `--quota-only-fallback off` on +the combo to allow fallback for other retryable failures before output begins. + +See [Combos](/guides/combos/) for target eligibility and [metered fallback consent](/guides/combos/#metered-fallback-consent). + +### Following the conversation's provider + +`followConversation` maps a provider id to a helper model. With it set, an intercepted helper call +goes to the model mapped to the provider the last ordinary turn of the same Codex conversation was +routed to, identified by the `thread-id` and `session-id` headers both requests carry. A turn sets +the provider once it is routed, so a turn that later fails or is cancelled still moves it. Each +sub-agent thread keeps its own record, so a sub-agent turn on another provider does not change the +provider its parent's helper calls follow. A +helper call in a conversation the proxy has not seen, in a conversation whose provider has no +mapping, or whose mapped model does not resolve uses `model` exactly as before, including the +`intercept_target_unavailable` refusal below. Mapping a provider to a source model such as +`openai` → `gpt-6-luna` leaves that conversation's helper calls native. The record of each +conversation's provider lives in memory only, holds at most 2048 conversations and starts empty +after a restart. Set it with `PUT /api/shadow-call-settings` (`followConversation` object, or +`null` to clear), `ocx models shadow set --follow-conversation `, or the +**Follow the chat's provider** pickers under Shadow Call Intercept on the Models page. A helper call +that went to a followed model shows the route reason `shadow-follow-conversation` in the request +log. Renaming a provider moves its entry and the routes that name it; deleting a provider removes +both. + +```json +{ + "shadowCallIntercept": { + "enabled": true, + "model": "gpt-5.5", + "followConversation": { + "anthropic": "anthropic/claude-haiku-5-5", + "openai": "gpt-6-luna" + } + } +} +``` + ### When the target is unavailable The replacement is the one destination the operator chose, so a target that stops resolving fails diff --git a/docs-site/src/content/docs/reference/management-api.md b/docs-site/src/content/docs/reference/management-api.md index f1bc4b7ae3d..da548b2891a 100644 --- a/docs-site/src/content/docs/reference/management-api.md +++ b/docs-site/src/content/docs/reference/management-api.md @@ -289,7 +289,7 @@ See [Codex prompt layers](/guides/codex-prompt/) for the layer model and the key | `POST /api/update/run` | Asynchronously check a fresh package version, then start an update job, optionally followed by restart | 400 invalid body; 409 `update_restart_unsupervised` when the proxy runs inside a systemd unit other than OpenCodex's own user service, or the worker cannot leave the service cgroup (with or without restart, since the update stops the proxy first); job-specific conflict/error status | | `GET /api/update/status` | Poll an update job by id | 404 unknown job | | `GET, PUT /api/sidecar-settings` | Read or update web-search and vision sidecar model/backend settings | 400 invalid shape, backend, or limit | -| `GET, PUT /api/shadow-call-settings` | Read or update shadow-call interception settings, including `sourceModels`; GET also returns the runtime-owned `sourceModelOptions` inventory | 400 invalid shape or value, including an empty, duplicate, whitespace-bearing, or provider-qualified source prefix, or more than 32 prefixes / 128 characters per prefix; source-list failures carry `code: shadow_call_source_invalid`, target conflicts `code: shadow_call_target_invalid` | +| `GET, PUT /api/shadow-call-settings` | Read or update shadow-call interception settings, including `sourceModels` and the `followConversation` provider → helper-model map (`null` clears it); GET also returns the runtime-owned `sourceModelOptions` inventory | 400 invalid shape or value, including an empty, duplicate, whitespace-bearing, or provider-qualified source prefix, or more than 32 prefixes / 128 characters per prefix; source-list failures carry `code: shadow_call_source_invalid`, target conflicts `code: shadow_call_target_invalid`, an invalid or unresolvable `followConversation` entry `code: shadow_call_follow_invalid` | ### Logs, usage, and storage diff --git a/docs-site/src/content/docs/reference/proxy-formats.md b/docs-site/src/content/docs/reference/proxy-formats.md index c8b462760c4..3cb48d585d5 100644 --- a/docs-site/src/content/docs/reference/proxy-formats.md +++ b/docs-site/src/content/docs/reference/proxy-formats.md @@ -911,12 +911,12 @@ from the URL and headers before the request is logged or forwarded. Errors use G delete it; a keyless loopback caller shares one owner. Retention is best effort: each key keeps at most 200 interactions and 16 MiB, the proxy keeps at most 1,000 and 64 MiB in total, and the proxy's memory budget can remove interactions earlier. Keys make room only by removing their own oldest interactions. - A keyless loopback write makes room only by removing earlier turns of the conversation it continues, so - other keyless conversations stay in place; when that is not enough to stay within the shared or global - limit, the proxy returns the answer without storing the new interaction. A key with nothing of its own to make room - with at the global limit likewise gets its answer without the interaction being kept, as does one larger - than 8 MiB or the configured inbound body limit, whichever is smaller. A buffered answer reports whether it - was kept in `x-opencodex-interaction-stored: true|false`. A restart forgets them all, and a missing + A keyless loopback write can remove only stored turns on the path back from its `previous_interaction_id`, + including that interaction itself. IDs unique to sibling branches and IDs from other conversations stay available. + If the eligible turns cannot make room within the owner and global limits, the proxy returns the answer without storing + the new interaction and keeps every unexpired entry. This applies to both keyed and keyless writes. + The proxy also skips interactions larger than 8 MiB or the configured inbound body limit, whichever is smaller. + A buffered answer reports whether it was kept in `x-opencodex-interaction-stored: true|false`. A restart forgets them all, and a missing or expired id answers 404, so a client should keep its history to resend it. A request with `store: false` is not kept. `GET /v1beta/interactions/{id}` returns a stored interaction, `DELETE` removes it, and `POST /v1beta/interactions/{id}/cancel` answers 400 because nothing runs in the diff --git a/docs-site/src/content/docs/ru/reference/cli/lifecycle.md b/docs-site/src/content/docs/ru/reference/cli/lifecycle.md index 5d31678324e..dbf658e5062 100644 --- a/docs-site/src/content/docs/ru/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/ru/reference/cli/lifecycle.md @@ -113,6 +113,8 @@ ocx eject back устанавливается. Корректная история выделенного провайдера тоже входит в охват. Сначала сделайте резервную копию и запускайте команду только если нужен весь этот охват. +Если история треда сохранилась только в формате `.jsonl.zst`, после последней записи нет перевода строки или по последним 16 МиБ файла нельзя определить формат записей, предварительная проверка выдаст `history_rollout_uninspectable` и остановит команду до изменения меток. Сохраните исходные файлы на месте. Эта команда не перестраивает индекс бесед мобильного приложения. + ### `ocx recover-history --ocx-compaction --yes` Исправьте историю одной задачи, сжатой через маршрутизируемого провайдера, перед её возобновлением в нативном Codex. Команда выбирает ровно одну задачу по UUID, сначала сохраняет приватную побайтовую резервную копию, а затем преобразует только принадлежащее OpenCodeX состояние сжатия `ocx1:`/`ocx2:` в обычную сводку, которую может воспроизвести нативный Codex. Нативное зашифрованное содержимое и другие задачи не изменяются. Перед запуском закройте выбранную задачу; если rollout изменится во время обработки, восстановление остановится без замены файла. diff --git a/docs-site/src/content/docs/ru/reference/client-support.md b/docs-site/src/content/docs/ru/reference/client-support.md index 2784e8508f9..3ba61efd2d7 100644 --- a/docs-site/src/content/docs/ru/reference/client-support.md +++ b/docs-site/src/content/docs/ru/reference/client-support.md @@ -6,11 +6,11 @@ description: "К каким инструментам для кода подкл -opencodex — единый локальный шлюз для ваших ИИ-инструментов для кода и моделей. Часть инструментов он настраивает нативно; для остальных он экспортирует или ведёт файл конфигурации, который направляет инструмент на локальный прокси. Страница сгенерирована из реестров в коде и поэтому в точности соответствует текущему релизу. +opencodex — единый локальный шлюз для ваших ИИ-инструментов для кода и моделей. Он может настраивать инструменты нативно, экспортировать или вести файл конфигурации либо использовать отдельный коннектор шлюза. Страница сгенерирована из реестров в коде и поэтому в точности соответствует текущему релизу. ## Уровни поддержки -- **implemented**: клиент есть в реестре. Для экспортируемых конфигураций протокол берётся из конфигурации, которую генерирует opencodex, и генерация падает, если он меняется. Пометка *проверено* означает, что эндпоинт взят из ревью, а не из самой конфигурации (нативные клиенты и клиенты, которые превращают настройку в конкретный эндпоинт); генератор проверяет, что проверенный код на месте. Строки «Совместим с OpenAI» не утверждают конкретный эндпоинт. +- **implemented**: клиент есть в реестре. Для экспортируемых конфигураций протокол берётся из конфигурации, которую генерирует opencodex, и генерация падает, если он меняется. Пометка *проверено* означает, что протокол определён при ревью кода, а не при автоматической проверке конфигурации; генератор проверяет, что проверенный код на месте. Строки «Совместим с OpenAI» не утверждают конкретный эндпоинт. - **test-covered**: implemented, и есть ссылка на выбранный при ревью тест, который задействует этого клиента. Генератор проверяет только, что тест существует и не отключён; что именно он проверяет, смотрите в самом тесте. - **Проверено в работе**: историческое наблюдение: человек запустил указанные продукт и версию клиента с указанной версией opencodex по описанному сценарию в эту дату и приложил ссылку на подтверждение. Это ничего не говорит о других версиях или продуктах. Подтверждение проверяется при добавлении результата; генератор его не перезапускает. Прочерк означает, что результатов нет. @@ -47,6 +47,15 @@ opencodex — единый локальный шлюз для ваших ИИ-и | Gentle Shell | — | JSON | Да | Chat Completions | test-covered ([тест](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | Только локальный слушатель. | | T3 Code | — | JSON | Да | Anthropic Messages | test-covered ([тест](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | Только локальный слушатель. Перед применением выполняется проверка, специфичная для клиента, и возможен отказ. | +## Клиенты шлюза + +Откройте **Маршрут → Antigravity** на панели управления (ссылка также есть в разделе **Маршрут → Клиенты**) или выполните команды ниже. Эти коннекторы настраивают шлюз для клиента без экспорта конфигурации или управляемой файловой интеграции. Перед запуском agy перечитайте указанный профиль оболочки. + +| Клиент | Входящий протокол | Уровень | Проверено в работе | Настроить на этом компьютере | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | Совместим с OpenAI (эндпоинт выбирает клиент) (проверено) | test-covered ([тест](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (проверено) | test-covered ([тест](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## Входящие эндпоинты Прокси принимает эти протоколы. Инструмент, которого нет в таблице, всё равно может подключиться, если позволяет задать собственный эндпоинт для одного из них. @@ -54,7 +63,9 @@ opencodex — единый локальный шлюз для ваших ИИ-и - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## Актуальность страницы -Страница генерируется скриптом `scripts/generate-client-support-matrix.ts` из реестров экспорта, управляемых и нативных интеграций. Чтобы добавить клиента, добавьте запись в `scripts/client-support-matrix/metadata.ts` и выполните `bun run docs:clients`; `bun run docs:clients:check` падает, пока закоммиченная страница устарела. +Страница генерируется скриптом `scripts/generate-client-support-matrix.ts` из реестров экспорта, управляемых интеграций, нативных интеграций и клиентов шлюза. Чтобы добавить клиента, добавьте запись в `scripts/client-support-matrix/metadata.ts` и выполните `bun run docs:clients`; `bun run docs:clients:check` падает, пока закоммиченная страница устарела. diff --git a/docs-site/src/content/docs/tr/guides/chatgpt-desktop.md b/docs-site/src/content/docs/tr/guides/chatgpt-desktop.md index b3dd5372fc3..ce6163d4f50 100644 --- a/docs-site/src/content/docs/tr/guides/chatgpt-desktop.md +++ b/docs-site/src/content/docs/tr/guides/chatgpt-desktop.md @@ -51,7 +51,11 @@ uygundur. Normal `rate_limit_reached` işaretleri temizlenir. Bilinen kota bayra (`allowed`, `limit_reached` / `limitReached`, `ordinaryUsageAllowed`) yalnızca normal kota kanıtıyla açılır: temizlenmiş normal sınır türü veya %100 dolmuş pencere. Yükün açıklamadığı bir nedenle kapalı olan bayrak kapalı kalır. Çalışma alanı, -kredi, bilinmeyen sınır türü ve harcama denetimi kısıtlamaları geçidi kapalı tutar. +bilinmeyen sınır türü ve harcama denetimi kısıtlamaları geçidi kapalı tutar. +`chatgptDesktop.spendCredits: true` iken kredi türleri +(`workspace_member_credits_depleted`, `workspace_owner_usage_limit_reached`) +normal kota gibi açılır; abonelik kotası bitince masaüstü krediden çekebilir. +Bu kredileri OpenAI faturalandırır. Varsayılan, kredi sınırındaki composer'ı kilitli tutar. Gösterilen kullanım değişmez: yüzdeler, sıfırlanma zamanları, pencere süreleri, plan bilgileri ve diğer gösterim alanları alındığı gibi kalır. İlgisiz JSON-RPC diff --git a/docs-site/src/content/docs/tr/reference/cli/lifecycle.md b/docs-site/src/content/docs/tr/reference/cli/lifecycle.md index 9ef0865b6ae..f3c9b5639cb 100644 --- a/docs-site/src/content/docs/tr/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/tr/reference/cli/lifecycle.md @@ -111,6 +111,8 @@ Bu, geniş kapsamlı ve yıkıcı bir yeniden etiketlemedir: kullanıcı iletisi olarak normalleştirilir ve event marker ayarlanır. Geçerli dedicated-provider geçmişi de kapsama dahildir. Durumu yedekleyin ve yalnızca bu kapsamın tamamını istiyorsanız çalıştırın. +Bir konuşmanın geçmişi yalnızca `.jsonl.zst` biçiminde bulunuyorsa, son kaydın sonunda satır sonu karakteri yoksa veya dosyanın sonundan en fazla 16 MiB okunduğunda son kayıtların biçimi belirlenemiyorsa ön denetim `history_rollout_uninspectable` hatası verir ve etiketleme başlamadan komut durur. Mevcut dosyaları yerinde bırakın. Bu komut mobil uygulamanın konuşma dizinini yeniden oluşturmaz. + ### `ocx recover-history --ocx-compaction --yes` Yönlendirilmiş bir sağlayıcı üzerinden sıkıştırılmış bir görevi yerel Codex ile sürdürmeden önce geçmişini onarın. Komut UUID ile yalnızca bir görevi seçer, önce özel ve bayt bayt bir yedek kaydeder, ardından yalnızca OpenCodeX'e ait `ocx1:`/`ocx2:` sıkıştırma durumunu yerel Codex'in yeniden oynatabileceği düz bir özete dönüştürür. Yerel şifreli içerik ve diğer görevler değişmeden kalır. Komutu çalıştırmadan önce seçili görevi kapatın; işlem sırasında rollout değişirse kurtarma dosyayı değiştirmeden durur. diff --git a/docs-site/src/content/docs/tr/reference/client-support.md b/docs-site/src/content/docs/tr/reference/client-support.md index e0d62b2d51a..a305b1cc75f 100644 --- a/docs-site/src/content/docs/tr/reference/client-support.md +++ b/docs-site/src/content/docs/tr/reference/client-support.md @@ -6,11 +6,11 @@ description: "opencodex'in bağlandığı kodlama araçları, her birinin nasıl -opencodex, yapay zekâ kodlama araçlarınız ve modelleriniz için tek bir yerel ağ geçididir. Bazı araçları yerel olarak yapılandırır; diğerleri için aracı yerel proxy'ye yönlendiren bir yapılandırma dosyasını dışa aktarır veya yönetir. Bu sayfa koddaki kayıtlardan üretilir; bu yüzden mevcut sürümün sunduğu şeyle birebir aynıdır. +opencodex, yapay zekâ kodlama araçlarınız ve modelleriniz için tek bir yerel ağ geçididir. Araçları yerel olarak yapılandırabilir, yapılandırma dosyası dışa aktarabilir veya yönetebilir, ya da özel bir ağ geçidi bağlayıcısı kullanabilir. Bu sayfa koddaki kayıtlardan üretilir; bu yüzden mevcut sürümün sunduğu şeyle birebir aynıdır. ## Destek düzeyleri -- **implemented**: istemci kayıtta yer alır. Dışa aktarılan yapılandırmalarda gösterilen protokol, opencodex'in ürettiği yapılandırmadan okunur ve değişirse üretim başarısız olur. *İncelendi* işareti, uç noktanın yapılandırmanın kendisinden değil bir incelemeden geldiğini belirtir (yerel istemciler ve bir ayarı belirli bir uç noktaya çeviren istemciler); üretici, incelenen kodun hâlâ yerinde olduğunu denetler. "OpenAI uyumlu" satırlar belirli bir uç nokta iddia etmez. +- **implemented**: istemci kayıtta yer alır. Dışa aktarılan yapılandırmalarda gösterilen protokol, opencodex'in ürettiği yapılandırmadan okunur ve değişirse üretim başarısız olur. *İncelendi* işareti, protokolün otomatik yapılandırma denetiminden değil, kod incelemesinden geldiğini belirtir; üretici, incelenen kodun hâlâ yerinde olduğunu denetler. "OpenAI uyumlu" satırlar belirli bir uç nokta iddia etmez. - **test-covered**: implemented olmanın yanında, incelemede seçilmiş ve bu istemciyi çalıştıran bir test durumuna bağlantı verilir. Üretici yalnızca testin hâlâ var ve etkin olduğunu denetler; neyi doğruladığını görmek için testi okuyun. - **Çalışırken doğrulandı**: tarihli bir gözlem: bir kişi gösterilen istemci ürününü ve sürümünü gösterilen opencodex sürümüyle, belirtilen senaryo için o tarihte çalıştırdı ve kanıtı bağladı. Diğer sürümler veya ürünler hakkında bir şey söylemez. Kanıt sonuç eklenirken incelenir; üretici yeniden çalıştırmaz. Tire, kayıtlı sonuç olmadığı anlamına gelir. @@ -47,6 +47,15 @@ opencodex, yapay zekâ kodlama araçlarınız ve modelleriniz için tek bir yere | Gentle Shell | — | JSON | Evet | Chat Completions | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | Yalnızca yerel dinleyici. | | T3 Code | — | JSON | Evet | Anthropic Messages | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | Yalnızca yerel dinleyici. Uygulamadan önce istemciye özgü bir denetim çalışır ve reddedebilir. | +## Ağ geçidi istemcileri + +Panoda **Rota → Antigravity** bölümünü açın (**Rota → İstemciler** bölümünde de bağlantısı var) veya aşağıdaki komutları çalıştırın. Bu bağlayıcılar istemcinin ağ geçidini kurar; yapılandırma dışa aktarmaz veya yönetilen dosya entegrasyonu akışını kullanmaz. agy CLI’ını çalıştırmadan önce belirtilen kabuk profilini yeniden yükleyin. + +| İstemci | Gelen protokol | Destek düzeyi | Çalışırken doğrulandı | Bu makinede kur | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | OpenAI uyumlu (uç noktayı istemci seçer) (incelendi) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (incelendi) | test-covered ([test](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## Gelen uç noktalar Proxy bu protokolleri kabul eder. Yukarıda listelenmeyen bir araç, bunlardan biri için özel uç nokta ayarlamaya izin veriyorsa yine de bağlanabilir. @@ -54,7 +63,9 @@ Proxy bu protokolleri kabul eder. Yukarıda listelenmeyen bir araç, bunlardan b - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## Bu sayfayı güncel tutmak -Bu sayfa `scripts/generate-client-support-matrix.ts` tarafından dışa aktarma, yönetilen entegrasyon ve yerel entegrasyon kayıtlarından üretilir. İstemci eklemek için `scripts/client-support-matrix/metadata.ts` dosyasına kaydını ekleyip `bun run docs:clients` çalıştırın; işlenmiş sayfa eskidiğinde `bun run docs:clients:check` başarısız olur. +Bu sayfa `scripts/generate-client-support-matrix.ts` tarafından dışa aktarma, yönetilen entegrasyon, yerel entegrasyon ve ağ geçidi istemcisi kayıtlarından üretilir. İstemci eklemek için `scripts/client-support-matrix/metadata.ts` dosyasına kaydını ekleyip `bun run docs:clients` çalıştırın; işlenmiş sayfa eskidiğinde `bun run docs:clients:check` başarısız olur. diff --git a/docs-site/src/content/docs/tr/troubleshooting/update-failed.md b/docs-site/src/content/docs/tr/troubleshooting/update-failed.md index c88de504397..1c1f42bc61a 100644 --- a/docs-site/src/content/docs/tr/troubleshooting/update-failed.md +++ b/docs-site/src/content/docs/tr/troubleshooting/update-failed.md @@ -30,8 +30,8 @@ ocx --version ocx status ``` -Kurulum çıktısı yerel yollar içerebildiği için pano işi yalnızca çıkış durumunu -kaydeder. Terminalde `ocx update` çalıştırmak başarısız adımı ve sonraki işlemi gösterir. +Windows'ta npm veya pnpm ile kurulum yapıldıysa pano, paket değiştirilmeden önce güncellemenin neden durduğunu gösterebilir. Hizmet durdurulurken erişim reddedilmiş, hizmet veya işlem durumu okunamamış, sarmalayıcı işlemin sahipliği doğrulanamamış ya da durdurmayı doğrulamak için yeterli süre kalmamış olabilir. Aynı Windows hesabında `ocx stop` çalıştırın. Hizmetin durduğu doğrulandıktan sonra `ocx update` çalıştırın. +Diğer hatalarda ayrıntıları görmek için terminalde `ocx update` çalıştırın. Kurulum çıktısı yerel yollar içerebildiğinden pano ham çıktıyı göstermez. ## Güncellemeyi tamamlama diff --git a/docs-site/src/content/docs/troubleshooting/update-failed.md b/docs-site/src/content/docs/troubleshooting/update-failed.md index c6894268b2d..2cc945074e1 100644 --- a/docs-site/src/content/docs/troubleshooting/update-failed.md +++ b/docs-site/src/content/docs/troubleshooting/update-failed.md @@ -36,8 +36,12 @@ ocx --version ocx status ``` -The dashboard job only records the exit status, because the installer's own output can contain local -paths. Running `ocx update` in a terminal shows the step that failed and the next step to take. +For Windows npm and pnpm installs, a dashboard update can stop before replacing the package. +If the service stop reports access denied, unreadable service or process state, unverified wrapper +ownership, or insufficient time to verify the stop, the dashboard shows that reason. Run `ocx stop` +in the same Windows account. Once it confirms the stop, run `ocx update`. +For other failures, run `ocx update` in a terminal for details. The dashboard withholds raw +installer output because it can contain local paths. ## Finish the update diff --git a/docs-site/src/content/docs/troubleshooting/windows-loopback-startup.md b/docs-site/src/content/docs/troubleshooting/windows-loopback-startup.md index bd8fc57ca5f..897196be1a5 100644 --- a/docs-site/src/content/docs/troubleshooting/windows-loopback-startup.md +++ b/docs-site/src/content/docs/troubleshooting/windows-loopback-startup.md @@ -27,6 +27,17 @@ the proxy. If startup still reports an ownership conflict, check what owns the reported port and retry after that owner has stopped or recovered. Keep the PID record and recovery journal for the next ownership check. +During `ocx service install --scheduler`, a process-list or task-end timeout +includes the time budget. This can happen while Windows PowerShell starts or +Windows gathers ownership information. A Windows access denial is reported +separately. Check the named operation and the Windows account running the +installer before changing permissions. + +Some Windows images omit the optional VBScript component. On those images a +fresh Task Scheduler installation uses a JScript launcher for the same hidden +service wrapper. It runs under the signed-in user's existing permissions. +This requires Windows Script Host and the JScript engine to be available. + If the error includes `pid-probe-failed`, Windows may have reused a recorded PID for a process OpenCodex cannot query. A closed port does not prove process identity. Do not terminate a process based on the recorded PID alone, diff --git a/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md b/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md index c064870f2c5..71d8de7a8b0 100644 --- a/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md @@ -74,6 +74,8 @@ ocx eject back 这是范围很广且具有破坏性的重标记:所有包含用户消息且当前标记为 `opencodex` 的线程都会改标为 `openai`,`exec` 会规范化为 `cli`,并设置事件标记。正常的专用提供方历史记录也在范围内。请先备份状态,并且仅在确实需要这一完整范围时执行。 +如果某个线程的历史记录只剩 `.jsonl.zst` 文件、最后一条记录末尾没有换行符,或从文件末尾读取最多 16 MiB 仍无法判定末尾记录的格式,预检会报告 `history_rollout_uninspectable`,并在更改标签前停止。请保留现有文件。此命令不会重建移动应用的对话索引。 + ### `ocx recover-history --ocx-compaction --yes` 在通过原生 Codex 恢复某个曾由路由提供方压缩的任务前,修复该任务的历史记录。此命令按 UUID 精确选择一个任务,先保存私有的逐字节备份,然后仅将 OpenCodeX 自有的 `ocx1:`/`ocx2:` 压缩状态转换为原生 Codex 可重放的普通摘要。原生加密内容和其他任务保持不变。运行前请关闭所选任务;如果 rollout 在处理期间发生变化,恢复会停止且不会替换原文件。 diff --git a/docs-site/src/content/docs/zh-cn/reference/client-support.md b/docs-site/src/content/docs/zh-cn/reference/client-support.md index 100e1a9ff75..80f814b78bd 100644 --- a/docs-site/src/content/docs/zh-cn/reference/client-support.md +++ b/docs-site/src/content/docs/zh-cn/reference/client-support.md @@ -6,11 +6,11 @@ description: "opencodex 能连接哪些编程工具、每个工具如何接入 -opencodex 是一个本地网关,连接你的 AI 编程工具与模型。部分工具由它原生配置;其余工具则通过导出或托管一个指向本地代理的配置文件来接入。本页由代码中的注册表生成,因此与当前版本实际提供的内容完全一致。 +opencodex 是一个本地网关,连接你的 AI 编程工具与模型。它可以原生配置工具,也可以导出或托管配置文件,或使用专用网关连接器。本页由代码中的注册表生成,因此与当前版本实际提供的内容完全一致。 ## 支持级别 -- **implemented**: 客户端已在注册表中。对于导出的配置,表中协议读取自 opencodex 生成的配置,一旦变化生成就会失败。标有*已审阅*的协议表示其端点来自审阅而非配置本身(原生客户端,以及会把某个设置转换为特定端点的客户端);生成器会检查被审阅的代码是否仍然存在。“OpenAI 兼容”的行不声明具体端点。 +- **implemented**: 客户端已在注册表中。对于导出的配置,表中协议读取自 opencodex 生成的配置,一旦变化生成就会失败。标有*已审阅*的协议来自代码审阅,而非自动读取配置;生成器会检查被审阅的代码是否仍然存在。“OpenAI 兼容”的行不声明具体端点。 - **test-covered**: 满足 implemented,并链接了一个经评审选定、覆盖该客户端的测试用例。生成器只检查该测试仍然存在且未被禁用;它具体断言了什么,请阅读测试本身。 - **运行验证**: 一次历史观察:有人在该日期,用表中所列的 opencodex 版本运行了表中所列的客户端产品与版本,执行了所述场景,并附上证据链接。它不代表其他版本或产品。证据在添加结果时经过评审,生成器不会重新运行。短横线表示尚无记录。 @@ -47,6 +47,15 @@ opencodex 是一个本地网关,连接你的 AI 编程工具与模型。部分 | Gentle Shell | — | JSON | 是 | Chat Completions | test-covered ([测试](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | 仅限本地监听。 | | T3 Code | — | JSON | 是 | Anthropic Messages | test-covered ([测试](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | 仅限本地监听。应用前先运行针对该客户端的检查,可能拒绝。 | +## 网关客户端 + +在控制台打开 **路由 → Antigravity**(也可从 **路由 → 客户端** 进入),或运行下列命令。这些连接器为各自客户端设置网关,不导出配置,也不走托管文件集成流程。使用 agy 前,请重新加载提示的 shell 配置文件。 + +| 客户端 | 入站协议 | 支持级别 | 运行验证 | 在本机设置 | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | OpenAI 兼容(端点由客户端选择) (已审阅) | test-covered ([测试](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (已审阅) | test-covered ([测试](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## 入站端点 代理接受以下协议。未列在上表中的工具,只要能为其中之一设置自定义端点,也可以接入。 @@ -54,7 +63,9 @@ opencodex 是一个本地网关,连接你的 AI 编程工具与模型。部分 - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## 保持本页最新 -本页由 `scripts/generate-client-support-matrix.ts` 根据导出、托管集成和原生集成注册表生成。要添加客户端,请在 `scripts/client-support-matrix/metadata.ts` 中添加条目并运行 `bun run docs:clients`;已提交的页面过期时,`bun run docs:clients:check` 会失败。 +本页由 `scripts/generate-client-support-matrix.ts` 根据导出、托管集成、原生集成和网关客户端注册表生成。要添加客户端,请在 `scripts/client-support-matrix/metadata.ts` 中添加条目并运行 `bun run docs:clients`;已提交的页面过期时,`bun run docs:clients:check` 会失败。 diff --git a/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md b/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md index 2425eeca438..6fa0ca8b76f 100644 --- a/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md +++ b/docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md @@ -71,6 +71,8 @@ ocx eject back 這是範圍很廣且具破壞性的重新標記:所有含有使用者訊息且目前標記為 `opencodex` 的 thread 都會改標為 `openai`,`exec` 會正規化為 `cli`,並設定 event marker。正常的專用 provider 歷史也包含在內。請先備份狀態,而且只有在確實需要這個完整範圍時才執行。 +如果某個討論串的歷史記錄只剩 `.jsonl.zst` 檔案、最後一筆記錄末尾沒有換行字元,或從檔案末端讀取最多 16 MiB 仍無法判定末端記錄的格式,預先檢查會回報 `history_rollout_uninspectable`,並在變更標籤前停止。請保留現有檔案。此指令不會重建行動應用程式的對話索引。 + ### `ocx recover-history --ocx-compaction --yes` 在透過原生 Codex 恢復曾由路由提供方壓縮的工作前,修復該工作的歷史記錄。此命令依 UUID 精確選取一個工作,先儲存私有的逐位元組備份,然後只把 OpenCodeX 自有的 `ocx1:`/`ocx2:` 壓縮狀態轉換成原生 Codex 可重播的普通摘要。原生加密內容與其他工作不會變更。執行前請關閉所選工作;若 rollout 在處理期間發生變化,復原會停止且不會取代原始檔案。 diff --git a/docs-site/src/content/docs/zh-tw/reference/client-support.md b/docs-site/src/content/docs/zh-tw/reference/client-support.md index bb8c14dbddb..9a7ee10dccc 100644 --- a/docs-site/src/content/docs/zh-tw/reference/client-support.md +++ b/docs-site/src/content/docs/zh-tw/reference/client-support.md @@ -6,11 +6,11 @@ description: "opencodex 能連接哪些程式開發工具、每個工具如何 -opencodex 是一個本機閘道,連接你的 AI 程式開發工具與模型。部分工具由它原生設定;其餘工具則透過匯出或代管一個指向本機代理的設定檔來接入。本頁由程式碼中的登錄表產生,因此與目前版本實際提供的內容完全一致。 +opencodex 是一個本機閘道,連接你的 AI 程式開發工具與模型。它可以原生設定工具,也可以匯出或代管設定檔,或使用專用閘道連接器。本頁由程式碼中的登錄表產生,因此與目前版本實際提供的內容完全一致。 ## 支援等級 -- **implemented**: 用戶端已在登錄表中。對於匯出的設定,表中協定讀取自 opencodex 產生的設定,一旦變更產生就會失敗。標示*已審查*的協定表示其端點來自審查而非設定本身(原生用戶端,以及會把某個設定轉換為特定端點的用戶端);產生器會檢查被審查的程式碼是否仍然存在。「OpenAI 相容」的列不聲明具體端點。 +- **implemented**: 用戶端已在登錄表中。對於匯出的設定,表中協定讀取自 opencodex 產生的設定,一旦變更產生就會失敗。標示*已審查*的協定來自程式碼審查,而非自動讀取設定;產生器會檢查被審查的程式碼是否仍然存在。「OpenAI 相容」的列不聲明具體端點。 - **test-covered**: 符合 implemented,並連結了一個經審查選定、涵蓋該用戶端的測試案例。產生器只檢查該測試仍然存在且未被停用;它實際驗證什麼,請閱讀測試本身。 - **執行驗證**: 一次歷史觀察:有人在該日期,以表中所列的 opencodex 版本執行了表中所列的用戶端產品與版本,執行了所述情境,並附上證據連結。它不代表其他版本或產品。證據在新增結果時經過審查,產生器不會重新執行。短橫線表示尚無紀錄。 @@ -47,6 +47,15 @@ opencodex 是一個本機閘道,連接你的 AI 程式開發工具與模型。 | Gentle Shell | — | JSON | 是 | Chat Completions | test-covered ([測試](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gentle-shell-client.test.ts)) | — | 僅限本機監聽。 | | T3 Code | — | JSON | 是 | Anthropic Messages | test-covered ([測試](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/t3code-client.test.ts)) | — | 僅限本機監聽。套用前先執行該用戶端專屬的檢查,可能拒絕。 | +## 閘道用戶端 + +在控制台開啟 **路由 → Antigravity**(也可從 **路由 → 用戶端** 前往),或執行下列指令。這些連接器為各自的用戶端設定閘道,不匯出設定,也不使用受管理檔案整合流程。執行 agy 前,請重新載入提示的 shell 設定檔。 + +| 用戶端 | 入站協定 | 支援等級 | 執行驗證 | 在本機設定 | +| --- | --- | --- | --- | --- | +| Antigravity (desktop) | OpenAI 相容(端點由用戶端選擇) (已審查) | test-covered ([測試](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect antigravity` | +| agy (CLI) | Gemini-compatible (GenAI) (已審查) | test-covered ([測試](https://github.com/lidge-jun/opencodex/blob/dev/tests/clients/gateway-clients.test.ts)) | — | `ocx connect agy` | + ## 入站端點 代理接受以下協定。未列在上表中的工具,只要能為其中之一設定自訂端點,也可以接入。 @@ -54,7 +63,9 @@ opencodex 是一個本機閘道,連接你的 AI 程式開發工具與模型。 - `POST /v1/responses`: Responses - `POST /v1/chat/completions`: Chat Completions - `POST /v1/messages`: Anthropic Messages +- `POST /v1beta/models/{model}:generateContent`: Gemini-compatible (GenAI) +- `POST /v1beta/models/{model}:streamGenerateContent`: Gemini-compatible (GenAI) ## 保持本頁最新 -本頁由 `scripts/generate-client-support-matrix.ts` 根據匯出、代管整合與原生整合登錄表產生。要新增用戶端,請在 `scripts/client-support-matrix/metadata.ts` 中加入項目並執行 `bun run docs:clients`;已提交的頁面過期時,`bun run docs:clients:check` 會失敗。 +本頁由 `scripts/generate-client-support-matrix.ts` 根據匯出、代管整合、原生整合與閘道用戶端登錄表產生。要新增用戶端,請在 `scripts/client-support-matrix/metadata.ts` 中加入項目並執行 `bun run docs:clients`;已提交的頁面過期時,`bun run docs:clients:check` 會失敗。 diff --git a/gui/bun.lock b/gui/bun.lock index 9b21e0fe15d..95a94e2ca9a 100644 --- a/gui/bun.lock +++ b/gui/bun.lock @@ -38,6 +38,7 @@ "brace-expansion": "5.0.9", "nanoid": "3.3.18", "postcss": "8.5.26", + "ws": "8.23.1", }, "packages": { "@fontsource-variable/geist": ["@fontsource-variable/geist@5.3.0", "", {}, "sha512-j0m+vLQuG5XAYoHtGCVu0spvlGreR3EzpECUVzkFmI1mTVnAO38l/NEPDCFgZ177JxzYJCLSmTQibIiYPilGrA=="], @@ -282,7 +283,7 @@ "whatwg-mimetype": ["whatwg-mimetype@3.0.0", "", {}, "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q=="], - "ws": ["ws@8.21.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-+0NTnW77fFN/DjQi6k/Sq/Yvk4Sgajw7urW8V+asjXnRgDs9gyGkdb7EzgfhA4goXsRIZKE28fzIXBHEzhuiWw=="], + "ws": ["ws@8.23.1", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-1rzWDSN0NOi3tpwgHsQExjWRoKUGtjCkJ2gZRaaRtzhYLboMytOI9pj9PU7yCgY37auqdd4OyLofZDbkeuZmPA=="], "@tailwindcss/node/lightningcss": ["lightningcss@1.32.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="], diff --git a/gui/package.json b/gui/package.json index 2cc06287816..cec253e6f11 100644 --- a/gui/package.json +++ b/gui/package.json @@ -47,6 +47,7 @@ "overrides": { "brace-expansion": "5.0.9", "nanoid": "3.3.18", - "postcss": "8.5.26" + "postcss": "8.5.26", + "ws": "8.23.1" } } diff --git a/gui/src/components/CompactionRoutingPanel.tsx b/gui/src/components/CompactionRoutingPanel.tsx index b9b73c7197b..328b8fa5135 100644 --- a/gui/src/components/CompactionRoutingPanel.tsx +++ b/gui/src/components/CompactionRoutingPanel.tsx @@ -8,6 +8,21 @@ import { comboModelId, parseComboList } from "../combo-workspace-data"; import { formatNamespacedModelId } from "../provider-icons"; type Setting = { model: string; reasoningEffort?: string; triggers?: string[]; sourceModels?: string[] } | null; +type PromptDefaults = { standard: string; preservePrefix: string; maxAdditionalInstructionsLength: number }; +type SettingsPayload = { compactionRouting?: unknown; compactionAdditionalInstructions?: unknown; routedCompactionPromptDefaults?: unknown }; + +function readPromptDefaults(value: unknown): PromptDefaults { + if (!value || typeof value !== "object") throw new Error("invalid compaction prompt defaults"); + const record = value as Record; + if (!Object.prototype.hasOwnProperty.call(record, "standard") || typeof record.standard !== "string" || !record.standard.length + || !Object.prototype.hasOwnProperty.call(record, "preservePrefix") || typeof record.preservePrefix !== "string" || !record.preservePrefix.length + || !Object.prototype.hasOwnProperty.call(record, "maxAdditionalInstructionsLength") || typeof record.maxAdditionalInstructionsLength !== "number" + || !Number.isSafeInteger(record.maxAdditionalInstructionsLength) || record.maxAdditionalInstructionsLength < 1) { + throw new Error("invalid compaction prompt defaults"); + } + return { standard: record.standard, preservePrefix: record.preservePrefix, maxAdditionalInstructionsLength: record.maxAdditionalInstructionsLength }; +} + const EFFORTS = ["none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra"]; const TRIGGERS = ["manual", "auto"]; const SOURCE_RENDER_CAP = 300; @@ -64,7 +79,7 @@ function readComboProviders(payload: unknown): Map { return result; } -function readSetting(payload: { compactionRouting?: unknown }): Setting { +function readSetting(payload: SettingsPayload): Setting { const value = payload.compactionRouting; if (value == null) return null; if (!value || typeof value !== "object" || !("model" in value) || typeof value.model !== "string" || !value.model.trim()) { @@ -109,6 +124,9 @@ export default function CompactionRoutingPanel(props: { apiBase: string; models: function CompactionRoutingControls({ apiBase, models, providers: providerList = [] }: { apiBase: string; models: ModelInfo[]; providers?: Array<{ name: string; baseUrl: string }> }) { const t = useT(); const [saved, setSaved] = useState(undefined); + const [promptDefaults, setPromptDefaults] = useState(null); + const [savedInstructions, setSavedInstructions] = useState(""); + const [instructions, setInstructions] = useState(""); const [model, setModel] = useState(""); const [effort, setEffort] = useState(""); const [triggers, setTriggers] = useState("manual"); @@ -116,13 +134,23 @@ function CompactionRoutingControls({ apiBase, models, providers: providerList = const [sources, setSources] = useState([]); const [sourceQuery, setSourceQuery] = useState(""); const [busy, setBusy] = useState(false); + const [loading, setLoading] = useState(true); const [loadError, setLoadError] = useState(false); const [feedback, setFeedback] = useState<"saved" | "failed" | null>(null); const [comboProviders, setComboProviders] = useState>(() => new Map()); const active = useRef(false); const pending = useRef | null>(null); - const accept = useCallback((value: Setting) => { + const accept = useCallback((payload: SettingsPayload, isSave = false) => { + const value = readSetting(payload); + const extra = payload.compactionAdditionalInstructions; + if (extra != null && typeof extra !== "string") throw new Error("invalid compaction instructions"); + // Defaults are GET-only; preserve the loaded preview across saves and hide it if a reload omits or nulls them. + if (payload.routedCompactionPromptDefaults != null) setPromptDefaults(readPromptDefaults(payload.routedCompactionPromptDefaults)); + else if (!isSave) setPromptDefaults(null); + const normalizedExtra = extra?.trim() ? extra.replace(/\r\n?/g, "\n") : ""; + setSavedInstructions(normalizedExtra); + setInstructions(normalizedExtra); setSaved(value); setModel(value?.model ?? ""); setEffort(value?.reasoningEffort ?? ""); @@ -143,10 +171,11 @@ function CompactionRoutingControls({ apiBase, models, providers: providerList = const request = createBoundedFetch(15_000); pending.current = request; setLoadError(false); + setLoading(true); try { const response = await fetch(`${apiBase}/api/settings`, { signal: request.signal }); - const value = readSetting(await requireJson(response)); - if (active.current && pending.current === request) accept(value); + const payload = await requireJson(response); + if (active.current && pending.current === request) accept(payload); const combos = await fetch(`${apiBase}/api/combos`, { signal: request.signal }) .then(requireJson).then(readComboProviders).catch(() => new Map()); if (active.current && pending.current === request) setComboProviders(combos); @@ -154,6 +183,7 @@ function CompactionRoutingControls({ apiBase, models, providers: providerList = if (active.current && pending.current === request) setLoadError(true); } finally { request.clear(); + if (active.current && pending.current === request) setLoading(false); if (pending.current === request) pending.current = null; } }, [apiBase, accept]); @@ -181,20 +211,21 @@ function CompactionRoutingControls({ apiBase, models, providers: providerList = method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ - compactionRouting: model + ...(routingDirty ? { compactionRouting: model ? { model, ...(effort ? { reasoningEffort: effort } : {}), ...(choiceToTriggers(triggers) ? { triggers: choiceToTriggers(triggers) } : {}), ...(scope === "selected" && sources.length > 0 ? { sourceModels: sources } : {}), } - : null, + : null } : {}), + ...(instructionsDirty ? { compactionAdditionalInstructions: instructions.trim() ? instructions : null } : {}), }), signal: request.signal, }); - const value = readSetting(await requireJson(response)); + const payload = await requireJson(response); if (active.current && pending.current === request) { - accept(value); + accept(payload, true); setFeedback("saved"); } } catch { @@ -219,16 +250,17 @@ function CompactionRoutingControls({ apiBase, models, providers: providerList = // Saved selectors the catalog no longer lists stay visible, so saving never drops them by // omission and the operator removes them deliberately. const savedOnlySelectors = (saved?.sourceModels ?? []).filter(selector => !knownSelectors.has(selector)); - const disabled = busy || saved === undefined || loadError; + const disabled = busy || loading || saved === undefined || loadError; const savedScope = saved?.sourceModels ? "selected" : "all"; const savedSources = new Set(saved?.sourceModels); - const dirty = model !== (saved?.model ?? "") + const routingDirty = model !== (saved?.model ?? "") || effort !== (saved?.reasoningEffort ?? "") || triggers !== triggersToChoice(saved?.triggers) || scope !== savedScope || (scope === "selected" && (sources.length !== (saved?.sourceModels?.length ?? 0) || sources.some(selector => !savedSources.has(selector)))); + const instructionsDirty = promptDefaults !== null && (instructions.trim() ? instructions.replace(/\r\n?/g, "\n") : "") !== savedInstructions; const scopeEmpty = scope === "selected" && sources.length === 0; const selectedSources = new Set(sources); const filteredSources = [...new Set(models.map(item => item.namespaced))] @@ -265,7 +297,7 @@ function CompactionRoutingControls({ apiBase, models, providers: providerList = : t("compactionRouting.providerWarning", { provider })); return ( -
+
{t("compactionRouting.title")}
@@ -306,7 +338,7 @@ function CompactionRoutingControls({ apiBase, models, providers: providerList = options={[{ value: "", label: t("compactionRouting.currentEffort") }, ...EFFORTS.map(value => ({ value, label: t(`models.reasoningEffort.${value}` as TKey) }))]} onChange={value => { setEffort(value); setFeedback(null); }} />
-
@@ -335,6 +367,24 @@ function CompactionRoutingControls({ apiBase, models, providers: providerList = {scopeEmpty &&
{t("compactionRouting.sourcesNone")}
} } + {promptDefaults &&
+ +