Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions docs-site/src/content/docs/es/reference/management-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,22 @@ Las solicitudes PUT válidas a `/api/selected-models` y `/api/model-presets` dev

La visibilidad/selección exitosa escribe a `/api/disabled-models`, `/api/model-visibility`, `/api/selected-models` y `/api/model-presets` para informar los resultados de seguimiento en `catalogRefresh` y `clientIntegrations` cuando se ejecuta esa ruta de actualización. HTTP 200 y `ok: true` confirman la selección guardar; no garantizan todos los catálogos de clientes actualizados. Inspeccione `clientIntegrations[]` para `ok: false`, `client`, opcional Aparte `profileId`, y el rechazo `reason`; los detalles de recuperación también pueden incluir `refusalReason`, `snapshotPath` y `residual`. La página Modelos mantiene la selección guardada y muestra una advertencia de actualización del cliente por separado. Inspeccione las integraciones y resuelva el problema notificado antes de volver a intentar `ocx sync`. Los campos de resultado que faltan de un servidor antiguo no establecen una recuperación exitosa.

<a id="live-meter-get-v1usagelive"></a>

### Medidor en vivo (`GET /v1/usage/live`)

Un endpoint de solo lectura del plano de datos informa de la solicitud completada más reciente: velocidad de salida, acierto de caché y ocupación del contexto. Un cliente, como un userscript de Codex de escritorio, puede consultarlo para mostrar esas cifras junto al compositor. Se admite exactamente igual que `/v1/models`: sin credencial en un enlace loopback, con una clave de datos (`x-opencodex-api-key`, `Authorization: Bearer` o `x-api-key`) en otro caso, y nunca con el token de administración. El origen de la página de Codex de escritorio `app://-` puede leer solo esta ruta (y su preflight); las demás rutas del plano de datos conservan sus reglas de origen.

Consulta: `client=codex|claude|other` limita el resultado a una familia de clientes y `conversation=<id>` a una conversación. El filtro de conversación acepta el id original, el resumen registrado o un enlace `codex://threads/<id>`, y la respuesta nunca lo repite. El cuerpo es `{ "latest": Meter | null, "byClient": { "codex"?: Meter, "claude"?: Meter, "other"?: Meter }, "generatedAt": <ms> }`. Un `Meter` contiene `speed { value, reason }`, `outputTokens`, `generationMs`, `cache { readTokens, inputTokens, percent, reason }`, `context { usedTokens, limitTokens, percent, reason }`, `model`, `provider`, `client` y `timestamp`: solo números, nombres de modelo y proveedor y códigos de motivo. Las revisiones automáticas de aprobación (`codex-auto-review`) nunca se informan.

Un valor es `null` (se muestra como `--`) en lugar de una estimación cuando no se puede medir:

| Valor | `null` cuando |
| --- | --- |
| `speed` | La solicitud falló, se canceló o terminó incompleta; el uso falta o es estimado; faltan los tokens de salida; la ventana de generación no se registró, dura menos de 1 s o es incoherente. La velocidad es tokens de salida entre la ventana de generación, nunca el tiempo total. |
| `cache.percent` | El uso falta o es estimado, falta el recuento de entrada o la lectura de caché solo existe en el cable. |
| `context.percent` | El uso falta o es estimado, o la ventana de contexto del modelo no está en el catálogo persistido de Codex (`context.reason` es `limit_unknown`). |

<a id="oauth-accounts-provider-keys-and-data-plane-keys"></a>

### Cuentas OAuth, claves de proveedor y claves de plano de datos
Expand Down
14 changes: 14 additions & 0 deletions docs-site/src/content/docs/reference/management-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -672,6 +672,20 @@ The Models page keeps the saved selection and shows a separate client-refresh wa
Inspect Integrations and resolve the reported issue before retrying `ocx sync`. Missing
outcome fields from an older server do not establish successful recovery.

### Live meter (`GET /v1/usage/live`)

