Skip to content
Merged
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
2 changes: 2 additions & 0 deletions docs-site/src/content/docs/fr/reference/management-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,8 @@ lui-même s'il souhaite ajouter une étoile au dépôt.

### Cycle de vie du système

`POST /api/system/restart` conserve par défaut un délai de 60 secondes lorsque le corps est absent ou vaut `{}`. Une session de gestion ou un jeton administrateur peut choisir explicitement un délai plus court avec `{"drainGraceMs":2000}` : la valeur doit être un entier compris entre 1 et 60000 millisecondes. Un corps ou une valeur invalide renvoie 400 sans lancer le redémarrage ; la capacité locale liée à la cible ne permet pas cette option (403). `drainTimeoutMs` indique le délai accepté, fixé par le premier appel et inchangé lors des appels suivants. Il inclut le temps de transmission de la réponse ; les budgets de nettoyage et de préparation du processus de remplacement restent respectivement de 60 et 70 secondes. Une requête interrompue peut déjà avoir été exécutée : vérifiez son résultat avant de la renvoyer, sans répétition automatique.

| Méthode et chemin | Objectif | Erreurs notables |
| --- | --- | --- |
| `GET /api/system/memory` | Renvoyer les mesures scalaires du processus, du tas, des flux, de l'état des réponses, du mécanisme de surveillance et des tours actifs | — |
Expand Down
2 changes: 2 additions & 0 deletions docs-site/src/content/docs/ja/reference/management-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,8 @@ CLI コマンドは Anthropic OAuth アカウントを id または一意の別

### システムのライフサイクル

`POST /api/system/restart` は、本文を省略した場合や `{}` の場合、既定の 60 秒のドレイン猶予を維持します。管理セッションまたは管理者トークンを使う呼び出し元は、`{"drainGraceMs":2000}` で短い猶予を明示的に選択できます。値は 1~60000 ミリ秒の整数です。不正な本文や値は再起動を開始せずに 400 を返します。対象プロセスに限定されたローカル再起動 capability では、このオプションを設定できません(403)。応答の `drainTimeoutMs` は最初に受け入れた猶予を示し、繰り返しの呼び出しでも期限は変わりません。猶予には応答送信までの遅延を含み、クリーンアップと置換プロセスの準備には別々の 60 秒・70 秒の予算があります。中断された処理が既に実行された可能性があるため、再送前に結果を確認してください。自動再送は追加されません。

|メソッドとパス |目的 |注目すべきエラー |
| --- | --- | --- |
| `GET /api/system/memory` |スカラー プロセス、ヒープ、ストリーム、応答状態、ウォッチドッグ、およびアクティブ ターン メトリックを返します。 — |
Expand Down
2 changes: 2 additions & 0 deletions docs-site/src/content/docs/ko/reference/management-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,8 @@ OpenAI도 같은 규칙을 따르며, 스위치를 켠다고 별도의 922k 모

### 시스템 수명 주기

`POST /api/system/restart`는 본문이 없거나 `{}`이면 기본 60초 drain 유예 시간을 유지합니다. 관리 세션 또는 관리자 토큰을 사용하는 호출자는 `{"drainGraceMs":2000}`으로 짧은 유예 시간을 명시적으로 선택할 수 있습니다. 값은 1~60000밀리초의 정수여야 합니다. 잘못된 본문이나 값은 재시작을 시작하지 않고 400을 반환하며, 대상 프로세스에 한정된 로컬 재시작 capability는 이 옵션을 설정할 수 없습니다(403). 응답의 `drainTimeoutMs`는 처음 수락한 유예 시간을 나타내며 반복 호출은 기존 기한을 바꾸지 않습니다. 유예 시간에는 응답 전송 지연이 포함됩니다. 정리와 대체 프로세스 준비에는 각각 별도의 60초와 70초 예산이 유지됩니다. 중단된 요청이 이미 실행되었을 수 있으므로 재전송 전에 결과를 확인하세요. 자동 재전송은 추가되지 않습니다.

| HTTP 메서드와 경로 | 목적 | 주요 오류 |
| --- | --- | --- |
| `GET /api/system/memory` | 프로세스, heap, stream, response-state, watchdog, active-turn의 스칼라 메트릭을 반환합니다 | — |
Expand Down
19 changes: 18 additions & 1 deletion docs-site/src/content/docs/reference/management-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -662,6 +662,23 @@ whether to star the repository.

### System lifecycle

