Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6862: fix(codex): widen thread setup handshake budget (#7790)

mrlonely2ebe0ae327df
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index 39fbe045da..30999597b0 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -253,7 +253,7 @@ Daemon behavior is configured via flags or environment variables:
| Agent tool watchdog | — | `MULTICA_AGENT_TOOL_WATCHDOG` | same as the idle watchdog (`0` = never force-stop during a tool call) |
| Codex semantic inactivity timeout | `--codex-semantic-inactivity-timeout` | `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | same as the idle watchdog (Codex's timer is not tool-aware, so it tracks the larger of the idle / tool budgets) |
| Codex first-turn no-progress timeout | — | `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` (keeps the built-in `60s` ceiling) |
-| Codex handshake timeout | `--codex-handshake-timeout` | `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s` |
+| Codex handshake timeout | `--codex-handshake-timeout` | `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s`; `thread/start` and `thread/resume`: `60s` (an explicit value overrides both budgets globally) |
| OpenCode idle watchdog | — | `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` (`0` falls back to the generic idle watchdog; cannot extend it) |
| Max concurrent tasks | `--max-concurrent-tasks` | `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` | `20` |
| Daemon ID | `--daemon-id` | `MULTICA_DAEMON_ID` | hostname |
diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdx
index 545cca3de1..4a1350ecb6 100644
--- a/apps/docs/content/docs/environment-variables.ja.mdx
+++ b/apps/docs/content/docs/environment-variables.ja.mdx
@@ -231,7 +231,7 @@ API key と base URL の両方が空の場合、このレイヤーは無効に
| `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` | OpenCode 専用の静穏しきい値 |
| `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | `MULTICA_AGENT_IDLE_WATCHDOG` と同じ | Codex のセマンティック静穏しきい値。Codex 自身のタイマーはツール実行中かどうかを判別できないため、独自の短い上限を持たず idle / tool 予算の大きい方に追従します |
| `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` | Codex 初回ターンの無進捗上限を明示的に上書き;`0` はデフォルトを維持。実効の初回ターン待機は依然として `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` と全体の実行タイムアウトに制限される——`MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` をこの値より厳密に大きく(余裕を持たせて)設定すること。さもないと待機はその値で打ち切られ、モデルカタログの起動リトライがスキップされる。同値では不十分:セマンティックタイマーが先に起動するため、同値の場合でもリトライが失われることがある |
-| `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s` | Codex app-server 起動ハンドシェイクの上限 |
+| `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s`、`thread/start`・`thread/resume`:`60s` | Codex app-server 起動ハンドシェイクの上限。明示的な値は両方の予算を一括で上書きします |
| `MULTICA_DAEMON_AUTO_UPDATE` | Cloud は `true`、セルフホストは `false` | CLI の更新を自動でチェックして適用するか |
| `MULTICA_DAEMON_AUTO_UPDATE_INTERVAL` | `6h` | 更新チェックの間隔 |
| `MULTICA_DAEMON_AUTO_RELOAD` | `true` | 帯域外で置き換えられた `multica` バイナリ(`brew upgrade`、再ダウンロード、ローカルビルド)へ再起動して追従するかどうか。`MULTICA_DAEMON_AUTO_UPDATE` とは独立 |
@@ -272,7 +272,7 @@ multica config show
| `heartbeat_interval` | `15s` | ハートビート間隔 |
| `agent_timeout` | 無制限 | 1 回の実行の絶対時間上限 |
| `codex_semantic_inactivity_timeout` | 派生値 | Codex のセマンティック静穏しきい値。未設定なら idle と tool の watchdog 予算のうち大きい方を採用し、tool 予算が `0` の場合は idle 予算に回帰します。Codex 自身の `10m` が残るのは watchdog 一式を無効化したときだけです |
-| `codex_handshake_timeout` | `30s` | Codex app-server ハンドシェイクの上限 |
+| `codex_handshake_timeout` | `30s`、`thread/start`・`thread/resume`:`60s` | Codex app-server 起動ハンドシェイクの上限。明示的な値は両方の予算を一括で上書きします |
| `disable_auto_update` | 環境に従う | `true` で自動更新を無効化。`false` はローカルの上書きをクリアし、環境変数またはデフォルトに戻します |
| `auto_update_check_interval` | `6h` | 更新チェックの間隔 |
| `disable_auto_reload` | 環境に従う | `true` でディスク上の置き換えへの追従を停止。`false` はローカルの上書きをクリア。`disable_auto_update` とは別に解決されます |
diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdx
index 4144cb0715..af3966d28d 100644
--- a/apps/docs/content/docs/environment-variables.ko.mdx
+++ b/apps/docs/content/docs/environment-variables.ko.mdx
@@ -231,7 +231,7 @@ API key와 base URL이 모두 비어 있으면 이 레이어가 꺼지고 업스
| `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` | OpenCode 전용 무응답 기준값 |
| `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | `MULTICA_AGENT_IDLE_WATCHDOG`와 동일 | Codex 의미 활동 없음 기준값. Codex 자체 타이머는 도구 실행 중인지 알 수 없으므로 별도의 짧은 상한 대신 idle / tool 예산 중 큰 값을 따릅니다 |
| `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` | Codex 첫 턴 무진행 상한의 명시적 재정의; `0` 은 기본값 유지. 실제 첫 턴 대기는 여전히 `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` 및 전체 실행 타임아웃으로 제한됨 — `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` 을 이 값보다 엄격히 크게(여유를 두고) 설정해야 하며, 그렇지 않으면 대기가 그 값으로 잘리고 모델 카탈로그 시작 재시도가 건너뛰어짐. 값이 같으면 충분하지 않음: 의미 타이머가 먼저 시작되므로 값이 같을 때도 재시도가 손실될 수 있음 |
-| `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s` | Codex app-server 시작 handshake 상한 |
+| `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s`, `thread/start`·`thread/resume`: `60s` | Codex app-server 시작 handshake 상한. 명시적으로 설정한 값은 두 예산을 모두 일괄 재정의합니다 |
| `MULTICA_DAEMON_AUTO_UPDATE` | Cloud `true`, 자체 호스팅 `false` | CLI 자동 확인 및 업데이트 여부 |
| `MULTICA_DAEMON_AUTO_UPDATE_INTERVAL` | `6h` | 업데이트 확인 간격 |
| `MULTICA_DAEMON_AUTO_RELOAD` | `true` | 외부에서 교체된 `multica` 바이너리(`brew upgrade`, 재다운로드, 로컬 빌드)로 재시작할지 여부. `MULTICA_DAEMON_AUTO_UPDATE`와 독립적 |
@@ -272,7 +272,7 @@ multica config show
| `heartbeat_interval` | `15s` | heartbeat 간격 |
| `agent_timeout` | 제한 없음 | 단일 실행의 절대 시간 제한 |
| `codex_semantic_inactivity_timeout` | 파생 | Codex 의미 활동 없음 기준값. 설정하지 않으면 idle과 tool watchdog 예산 중 큰 값을 따르고, tool 예산이 `0`이면 idle 예산으로 되돌아갑니다. Codex 자체의 `10m`은 watchdog 전체를 비활성화했을 때만 유지됩니다 |
-| `codex_handshake_timeout` | `30s` | Codex app-server handshake 상한 |
+| `codex_handshake_timeout` | `30s`, `thread/start`·`thread/resume`: `60s` | Codex app-server 시작 handshake 상한. 명시적으로 설정한 값은 두 예산을 모두 일괄 재정의합니다 |
| `disable_auto_update` | 환경을 따름 | `true`는 자동 업데이트를 끔. `false`는 로컬 덮어쓰기를 지우고 환경 변수 또는 기본값으로 복귀 |
| `auto_update_check_interval` | `6h` | 업데이트 확인 간격 |
| `disable_auto_reload` | 환경을 따름 | `true`는 디스크에서 교체된 바이너리 추적을 끔. `false`는 로컬 덮어쓰기를 지움. `disable_auto_update`와 별도로 해석됨 |
diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdx
index 59d65253aa..8a7a461c4c 100644
--- a/apps/docs/content/docs/environment-variables.mdx
+++ b/apps/docs/content/docs/environment-variables.mdx
@@ -231,7 +231,7 @@ The variables below are read on the computer that runs your agents, not in the A
| `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` | OpenCode-specific silence threshold |
| `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | same as `MULTICA_AGENT_IDLE_WATCHDOG` | Codex semantic-silence threshold. Codex's own timer cannot see that a tool is running, so it tracks the larger of the idle / tool budgets instead of holding a separate, shorter ceiling |
| `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` | Explicit override for the Codex first-turn no-progress ceiling; `0` keeps the default. The effective first-turn wait stays bounded by `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` and the overall execution timeout — set `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` strictly above this value (with some margin), or the wait is truncated to it and the model-catalog startup retry is skipped. Equal values are not enough: the semantic timer is armed first, so at equal durations the retry can still be lost |
-| `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s` | Codex app-server startup handshake ceiling |
+| `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s`; `thread/start`, `thread/resume`: `60s` | Codex app-server startup handshake ceilings. An explicit value overrides both budgets globally |
| `MULTICA_DAEMON_AUTO_UPDATE` | Cloud `true`; self-hosted `false` | Whether to check for and apply CLI updates automatically |
| `MULTICA_DAEMON_AUTO_UPDATE_INTERVAL` | `6h` | Update check interval |
| `MULTICA_DAEMON_AUTO_RELOAD` | `true` | Whether to restart into a `multica` binary replaced on disk out of band (`brew upgrade`, a re-download, a local build). Independent of `MULTICA_DAEMON_AUTO_UPDATE` |
@@ -272,7 +272,7 @@ Supported keys:
| `heartbeat_interval` | `15s` | Heartbeat interval |
| `agent_timeout` | unlimited | Absolute time limit per run |
| `codex_semantic_inactivity_timeout` | derived | Codex semantic-silence threshold. With nothing set it takes the larger of the idle and tool watchdog budgets; a tool budget of `0` falls back to the idle budget, and only when the whole watchdog suite is disabled does Codex keep its own `10m` |
-| `codex_handshake_timeout` | `30s` | Codex app-server handshake ceiling |
+| `codex_handshake_timeout` | `30s`; `thread/start`, `thread/resume`: `60s` | Codex app-server startup handshake ceilings. An explicit value overrides both budgets globally |
| `disable_auto_update` | follows environment | `true` turns auto-update off; `false` clears the local override and returns to the env var or default |
| `auto_update_check_interval` | `6h` | Update check interval |
| `disable_auto_reload` | follows environment | `true` stops the daemon following a binary replaced on disk; `false` clears the local override. Resolved separately from `disable_auto_update` |
diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdx
index 63cb85a613..aca24def63 100644
--- a/apps/docs/content/docs/environment-variables.zh.mdx
+++ b/apps/docs/content/docs/environment-variables.zh.mdx
@@ -231,7 +231,7 @@ API key 与 base URL 都为空时,这一层关闭,不会发出任何上游
| `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` | OpenCode 专用静默阈值 |
| `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | 同 `MULTICA_AGENT_IDLE_WATCHDOG` | Codex 语义静默阈值。Codex 自己的计时器看不到工具是否在执行,因此跟随 idle / tool 预算中较大的那个,而不再单独保留一个更短的上限 |
| `MULTICA_CODEX_FIRST_TURN_TIMEOUT` | `0` | 显式覆盖 Codex 首轮无进展上限;`0` 保持默认值。实际首轮等待仍受 `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` 和总执行超时限制——需将 `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` 设为严格大于此值(并留出余量),否则等待会被截断至该值,且会跳过模型目录启动重试。设为相等还不够:语义计时器先启动,两者相等时仍可能丢失该重试 |
-| `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s` | Codex app-server 启动握手上限 |
+| `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s`;`thread/start`、`thread/resume`:`60s` | Codex app-server 启动握手上限;显式设置后会统一覆盖两类预算 |
| `MULTICA_DAEMON_AUTO_UPDATE` | Cloud `true`;自托管 `false` | 是否自动检查并更新 CLI |
| `MULTICA_DAEMON_AUTO_UPDATE_INTERVAL` | `6h` | 检查更新的间隔 |
| `MULTICA_DAEMON_AUTO_RELOAD` | `true` | 是否在 `multica` 二进制被带外替换(`brew upgrade`、重新下载、本地构建)后重启到新二进制。与 `MULTICA_DAEMON_AUTO_UPDATE` 相互独立 |
@@ -272,7 +272,7 @@ multica config show
| `heartbeat_interval` | `15s` | 心跳间隔 |
| `agent_timeout` | 不限制 | 单次执行的绝对时限 |
| `codex_semantic_inactivity_timeout` | 派生 | Codex 语义静默阈值。未设置时取 idle 与 tool watchdog 预算中较大的那个;tool 预算为 `0` 时回落到 idle 预算;只有整套 watchdog 关闭时才保留 Codex 自己的 `10m` |
-| `codex_handshake_timeout` | `30s` | Codex app-server 握手上限 |
+| `codex_handshake_timeout` | `30s`;`thread/start`、`thread/resume`:`60s` | Codex app-server 启动握手上限;显式设置后会统一覆盖两类预算 |
| `disable_auto_update` | 跟随环境 | `true` 关闭自动更新;`false` 清除本地覆盖,回到环境变量或默认 |
| `auto_update_check_interval` | `6h` | 检查更新的间隔 |
| `disable_auto_reload` | 跟随环境 | `true` 让守护进程不再跟随磁盘上被替换的二进制;`false` 清除本地覆盖。与 `disable_auto_update` 分开解析 |
diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.go
index 422bb88353..1ca239c2de 100644
--- a/server/internal/daemon/config.go
+++ b/server/internal/daemon/config.go
@@ -30,6 +30,7 @@ const (
DefaultAgentTimeout = 0
DefaultCodexSemanticInactivityTimeout = 10 * time.Minute
DefaultCodexHandshakeTimeout = 30 * time.Second
+ DefaultCodexThreadHandshakeTimeout = 60 * time.Second
// DefaultOpenCodeIdleWatchdog shortens the no-message budget for OpenCode
// runs while they are not executing a tool. OpenCode streams text and tool
// events incrementally, so a completely silent interval here covers both a
@@ -134,6 +135,7 @@ type Config struct {
// for app-servers that are legitimately slow to their first event (GH #3262).
CodexFirstTurnNoProgressTimeout time.Duration
CodexHandshakeTimeout time.Duration
+ CodexThreadHandshakeTimeout time.Duration
OpenCodeIdleWatchdog time.Duration // OpenCode-specific no-message window; 0 falls back to AgentIdleWatchdog and values above it cannot extend the global bound
AgentIdleWatchdog time.Duration // force-stop a run when the backend goes silent this long with an empty queue (0 = disabled)
AgentToolWatchdog time.Duration // force-stop a run when a single tool call stays in flight (silent) this long (0 = never force-stop during a tool call); defaults to AgentIdleWatchdog, so operators tune one number unless they deliberately want a wider tool budget
@@ -416,6 +418,19 @@ func LoadConfig(overrides Overrides) (Config, error) {
if overrides.CodexHandshakeTimeout > 0 {
codexHandshakeTimeout = overrides.CodexHandshakeTimeout
}
+ // Preserve the legacy global override semantics while giving the heavy
+ // thread RPCs a wider built-in default. The CLI resolves flag, env and
+ // persisted config values into Overrides, while embedded callers may reach
+ // LoadConfig with the environment directly.
+ codexThreadHandshakeTimeout := DefaultCodexThreadHandshakeTimeout
+ if raw, ok := os.LookupEnv("MULTICA_CODEX_HANDSHAKE_TIMEOUT"); ok && strings.TrimSpace(raw) != "" {
+ if parsed, parseErr := parseFlexDuration(strings.TrimSpace(raw)); parseErr == nil && parsed > 0 {
+ codexThreadHandshakeTimeout = codexHandshakeTimeout
+ }
+ }
+ if overrides.CodexHandshakeTimeout > 0 {
+ codexThreadHandshakeTimeout = overrides.CodexHandshakeTimeout
+ }
maxConcurrentTasks, err := intFromEnv("MULTICA_DAEMON_MAX_CONCURRENT_TASKS", DefaultMaxConcurrentTasks)
if err != nil {
@@ -602,6 +617,7 @@ func LoadConfig(overrides Overrides) (Config, error) {
CodexSemanticInactivityTimeout: codexSemanticInactivityTimeout,
CodexFirstTurnNoProgressTimeout: codexFirstTurnNoProgressTimeout,
CodexHandshakeTimeout: codexHandshakeTimeout,
+ CodexThreadHandshakeTimeout: codexThreadHandshakeTimeout,
OpenCodeIdleWatchdog: openCodeIdleWatchdog,
AgentIdleWatchdog: agentIdleWatchdog,
AgentToolWatchdog: agentToolWatchdog,
diff --git a/server/internal/daemon/config_test.go b/server/internal/daemon/config_test.go
index 7068c452be..52bf0e0c63 100644
--- a/server/internal/daemon/config_test.go
+++ b/server/internal/daemon/config_test.go
@@ -628,6 +628,9 @@ func TestLoadConfig_CodexHandshakeTimeout(t *testing.T) {
if cfg.CodexHandshakeTimeout != DefaultCodexHandshakeTimeout {
t.Fatalf("CodexHandshakeTimeout = %s, want default %s", cfg.CodexHandshakeTimeout, DefaultCodexHandshakeTimeout)
}
+ if cfg.CodexThreadHandshakeTimeout != DefaultCodexThreadHandshakeTimeout {
+ t.Fatalf("CodexThreadHandshakeTimeout = %s, want default %s", cfg.CodexThreadHandshakeTimeout, DefaultCodexThreadHandshakeTimeout)
+ }
t.Setenv("MULTICA_CODEX_HANDSHAKE_TIMEOUT", "47s")
@@ -641,6 +644,24 @@ func TestLoadConfig_CodexHandshakeTimeout(t *testing.T) {
if cfg.CodexHandshakeTimeout != 47*time.Second {
t.Fatalf("CodexHandshakeTimeout = %s, want 47s from env", cfg.CodexHandshakeTimeout)
}
+ if cfg.CodexThreadHandshakeTimeout != 47*time.Second {
+ t.Fatalf("CodexThreadHandshakeTimeout = %s, want legacy 47s env override", cfg.CodexThreadHandshakeTimeout)
+ }
+
+ t.Setenv("MULTICA_CODEX_HANDSHAKE_TIMEOUT", "1d")
+ cfg, err = LoadConfig(Overrides{
+ ServerURL: "http://localhost:8080",
+ WorkspacesRoot: t.TempDir(),
+ })
+ if err != nil {
+ t.Fatalf("LoadConfig with day-unit env: %v", err)
+ }
+ if cfg.CodexHandshakeTimeout != 24*time.Hour {
+ t.Fatalf("CodexHandshakeTimeout = %s, want 24h from 1d env", cfg.CodexHandshakeTimeout)
+ }
+ if cfg.CodexThreadHandshakeTimeout != 24*time.Hour {
+ t.Fatalf("CodexThreadHandshakeTimeout = %s, want legacy 24h env override", cfg.CodexThreadHandshakeTimeout)
+ }
t.Setenv("MULTICA_CODEX_HANDSHAKE_TIMEOUT", "0")
cfg, err = LoadConfig(Overrides{
@@ -653,6 +674,9 @@ func TestLoadConfig_CodexHandshakeTimeout(t *testing.T) {
if cfg.CodexHandshakeTimeout != DefaultCodexHandshakeTimeout {
t.Fatalf("CodexHandshakeTimeout = %s, want default %s for zero env", cfg.CodexHandshakeTimeout, DefaultCodexHandshakeTimeout)
}
+ if cfg.CodexThreadHandshakeTimeout != DefaultCodexThreadHandshakeTimeout {
+ t.Fatalf("CodexThreadHandshakeTimeout = %s, want default %s for zero env", cfg.CodexThreadHandshakeTimeout, DefaultCodexThreadHandshakeTimeout)
+ }
cfg, err = LoadConfig(Overrides{
ServerURL: "http://localhost:8080",
@@ -665,6 +689,9 @@ func TestLoadConfig_CodexHandshakeTimeout(t *testing.T) {
if cfg.CodexHandshakeTimeout != 12*time.Second {
t.Fatalf("CodexHandshakeTimeout = %s, want 12s from override", cfg.CodexHandshakeTimeout)
}
+ if cfg.CodexThreadHandshakeTimeout != 12*time.Second {
+ t.Fatalf("CodexThreadHandshakeTimeout = %s, want legacy 12s override", cfg.CodexThreadHandshakeTimeout)
+ }
}
// TestLoadConfig_CodexFirstTurnNoProgressTimeout pins the env-only
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index fa39590c2a..5ffb089807 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -7629,6 +7629,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
FirstTurnNoProgressTimeout: d.cfg.CodexFirstTurnNoProgressTimeout,
IdleWatchdogTimeout: idleWatchdogTimeout,
HandshakeTimeout: d.cfg.CodexHandshakeTimeout,
+ ThreadHandshakeTimeout: d.cfg.CodexThreadHandshakeTimeout,
ResumeSessionID: task.PriorSessionID,
// Post-gate intent: PriorSessionID here already reflects the pre-flight
// resume gates (a dropped resume is surfaced via the prompt instead). If it
diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.go
index e3246d4a4c..6f1f2a093e 100644
--- a/server/pkg/agent/agent.go
+++ b/server/pkg/agent/agent.go
@@ -59,7 +59,12 @@ type ExecOptions struct {
// protocol transport. It is currently consumed by Codex app-server;
// zero uses the provider default rather than disabling the bound.
HandshakeTimeout time.Duration
- ResumeSessionID string // if non-empty, resume a previous agent session
+ // ThreadHandshakeTimeout optionally gives Codex's heavier thread/start and
+ // thread/resume RPCs a wider budget than initialize and turn/start. Zero
+ // preserves the legacy behavior for callers that explicitly set
+ // HandshakeTimeout; when both are zero Codex uses separate built-in defaults.
+ ThreadHandshakeTimeout time.Duration
+ ResumeSessionID string // if non-empty, resume a previous agent session
// ResumeExpected records that this task intended to continue a prior
// conversation, independent of ResumeSessionID (which a fallback retry may
// clear). When it is true but the backend ends up on a fresh thread — the
diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.go
index c72c53b834..325ea71927 100644
--- a/server/pkg/agent/codex.go
+++ b/server/pkg/agent/codex.go
@@ -59,7 +59,12 @@ const (
// while keeping the fast-fail value (MUL-5542).
defaultCodexFirstTurnNoProgressTimeout = 60 * time.Second
defaultCodexHandshakeTimeout = 30 * time.Second
- codexVersionDiagnosticTimeout = 2 * time.Second
+ // thread/start and thread/resume may refresh the model catalog, initialize
+ // MCP integrations, and restore persisted history. Field evidence shows
+ // healthy calls crossing the 30s budget used for local initialize, so keep
+ // their default separate without slowing failures for lightweight RPCs.
+ defaultCodexThreadHandshakeTimeout = 60 * time.Second
+ codexVersionDiagnosticTimeout = 2 * time.Second
// codexGracefulShutdownTimeout bounds how long the lifecycle goroutine
// waits for codex to exit on its own after stdin is closed, before forcing
// a context-cancel kill. A clean exit lets codex run its shutdown path and
@@ -947,10 +952,7 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
if semanticInactivityTimeout == 0 {
semanticInactivityTimeout = defaultCodexSemanticInactivityTimeout
}
- handshakeTimeout := opts.HandshakeTimeout
- if handshakeTimeout <= 0 {
- handshakeTimeout = defaultCodexHandshakeTimeout
- }
+ handshakeTimeout, threadHandshakeTimeout := resolveCodexHandshakeTimeouts(opts)
runCtx, cancel := runContext(ctx, timeout)
// Materialise the agent's MCP config into the per-task
@@ -1108,16 +1110,17 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
turnDone := make(chan bool, 1) // true = aborted
c := &codexClient{
- cfg: b.cfg,
- stdin: stdin,
- pending: make(map[int]*pendingRPC),
- processDone: make(chan struct{}),
- handshakeTimeout: handshakeTimeout,
- pid: cmd.Process.Pid,
- attempt: attempt,
- activeLaunches: activeLaunches,
- notificationProtocol: "unknown",
- acceptNotification: turnNotificationGate.accept,
+ cfg: b.cfg,
+ stdin: stdin,
+ pending: make(map[int]*pendingRPC),
+ processDone: make(chan struct{}),
+ handshakeTimeout: handshakeTimeout,
+ threadHandshakeTimeout: threadHandshakeTimeout,
+ pid: cmd.Process.Pid,
+ attempt: attempt,
+ activeLaunches: activeLaunches,
+ notificationProtocol: "unknown",
+ acceptNotification: turnNotificationGate.accept,
onDiscardedNotification: func(string, map[string]any) {
// Any app-server notification proves the process made semantic
// progress, even when it is intentionally excluded from the active
@@ -1398,9 +1401,9 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
threadID, resumed, err := c.startOrResumeThread(runCtx, opts, b.cfg.Logger)
if err != nil {
var handshakeErr *codexHandshakeTimeoutError
- timedOut := errors.As(err, &handshakeErr) && handshakeErr.Method == "thread/start"
+ timedOut := errors.As(err, &handshakeErr) && isCodexThreadSetupRPC(handshakeErr.Method)
if timedOut {
- // A timed-out thread/start has an uncertain provider outcome. Kill
+ // A timed-out thread setup has an uncertain provider outcome. Kill
// the whole process group before waiting so a leader that exits on
// EOF cannot leave detached-stdio descendants behind.
signalProcessGroup(cmd, syscall.SIGKILL)
@@ -1409,18 +1412,18 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
finalStatus = "failed"
stderrTail := sanitizeCodexDiagnostic(stderrBuf.Tail())
finalError = err.Error()
- if c.threadStartSent {
+ if c.threadSetupMethod != "" {
classification := classifyCodexStartupStderr(stderrTail, timedOut)
b.cfg.Logger.Warn("codex lifecycle",
- "phase", "thread_start_failure",
+ "phase", strings.ReplaceAll(c.threadSetupMethod, "/", "_")+"_failure",
"task_id", b.cfg.TaskID,
"runtime_id", b.cfg.RuntimeID,
"pid", cmd.Process.Pid,
"attempt", attempt,
"active_launches", activeLaunches,
- "method", "thread/start",
- "latency", time.Since(c.threadStartStarted).Round(time.Millisecond).String(),
- "latency_ms", time.Since(c.threadStartStarted).Milliseconds(),
+ "method", c.threadSetupMethod,
+ "latency", time.Since(c.threadSetupStarted).Round(time.Millisecond).String(),
+ "latency_ms", time.Since(c.threadSetupStarted).Milliseconds(),
"cleanup_confirmed", cleanupConfirmed,
"reaped", cleanupConfirmed,
"retry_safe", false,
@@ -1761,6 +1764,24 @@ func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts Exec
return &Session{Messages: msgCh, Result: resCh}, nil
}
+func resolveCodexHandshakeTimeouts(opts ExecOptions) (time.Duration, time.Duration) {
+ handshakeTimeout := opts.HandshakeTimeout
+ if handshakeTimeout <= 0 {
+ handshakeTimeout = defaultCodexHandshakeTimeout
+ }
+ threadHandshakeTimeout := opts.ThreadHandshakeTimeout
+ if threadHandshakeTimeout <= 0 {
+ if opts.HandshakeTimeout > 0 {
+ // Backward compatibility: an explicit legacy override historically
+ // bounded every startup RPC, including thread setup.
+ threadHandshakeTimeout = opts.HandshakeTimeout
+ } else {
+ threadHandshakeTimeout = defaultCodexThreadHandshakeTimeout
+ }
+ }
+ return handshakeTimeout, threadHandshakeTimeout
+}
+
// The continuity notice this backend prepends is supplied by the caller via
// ExecOptions.ResumeContinuityNotice rather than written here. It used to be a
// constant in this file that mirrored the daemon's, which meant two hand-kept
@@ -1812,9 +1833,31 @@ func (c *codexClient) startOrResumeThread(ctx context.Context, opts ExecOptions,
// resume must honour the live config, not the stored one.
applyCodexReasoningEffort(resumeParams, opts.ThinkingLevel)
applyCodexServiceTier(resumeParams, opts.ServiceTier)
+ c.threadSetupMethod = "thread/resume"
+ c.threadSetupStarted = time.Now()
+ logger.Info("codex lifecycle",
+ "phase", "thread_resume_sent",
+ "task_id", c.cfg.TaskID,
+ "runtime_id", c.cfg.RuntimeID,
+ "pid", c.pid,
+ "attempt", c.attempt,
+ "active_launches", c.activeLaunches,
+ "method", c.threadSetupMethod,
+ )
resumeResult, err := c.request(ctx, "thread/resume", resumeParams)
if err == nil {
if threadID := extractThreadID(resumeResult); threadID != "" {
+ logger.Info("codex lifecycle",
+ "phase", "thread_resume_response",
+ "task_id", c.cfg.TaskID,
+ "runtime_id", c.cfg.RuntimeID,
+ "pid", c.pid,
+ "attempt", c.attempt,
+ "active_launches", c.activeLaunches,
+ "method", c.threadSetupMethod,
+ "latency", time.Since(c.threadSetupStarted).Round(time.Millisecond).String(),
+ "latency_ms", time.Since(c.threadSetupStarted).Milliseconds(),
+ )
return threadID, true, nil
}
logger.Warn("codex thread/resume returned no thread ID; falling back to thread/start", "prior_thread_id", priorThreadID)
@@ -1850,8 +1893,8 @@ func (c *codexClient) startOrResumeThread(ctx context.Context, opts ExecOptions,
}
applyCodexReasoningEffort(startParams, opts.ThinkingLevel)
applyCodexServiceTier(startParams, opts.ServiceTier)
- c.threadStartSent = true
- c.threadStartStarted = time.Now()
+ c.threadSetupMethod = "thread/start"
+ c.threadSetupStarted = time.Now()
logger.Info("codex lifecycle",
"phase", "thread_start_sent",
"task_id", c.cfg.TaskID,
@@ -1859,7 +1902,7 @@ func (c *codexClient) startOrResumeThread(ctx context.Context, opts ExecOptions,
"pid", c.pid,
"attempt", c.attempt,
"active_launches", c.activeLaunches,
- "method", "thread/start",
+ "method", c.threadSetupMethod,
)
startResult, err := c.request(ctx, "thread/start", startParams)
if err != nil {
@@ -1877,8 +1920,8 @@ func (c *codexClient) startOrResumeThread(ctx context.Context, opts ExecOptions,
"attempt", c.attempt,
"active_launches", c.activeLaunches,
"method", "thread/start",
- "latency", time.Since(c.threadStartStarted).Round(time.Millisecond).String(),
- "latency_ms", time.Since(c.threadStartStarted).Milliseconds(),
+ "latency", time.Since(c.threadSetupStarted).Round(time.Millisecond).String(),
+ "latency_ms", time.Since(c.threadSetupStarted).Milliseconds(),
)
c.trySetThreadName(ctx, threadID, opts.ThreadName, logger)
return threadID, false, nil
@@ -2135,24 +2178,25 @@ func describeCodexSemanticActivity(msg Message) string {
// ── codexClient: JSON-RPC 2.0 transport ──
type codexClient struct {
- cfg Config
- stdin interface{ Write([]byte) (int, error) }
- mu sync.Mutex
- nextID int
- pending map[int]*pendingRPC
- processDone chan struct{}
- processErr error
- handshakeTimeout time.Duration
- pid int
- attempt int
- activeLaunches int64
- threadStartSent bool
- threadStartStarted time.Time
- threadID string
- turnID string
- onMessage func(Message)
- onSemanticActivity func(description string)
- onTurnDone func(aborted bool)
+ cfg Config
+ stdin interface{ Write([]byte) (int, error) }
+ mu sync.Mutex
+ nextID int
+ pending map[int]*pendingRPC
+ processDone chan struct{}
+ processErr error
+ handshakeTimeout time.Duration
+ threadHandshakeTimeout time.Duration
+ pid int
+ attempt int
+ activeLaunches int64
+ threadSetupMethod string
+ threadSetupStarted time.Time
+ threadID string
+ turnID string
+ onMessage func(Message)
+ onSemanticActivity func(description string)
+ onTurnDone func(aborted bool)
// onFinalAnswer fires only for an agent message the app-server itself
// labelled `phase: "final_answer"` — the turn's deliverable, as opposed to
// the intermediate agent messages that narrate work between tool calls.
@@ -2293,6 +2337,22 @@ func isCodexHandshakeRPC(method string) bool {
}
}
+func isCodexThreadSetupRPC(method string) bool {
+ return method == "thread/start" || method == "thread/resume"
+}
+
+func (c *codexClient) handshakeTimeoutFor(method string) time.Duration {
+ switch method {
+ case "thread/start", "thread/resume":
+ if c.threadHandshakeTimeout > 0 {
+ return c.threadHandshakeTimeout
+ }
+ return c.handshakeTimeout
+ default:
+ return c.handshakeTimeout
+ }
+}
+
func codexRequestContextError(ctx context.Context) error {
var handshakeErr *codexHandshakeTimeoutError
if errors.As(context.Cause(ctx), &handshakeErr) {
@@ -2307,9 +2367,9 @@ func (c *codexClient) request(ctx context.Context, method string, params any) (j
}
requestCtx := ctx
cancelRequest := func() {}
- if c.handshakeTimeout > 0 && isCodexHandshakeRPC(method) {
- timeoutErr := &codexHandshakeTimeoutError{Method: method, Timeout: c.handshakeTimeout}
- requestCtx, cancelRequest = context.WithTimeoutCause(ctx, c.handshakeTimeout, timeoutErr)
+ if timeout := c.handshakeTimeoutFor(method); timeout > 0 && isCodexHandshakeRPC(method) {
+ timeoutErr := &codexHandshakeTimeoutError{Method: method, Timeout: timeout}
+ requestCtx, cancelRequest = context.WithTimeoutCause(ctx, timeout, timeoutErr)
}
defer cancelRequest()
diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.go
index 5a5b218339..c175fcb7f2 100644
--- a/server/pkg/agent/codex_test.go
+++ b/server/pkg/agent/codex_test.go
@@ -2544,6 +2544,67 @@ func TestCodexExecuteStartupRPCsHaveBoundedHandshakeTimeout(t *testing.T) {
}
}
+func TestResolveCodexHandshakeTimeouts(t *testing.T) {
+ tests := []struct {
+ name string
+ opts ExecOptions
+ wantBase time.Duration
+ wantThread time.Duration
+ }{
+ {
+ name: "separate defaults",
+ wantBase: defaultCodexHandshakeTimeout,
+ wantThread: defaultCodexThreadHandshakeTimeout,
+ },
+ {
+ name: "legacy global override remains global",
+ opts: ExecOptions{HandshakeTimeout: 42 * time.Second},
+ wantBase: 42 * time.Second,
+ wantThread: 42 * time.Second,
+ },
+ {
+ name: "dedicated thread override wins",
+ opts: ExecOptions{
+ HandshakeTimeout: 30 * time.Second,
+ ThreadHandshakeTimeout: 75 * time.Second,
+ },
+ wantBase: 30 * time.Second,
+ wantThread: 75 * time.Second,
+ },
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ base, thread := resolveCodexHandshakeTimeouts(tc.opts)
+ if base != tc.wantBase || thread != tc.wantThread {
+ t.Fatalf("timeouts = (%s, %s), want (%s, %s)", base, thread, tc.wantBase, tc.wantThread)
+ }
+ })
+ }
+}
+
+func TestCodexHandshakeTimeoutFor(t *testing.T) {
+ c := &codexClient{
+ handshakeTimeout: 30 * time.Second,
+ threadHandshakeTimeout: 60 * time.Second,
+ }
+ for _, method := range []string{"thread/start", "thread/resume"} {
+ if got := c.handshakeTimeoutFor(method); got != 60*time.Second {
+ t.Fatalf("handshakeTimeoutFor(%q) = %s, want 60s", method, got)
+ }
+ }
+ for _, method := range []string{"initialize", "thread/name/set", "turn/start"} {
+ if got := c.handshakeTimeoutFor(method); got != 30*time.Second {
+ t.Fatalf("handshakeTimeoutFor(%q) = %s, want 30s", method, got)
+ }
+ }
+ c.threadHandshakeTimeout = 0
+ for _, method := range []string{"thread/start", "thread/resume"} {
+ if got := c.handshakeTimeoutFor(method); got != 30*time.Second {
+ t.Fatalf("zero thread timeout handshakeTimeoutFor(%q) = %s, want base 30s fallback", method, got)
+ }
+ }
+}
+
func TestCodexExecuteThreadStartTimeoutLifecycleIsFailClosed(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("shell-script fixture is POSIX-only")
@@ -2632,6 +2693,73 @@ func TestCodexExecuteThreadStartTimeoutLifecycleIsFailClosed(t *testing.T) {
}
}
+func TestCodexExecuteThreadResumeTimeoutUsesThreadBudgetAndLifecycle(t *testing.T) {
+ if runtime.GOOS == "windows" {
+ t.Skip("shell-script fixture is POSIX-only")
+ }
+ codexGracefulShutdownTimeoutNanos.Store(int64(100 * time.Millisecond))
+ t.Cleanup(func() { codexGracefulShutdownTimeoutNanos.Store(0) })
+
+ fakePath := writeFakeCodexAppServer(t, ""+
+ `DIR="$(dirname "$0")"`+"\n"+
+ `echo 1 > "$DIR/attempts"`+"\n"+
+ `read line`+"\n"+
+ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'`+"\n"+
+ `read line`+"\n"+
+ `read line`+"\n"+
+ `sleep 5`+"\n")
+
+ var logs bytes.Buffer
+ backend, err := New("codex", Config{
+ ExecutablePath: fakePath,
+ Logger: slog.New(slog.NewJSONHandler(&logs, nil)),
+ TaskID: "task-thread-resume-timeout",
+ RuntimeID: "runtime-thread-resume-timeout",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ session, err := backend.Execute(context.Background(), "prompt", ExecOptions{
+ Timeout: 5 * time.Second,
+ HandshakeTimeout: 3 * time.Second,
+ ThreadHandshakeTimeout: 500 * time.Millisecond,
+ SemanticInactivityTimeout: time.Second,
+ ResumeSessionID: "thr-prior",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+ result := <-session.Result
+ if result.Status != "failed" || !strings.Contains(result.Error, "thread/resume did not respond after 500ms") {
+ t.Fatalf("expected thread/resume timeout failure, got %+v", result)
+ }
+ assertCodexAttemptCount(t, fakePath, "1")
+
+ entries := parseJSONLogEntries(t, logs.String())
+ sent := findCodexLifecyclePhase(t, entries, "thread_resume_sent")
+ failure := findCodexLifecyclePhase(t, entries, "thread_resume_failure")
+ for key, want := range map[string]any{
+ "task_id": "task-thread-resume-timeout",
+ "runtime_id": "runtime-thread-resume-timeout",
+ "attempt": float64(1),
+ "method": "thread/resume",
+ } {
+ if got := sent[key]; got != want {
+ t.Fatalf("sent[%s]=%v, want %v; entry=%v", key, got, want, sent)
+ }
+ }
+ if failure["cleanup_confirmed"] != true || failure["reaped"] != true {
+ t.Fatalf("failure lacks confirmed cleanup/reap: %v", failure)
+ }
+ if failure["retry_safe"] != false || failure["retry_attempted"] != false {
+ t.Fatalf("thread/resume timeout must remain fail-closed: %v", failure)
+ }
+}
+
func TestCodexExecuteThreadStartResponseRequiresThreadID(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("shell-script fixture is POSIX-only")