A read-only data-plane endpoint reports the newest completed request: output speed, cache hit and context fill. A client such as a Codex desktop userscript can poll it to show those numbers next to the composer. It is admitted exactly like `/v1/models`: no credential on a loopback bind, a data key (`x-opencodex-api-key`, `Authorization: Bearer` or `x-api-key`) otherwise, and never the admin token. The Codex desktop page origin `app://-` may read this one route (and its preflight); every other data-plane route keeps its existing origin rules.

Query: `client=codex|claude|other` narrows the result to one client family, and `conversation=<id>` to one conversation. The conversation filter accepts the raw id, the logged digest or a `codex://threads/<id>` link, and the response never echoes it. The body is `{ "latest": Meter | null, "byClient": { "codex"?: Meter, "claude"?: Meter, "other"?: Meter }, "generatedAt": <ms> }`. A `Meter` carries `speed { value, reason }`, `outputTokens`, `generationMs`, `cache { readTokens, inputTokens, percent, reason }`, `context { usedTokens, limitTokens, percent, reason }`, `model`, `provider`, `client` and `timestamp`: numbers, model and provider names and reason codes only. Automatic approval reviews (`codex-auto-review`) are never reported.

A value is `null` (shown as `--`) instead of a guess when it cannot be measured:

| Value | `null` when |
| --- | --- |
| `speed` | The request failed, was cancelled or ended incomplete; usage is missing or estimated; output tokens are missing; the generation window is not recorded, shorter than 1 s or inconsistent. Speed is output tokens over the generation window, never wall time. |
| `cache.percent` | Usage is missing or estimated, the input count is missing or the cache read is wire-only. |
| `context.percent` | Usage is missing or estimated, or the model's context window is not in the persisted Codex catalog (`context.reason` is `limit_unknown`). |

### OAuth accounts, provider keys, and data-plane keys

OAuth account rows always include `plan`: a validated upstream subscription label or `null`
Expand Down
14 changes: 14 additions & 0 deletions docs-site/src/content/docs/zh-cn/reference/management-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,20 @@ Aside 配置档的变更在这种情况下仍会保存一件事:确认之后

可靠的初始模型列表尚未确认时,有效的 `PUT /api/selected-models` 和 `PUT /api/model-presets` 请求也会返回 HTTP 409 和代码 `initial_model_selection_pending`。请使用 `GET /api/models` 等方式刷新模型列表,成功后再重试。

### 实时指标(`GET /v1/usage/live`)

只读的数据平面端点,返回最近一次已完成请求的输出速度、缓存命中率和上下文占用,例如供 Codex 桌面端用户脚本在输入框旁显示。准入与 `/v1/models` 完全相同:回环绑定无需凭据,否则需要数据密钥(`x-opencodex-api-key`、`Authorization: Bearer` 或 `x-api-key`),永远不接受管理令牌。Codex 桌面端页面来源 `app://-` 仅可读取这一条路由(及其预检),其他数据平面路由的来源规则不变。

查询参数:`client=codex|claude|other` 限定客户端类别,`conversation=<id>` 限定单个会话;会话过滤接受原始 id、日志中的摘要或 `codex://threads/<id>` 链接,响应不会回显它。响应体为 `{ "latest": Meter | null, "byClient": { "codex"?: Meter, "claude"?: Meter, "other"?: Meter }, "generatedAt": <毫秒> }`。`Meter` 含 `speed { value, reason }`、`outputTokens`、`generationMs`、`cache { readTokens, inputTokens, percent, reason }`、`context { usedTokens, limitTokens, percent, reason }`、`model`、`provider`、`client`、`timestamp`,只有数字、模型与 provider 名称和原因码。自动审批审查(`codex-auto-review`)不会被报告。

无法测量时对应值为 `null`(显示为 `--`),绝不猜测:

| 值 | 为 `null` 的情况 |
| --- | --- |
| `speed` | 请求失败、被取消或未完整结束;用量缺失或为估算值;缺少输出 token;生成窗口未记录、短于 1 秒或不一致。速度是输出 token 除以生成窗口,而不是墙钟时间。 |
| `cache.percent` | 用量缺失或为估算值、缺少输入数,或缓存读取仅存在于线路层。 |
| `context.percent` | 用量缺失或为估算值,或该模型的上下文窗口不在已持久化的 Codex 目录中(`context.reason` 为 `limit_unknown`)。 |