`POST /api/system/restart` keeps the 60-second drain by default, including requests
with no body or `{}`. An authenticated caller can explicitly send a JSON body such
as `{"drainGraceMs":2000}` to choose a shorter active-request/scoped-drain grace.
The value must be an integer from 1 to 60000 milliseconds. Invalid bodies or values
return 400 before starting a drain; the standard management-body limit still applies.
The target-bound local restart capability retains the default grace; setting this
body option requires a management session or admin token (otherwise 403).
The response's `drainTimeoutMs` reports the accepted grace. Repeated calls retain
the first accepted restart's grace and do not change its deadline.

Grace is measured from acceptance, including the response-flush delay. The cleanup
watchdog remains 60 seconds and replacement readiness retains its separate 70-second
budget. A short grace can interrupt a turn that already executed upstream. Check its
outcome before resubmitting; OpenCodex adds no automatic replay of ambiguous work,
and a healthy replacement does not prove resending is safe. The dashboard, CLI, tray
and automatic restarts continue using the 60-second default.

During a restart drain, new data-plane requests receive HTTP 503 with JSON
`error.type: "server_error"`, `error.code: "server_restarting"`, and the message
"OpenCodex is restarting; retry this request." Responses retain `Retry-After: 5`
Expand All @@ -671,7 +688,7 @@ the 503 without reporting model capacity; provider overload errors retain their
| Method and path | Purpose | Notable errors |
| --- | --- | --- |
| `GET /api/system/memory` | Return scalar process, heap, stream, response-state, watchdog, and active-turn metrics. Response-state diagnostics include spill-write status, consecutive failures, fixed privacy-safe failure class, and last failure/success timestamps. `spillLastWriteFailureOrigin` is `retry_returned_timeout`, `timeout_memo_refusal`, or null; cumulative `spillAclRetryReturnedTimeouts` and `spillAclTimeoutMemoRefusals` count terminal failed publications. See [Windows spill diagnostics](/troubleshooting/windows-memory/) for process-local semantics. Raw errors and paths are never returned. | — |
| `POST /api/system/restart` | Begin a drain-aware process restart without removing client injection | Returns 202; repeated calls report the existing drain |
| `POST /api/system/restart` | Begin a drain-aware process restart without removing client injection; optional JSON `drainGraceMs` explicitly shortens the default 60s grace | Returns 202; repeated calls report the existing grace; 400 invalid body or grace |
| `POST /api/stop` | Stop the service, restore native Codex, remove managed Grok injection, and drain the proxy | 409 service ownership conflict; 409 `respawnable_service` when a Windows Task Scheduler wrapper could respawn the proxy and the caller is not `ocx stop` (nothing is changed); 409 `self_unload_service` when this proxy is running as the installed launchd/systemd service, because stopping the manager from inside it would end the process before native Codex is restored — run `ocx stop` instead (nothing is changed); 409 when the installed manager refuses to stop; 409 `service_state_unknown` when the Task Scheduler state cannot be read (nothing is changed; repair the query and retry) |
| `GET /api/system/codex-app-server` | Report whether running Codex app-servers predate the current model catalog | — |
| `POST /api/system/codex-restart` | Refresh the catalog, then restart stale Codex app-servers and fully quit and relaunch the Codex desktop app so the model picker reloads. When the proxy itself is running inside the Codex app, the desktop restart is refused rather than handed off. | Returns 200 with `code: partially_stopped` when a target survives |
Expand Down
2 changes: 2 additions & 0 deletions docs-site/src/content/docs/ru/reference/management-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -338,6 +338,8 @@ Management-аутентификация доказывает доступ к п

### Жизненный цикл системы

`POST /api/system/restart` сохраняет стандартный период drain в 60 секунд, если тело отсутствует или равно `{}`. Сессия управления или токен администратора позволяют явно выбрать более короткий период через `{"drainGraceMs":2000}`. Значение должно быть целым числом от 1 до 60000 миллисекунд. Некорректное тело или значение возвращает 400 без запуска перезапуска; локальная capability, привязанная к целевому процессу, не разрешает этот параметр (403). Поле ответа `drainTimeoutMs` сообщает первый принятый период, который повторные вызовы не меняют. Отсчёт включает задержку отправки ответа; отдельные бюджеты очистки и готовности замены остаются равными 60 и 70 секундам. Прерванный запрос мог уже выполниться: проверьте результат перед повторной отправкой. Автоматическая повторная отправка не добавляется.

| Метод и путь | Назначение | Особые ошибки |
| --- | --- | --- |
| `GET /api/system/memory` | Вернуть скалярные метрики процесса, heap, stream, response-state, watchdog и active-turn | — |
Expand Down
2 changes: 2 additions & 0 deletions docs-site/src/content/docs/tr/reference/management-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,8 @@ dolaşmamalıdır. Depoya yıldız verip vermeyeceğini kullanıcı seçmelidir.

### Sistem yaşam döngüsü

