Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-4424: bound Codex app-server startup RPCs (#5319)
Multica Eve41b3045efa75
diff --git a/apps/docs/content/docs/cli/reference.zh.mdx b/apps/docs/content/docs/cli/reference.zh.mdxindex 976e5ef7f2..23cc2b286b 100644--- a/apps/docs/content/docs/cli/reference.zh.mdx+++ b/apps/docs/content/docs/cli/reference.zh.mdx@@ -120,6 +120,7 @@ Daemon behavior is configured via flags or environment variables:| Poll interval | `--poll-interval` | `MULTICA_DAEMON_POLL_INTERVAL` | `3s` || Heartbeat interval | `--heartbeat-interval` | `MULTICA_DAEMON_HEARTBEAT_INTERVAL` | `15s` || Agent timeout | `--agent-timeout` | `MULTICA_AGENT_TIMEOUT` | `0`(不限制,由看门狗兜底)|+| Codex app-server handshake timeout | `--codex-handshake-timeout` | `MULTICA_CODEX_HANDSHAKE_TIMEOUT` | `30s` || Max concurrent tasks | `--max-concurrent-tasks` | `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` | `20` || Daemon ID | `--daemon-id` | `MULTICA_DAEMON_ID` | hostname || Device name | `--device-name` | `MULTICA_DAEMON_DEVICE_NAME` | hostname |diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.goindex 1ccaa22afb..ac8caffe14 100644--- a/server/cmd/multica/cmd_daemon.go+++ b/server/cmd/multica/cmd_daemon.go@@ -87,6 +87,7 @@ func init() {f.Duration("heartbeat-interval", 0, "Heartbeat interval (env: MULTICA_DAEMON_HEARTBEAT_INTERVAL)")f.Duration("agent-timeout", 0, "Absolute per-task wall-clock cap; 0 = no cap, rely on the watchdogs (env: MULTICA_AGENT_TIMEOUT)")f.Duration("codex-semantic-inactivity-timeout", 0, "Codex semantic inactivity timeout (env: MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT)")+ f.Duration("codex-handshake-timeout", 0, "Codex app-server startup RPC timeout (env: MULTICA_CODEX_HANDSHAKE_TIMEOUT)")f.Int("max-concurrent-tasks", 0, "Max tasks running in parallel (env: MULTICA_DAEMON_MAX_CONCURRENT_TASKS)")f.Bool("no-auto-update", false, "Disable periodic CLI self-update (env: MULTICA_DAEMON_AUTO_UPDATE=false)")f.Duration("auto-update-interval", 0, "How often to poll GitHub for a newer release (env: MULTICA_DAEMON_AUTO_UPDATE_INTERVAL)")@@ -106,6 +107,7 @@ func init() {rf.Duration("heartbeat-interval", 0, "Heartbeat interval (env: MULTICA_DAEMON_HEARTBEAT_INTERVAL)")rf.Duration("agent-timeout", 0, "Absolute per-task wall-clock cap; 0 = no cap, rely on the watchdogs (env: MULTICA_AGENT_TIMEOUT)")rf.Duration("codex-semantic-inactivity-timeout", 0, "Codex semantic inactivity timeout (env: MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT)")+ rf.Duration("codex-handshake-timeout", 0, "Codex app-server startup RPC timeout (env: MULTICA_CODEX_HANDSHAKE_TIMEOUT)")rf.Int("max-concurrent-tasks", 0, "Max tasks running in parallel (env: MULTICA_DAEMON_MAX_CONCURRENT_TASKS)")rf.Bool("no-auto-update", false, "Disable periodic CLI self-update (env: MULTICA_DAEMON_AUTO_UPDATE=false)")rf.Duration("auto-update-interval", 0, "How often to poll GitHub for a newer release (env: MULTICA_DAEMON_AUTO_UPDATE_INTERVAL)")@@ -392,6 +394,9 @@ func buildDaemonStartArgs(cmd *cobra.Command) []string {if d, _ := cmd.Flags().GetDuration("codex-semantic-inactivity-timeout"); d > 0 {args = append(args, "--codex-semantic-inactivity-timeout", d.String())}+ if d, _ := cmd.Flags().GetDuration("codex-handshake-timeout"); d > 0 {+ args = append(args, "--codex-handshake-timeout", d.String())+ }if n, _ := cmd.Flags().GetInt("max-concurrent-tasks"); n > 0 {args = append(args, "--max-concurrent-tasks", strconv.Itoa(n))}@@ -475,6 +480,9 @@ func runDaemonForeground(cmd *cobra.Command) error {if d, _ := cmd.Flags().GetDuration("codex-semantic-inactivity-timeout"); d > 0 {overrides.CodexSemanticInactivityTimeout = d}+ if d, _ := cmd.Flags().GetDuration("codex-handshake-timeout"); d > 0 {+ overrides.CodexHandshakeTimeout = d+ }if n, _ := cmd.Flags().GetInt("max-concurrent-tasks"); n > 0 {overrides.MaxConcurrentTasks = n}diff --git a/server/cmd/multica/cmd_daemon_test.go b/server/cmd/multica/cmd_daemon_test.goindex d25c450099..53efbfa15a 100644--- a/server/cmd/multica/cmd_daemon_test.go+++ b/server/cmd/multica/cmd_daemon_test.go@@ -6,8 +6,10 @@ import ("path/filepath""strings""testing"+ "time""github.com/multica-ai/multica/server/internal/daemon"+ "github.com/spf13/cobra")// TestDaemonAlive locks in the liveness predicate the lifecycle commands rely@@ -60,6 +62,20 @@ func TestPrintDaemonStatusIncludesCLIVersion(t *testing.T) {}}+func TestBuildDaemonStartArgsForwardsCodexHandshakeTimeout(t *testing.T) {+ cmd := &cobra.Command{}+ cmd.Flags().Duration("codex-handshake-timeout", 0, "")+ if err := cmd.Flags().Set("codex-handshake-timeout", "42s"); err != nil {+ t.Fatalf("set flag: %v", err)+ }++ args := buildDaemonStartArgs(cmd)+ want := []string{"daemon", "start", "--foreground", "--codex-handshake-timeout", (42 * time.Second).String()}+ if strings.Join(args, " ") != strings.Join(want, " ") {+ t.Fatalf("buildDaemonStartArgs() = %q, want %q", args, want)+ }+}+// TestPrintDaemonStatusOmitsVersionWhenMissing pins the back-compat contract:// when the daemon doesn't report cli_version (older daemon paired with a newer// CLI) or reports an empty string, the CLI must skip the line entirely insteaddiff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex f58c27f1eb..fa48bdfe77 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -28,6 +28,7 @@ const (// hard ceiling for cost/resource control can set MULTICA_AGENT_TIMEOUT.DefaultAgentTimeout = 0DefaultCodexSemanticInactivityTimeout = 10 * time.Minute+ DefaultCodexHandshakeTimeout = 30 * time.Second// DefaultAgentIdleWatchdog is the per-task safety net that force-stops a// run when the backend has emitted no message for this long AND its// message queue is empty. Backends like Claude Code can hang indefinitely@@ -97,6 +98,7 @@ type Config struct {HeartbeatInterval time.DurationAgentTimeout time.DurationCodexSemanticInactivityTimeout time.Duration+ CodexHandshakeTimeout time.DurationAgentIdleWatchdog 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 = disabled); backstop for hung tools now that there is no wall-clock capClaudeArgs []string@@ -123,6 +125,7 @@ type Overrides struct {// distinguishable from "flag not passed". nil = use env/default.AgentTimeout *time.DurationCodexSemanticInactivityTimeout time.Duration+ CodexHandshakeTimeout time.DurationMaxConcurrentTasks intDaemonID stringDeviceName string@@ -367,6 +370,17 @@ func LoadConfig(overrides Overrides) (Config, error) {codexSemanticInactivityTimeout = overrides.CodexSemanticInactivityTimeout}+ codexHandshakeTimeout, err := durationFromEnv("MULTICA_CODEX_HANDSHAKE_TIMEOUT", DefaultCodexHandshakeTimeout)+ if err != nil {+ return Config{}, err+ }+ if codexHandshakeTimeout <= 0 {+ codexHandshakeTimeout = DefaultCodexHandshakeTimeout+ }+ if overrides.CodexHandshakeTimeout > 0 {+ codexHandshakeTimeout = overrides.CodexHandshakeTimeout+ }+// MULTICA_AGENT_IDLE_WATCHDOG=0 disables the per-task idle watchdog. We// route 0 through durationFromEnv so the operator can opt out without// patching the binary; any positive duration overrides DefaultAgentIdleWatchdog.@@ -529,6 +543,7 @@ func LoadConfig(overrides Overrides) (Config, error) {HeartbeatInterval: heartbeatInterval,AgentTimeout: agentTimeout,CodexSemanticInactivityTimeout: codexSemanticInactivityTimeout,+ CodexHandshakeTimeout: codexHandshakeTimeout,AgentIdleWatchdog: agentIdleWatchdog,AgentToolWatchdog: agentToolWatchdog,ClaudeArgs: claudeArgs,diff --git a/server/internal/daemon/config_test.go b/server/internal/daemon/config_test.goindex 4a41559941..2855b9f11a 100644--- a/server/internal/daemon/config_test.go+++ b/server/internal/daemon/config_test.go@@ -379,6 +379,59 @@ func TestLoadConfig_AutoUpdateDefault_SelfHostOff(t *testing.T) {}}+func TestLoadConfig_CodexHandshakeTimeout(t *testing.T) {+ stageFakeAgent(t)+ t.Setenv("MULTICA_CODEX_HANDSHAKE_TIMEOUT", "")++ cfg, err := LoadConfig(Overrides{+ ServerURL: "http://localhost:8080",+ WorkspacesRoot: t.TempDir(),+ })+ if err != nil {+ t.Fatalf("LoadConfig with default: %v", err)+ }+ if cfg.CodexHandshakeTimeout != DefaultCodexHandshakeTimeout {+ t.Fatalf("CodexHandshakeTimeout = %s, want default %s", cfg.CodexHandshakeTimeout, DefaultCodexHandshakeTimeout)+ }++ t.Setenv("MULTICA_CODEX_HANDSHAKE_TIMEOUT", "47s")++ cfg, err = LoadConfig(Overrides{+ ServerURL: "http://localhost:8080",+ WorkspacesRoot: t.TempDir(),+ })+ if err != nil {+ t.Fatalf("LoadConfig with env: %v", err)+ }+ if cfg.CodexHandshakeTimeout != 47*time.Second {+ t.Fatalf("CodexHandshakeTimeout = %s, want 47s from env", cfg.CodexHandshakeTimeout)+ }++ t.Setenv("MULTICA_CODEX_HANDSHAKE_TIMEOUT", "0")+ cfg, err = LoadConfig(Overrides{+ ServerURL: "http://localhost:8080",+ WorkspacesRoot: t.TempDir(),+ })+ if err != nil {+ t.Fatalf("LoadConfig with zero env: %v", err)+ }+ if cfg.CodexHandshakeTimeout != DefaultCodexHandshakeTimeout {+ t.Fatalf("CodexHandshakeTimeout = %s, want default %s for zero env", cfg.CodexHandshakeTimeout, DefaultCodexHandshakeTimeout)+ }++ cfg, err = LoadConfig(Overrides{+ ServerURL: "http://localhost:8080",+ WorkspacesRoot: t.TempDir(),+ CodexHandshakeTimeout: 12 * time.Second,+ })+ if err != nil {+ t.Fatalf("LoadConfig with override: %v", err)+ }+ if cfg.CodexHandshakeTimeout != 12*time.Second {+ t.Fatalf("CodexHandshakeTimeout = %s, want 12s from override", cfg.CodexHandshakeTimeout)+ }+}+// TestLoadConfig_AutoUpdateDefault_CloudOn confirms the symmetric case: a// daemon pointed at Multica's hosted cloud keeps the historical opt-in// auto-update default. We pass the WSS form of the URL to also exercise thatdiff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 9a9d4d6ddb..ab251b32b4 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -3915,6 +3915,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iThreadName: deriveTaskThreadName(task),Timeout: d.cfg.AgentTimeout,SemanticInactivityTimeout: d.cfg.CodexSemanticInactivityTimeout,+ HandshakeTimeout: d.cfg.CodexHandshakeTimeout,ResumeSessionID: task.PriorSessionID,ExtraArgs: extraArgs,CustomArgs: customArgs,diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex f07a4a3f56..d46754a246 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -32,10 +32,14 @@ type ExecOptions struct {MaxTurns intTimeout time.DurationSemanticInactivityTimeout time.Duration- ResumeSessionID string // if non-empty, resume a previous agent session- ExtraArgs []string // daemon-wide default CLI arguments appended before CustomArgs; currently read by claude and codex backends only- CustomArgs []string // per-agent CLI arguments appended after ExtraArgs- McpConfig json.RawMessage // if non-nil, MCP server config to pass via --mcp-config+ // HandshakeTimeout bounds startup RPCs for providers with a long-lived+ // 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+ ExtraArgs []string // daemon-wide default CLI arguments appended before CustomArgs; currently read by claude and codex backends only+ CustomArgs []string // per-agent CLI arguments appended after ExtraArgs+ McpConfig json.RawMessage // if non-nil, MCP server config to pass via --mcp-config// ThinkingLevel is the runtime-native reasoning/effort value (e.g.// Claude's "low|medium|high|xhigh|max", Codex's "none|minimal|low|// medium|high|xhigh", OpenCode's model variant names). Empty meansdiff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.goindex 7d83a4d0c9..86c64e1607 100644--- a/server/pkg/agent/codex.go+++ b/server/pkg/agent/codex.go@@ -39,6 +39,7 @@ const (codexStderrTailBytes = 2048defaultCodexSemanticInactivityTimeout = 10 * time.MinutedefaultCodexFirstTurnNoProgressTimeout = 30 * time.Second+ defaultCodexHandshakeTimeout = 30 * time.SecondcodexVersionDiagnosticTimeout = 2 * time.Second// codexGracefulShutdownTimeout bounds how long the lifecycle goroutine// waits for codex to exit on its own after stdin is closed, before forcing@@ -73,6 +74,10 @@ const CodexSemanticInactivityMarker = "codex semantic inactivity timeout"// Codex accepts a turn and then never emits any item, completion, or error.const CodexFirstTurnNoProgressMarker = "codex app-server no progress timeout"+// CodexHandshakeTimeoutMarker identifies a Codex app-server startup RPC that+// did not answer within the bounded handshake window.+const CodexHandshakeTimeoutMarker = "codex app-server handshake timeout"+const codexModelCatalogRefreshTimeoutSignal = "failed to refresh available models: timeout waiting for child process to exit"var errCodexProcessExited = errors.New("codex process exited")@@ -574,6 +579,10 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOptiif semanticInactivityTimeout == 0 {semanticInactivityTimeout = defaultCodexSemanticInactivityTimeout}+ handshakeTimeout := opts.HandshakeTimeout+ if handshakeTimeout <= 0 {+ handshakeTimeout = defaultCodexHandshakeTimeout+ }runCtx, cancel := runContext(ctx, timeout)// Materialise the agent's MCP config into the per-task@@ -674,6 +683,7 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOptistdin: stdin,pending: make(map[int]*pendingRPC),processDone: make(chan struct{}),+ handshakeTimeout: handshakeTimeout,notificationProtocol: "unknown",onMessage: func(msg Message) {logCodexAgentMessage(b.cfg.Logger, msg)@@ -1353,6 +1363,7 @@ type codexClient struct {pending map[int]*pendingRPCprocessDone chan struct{}processErr error+ handshakeTimeout time.DurationthreadID stringturnID stringonMessage func(Message)@@ -1397,10 +1408,48 @@ type rpcResult struct {err error}+type codexHandshakeTimeoutError struct {+ Method string+ Timeout time.Duration+}++func (e *codexHandshakeTimeoutError) Error() string {+ return fmt.Sprintf("%s: %s did not respond after %s", CodexHandshakeTimeoutMarker, e.Method, e.Timeout)+}++func (e *codexHandshakeTimeoutError) Unwrap() error {+ return context.DeadlineExceeded+}++func isCodexHandshakeRPC(method string) bool {+ switch method {+ case "initialize", "thread/start", "thread/resume", "thread/name/set", "turn/start":+ return true+ default:+ return false+ }+}++func codexRequestContextError(ctx context.Context) error {+ var handshakeErr *codexHandshakeTimeoutError+ if errors.As(context.Cause(ctx), &handshakeErr) {+ return handshakeErr+ }+ return ctx.Err()+}+func (c *codexClient) request(ctx context.Context, method string, params any) (json.RawMessage, error) {if err := ctx.Err(); err != nil {return nil, err}+ 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)+ }+ defer cancelRequest()+c.mu.Lock()if c.processErr != nil {err := c.processErr@@ -1458,18 +1507,18 @@ func (c *codexClient) request(ctx context.Context, method string, params any) (jdelete(c.pending, id)err := c.processErrc.mu.Unlock()- if ctxErr := ctx.Err(); ctxErr != nil {- return nil, ctxErr+ if requestCtx.Err() != nil {+ return nil, codexRequestContextError(requestCtx)}if err == nil {err = errCodexProcessExited}return nil, err- case <-ctx.Done():+ case <-requestCtx.Done():c.mu.Lock()delete(c.pending, id)c.mu.Unlock()- return nil, ctx.Err()+ return nil, codexRequestContextError(requestCtx)}}@@ -1548,6 +1597,10 @@ func isCodexTransportError(err error) bool {if errors.Is(err, errCodexProcessExited) {return true}+ var handshakeErr *codexHandshakeTimeoutError+ if errors.As(err, &handshakeErr) {+ return true+ }return strings.HasPrefix(err.Error(), "write ")}diff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.goindex 56ab464375..cc7c8b200e 100644--- a/server/pkg/agent/codex_test.go+++ b/server/pkg/agent/codex_test.go@@ -1502,6 +1502,96 @@ func TestCodexExecuteSurfacesStderrWhenChildExitsEarly(t *testing.T) {}}+func TestCodexExecuteStartupRPCsHaveBoundedHandshakeTimeout(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fixture is POSIX-only")+ }++ // Every startup RPC shares one handshake bound, so the *successful*+ // preamble RPCs (e.g. initialize) must also round-trip within it. The fake+ // app-server is a forked /bin/sh script; under parallel test load its+ // startup + first read/echo can spike well past a few hundred ms, which+ // used to make initialize spuriously time out before the subtest reached+ // the RPC it targets. Keep this comfortably above sh startup jitter yet+ // below the 5s semantic timeout and the 10s executeFakeCodex ceiling.+ const handshakeTimeout = 3 * time.Second+ tests := []struct {+ name string+ method string+ body string+ opts ExecOptions+ }{+ {+ name: "initialize",+ method: "initialize",+ body: "" ++ `read line` + "\n" ++ `read line` + "\n",+ },+ {+ name: "thread start",+ method: "thread/start",+ body: "" ++ `read line` + "\n" ++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'` + "\n" ++ `read line` + "\n" ++ `read line` + "\n" ++ `read line` + "\n",+ },+ {+ name: "thread resume",+ method: "thread/resume",+ body: "" ++ `read line` + "\n" ++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'` + "\n" ++ `read line` + "\n" ++ `read line` + "\n" ++ `read line` + "\n",+ opts: ExecOptions{ResumeSessionID: "thr-prior"},+ },+ {+ name: "turn start",+ method: "turn/start",+ body: "" ++ `read line` + "\n" ++ `echo '{"jsonrpc":"2.0","id":1,"result":{}}'` + "\n" ++ `read line` + "\n" ++ `read line` + "\n" ++ `echo '{"jsonrpc":"2.0","id":2,"result":{"thread":{"id":"thr-timeout"}}}'` + "\n" ++ `read line` + "\n" ++ `read line` + "\n",+ },+ }++ for _, tc := range tests {+ tc := tc+ t.Run(tc.name, func(t *testing.T) {+ fakePath := writeFakeCodexAppServer(t, tc.body)+ tc.opts.HandshakeTimeout = handshakeTimeout+ tc.opts.SemanticInactivityTimeout = 5 * time.Second++ started := time.Now()+ result := executeFakeCodex(t, fakePath, tc.opts)+ elapsed := time.Since(started)++ if result.Status != "failed" {+ t.Fatalf("expected failed, got status=%q error=%q", result.Status, result.Error)+ }+ for _, want := range []string{CodexHandshakeTimeoutMarker, tc.method, handshakeTimeout.String()} {+ if !strings.Contains(result.Error, want) {+ t.Fatalf("expected error to contain %q, got %q", want, result.Error)+ }+ }+ // Proves the RPC was bounded rather than hanging to the 10s+ // executeFakeCodex ceiling; the handshake fires at ~3s and+ // shutdown is fast (closing stdin EOFs the fake).+ if elapsed > 8*time.Second {+ t.Fatalf("handshake timeout took %s, expected < 8s", elapsed)+ }+ })+ }+}+func TestCodexExecuteTimesOutWhenTurnStopsAfterToolResult(t *testing.T) {t.Parallel()if runtime.GOOS == "windows" {