### OAuth 账户、provider 密钥和数据平面密钥

| 方法和路径 | 用途 | 典型错误 |
Expand Down
14 changes: 14 additions & 0 deletions docs-site/src/content/docs/zh-tw/reference/management-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,20 @@ Aside 設定檔的變更在這種情況下仍會儲存一件事:確認之後

尚未確認可靠的初始模型清單時,有效的 `PUT /api/selected-models` 和 `PUT /api/model-presets` 請求也會回傳 HTTP 409 和代碼 `initial_model_selection_pending`。請使用 `GET /api/models` 等方式更新模型清單,成功後再重試。

### 即時指標(`GET /v1/usage/live`)

唯讀的資料平面端點,回傳最近一次已完成請求的輸出速度、快取命中率與上下文占用,例如供 Codex 桌面端使用者腳本在輸入框旁顯示。存取許可與 `/v1/models` 完全相同:回送綁定不需憑證,否則需要資料金鑰(`x-opencodex-api-key`、`Authorization: Bearer` 或 `x-api-key`),永遠不接受管理權杖。Codex 桌面端頁面來源 `app://-` 僅可讀取這一條路由(及其預檢),其他資料平面路由的來源規則不變。

查詢參數:`client=codex|claude|other` 限定用戶端類別,`conversation=<id>` 限定單一對話;對話過濾接受原始 id、日誌中的摘要或 `codex://threads/<id>` 連結,回應不會回顯它。回應本體為 `{ "latest": Meter | null, "byClient": { "codex"?: Meter, "claude"?: Meter, "other"?: Meter }, "generatedAt": <毫秒> }`。`Meter` 含 `speed { value, reason }`、`outputTokens`、`generationMs`、`cache { readTokens, inputTokens, percent, reason }`、`context { usedTokens, limitTokens, percent, reason }`、`model`、`provider`、`client`、`timestamp`,只有數字、模型與供應商名稱和原因碼。自動核准審查(`codex-auto-review`)不會被回報。

無法量測時對應值為 `null`(顯示為 `--`),絕不猜測:

| 值 | 為 `null` 的情況 |
| --- | --- |
| `speed` | 請求失敗、被取消或未完整結束;用量缺失或為估算值;缺少輸出 token;生成視窗未記錄、短於 1 秒或不一致。速度是輸出 token 除以生成視窗,而不是牆鐘時間。 |
| `cache.percent` | 用量缺失或為估算值、缺少輸入數,或快取讀取僅存在於線路層。 |
| `context.percent` | 用量缺失或為估算值,或該模型的上下文視窗不在已持久化的 Codex 目錄中(`context.reason` 為 `limit_unknown`)。 |

### OAuth 帳號、供應商金鑰與 data-plane 金鑰