`POST /api/system/restart`, gövde yoksa veya `{}` ise varsayılan 60 saniyelik boşaltma süresini korur. Bir yönetim oturumu veya yönetici token'ı, `{"drainGraceMs":2000}` ile daha kısa süreyi açıkça seçebilir. Değer 1 ile 60000 milisaniye arasında bir tam sayı olmalıdır. Geçersiz gövde veya değer, yeniden başlatmayı başlatmadan 400 döndürür; hedef sürece bağlı yerel yeniden başlatma capability'si bu seçeneğe izin vermez (403). Yanıttaki `drainTimeoutMs`, ilk kabul edilen süreyi bildirir; tekrarlanan çağrılar mevcut süreyi veya son tarihi değiştirmez. Yanıt gönderme gecikmesi bu süreye dahildir; temizleme ve yeni sürecin hazır olması için ayrı 60 ve 70 saniyelik bütçeler korunur. Kesilen bir istek zaten yürütülmüş olabilir: yeniden göndermeden önce sonucunu kontrol edin. Otomatik yeniden gönderme eklenmez.

| Yöntem ve yol | Amaç | Dikkate değer hatalar |
| --- | --- | --- |
| `GET /api/system/memory` | Skaler süreç, yığın (heap), akış, yanıt durumu, denetleyici ve aktif tur metriklerini döndürün | — |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,8 @@ OpenAI 也遵循此规则:开关不会选择特殊的 922k 模式。有效上

### 系统生命周期

`POST /api/system/restart` 在没有请求体或请求体为 `{}` 时保留默认的 60 秒排空等待。使用管理会话或管理员令牌的调用方可通过 `{"drainGraceMs":2000}` 显式选择短等待,取值须为 1–60000 毫秒的整数。无效 JSON 或参数返回 400,且不会开始重启;绑定目标进程的本机 restart capability 不允许设置该参数(403)。响应中的 `drainTimeoutMs` 表示首次接受的等待时间,重复调用不会改变已接受的时间或截止点。等待时间包含发送接受响应前的延迟,清理和替代进程就绪仍分别保留独立的 60 秒、70 秒预算。被中断的请求可能已经执行,重发前应核对结果;此选项不会增加自动重发。

| 方法和路径 | 用途 | 典型错误 |
| --- | --- | --- |
| `GET /api/system/memory` | 返回标量级的进程、堆、流、响应状态、看门狗和活跃回合指标 | — |
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,8 @@ OpenAI 也遵循此規則:開關不會選擇特殊的 922k 模式。生效中

### 系統生命週期

`POST /api/system/restart` 在沒有請求本文或本文為 `{}` 時,保留預設的 60 秒排空等待。使用管理工作階段或管理員權杖的呼叫端可透過 `{"drainGraceMs":2000}` 明確選擇短等待;值必須是 1–60000 毫秒的整數。無效 JSON 或參數回傳 400,且不會開始重新啟動;綁定目標行程的本機 restart capability 不允許設定此參數(403)。回應中的 `drainTimeoutMs` 表示第一次接受的等待時間,重複呼叫不會變更已接受的時間或截止點。等待時間包含傳送接受回應前的延遲;清理與替代行程就緒仍分別保留獨立的 60 秒及 70 秒預算。被中斷的請求可能已經執行,重新傳送前應核對結果;此選項不會增加自動重新傳送。

| 方法與路徑 | 用途 | 主要錯誤 |
| --- | --- | --- |
| `GET /api/system/memory` | 回傳純量行程、heap、串流、回應狀態、看門狗與活躍回合指標 | — |
Expand Down
1 change: 1 addition & 0 deletions scripts/test-layout/layout.json
Original file line number Diff line number Diff line change
Expand Up @@ -1807,6 +1807,7 @@
"system-restart-client-package-tree.test.ts": "cli",
"system-restart-client.test.ts": "cli",
"system-restart-contract-security.test.ts": "lib",
"system-restart-admission.test.ts": "server",
"system-restart.test.ts": "server",
"system-routes.test.ts": "server",
"systemd-install-cleanup-hardening.test.ts": "service",
Expand Down
2 changes: 1 addition & 1 deletion src/server/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,7 @@ export async function drainAndShutdown(
beginBackgroundShellShutdown();
try {
while (admittedTurns.size > 0 && Date.now() < deadline) {
await Bun.sleep(100);
await Bun.sleep(Math.min(100, Math.max(0, deadline - Date.now())));
}
if (admittedTurns.size > 0) {
console.warn(`⚠️ Aborting ${admittedTurns.size} in-flight turn(s) after ${timeoutMs}ms deadline`);
Expand Down
Loading
Loading