| 方法與路徑 | 用途 | 主要錯誤 |
Expand Down
4 changes: 2 additions & 2 deletions scripts/test-layout/layout.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"anthropic2-discovery-ownership.test.ts": "oauth",
"codex-shim-runtime-preflight.test.ts": "codex-integration",
"cli-anthropic2-account.test.ts": "cli", "anthropic2-catalog.test.ts": "codex-integration", "provider-anthropic-instance-quota.test.ts": "providers", "anthropic2-management.test.ts": "server",
"management-sidecar-anthropic-instance.test.ts": "server", "anthropic2-usage-attribution.test.ts": "usage", "vision-anthropic-instance-sidecar.test.ts": "vision", "web-search-anthropic-instance.test.ts": "web-search",
"management-sidecar-anthropic-instance.test.ts": "server", "anthropic2-usage-attribution.test.ts": "usage", "live-meter.test.ts": "usage", "vision-anthropic-instance-sidecar.test.ts": "vision", "web-search-anthropic-instance.test.ts": "web-search",
"provider-anthropic-instance.test.ts": "providers", "config-anthropic-instance-pool.test.ts": "config", "oauth-anthropic-instance-registration.test.ts": "oauth", "oauth-anthropic-instance-refresh.test.ts": "oauth",
"model-costs-pricing-cache.test.ts": "server", "model-costs-prompt-length-pricing.test.ts": "server", "cli-models-prompt-length-pricing.test.ts": "cli", "usage-prompt-length-pricing.test.ts": "usage",
"claude-picker-upload.test.ts": "claude-integration", "claude-picker-linger.test.ts": "claude-integration", "messages-native-scope.test.ts": "claude-integration", "catalog-auto-review-row.test.ts": "codex-integration",
Expand Down Expand Up @@ -1049,7 +1049,7 @@
"history-paginated-transition-destinations.test.ts": "codex-integration",
"hub-gated-local-clients.test.ts": "cli",
"hub-invite.test.ts": "cli", "hub-disable.test.ts": "cli",
"hub-usage.test.ts": "server",
"hub-usage.test.ts": "server", "live-meter-handler.test.ts": "server",
"hyperbolic-provider.test.ts": "providers",
"identity-neutralize.test.ts": "adapters",
"identity-subagent.test.ts": "adapters",
Expand Down
2 changes: 2 additions & 0 deletions src/server/auth-cors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -704,6 +704,8 @@ export const AUTH_MATRIX: readonly ApiAuthMatrixRow[] = [
{ endpoint: "/v1/hub-state", bearer: "accepted", dedicated: "accepted", xApiKey: "accepted" },
// Usage additionally requires a configured key identity; unscoped environment keys are refused.
{ endpoint: "/v1/usage", bearer: "rejected", dedicated: "accepted", xApiKey: "rejected" },
// The live meter reads the in-process request log only (numbers and model names), admitted like /v1/models.
{ endpoint: "/v1/usage/live", bearer: "accepted", dedicated: "accepted", xApiKey: "accepted" },
];

/** Whether `token` is the environment-provided management secret. */
Expand Down
2 changes: 2 additions & 0 deletions src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -413,6 +413,8 @@ function startServerWithSpendLedgerOwner(port: number | undefined, deps: StartSe
if (path === "/v1/audio/transcriptions") return req.method === "POST";
if (path === "/v1/audio/transcriptions/stream") return req.headers.get("upgrade")?.toLowerCase() === "websocket";
if (path === "/v1/alpha/search") return req.method === "POST";
// Live meter (#8735): GET-only numbers from the local request log; Codex++ reads it here.
if (path === "/v1/usage/live") return req.method === "GET";
if (contextEndpoint(path)) return req.method === "POST";
if (path === "/v1/images/generations" || path === "/v1/images/edits") {
return req.method === "POST";
Expand Down
10 changes: 10 additions & 0 deletions src/server/index/serve-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,10 @@ export function createServeOptions(ctx: ServeOptionsContext) {
if (readyzPath !== undefined) {
return withCors(formatErrorResponse(404, "not_found", messagesUnknownEndpointMessage(req)), req, policy);
}
if (url.pathname === "/v1/usage/live") {
const preflight = (await import("../live-meter-handler")).liveMeterPreflight(req, policy);
if (preflight) return preflight;
}
// The exact Ollama-compatible paths are data-plane routes and take data-plane CORS.
const managementPreflight = url.pathname.startsWith("/api/") && !isOllamaNativePath(url.pathname);
const allowed = managementPreflight
Expand Down Expand Up @@ -795,6 +799,12 @@ export function createServeOptions(ctx: ServeOptionsContext) {
);
}

if (url.pathname === "/v1/usage/live" && req.method === "GET") {
// Same admission as the model routes; the module adds only the Codex desktop origin for this read.
const { handleLiveMeterData } = await import("../live-meter-handler");
return handleLiveMeterData(req, policy);
}

if (url.pathname === "/v1/usage" && req.method === "GET") {
const { handleHubUsage } = await import("../hub-usage");
return handleHubUsage(req, config, policy);
Expand Down
Loading
Loading