Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
perf(daemon,agent): warm session pool & streaming latency wins for Codex and Claude (MUL-9854) (#11217)
Jiayuan Zhang23dfa0ab71b3
diff --git a/apps/docs/content/docs/daemon-runtimes.fr.mdx b/apps/docs/content/docs/daemon-runtimes.fr.mdxindex a11ec344c7..864f6a511f 100644--- a/apps/docs/content/docs/daemon-runtimes.fr.mdx+++ b/apps/docs/content/docs/daemon-runtimes.fr.mdx@@ -280,8 +280,12 @@ Le tableau liste les variables que les runtimes personnalisés peuvent utiliserLe serveur détermine l'auteur des requêtes effectuées avec `MULTICA_TOKEN` ; les écritures telles que les commentaires de tâche sont attribuées à l'agent assigné et à l'exécution en cours. Pour tout savoir sur le rattachement du jeton, ses permissions, l'attribution, sa durée de vie maximale de 24 heures et son nettoyage, consultez [Jetons temporaires pour les exécutions d'agents](/auth-tokens#jetons-temporaires-pour-les-exécutions-dagents).+<Callout type="info">+Les runtimes intégrés **Codex** et **Claude Code** réutilisent par défaut des processus chauds entre les tours suivants d'une même conversation. Lors des exécutions en pool chaud, les variables propres à chaque tâche (`MULTICA_TOKEN`, `MULTICA_TASK_ID`, `MULTICA_TASK_CONFIG_ROOT`, `MULTICA_TASK_SLOT`) sont transmises au CLI `multica` du daemon via un fichier de surcharge privé par tour plutôt que figées dans l'environnement statique du processus persistant ; elles ne sont donc pas garanties dans l'environnement du processus fournisseur ni dans les scripts enfants arbitraires. Les commandes de profil de runtime personnalisé n'utilisent pas le pool chaud et continuent de recevoir toutes les variables directement dans l'environnement du processus. Définissez `MULTICA_WARM_POOL=0` sur le daemon si un workflow Codex ou Claude Code intégré nécessite l'ancien comportement direct par variables d'environnement.+</Callout>+<Callout type="warning">-Ces valeurs se trouvent dans l'environnement réel du processus du runtime. Tout processus enfant lancé par le runtime hérite par défaut de toutes ces valeurs, y compris `MULTICA_TOKEN`. Si un processus enfant ne doit pas détenir cet identifiant, retirez-le explicitement ; ne comptez pas sur une isolation des processus qui n'existe pas. L'exception va dans l'autre sens : les outils qui filtrent l'environnement de leurs propres sous-processus peuvent exiger une règle d'autorisation explicite. Par exemple, l'outil shell de Codex écarte les noms contenant `TOKEN`, `KEY` ou `SECRET` ; le daemon installe donc une politique shell gérée qui autorise les variables d'exécution requises. Conservez le jeton uniquement dans les environnements de processus — jamais dans un prompt, un journal, un fichier du dépôt ou une configuration persistante. Un processus enfant partage l'identité et les permissions de l'exécution parente ; il ne reçoit pas de nouvelle identité à la portée indépendante.+Lorsqu'elles sont injectées directement dans l'environnement du processus (y compris pour les profils de runtime personnalisés et les exécutions avec `MULTICA_WARM_POOL=0`), ces valeurs se trouvent dans l'environnement réel du processus du runtime. Tout processus enfant lancé par le runtime hérite par défaut de toutes ces valeurs, y compris `MULTICA_TOKEN`. Si un processus enfant ne doit pas détenir cet identifiant, retirez-le explicitement ; ne comptez pas sur une isolation des processus qui n'existe pas. L'exception va dans l'autre sens : les outils qui filtrent l'environnement de leurs propres sous-processus peuvent exiger une règle d'autorisation explicite. Par exemple, l'outil shell de Codex écarte les noms contenant `TOKEN`, `KEY` ou `SECRET` ; le daemon installe donc une politique shell gérée qui autorise les variables d'exécution requises. Conservez le jeton uniquement dans les environnements de processus — jamais dans un prompt, un journal, un fichier du dépôt ou une configuration persistante. Un processus enfant partage l'identité et les permissions de l'exécution parente ; il ne reçoit pas de nouvelle identité à la portée indépendante.</Callout>### Créer un profildiff --git a/apps/docs/content/docs/daemon-runtimes.ja.mdx b/apps/docs/content/docs/daemon-runtimes.ja.mdxindex 7a5a76b082..2508ec1d6f 100644--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx@@ -280,8 +280,12 @@ Codex のネイティブサブエージェントも既定でオフです。Multi`MULTICA_TOKEN` を使ったリクエストの作成者はサーバーが決定し、タスクへのコメントなどの書き込みは、割り当てられたエージェントと実行中の作業に帰属します。認証情報の完全な紐付け、権限、帰属、最長 24 時間の有効期間、クリーンアップについては、[エージェント実行用の一時トークン](/auth-tokens#エージェント実行用の一時トークン)を参照してください。+<Callout type="info">+組み込みの **Codex** および **Claude Code** ランタイムは、後続ターンのためにウォームプロセスプールを既定で有効化します。ウォームプール実行時は、ターンごとに変化する作業変数(`MULTICA_TOKEN`、`MULTICA_TASK_ID`、`MULTICA_TASK_CONFIG_ROOT`、`MULTICA_TASK_SLOT`)が常駐プロセスの静的環境ではなく専用のターン単位オーバーレイファイル経由で `multica` CLI に渡されるため、プロバイダーのプロセス環境や任意の子スクリプトに現れることは保証されません。カスタムランタイムプロファイルのコマンドではウォームプールを使用しないため、引き続きすべての変数をプロセス環境から直接受け取ります。組み込みの Codex または Claude Code で従来の直接環境変数が必要な場合は、デーモンに `MULTICA_WARM_POOL=0` を設定してください。+</Callout>+<Callout type="warning">-これらの値はランタイムプロセスの実際の環境に存在します。ランタイムが起動する子プロセスは、`MULTICA_TOKEN` を含むすべての値をデフォルトで継承します。子プロセスに認証情報を渡すべきでない場合は、明示的に削除してください。存在しないプロセス分離を前提にしてはいけません。逆に、独自に子プロセス環境をフィルタするツールでは、変数の明示的な許可が必要な場合があります。たとえば Codex の shell ツールは、名前に `TOKEN`、`KEY`、`SECRET` を含む変数を除外するため、デーモンは必要な作業変数を許可する管理対象の shell ポリシーを設定します。トークンはプロセス環境内だけに保持し、prompt、ログ、リポジトリファイル、永続設定には書き込まないでください。子プロセスは親の作業と同じ ID と権限を共有し、独立した新しいスコープ ID は受け取りません。+これらの値がプロセス環境へ直接注入される場合(カスタムランタイムプロファイルや `MULTICA_WARM_POOL=0` を設定した実行を含む)、ランタイムプロセスの実際の環境に存在します。ランタイムが起動する子プロセスは、`MULTICA_TOKEN` を含むすべての値をデフォルトで継承します。子プロセスに認証情報を渡すべきでない場合は、明示的に削除してください。存在しないプロセス分離を前提にしてはいけません。逆に、独自に子プロセス環境をフィルタするツールでは、変数の明示的な許可が必要な場合があります。たとえば Codex の shell ツールは、名前に `TOKEN`、`KEY`、`SECRET` を含む変数を除外するため、デーモンは必要な作業変数を許可する管理対象の shell ポリシーを設定します。トークンはプロセス環境内だけに保持し、prompt、ログ、リポジトリファイル、永続設定には書き込まないでください。子プロセスは親の作業と同じ ID と権限を共有し、独立した新しいスコープ ID は受け取りません。</Callout>### プロファイルの作成diff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdxindex fdc6d6e611..d2a4dd63c2 100644--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx@@ -280,8 +280,12 @@ Codex 기본 하위 에이전트도 기본적으로 꺼져 있습니다. Multica`MULTICA_TOKEN`을 사용하는 요청의 작성자는 서버가 결정하며, 태스크 댓글 같은 쓰기는 할당된 에이전트와 실행 중인 작업에 귀속됩니다. 자격 증명의 전체 바인딩, 권한, 귀속, 최대 24시간의 유효 기간 및 정리 동작은 [에이전트 실행용 임시 토큰](/auth-tokens#에이전트-실행용-임시-토큰)을 참고하세요.+<Callout type="info">+기본 제공 **Codex** 및 **Claude Code** 런타임은 후속 턴을 위해 기본적으로 웜 프로세스 풀을 재사용합니다. 웜 풀 실행 중에는 턴마다 바뀌는 작업 변수(`MULTICA_TOKEN`, `MULTICA_TASK_ID`, `MULTICA_TASK_CONFIG_ROOT`, `MULTICA_TASK_SLOT`)가 상주 프로세스의 정적 환경이 아니라 비공개 턴별 오버레이 파일을 통해 `multica` CLI에 전달되므로, 프로바이더 프로세스 환경이나 임의의 자식 스크립트에 노출되는 것은 보장되지 않습니다. 사용자 지정 런타임 프로필 명령은 웜 풀을 사용하지 않으며 계속해서 프로세스 환경에서 모든 변수를 직접 받습니다. 기본 제공 Codex 또는 Claude Code에서 기존 직접 환경 변수가 필요하면 데몬에 `MULTICA_WARM_POOL=0`을 설정하세요.+</Callout>+<Callout type="warning">-이 값은 런타임 프로세스의 실제 환경에 존재합니다. 런타임이 시작하는 모든 자식 프로세스는 기본적으로 `MULTICA_TOKEN`을 포함한 모든 값을 상속합니다. 자식 프로세스가 자격 증명을 보유하면 안 되는 경우 명시적으로 제거하세요. 존재하지 않는 프로세스 격리를 전제로 하면 안 됩니다. 반대로 자체적으로 하위 프로세스 환경을 필터링하는 도구에는 명시적인 변수 허용 규칙이 필요할 수 있습니다. 예를 들어 Codex의 shell 도구는 이름에 `TOKEN`, `KEY`, `SECRET`이 포함된 변수를 제거하므로 데몬은 필요한 작업 변수를 허용하는 관리형 shell 정책을 설정합니다. 토큰은 프로세스 환경에만 두고 prompt, 로그, 저장소 파일 또는 영구 설정에 기록하지 마세요. 자식 프로세스는 상위 작업의 ID와 권한을 공유하며 독립된 새 범위 ID를 받지 않습니다.+이 값이 프로세스 환경에 직접 주입되는 경우(사용자 지정 런타임 프로필 및 `MULTICA_WARM_POOL=0` 실행 포함) 런타임 프로세스의 실제 환경에 존재합니다. 런타임이 시작하는 모든 자식 프로세스는 기본적으로 `MULTICA_TOKEN`을 포함한 모든 값을 상속합니다. 자식 프로세스가 자격 증명을 보유하면 안 되는 경우 명시적으로 제거하세요. 존재하지 않는 프로세스 격리를 전제로 하면 안 됩니다. 반대로 자체적으로 하위 프로세스 환경을 필터링하는 도구에는 명시적인 변수 허용 규칙이 필요할 수 있습니다. 예를 들어 Codex의 shell 도구는 이름에 `TOKEN`, `KEY`, `SECRET`이 포함된 변수를 제거하므로 데몬은 필요한 작업 변수를 허용하는 관리형 shell 정책을 설정합니다. 토큰은 프로세스 환경에만 두고 prompt, 로그, 저장소 파일 또는 영구 설정에 기록하지 마세요. 자식 프로세스는 상위 작업의 ID와 권한을 공유하며 독립된 새 범위 ID를 받지 않습니다.</Callout>### 설정 만들기diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdxindex 3c2c5d3e3d..dbb02368f1 100644--- a/apps/docs/content/docs/daemon-runtimes.mdx+++ b/apps/docs/content/docs/daemon-runtimes.mdx@@ -280,8 +280,12 @@ The table lists the variables that custom runtimes can use today. It is intentioThe server determines authorship for requests made with `MULTICA_TOKEN`; writes such as issue comments are attributed to the assigned agent and active task. For the token's complete binding, permissions, attribution, 24-hour maximum lifetime, and cleanup behavior, see [Temporary tokens for agent runs](/auth-tokens#temporary-tokens-for-agent-runs).+<Callout type="info">+Built-in **Codex** and **Claude Code** runtimes reuse warm provider processes across follow-up turns by default. During warm-pooled runs, per-task variables that change every turn (`MULTICA_TOKEN`, `MULTICA_TASK_ID`, `MULTICA_TASK_CONFIG_ROOT`, `MULTICA_TASK_SLOT`) are provided to the daemon's `multica` CLI through a private per-turn overlay file rather than set in the long-lived provider process's static environment, so they are not guaranteed to appear in the provider process environment or arbitrary child scripts. Custom runtime profile commands do not use the warm pool and continue receiving all variables directly in the process environment. Set `MULTICA_WARM_POOL=0` on the daemon if a built-in Codex or Claude Code workflow needs the legacy direct environment variables.+</Callout>+<Callout type="warning">-These values live in the runtime process's real environment. Any child process the runtime starts inherits all of them by default, including `MULTICA_TOKEN`. If a child should not hold the credential, strip it explicitly; do not rely on process isolation that is not there. The exception runs the other way: tools that filter their own subprocess environment may require an explicit allow rule. For example, Codex's shell tool drops names containing `TOKEN`, `KEY`, or `SECRET`, so the daemon installs a managed shell policy that allows the required task variables. Keep the token in process environments only—never in a prompt, log, repository file, or persistent configuration. A child shares the parent task's identity and permissions; it does not receive a new, independently scoped identity.+When injected directly into the process environment (including custom runtime profiles and runs with `MULTICA_WARM_POOL=0`), these values live in the runtime process's real environment. Any child process the runtime starts inherits all of them by default, including `MULTICA_TOKEN`. If a child should not hold the credential, strip it explicitly; do not rely on process isolation that is not there. The exception runs the other way: tools that filter their own subprocess environment may require an explicit allow rule. For example, Codex's shell tool drops names containing `TOKEN`, `KEY`, or `SECRET`, so the daemon installs a managed shell policy that allows the required task variables. Keep the token in process environments only—never in a prompt, log, repository file, or persistent configuration. A child shares the parent task's identity and permissions; it does not receive a new, independently scoped identity.</Callout>### Creating a profilediff --git a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdxindex 4c69b3ffa5..bda5ad44c7 100644--- a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx@@ -281,8 +281,12 @@ Codex 原生子 AI 代理同樣預設關閉:父執行緒結束時,Multica使用 `MULTICA_TOKEN` 發起請求時,作者身份由服務端決定;任務評論等寫入操作會歸屬到被指派的 AI 代理和當前 task。令牌的完整繫結關係、權限、歸屬方式、最長 24 小時的有效期和清理規則見[AI 代理執行的臨時令牌](/auth-tokens#ai-代理執行的臨時令牌)。+<Callout type="info">+內建的 **Codex** 與 **Claude Code** 執行時預設啟用工作階段程序池以複用後續輪次程序。在程序池模式下,每輪都會變動的任務變數(`MULTICA_TOKEN`、`MULTICA_TASK_ID`、`MULTICA_TASK_CONFIG_ROOT`、`MULTICA_TASK_SLOT`)改由守護程序透過私有的單輪覆蓋檔案提供給 `multica` CLI,不再寫入常駐程序的靜態環境變數,因此不保證出現在 provider 程序環境或任意子指令碼中。自定義執行時配置命令不啟用程序池,仍直接在程序環境中接收全部變數。如果內建 Codex 或 Claude Code 的工作流需要舊的直接環境變數行為,可在守護程序環境中設定 `MULTICA_WARM_POOL=0`。+</Callout>+<Callout type="warning">-這些值存在於執行時程序的實際環境中。執行時啟動的任何子程序預設都會繼承全部變數,包括 `MULTICA_TOKEN`。子程序不應持有該憑據時,必須顯式移除,程序之間沒有自動隔離。反過來,有些工具會過濾自己的子程序環境,這時可能需要顯式放行變數。例如,Codex 的 shell 工具會丟棄名稱中含有 `TOKEN`、`KEY` 或 `SECRET` 的變數,所以守護程序會安裝託管的 shell 策略,放行所需的 task 變數。令牌只能存在於程序環境中,不得寫入 prompt、日誌、倉庫檔案或持久配置。子程序與父 task 共享身份和權限,不會獲得新的獨立作用域身份。+當這些值直接注入程序環境時(包括自定義執行時配置,以及設定了 `MULTICA_WARM_POOL=0` 的執行),它們存在於執行時程序的實際環境中。執行時啟動的任何子程序預設都會繼承全部變數,包括 `MULTICA_TOKEN`。子程序不應持有該憑據時,必須顯式移除,程序之間沒有自動隔離。反過來,有些工具會過濾自己的子程序環境,這時可能需要顯式放行變數。例如,Codex 的 shell 工具會丟棄名稱中含有 `TOKEN`、`KEY` 或 `SECRET` 的變數,所以守護程序會安裝託管的 shell 策略,放行所需的 task 變數。令牌只能存在於程序環境中,不得寫入 prompt、日誌、倉庫檔案或持久配置。子程序與父 task 共享身份和權限,不會獲得新的獨立作用域身份。</Callout>### 建立配置diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdxindex 817e14fd8b..a6866860ca 100644--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx@@ -281,8 +281,12 @@ Codex 原生子智能体同样默认关闭:父线程结束时,Multica 就把使用 `MULTICA_TOKEN` 发起请求时,作者身份由服务端决定;任务评论等写入操作会归属到被指派的智能体和当前 task。令牌的完整绑定关系、权限、归属方式、最长 24 小时的有效期和清理规则见[智能体执行的临时令牌](/auth-tokens#智能体执行的临时令牌)。+<Callout type="info">+内置的 **Codex** 和 **Claude Code** 运行时默认开启会话进程池以复用跟进轮进程。在进程池模式下,每轮都会变化的任务变量(`MULTICA_TOKEN`、`MULTICA_TASK_ID`、`MULTICA_TASK_CONFIG_ROOT`、`MULTICA_TASK_SLOT`)改由守护进程通过私有的单轮覆盖文件提供给 `multica` CLI,不再写入常驻进程的静态环境变量,因此不保证出现在 provider 进程环境或任意子脚本中。自定义运行时配置命令不启用进程池,仍直接在进程环境中接收全部变量。如果内置 Codex 或 Claude Code 的工作流需要旧的直接环境变量行为,可在守护进程环境中设置 `MULTICA_WARM_POOL=0`。+</Callout>+<Callout type="warning">-这些值存在于运行时进程的实际环境中。运行时启动的任何子进程默认都会继承全部变量,包括 `MULTICA_TOKEN`。子进程不应持有该凭据时,必须显式移除,进程之间没有自动隔离。反过来,有些工具会过滤自己的子进程环境,这时可能需要显式放行变量。例如,Codex 的 shell 工具会丢弃名称中含有 `TOKEN`、`KEY` 或 `SECRET` 的变量,所以守护进程会安装托管的 shell 策略,放行所需的 task 变量。令牌只能存在于进程环境中,不得写入 prompt、日志、仓库文件或持久配置。子进程与父 task 共享身份和权限,不会获得新的独立作用域身份。+当这些值直接注入进程环境时(包括自定义运行时配置,以及设置了 `MULTICA_WARM_POOL=0` 的运行),它们存在于运行时进程的实际环境中。运行时启动的任何子进程默认都会继承全部变量,包括 `MULTICA_TOKEN`。子进程不应持有该凭据时,必须显式移除,进程之间没有自动隔离。反过来,有些工具会过滤自己的子进程环境,这时可能需要显式放行变量。例如,Codex 的 shell 工具会丢弃名称中含有 `TOKEN`、`KEY` 或 `SECRET` 的变量,所以守护进程会安装托管的 shell 策略,放行所需的 task 变量。令牌只能存在于进程环境中,不得写入 prompt、日志、仓库文件或持久配置。子进程与父 task 共享身份和权限,不会获得新的独立作用域身份。</Callout>### 创建配置diff --git a/server/cmd/multica/main.go b/server/cmd/multica/main.goindex 9627609a55..555d71dfac 100644--- a/server/cmd/multica/main.go+++ b/server/cmd/multica/main.go@@ -110,6 +110,10 @@ func init() {}func main() {+ if err := agent.ApplyTaskEnvFileOverlay(); err != nil {+ fmt.Fprintln(os.Stderr, err)+ os.Exit(1)+ }if len(os.Args) == 2 && os.Args[1] == execenv.PreparationHelperArg {logger := slog.New(slog.NewTextHandler(os.Stderr, nil))if err := execenv.RunPreparationHelper(os.Stdin, os.Stdout, logger); err != nil {diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 388c30abfe..4d3e835a67 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -179,6 +179,10 @@ func taskScopedAuthToken(task Task) (string, error) {return token, nil}+// taskMessageFlushInterval bounds how often live transcript chunks are batched+// to the server. First visible output still flushes immediately via firstVisible.+var taskMessageFlushInterval = 150 * time.Millisecond+func taskMulticaEnvironment(task Task, provider, agentName, token, configRoot, workspacesRoot, serverURL string, healthPort, slot int, tempDir string) map[string]string {env := map[string]string{"MULTICA_TOKEN": token,@@ -460,6 +464,7 @@ type Daemon struct {client *ClientrepoCache repoCacheBackendskillCache *SkillBundleCache+ warmPool *agent.WarmSessionPoollogger *slog.Logger// gitCALastErr is the last applyGitCACerts failure, so a persistent one@@ -814,6 +819,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {client: client,repoCache: repocache.New(cacheRoot, logger),skillCache: NewSkillBundleCache(skillCacheRoot),+ warmPool: agent.NewWarmSessionPoolFromEnv(logger),logger: logger,terminalReports: newTerminalReportStore(cfg),terminalReportWakeup: make(chan struct{}, 1),@@ -2124,6 +2130,11 @@ func (d *Daemon) run(ctx context.Context, healthLn net.Listener) error {}}defer healthLn.Close()+ defer func() {+ if d.warmPool != nil && !d.warmPool.Close() {+ d.cleanupUnconfirmed.Store(true)+ }+ }()agentNames := make([]string, 0, len(d.agents()))for name := range d.agents() {@@ -5578,6 +5589,9 @@ func (d *Daemon) pollLoop(ctx context.Context, taskWakeups <-chan taskWakeup) er// taskWG.Wait at a zero counter.<-pollerDoned.waitForTaskCleanup(&taskWG, 30*time.Second)+ if d.warmPool != nil && !d.warmPool.Close() {+ d.cleanupUnconfirmed.Store(true)+ }return ctx.Err()case <-runtimeSetCh:// The batch poller re-derives allRuntimeIDs() each cycle; nudge it to@@ -9084,7 +9098,19 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot istopPrepareLease()prepareComplete = truecancelPrepare()- _ = d.client.ReportProgress(ctx, task.ID, fmt.Sprintf("Launching %s", provider), 1, 2)+ // Run best-effort pre-launch progress and context-receipt HTTP reports off+ // the critical launch path so the provider process starts immediately+ // without waiting for two synchronous API round trips (~1-1.5s). Wait for+ // them to drain before runTask returns so they never outlive the task.+ var preLaunchWG sync.WaitGroup+ defer preLaunchWG.Wait()+ preLaunchWG.Add(1)+ go func(reqCtx context.Context) {+ defer preLaunchWG.Done()+ progressCtx, progressCancel := context.WithTimeout(reqCtx, 5*time.Second)+ defer progressCancel()+ _ = d.client.ReportProgress(progressCtx, task.ID, fmt.Sprintf("Launching %s", provider), 1, 2)+ }(ctx)taskCtx = execenv.ApplyPreparedSkillNames(taskCtx, env.PreparedSkillNames)// usesCustomProfileCommand is the same provenance the backend receives as@@ -9256,7 +9282,19 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iagentEnv["MULTICA_DSH_SESSION_ROOT"] = dshSessionRootagentEnv["DSH_TELEMETRY_DISABLED"] = "1"}- if err := configureCodexTaskShellEnvironment(provider, env.CodexHome, os.Environ(), agentEnv, agentCustomEnv, d.logger); err != nil {+ taskWarmPool := selectTaskWarmPool(d.warmPool, usesCustomProfileCommand)+ codexShellEnv := agentEnv+ if provider == "codex" && taskWarmPool != nil {+ // Ensure Codex's managed shell_environment_policy allowlist permits+ // MULTICA_TASK_ENV_FILE so warm pooled sessions can deliver fresh+ // per-turn credentials to `multica` CLI subprocesses.+ codexShellEnv = make(map[string]string, len(agentEnv)+1)+ for k, v := range agentEnv {+ codexShellEnv[k] = v+ }+ codexShellEnv[agent.TaskEnvFileEnv] = "1"+ }+ if err := configureCodexTaskShellEnvironment(provider, env.CodexHome, os.Environ(), codexShellEnv, agentCustomEnv, d.logger); err != nil {return TaskResult{}, err}// The overlay is authoritative once built, so nothing on the command line@@ -9290,6 +9328,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iDaemonVersion: d.cfg.CLIVersion,CodexVersion: codexVersion,BuiltinRuntime: !usesCustomProfileCommand,+ WarmPool: taskWarmPool,}if hermesOverlayActive {// Retire an owner left by a crashed/interrupted daemon before it can@@ -9439,6 +9478,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iOpenclawModelOverride: openclawModelOverride,ClaudeSettingsPath: env.ClaudeSettingsPath,QwenpawWorkspace: env.QwenpawWorkspace,+ WarmPoolBriefHash: agent.HashWarmBrief(runtimeBrief),}// Some providers do not reliably load the per-task runtime config files we// write into the task workdir:@@ -9530,7 +9570,14 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iSkills: env.SkillReceipts(provider, taskCtx.AgentSkills),ExistingInstructions: execenv.ExistingRuntimeConfigContent(env.WorkDir, provider),}- d.reportContextReceipt(ctx, task.ID, buildContextReceipt(receiptInput), taskLog)+ initialReceipt := buildContextReceipt(receiptInput)+ preLaunchWG.Add(1)+ go func(reqCtx context.Context) {+ defer preLaunchWG.Done()+ receiptCtx, receiptCancel := context.WithTimeout(reqCtx, 5*time.Second)+ defer receiptCancel()+ d.reportContextReceipt(receiptCtx, task.ID, initialReceipt, taskLog)+ }(ctx)// Shared across the resume-retry below so the retry's transcript rows// keep ascending seq values for the same task.@@ -9617,6 +9664,9 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i// paragraph twice.// task and taskCtx are local (runTask takes task by value), so these// mutations only affect the retry.+ if taskWarmPool != nil && task.PriorSessionID != "" {+ taskWarmPool.Evict(provider, task.PriorSessionID)+ }execOpts.ResumeSessionID = ""task.PriorSessionID = ""task.PriorSessionResumeUnavailable = true@@ -9635,6 +9685,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i}freshPrompt, freshSkills := buildRuntimePrompt(task, provider, env.SkillDirectories, promptOptions...)execOpts.SkillInvocation = freshSkills+ execOpts.WarmPoolBriefHash = agent.HashWarmBrief(runtimeBrief)receiptInput.Prompt = freshPromptreceiptInput.RuntimeBrief = freshBrief@@ -9649,7 +9700,14 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ireceiptInput.TaskCtx = taskCtxreceiptInput.Skills = env.SkillReceipts(provider, taskCtx.AgentSkills)receiptInput.ExistingInstructions = execenv.ExistingRuntimeConfigContent(env.WorkDir, provider)- d.reportContextReceipt(ctx, task.ID, buildContextReceipt(receiptInput), taskLog)+ retryReceipt := buildContextReceipt(receiptInput)+ preLaunchWG.Add(1)+ go func(reqCtx context.Context) {+ defer preLaunchWG.Done()+ receiptCtx, receiptCancel := context.WithTimeout(reqCtx, 5*time.Second)+ defer receiptCancel()+ d.reportContextReceipt(receiptCtx, task.ID, retryReceipt, taskLog)+ }(ctx)retryResult, retryTools, retryErr := d.executeAndDrain(ctx, backend, freshPrompt, withPriorTaskUsage(execOpts, firstUsage), taskLog, task.ID, env.CodexHome, &msgSeq)if retryErr != nil {@@ -10508,7 +10566,7 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro}}- ticker := time.NewTicker(500 * time.Millisecond)+ ticker := time.NewTicker(taskMessageFlushInterval)defer ticker.Stop()done := make(chan struct{})@@ -11676,6 +11734,18 @@ func codexShellAuthorizedCustomEnvNames(customEnv map[string]string) []string {return names}+// selectTaskWarmPool returns the daemon's warm session pool only for built-in+// runtimes. Custom runtime profile commands (wrappers, version-pinned shims,+// sandbox launchers) always launch cold so startup wrappers can read per-task+// variables such as MULTICA_TOKEN and MULTICA_TASK_ID directly from the process+// environment.+func selectTaskWarmPool(pool *agent.WarmSessionPool, usesCustomProfileCommand bool) *agent.WarmSessionPool {+ if usesCustomProfileCommand {+ return nil+ }+ return pool+}+// configureCodexTaskShellEnvironment writes the managed shell policy only// after the task and agent custom environment are fully assembled. This makes// the allowlist reflect the child environment that will actually be launched,diff --git a/server/internal/daemon/warm_pool_test.go b/server/internal/daemon/warm_pool_test.gonew file mode 100644index 0000000000..2591155de2--- /dev/null+++ b/server/internal/daemon/warm_pool_test.go@@ -0,0 +1,28 @@+package daemon++import (+ "io"+ "log/slog"+ "testing"++ "github.com/multica-ai/multica/server/pkg/agent"+)++func TestSelectTaskWarmPoolDisablesCustomProfileCommands(t *testing.T) {+ t.Parallel()++ pool := agent.NewWarmSessionPool(agent.WarmSessionPoolConfig{+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ })+ defer pool.Close()++ if got := selectTaskWarmPool(pool, false); got != pool {+ t.Fatalf("selectTaskWarmPool(pool, false) = %v, want %v", got, pool)+ }+ if got := selectTaskWarmPool(pool, true); got != nil {+ t.Fatalf("selectTaskWarmPool(pool, true) = %v, want nil for custom profile command", got)+ }+ if got := selectTaskWarmPool(nil, false); got != nil {+ t.Fatalf("selectTaskWarmPool(nil, false) = %v, want nil", got)+ }+}diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex c9dfe07287..d5358812a8 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -184,6 +184,12 @@ type ExecOptions struct {// Like OnUsage it runs on the backend's protocol reader goroutine and MUST// NOT block.OnRateLimits func(RateLimitSnapshot)+ // WarmPoolBriefHash optionally fingerprints the workdir runtime brief+ // (AGENTS.md / CLAUDE.md) for warm session pool invalidation. When the brief+ // changes between turns (e.g. edited persona, skills, or workspace context),+ // the pool evicts the stale warm process and spawns fresh so the provider+ // loads the updated instructions.+ WarmPoolBriefHash string// piMcpExtensionPath is set by piBackend.Execute after it writes the// temporary MCP extension. The daemon does not fill it.piMcpExtensionPath string@@ -399,6 +405,10 @@ type Config struct {// Command boundary applies it to every process the package spawns, task// launches and CLI probes alike. Backends never read it directly.LaunchPrefix []string+ // WarmPool optionally enables warm provider process reuse across turns of+ // the same conversation for supported backends (Codex, Claude Code). Nil+ // disables pooling and preserves one-process-per-turn behavior.+ WarmPool *WarmSessionPool}// New creates a Backend for the given agent type.diff --git a/server/pkg/agent/claude.go b/server/pkg/agent/claude.goindex 8420941eaf..aa2104eb2a 100644--- a/server/pkg/agent/claude.go+++ b/server/pkg/agent/claude.go@@ -58,6 +58,9 @@ type claudeBackend struct {}func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {+ if b.cfg.WarmPool != nil {+ return b.executeWarm(ctx, prompt, opts)+ }execPath := b.cfg.ExecutablePathif execPath == "" {execPath = "claude"@@ -304,6 +307,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt}()scanner := newAgentStreamScanner(stdout)+ streamCoalescer := newClaudeStreamCoalescer(msgCh, nil)for scanner.Scan() {line := strings.TrimSpace(scanner.Text())@@ -319,15 +323,20 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpteventCount++switch msg.Type {+ case "stream_event":+ if msg.ParentToolUseID == "" {+ streamCoalescer.handleEvent(msg.Event)+ }case "assistant":assistantEventCount++- turn := b.handleAssistant(msg, msgCh, usage, seenUsage)+ turn := b.handleAssistantWithStream(msg, msgCh, usage, seenUsage, streamCoalescer)toolUseCount += turn.toolUsesif !turn.understood {unreadableAssistantCount++}lastAssistantText = turn.resolveFallback(lastAssistantText)case "user":+ streamCoalescer.flushAll()if b.handleUser(msg, msgCh) {sawAsyncLaunch = true}@@ -341,6 +350,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt}trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: sessionID})case "result":+ streamCoalescer.flushAll()sawResult = truefinalResultText = msg.ResultTextresultIsError = msg.IsError@@ -419,6 +429,7 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt}}}+ streamCoalescer.flushAll()scanErr := scanner.Err()if scanErr != nil {// Scanner stopped consuming stdout. Close the pipe before Wait so a@@ -553,14 +564,22 @@ func (b *claudeBackend) Execute(ctx context.Context, prompt string, opts ExecOpt}func (b *claudeBackend) handleAssistant(msg claudeSDKMessage, ch chan<- Message, usage map[string]TokenUsage, seenUsage map[string]struct{}) assistantTurn {+ return b.handleAssistantWithStream(msg, ch, usage, seenUsage, nil)+}++func (b *claudeBackend) handleAssistantWithStream(msg claudeSDKMessage, ch chan<- Message, usage map[string]TokenUsage, seenUsage map[string]struct{}, coalescer *claudeStreamCoalescer) assistantTurn {var content claudeMessageContentif err := json.Unmarshal(msg.Message, &content); err != nil {// Unreadable body: understood stays false so the caller drops any// fallback rather than let an older turn stand in for this one.return assistantTurn{}}+ if coalescer != nil && msg.ParentToolUseID == "" {+ coalescer.flushAll()+ }turn := assistantTurn{understood: true}var assistantText strings.Builder+ var assistantThinking strings.BuildertoolUseCount := 0// A response can emit several assistant blocks with the same message ID@@ -589,11 +608,16 @@ func (b *claudeBackend) handleAssistant(msg claudeSDKMessage, ch chan<- Message,case "text":if block.Text != "" {assistantText.WriteString(block.Text)- trySend(ch, Message{Type: MessageText, Content: block.Text})+ if coalescer == nil || msg.ParentToolUseID != "" || !coalescer.hasStreamedText() {+ trySend(ch, Message{Type: MessageText, Content: block.Text})+ }}case "thinking":if block.Thinking != "" {- trySend(ch, Message{Type: MessageThinking, Content: block.Thinking})+ assistantThinking.WriteString(block.Thinking)+ if coalescer == nil || msg.ParentToolUseID != "" || !coalescer.hasStreamedThinking() {+ trySend(ch, Message{Type: MessageThinking, Content: block.Thinking})+ }}case "tool_use":toolUseCount++@@ -615,11 +639,176 @@ func (b *claudeBackend) handleAssistant(msg claudeSDKMessage, ch chan<- Message,turn.understood = false}}+ if coalescer != nil && msg.ParentToolUseID == "" {+ coalescer.reconcileAssistant(assistantText.String(), assistantThinking.String())+ }turn.text = assistantText.String()turn.toolUses = toolUseCountreturn turn}+const (+ claudeStreamFlushInterval = 50 * time.Millisecond+ claudeStreamAggregateBytes = agentStreamMaxLineBytes / 64+)++// claudeStreamCoalescer handles Anthropic SSE `stream_event` envelopes emitted+// by `claude --include-partial-messages`, delivering the leading delta+// immediately and coalescing subsequent tokens at claudeStreamFlushInterval.+// When the matching `assistant` snapshot arrives, reconcileAssistant emits any+// trailing suffix not already delivered and resets per-message state so zero+// text is duplicated or dropped.+type claudeStreamCoalescer struct {+ ch chan<- Message+ now func() time.Time++ streamedText bool+ deliveredText strings.Builder+ pendingText strings.Builder+ lastTextFlush time.Time+ streamedThinking bool+ deliveredThink strings.Builder+ pendingThink strings.Builder+ lastThinkFlush time.Time+}++func newClaudeStreamCoalescer(ch chan<- Message, now func() time.Time) *claudeStreamCoalescer {+ if now == nil {+ now = time.Now+ }+ return &claudeStreamCoalescer{ch: ch, now: now}+}++func (c *claudeStreamCoalescer) hasStreamedText() bool {+ return c != nil && c.streamedText+}++func (c *claudeStreamCoalescer) hasStreamedThinking() bool {+ return c != nil && c.streamedThinking+}++func (c *claudeStreamCoalescer) handleEvent(raw json.RawMessage) {+ if c == nil || len(raw) == 0 {+ return+ }+ var env struct {+ Type string `json:"type"`+ Delta struct {+ Type string `json:"type"`+ Text string `json:"text"`+ Thinking string `json:"thinking"`+ } `json:"delta"`+ }+ if err := json.Unmarshal(raw, &env); err != nil {+ return+ }+ switch env.Type {+ case "message_start":+ c.flushAll()+ c.resetMessage()+ case "content_block_delta":+ switch env.Delta.Type {+ case "text_delta":+ if env.Delta.Text != "" {+ c.appendText(env.Delta.Text)+ }+ case "thinking_delta":+ if env.Delta.Thinking != "" {+ c.appendThinking(env.Delta.Thinking)+ }+ }+ case "content_block_stop", "message_stop":+ c.flushAll()+ }+}++func (c *claudeStreamCoalescer) appendText(delta string) {+ firstDelta := !c.streamedText && c.pendingText.Len() == 0+ c.streamedText = true+ c.pendingText.WriteString(delta)+ now := c.now()+ if firstDelta || c.pendingText.Len() >= claudeStreamAggregateBytes || (!c.lastTextFlush.IsZero() && now.Sub(c.lastTextFlush) >= claudeStreamFlushInterval) {+ c.flushText(now)+ }+}++func (c *claudeStreamCoalescer) appendThinking(delta string) {+ firstDelta := !c.streamedThinking && c.pendingThink.Len() == 0+ c.streamedThinking = true+ c.pendingThink.WriteString(delta)+ now := c.now()+ if firstDelta || c.pendingThink.Len() >= claudeStreamAggregateBytes || (!c.lastThinkFlush.IsZero() && now.Sub(c.lastThinkFlush) >= claudeStreamFlushInterval) {+ c.flushThinking(now)+ }+}++func (c *claudeStreamCoalescer) flushText(now time.Time) {+ if c.pendingText.Len() == 0 {+ return+ }+ chunk := c.pendingText.String()+ if trySend(c.ch, Message{Type: MessageText, Content: chunk}) {+ c.deliveredText.WriteString(chunk)+ c.pendingText.Reset()+ c.lastTextFlush = now+ }+}++func (c *claudeStreamCoalescer) flushThinking(now time.Time) {+ if c.pendingThink.Len() == 0 {+ return+ }+ chunk := c.pendingThink.String()+ if trySend(c.ch, Message{Type: MessageThinking, Content: chunk}) {+ c.deliveredThink.WriteString(chunk)+ c.pendingThink.Reset()+ c.lastThinkFlush = now+ }+}++func (c *claudeStreamCoalescer) flushAll() {+ if c == nil {+ return+ }+ now := c.now()+ c.flushText(now)+ c.flushThinking(now)+}++func (c *claudeStreamCoalescer) reconcileAssistant(fullText, fullThinking string) {+ if c == nil {+ return+ }+ if c.streamedText && fullText != "" {+ delivered := c.deliveredText.String()+ if len(fullText) > len(delivered) && strings.HasPrefix(fullText, delivered) {+ if tail := fullText[len(delivered):]; tail != "" {+ trySend(c.ch, Message{Type: MessageText, Content: tail})+ }+ }+ }+ if c.streamedThinking && fullThinking != "" {+ delivered := c.deliveredThink.String()+ if len(fullThinking) > len(delivered) && strings.HasPrefix(fullThinking, delivered) {+ if tail := fullThinking[len(delivered):]; tail != "" {+ trySend(c.ch, Message{Type: MessageThinking, Content: tail})+ }+ }+ }+ c.resetMessage()+}++func (c *claudeStreamCoalescer) resetMessage() {+ c.streamedText = false+ c.deliveredText.Reset()+ c.pendingText.Reset()+ c.lastTextFlush = time.Time{}+ c.streamedThinking = false+ c.deliveredThink.Reset()+ c.pendingThink.Reset()+ c.lastThinkFlush = time.Time{}+}+func (b *claudeBackend) handleUser(msg claudeSDKMessage, ch chan<- Message) bool {var content claudeMessageContentif err := json.Unmarshal(msg.Message, &content); err != nil {@@ -762,6 +951,9 @@ type claudeSDKMessage struct {// rate_limit_event fieldsRateLimitInfo json.RawMessage `json:"rate_limit_info,omitempty"`+ // stream_event fields (--include-partial-messages)+ Event json.RawMessage `json:"event,omitempty"`+// control request fieldsRequestID string `json:"request_id,omitempty"`Request json.RawMessage `json:"request,omitempty"`@@ -1164,11 +1356,12 @@ func trySend(ch chan<- Message, msg Message) bool {// overridden by user-configured custom_args. Overriding these would break// the daemon↔Claude communication protocol.var claudeBlockedArgs = map[string]blockedArgMode{- "-p": blockedStandalone, // non-interactive mode- "--output-format": blockedWithValue, // stream-json protocol- "--input-format": blockedWithValue, // stream-json protocol- "--permission-mode": blockedWithValue, // bypassPermissions for autonomous operation- "--mcp-config": blockedWithValue, // set by daemon from agent.mcp_config+ "-p": blockedStandalone, // non-interactive mode+ "--output-format": blockedWithValue, // stream-json protocol+ "--input-format": blockedWithValue, // stream-json protocol+ "--include-partial-messages": blockedStandalone, // incremental stream_event deltas+ "--permission-mode": blockedWithValue, // bypassPermissions for autonomous operation+ "--mcp-config": blockedWithValue, // set by daemon from agent.mcp_config// `--effort` is owned by the per-agent thinking_level picker so a// user-supplied custom_arg cannot silently outvote it. The daemon// injects --effort only when opts.ThinkingLevel is set; if a user@@ -1184,6 +1377,7 @@ func buildClaudeArgs(opts ExecOptions, logger *slog.Logger) []string {"--output-format", "stream-json","--input-format", "stream-json","--verbose",+ "--include-partial-messages","--permission-mode", "bypassPermissions",// AskUserQuestion is Claude Code's built-in interactive question tool.// The daemon runs Claude in non-interactive stream-json mode and hasdiff --git a/server/pkg/agent/claude_pool.go b/server/pkg/agent/claude_pool.gonew file mode 100644index 0000000000..47e2635604--- /dev/null+++ b/server/pkg/agent/claude_pool.go@@ -0,0 +1,729 @@+package agent++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "sync"+ "sync/atomic"+ "syscall"+ "time"+)++type claudeWarmTurn struct {+ backend *claudeBackend+ runCtx context.Context+ cancel context.CancelFunc+ opts ExecOptions+ msgCh chan Message+ coalescer *claudeStreamCoalescer+ inputWriter *claudeInputWriter+ supplements *claudeSupplementSession+ initializer *claudeSupplementSession+ usageSnapshot *claudeUsageSnapshot+ baselineUsage map[string]TokenUsage+ rateLimits *rateLimitTracker+ controlWrites sync.WaitGroup+ controlErrors chan error+ resultCh chan struct{}+ resultOnce sync.Once++ mu sync.Mutex+ lastAssistantText string+ finalResultText string+ sawResult bool+ resultIsError bool+ terminalReasonError string+ sessionID string+ lastUsageResult *claudeSDKMessage+ lastRawModelUsage map[string]TokenUsage+ sawAsyncLaunch bool+ usage map[string]TokenUsage+ seenUsage map[string]struct{}+ eventCount int+ invalidEventCount int+ assistantEventCount int+ toolUseCount int+ unreadableAssistantCount int+}++func (t *claudeWarmTurn) handleMessage(msg claudeSDKMessage) {+ t.mu.Lock()+ t.eventCount+++ switch msg.Type {+ case "stream_event":+ if msg.ParentToolUseID == "" {+ t.coalescer.handleEvent(msg.Event)+ }+ t.mu.Unlock()+ case "assistant":+ t.assistantEventCount+++ turn := t.backend.handleAssistantWithStream(msg, t.msgCh, t.usage, t.seenUsage, t.coalescer)+ t.toolUseCount += turn.toolUses+ if !turn.understood {+ t.unreadableAssistantCount+++ }+ t.lastAssistantText = turn.resolveFallback(t.lastAssistantText)+ t.mu.Unlock()+ case "user":+ t.coalescer.flushAll()+ if t.backend.handleUser(msg, t.msgCh) {+ t.sawAsyncLaunch = true+ }+ t.mu.Unlock()+ case "rate_limit_event":+ rl := t.rateLimits+ t.mu.Unlock()+ if update, ok := parseClaudeRateLimitEvent(msg.RateLimitInfo); ok {+ rl.apply(update)+ }+ case "system":+ if msg.SessionID != "" {+ t.sessionID = msg.SessionID+ }+ sid := t.sessionID+ t.mu.Unlock()+ trySend(t.msgCh, Message{Type: MessageStatus, Status: "running", SessionID: sid})+ case "result":+ t.coalescer.flushAll()+ t.sawResult = true+ t.finalResultText = msg.ResultText+ t.resultIsError = msg.IsError+ t.terminalReasonError = claudeTerminalReasonFailure(msg.TerminalReason, msg.ResultText)+ if msg.SessionID != "" {+ t.sessionID = msg.SessionID+ }+ if len(msg.ModelUsage) > 0 {+ t.lastRawModelUsage = claudeModelUsage(msg.ModelUsage)+ }+ unverifiableBaseline := t.usageSnapshot == nil && t.baselineUsage == nil && t.opts.ResumeSessionID != ""+ baseline := t.baselineUsage+ if baseline == nil && t.usageSnapshot != nil {+ baseline = t.usageSnapshot.baseline+ }+ if resultUsage, authoritative := claudeResultUsageSince(msg, t.opts.Model, baseline); authoritative {+ usageMsg := msg+ t.lastUsageResult = &usageMsg+ if !unverifiableBaseline {+ t.usage = resultUsage+ }+ }+ t.mu.Unlock()+ t.resultOnce.Do(func() { close(t.resultCh) })+ case "log":+ t.mu.Unlock()+ if msg.Log != nil {+ trySend(t.msgCh, Message{+ Type: MessageLog,+ Level: msg.Log.Level,+ Content: msg.Log.Message,+ })+ }+ case "control_request":+ supplements := t.supplements+ t.mu.Unlock()+ var reply func(io.Writer) error+ if supplements != nil {+ reply, _ = supplements.prepareHook(msg)+ }+ t.controlWrites.Add(1)+ go func(msg claudeSDKMessage, reply func(io.Writer) error) {+ defer t.controlWrites.Done()+ if reply == nil {+ t.backend.handleControlRequest(msg, t.inputWriter)+ return+ }+ if err := reply(t.inputWriter); err != nil {+ select {+ case t.controlErrors <- err:+ default:+ }+ t.cancel()+ }+ }(msg, reply)+ case "control_response":+ init := t.initializer+ t.mu.Unlock()+ if init != nil {+ init.handleResponse(msg.Response)+ }+ default:+ t.mu.Unlock()+ }+}++func (t *claudeWarmTurn) noteInvalidEvent() {+ t.mu.Lock()+ t.invalidEventCount+++ t.mu.Unlock()+}++type warmClaudeProcess struct {+ fingerprint string+ sessionID string+ cmd *exec.Cmd+ stdin io.WriteCloser+ inputWriter *claudeInputWriter+ stdout io.ReadCloser+ stderrBuf *stderrTail+ procDone chan struct{}+ mcpConfigPath string+ sessionDir string+ taskEnvFile string+ sessionTempDir string+ logger *slog.Logger+ initialized bool+ initializedCommands map[string]bool+ lastCumulativeModelUsage map[string]TokenUsage++ turnMu sync.Mutex+ activeTurn *claudeWarmTurn+ scanErr error+ exitErr error++ closed atomic.Bool+ closeOnce sync.Once+}++func (p *warmClaudeProcess) Fingerprint() string { return p.fingerprint }++func (p *warmClaudeProcess) Alive() bool {+ if p.closed.Load() {+ return false+ }+ select {+ case <-p.procDone:+ return false+ default:+ return true+ }+}++func (p *warmClaudeProcess) setActiveTurn(t *claudeWarmTurn) {+ p.turnMu.Lock()+ p.activeTurn = t+ p.turnMu.Unlock()+}++func (p *warmClaudeProcess) getErrors() (scanErr, exitErr error) {+ p.turnMu.Lock()+ defer p.turnMu.Unlock()+ return p.scanErr, p.exitErr+}++func (p *warmClaudeProcess) Close() bool {+ p.closeOnce.Do(func() {+ p.closed.Store(true)+ _ = ClearTaskEnvFile(p.taskEnvFile)+ _ = p.stdin.Close()++ // Give the CLI a brief window to exit cleanly on stdin EOF before+ // signalling the process group, mirroring claudeBackend.Execute.+ select {+ case <-p.procDone:+ case <-time.After(1500 * time.Millisecond):+ if p.cmd.Process != nil {+ signalProcessGroup(p.cmd, syscall.SIGTERM)+ if !waitProcessGroupGone(p.cmd, claudeTerminateGrace()) {+ signalProcessGroup(p.cmd, syscall.SIGKILL)+ }+ }+ _ = p.stdout.Close()+ <-p.procDone+ }++ if p.mcpConfigPath != "" {+ cleanupMcpConfigTemp(p.mcpConfigPath)+ }+ if p.sessionDir != "" {+ _ = os.RemoveAll(p.sessionDir)+ }+ })+ return true+}++func (p *warmClaudeProcess) terminateImmediately() {+ p.closed.Store(true)+ _ = p.stdin.Close()+ if p.cmd.Process != nil {+ signalProcessGroup(p.cmd, syscall.SIGTERM)+ if !waitProcessGroupGone(p.cmd, claudeTerminateGrace()) {+ signalProcessGroup(p.cmd, syscall.SIGKILL)+ }+ }+ _ = p.stdout.Close()+}++func (b *claudeBackend) executeWarm(ctx context.Context, prompt string, opts ExecOptions) (*Session, error) {+ execPath := b.cfg.ExecutablePath+ if execPath == "" {+ execPath = "claude"+ }+ if _, err := exec.LookPath(execPath); err != nil {+ return nil, fmt.Errorf("claude executable not found at %q: %w", execPath, err)+ }++ timeout := opts.Timeout+ runCtx, cancel := runContext(ctx, timeout)++ // Build fingerprint args without --resume so a Turn-1 spawned process and+ // a Turn-2 resumed request for the same session share an identical key.+ optsForFP := opts+ optsForFP.ResumeSessionID = ""+ argsForFP := buildClaudeArgs(optsForFP, b.cfg.Logger)+ var configFiles []string+ if opts.ClaudeSettingsPath != "" {+ configFiles = append(configFiles, opts.ClaudeSettingsPath)+ }+ fingerprint := computeWarmSessionFingerprint(WarmSessionFingerprintInput{+ Provider: "claude",+ Executable: execPath,+ LaunchPrefix: b.cfg.LaunchPrefix,+ Args: argsForFP,+ Cwd: opts.Cwd,+ Model: opts.Model,+ ThinkingLevel: opts.ThinkingLevel,+ McpConfig: opts.McpConfig,+ ConfigFiles: configFiles,+ BriefHash: opts.WarmPoolBriefHash,+ Env: b.cfg.Env,+ ExtraFlags: []string{fmt.Sprintf("supplement=%t", opts.EnableTaskSupplement)},+ })++ var warmProc *warmClaudeProcess+ warmHit := false+ if opts.ResumeSessionID != "" {+ if acquired := b.cfg.WarmPool.Acquire("claude", opts.ResumeSessionID, fingerprint); acquired != nil {+ if candidate, ok := acquired.(*warmClaudeProcess); ok {+ if err := WriteTaskEnvFile(candidate.taskEnvFile, b.cfg.Env); err != nil {+ b.cfg.Logger.Warn("warm claude: failed to refresh task env overlay; evicting", "error", err)+ candidate.Close()+ } else {+ warmProc = candidate+ warmHit = true+ }+ } else {+ acquired.Close()+ }+ }+ }++ var usageSnapshot *claudeUsageSnapshot+ if !warmHit {+ var err error+ warmProc, usageSnapshot, err = b.spawnWarmClaudeProcess(execPath, opts, fingerprint)+ if err != nil {+ cancel()+ return nil, err+ }+ }++ msgCh := make(chan Message, 256)+ resCh := make(chan Result, 1)++ var supplements *claudeSupplementSession+ if opts.EnableTaskSupplement {+ supplements = newClaudeSupplementSession(runCtx)+ }+ initializer := supplements+ if initializer == nil && opts.SkillInvocation != nil {+ initializer = newClaudeSupplementSession(runCtx)+ }++ var baselineUsage map[string]TokenUsage+ if warmHit && len(warmProc.lastCumulativeModelUsage) > 0 {+ baselineUsage = make(map[string]TokenUsage, len(warmProc.lastCumulativeModelUsage))+ for k, v := range warmProc.lastCumulativeModelUsage {+ baselineUsage[k] = v+ }+ }++ turn := &claudeWarmTurn{+ backend: b,+ runCtx: runCtx,+ cancel: cancel,+ opts: opts,+ msgCh: msgCh,+ coalescer: newClaudeStreamCoalescer(msgCh, nil),+ inputWriter: warmProc.inputWriter,+ supplements: supplements,+ initializer: initializer,+ usageSnapshot: usageSnapshot,+ baselineUsage: baselineUsage,+ rateLimits: newRateLimitTracker(opts.OnRateLimits),+ controlErrors: make(chan error, 1),+ resultCh: make(chan struct{}),+ usage: make(map[string]TokenUsage),+ seenUsage: make(map[string]struct{}),+ }+ if warmHit {+ turn.sessionID = warmProc.sessionID+ }+ warmProc.setActiveTurn(turn)++ if warmHit {+ b.cfg.Logger.Info("claude warm session reused",+ "pid", warmProc.cmd.Process.Pid,+ "session_id", warmProc.sessionID,+ "cwd", opts.Cwd,+ "model", opts.Model,+ )+ trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: warmProc.sessionID})+ }++ writeDone := make(chan error, 1)+ go func() {+ var commands map[string]bool+ if warmHit {+ if warmProc.initialized && !slashCommandsDisabled(b.cfg.LaunchPrefix, opts.ExtraArgs, opts.CustomArgs) {+ commands = warmProc.initializedCommands+ }+ } else if initializer != nil {+ if initErr := initializer.initialize(warmProc.inputWriter, opts.HandshakeTimeout, opts.EnableTaskSupplement); initErr != nil {+ b.cfg.Logger.Warn("Claude initialization unavailable; continuing with text input", "error", initErr)+ initializer.end()+ } else {+ warmProc.initialized = true+ warmProc.initializedCommands = initializer.availableCommands()+ if !slashCommandsDisabled(b.cfg.LaunchPrefix, opts.ExtraArgs, opts.CustomArgs) {+ commands = warmProc.initializedCommands+ }+ }+ }+ blocks := []string{prompt}+ if opts.SkillInvocation != nil {+ blocks = opts.SkillInvocation.claudeTextBlocks(commands)+ }+ err := writeClaudeInput(warmProc.inputWriter, blocks...)+ if err != nil {+ if supplements != nil {+ cancel()+ }+ }+ writeDone <- err+ }()++ go func() {+ defer cancel()+ defer close(msgCh)+ defer close(resCh)++ startTime := time.Now()++ // Wait for either the turn's result event, process exit, or context+ // cancellation/timeout.+ var cancelledOrTimedOut bool+ select {+ case <-turn.resultCh:+ case <-warmProc.procDone:+ case <-runCtx.Done():+ cancelledOrTimedOut = true+ warmProc.terminateImmediately()+ <-warmProc.procDone+ }++ if initializer != nil {+ initializer.end()+ }++ turn.mu.Lock()+ turn.coalescer.flushAll()+ sawResult := turn.sawResult+ resultIsError := turn.resultIsError+ terminalReasonError := turn.terminalReasonError+ sawAsyncLaunch := turn.sawAsyncLaunch+ sessionID := turn.sessionID+ lastAssistantText := turn.lastAssistantText+ finalResultText := turn.finalResultText+ lastUsageResult := turn.lastUsageResult+ lastRawModelUsage := turn.lastRawModelUsage+ usage := turn.usage+ eventCount := turn.eventCount+ invalidEventCount := turn.invalidEventCount+ assistantEventCount := turn.assistantEventCount+ toolUseCount := turn.toolUseCount+ unreadableAssistantCount := turn.unreadableAssistantCount+ turn.mu.Unlock()++ turn.controlWrites.Wait()+ writeErr := <-writeDone+ if writeErr == nil {+ select {+ case writeErr = <-turn.controlErrors:+ default:+ }+ }++ if supplements != nil && writeErr != nil && ctx.Err() == nil && terminalReasonError == "" && !errors.Is(runCtx.Err(), context.DeadlineExceeded) {+ terminalReasonError = fmt.Sprintf("claude input/control protocol failed: %v", writeErr)+ }++ // Detach the turn before deciding to park or close.+ warmProc.setActiveTurn(nil)+ _ = ClearTaskEnvFile(warmProc.taskEnvFile)++ scanErr, exitErr := warmProc.getErrors()+ canPark := sawResult &&+ !resultIsError &&+ terminalReasonError == "" &&+ !sawAsyncLaunch &&+ !cancelledOrTimedOut &&+ writeErr == nil &&+ scanErr == nil &&+ runCtx.Err() == nil &&+ sessionID != "" &&+ warmProc.Alive()++ if canPark {+ warmProc.sessionID = sessionID+ if len(lastRawModelUsage) > 0 {+ warmProc.lastCumulativeModelUsage = lastRawModelUsage+ }+ b.cfg.WarmPool.Park("claude", sessionID, warmProc)+ } else {+ // Close stdin immediately so a persistent stream-json CLI waiting for+ // the next user frame exits on EOF instead of blocking for the error+ // result grace window.+ warmProc.Close()+ scanErr, exitErr = warmProc.getErrors()+ }++ duration := time.Since(startTime)++ if !sawResult && usageSnapshot != nil {+ appendedUsage, found, snapshotErr := usageSnapshot.appendedCostStateUsage()+ switch {+ case snapshotErr != nil:+ b.cfg.Logger.Warn("claude final cost state unavailable; keeping stream usage fallback", "error", snapshotErr)+ case found:+ usage = subtractClaudeUsage(appendedUsage, usageSnapshot.baseline)+ }+ }++ completionGuardError := ""+ if sawAsyncLaunch {+ completionGuardError = "claude launched an async background task; Multica-managed runs require foreground execution"+ }+ finalStatus, finalOutput, finalError := finalizeStreamResult(+ "claude",+ timeout,+ runCtx.Err(),+ writeErr,+ exitErr,+ sessionID,+ streamTerminalState{+ lastAssistantText: lastAssistantText,+ finalResultText: finalResultText,+ sawResult: sawResult,+ resultIsError: resultIsError,+ scanErr: scanErr,+ terminalReasonError: terminalReasonError,+ },+ completionGuardError,+ )++ stderrTail := warmProc.stderrBuf.Tail()+ if finalError != "" {+ finalError = withAgentStderr(finalError, "claude", stderrTail)+ }+ logStreamProtocolObservation(b.cfg.Logger, streamProtocolObservation{+ provider: "claude",+ cliVersion: b.cfg.CLIVersion,+ model: opts.Model,+ exitCode: streamProcessExitCode(exitErr),+ eventCount: eventCount,+ invalidEventCount: invalidEventCount,+ assistantEventCount: assistantEventCount,+ toolUseCount: toolUseCount,+ sawResult: sawResult,+ resultIsError: resultIsError,+ resultBytes: len(finalResultText),+ lastAssistantBytes: len(lastAssistantText),+ scannerError: scanErr != nil,+ unreadableAssistantCount: unreadableAssistantCount,+ anthropicBaseURLConfigured: strings.TrimSpace(b.cfg.Env["ANTHROPIC_BASE_URL"]) != "",+ })++ b.cfg.Logger.Info("claude finished",+ "pid", warmProc.cmd.Process.Pid,+ "warm_hit", warmHit,+ "parked", canPark,+ "status", finalStatus,+ "duration", duration.Round(time.Millisecond).String(),+ )++ resumeRejected := resumeWasRejected(opts.ResumeSessionID, sessionID, finalStatus == "failed", finalError, stderrTail)+ reportedSessionID := resolveSessionID(opts.ResumeSessionID, sessionID, finalStatus == "failed", finalError, stderrTail)+ if resumeRejected {+ if lastUsageResult != nil {+ if resultUsage, authoritative := claudeResultUsageSince(*lastUsageResult, opts.Model, nil); authoritative {+ usage = resultUsage+ }+ }+ b.cfg.Logger.Info("claude resume was rejected; dropping session id and signalling fresh-session retry",+ "requested_resume", opts.ResumeSessionID,+ "emitted_session", sessionID,+ )+ }++ resCh <- Result{+ Status: finalStatus,+ Output: finalOutput,+ Error: finalError,+ DurationMs: duration.Milliseconds(),+ SessionID: reportedSessionID,+ Usage: usage,+ ResumeRejected: resumeRejected,+ }+ }()++ session := &Session{Messages: msgCh, Result: resCh}+ if supplements != nil {+ session.Supplement = supplements.supplement+ session.SupplementReady = supplements.ready+ }+ return session, nil+}++func (b *claudeBackend) spawnWarmClaudeProcess(execPath string, opts ExecOptions, fingerprint string) (*warmClaudeProcess, *claudeUsageSnapshot, error) {+ sessionDir, err := os.MkdirTemp("", "multica-claude-warm-*")+ if err != nil {+ return nil, nil, fmt.Errorf("create warm claude session dir: %w", err)+ }+ sessionTempDir := filepath.Join(sessionDir, "tmp")+ if err := os.MkdirAll(sessionTempDir, 0o700); err != nil {+ _ = os.RemoveAll(sessionDir)+ return nil, nil, fmt.Errorf("create warm claude temp dir: %w", err)+ }+ taskEnvFile := filepath.Join(sessionDir, "task-env.json")+ if err := WriteTaskEnvFile(taskEnvFile, b.cfg.Env); err != nil {+ _ = os.RemoveAll(sessionDir)+ return nil, nil, fmt.Errorf("write warm claude task env overlay: %w", err)+ }++ args := buildClaudeArgs(opts, b.cfg.Logger)+ var mcpConfigPath string+ if hasManagedMcpConfig(opts.McpConfig) {+ path, err := writeMcpConfigToTemp(opts.McpConfig)+ if err != nil {+ _ = os.RemoveAll(sessionDir)+ return nil, nil, err+ }+ mcpConfigPath = path+ args = append(args, "--mcp-config", mcpConfigPath)+ }++ cleanupOnErr := func() {+ if mcpConfigPath != "" {+ cleanupMcpConfigTemp(mcpConfigPath)+ }+ _ = os.RemoveAll(sessionDir)+ }++ cmd := b.cfg.commandAt(execPath).exec(context.Background(), args...)+ hideAgentWindow(cmd)+ cmd.Cancel = func() error { return nil }+ b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(args))+ cmd.WaitDelay = 10 * time.Second+ if opts.Cwd != "" {+ cmd.Dir = opts.Cwd+ }+ cmd.Env = buildEnv(PreparePooledChildEnv(b.cfg.Env, taskEnvFile, sessionTempDir))+ if err := claudeRootSudoPreflight(args, cmd.Env); err != nil {+ cleanupOnErr()+ return nil, nil, err+ }++ var usageSnapshot *claudeUsageSnapshot+ if opts.ResumeSessionID != "" {+ snapshot, snapshotErr := captureClaudeUsageSnapshot(cmd.Env, cmd.Dir, opts.ResumeSessionID)+ if snapshotErr != nil {+ b.cfg.Logger.Warn("claude usage baseline unavailable; ignoring reported session totals, keeping per-run stream usage", "error", snapshotErr)+ } else {+ usageSnapshot = snapshot+ }+ }++ stdout, err := cmd.StdoutPipe()+ if err != nil {+ cleanupOnErr()+ return nil, nil, fmt.Errorf("claude stdout pipe: %w", err)+ }+ stdin, err := cmd.StdinPipe()+ if err != nil {+ cleanupOnErr()+ return nil, nil, fmt.Errorf("claude stdin pipe: %w", err)+ }+ stderrBuf := newStderrTail(newLogWriter(b.cfg.Logger, "[claude:stderr] "), agentStderrTailBytes)+ cmd.Stderr = stderrBuf++ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {+ _ = stdin.Close()+ cleanupOnErr()+ return nil, nil, fmt.Errorf("start claude: %w", err)+ }++ b.cfg.Logger.Info("claude started", "warm_pool", true, "pid", cmd.Process.Pid, "cwd", opts.Cwd, "model", opts.Model)++ proc := &warmClaudeProcess{+ fingerprint: fingerprint,+ cmd: cmd,+ stdin: stdin,+ inputWriter: &claudeInputWriter{w: stdin},+ stdout: stdout,+ stderrBuf: stderrBuf,+ procDone: make(chan struct{}),+ mcpConfigPath: mcpConfigPath,+ sessionDir: sessionDir,+ taskEnvFile: taskEnvFile,+ sessionTempDir: sessionTempDir,+ logger: b.cfg.Logger,+ }++ go func() {+ defer close(proc.procDone)+ scanner := newAgentStreamScanner(stdout)+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ if line == "" {+ continue+ }+ var msg claudeSDKMessage+ if err := json.Unmarshal([]byte(line), &msg); err != nil {+ proc.turnMu.Lock()+ turn := proc.activeTurn+ proc.turnMu.Unlock()+ if turn != nil {+ turn.noteInvalidEvent()+ }+ continue+ }+ proc.turnMu.Lock()+ turn := proc.activeTurn+ proc.turnMu.Unlock()+ if turn != nil {+ turn.handleMessage(msg)+ }+ }+ scanErr := scanner.Err()+ if scanErr != nil {+ _ = stdout.Close()+ }+ _ = stdin.Close()+ exitErr := cmd.Wait()+ releaseProcessGroup(cmd)+ proc.turnMu.Lock()+ proc.scanErr = scanErr+ proc.exitErr = exitErr+ proc.turnMu.Unlock()+ }()++ return proc, usageSnapshot, nil+}diff --git a/server/pkg/agent/claude_test.go b/server/pkg/agent/claude_test.goindex 7824632e69..9a1cb13952 100644--- a/server/pkg/agent/claude_test.go+++ b/server/pkg/agent/claude_test.go@@ -397,6 +397,7 @@ func TestBuildClaudeArgsInheritsMCPByDefault(t *testing.T) {"--output-format", "stream-json","--input-format", "stream-json","--verbose",+ "--include-partial-messages","--permission-mode", "bypassPermissions","--disallowedTools", "AskUserQuestion",}diff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.goindex 38c23614a7..325cda2cc9 100644--- a/server/pkg/agent/codex.go+++ b/server/pkg/agent/codex.go@@ -89,10 +89,10 @@ const (// chunk rather than split at an arbitrary byte boundary.codexAgentMessageAggregateBytes = agentStreamMaxLineBytes / 64// codexAgentMessageFlushInterval is how long pending agent text may wait- // before the next delta hands it off. It matches the daemon's 500 ms report- // batch, so a long answer streams at the rate the server can show it while- // a token burst still costs at most one channel slot per interval.- codexAgentMessageFlushInterval = 500 * time.Millisecond+ // before the next delta hands it off. Kept at 50 ms so streamed tokens reach+ // the daemon reporter without perceptible stall while bursts still coalesce+ // into bounded channel entries.+ codexAgentMessageFlushInterval = 50 * time.Millisecond// 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@@ -1080,6 +1080,9 @@ func (b *codexBackend) Execute(ctx context.Context, prompt string, opts ExecOpti}func (b *codexBackend) executeOnce(ctx context.Context, prompt string, opts ExecOptions, attempt int) (*Session, error) {+ if b.cfg.WarmPool != nil {+ return b.executeWarmOnce(ctx, prompt, opts, attempt)+ }execPath := b.cfg.ExecutablePathif execPath == "" {execPath = "codex"@@ -2414,9 +2417,12 @@ 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+ cfg Config+ stdin interface{ Write([]byte) (int, error) }+ mu sync.Mutex+ // hookMu serializes turn-state attachment/detachment on pooled warm clients+ // against the persistent stdout reader goroutine's notification dispatch.+ hookMu sync.MutexnextID intpending map[int]*pendingRPCprocessDone chan struct{}@@ -2940,14 +2946,18 @@ func (c *codexClient) handleLine(line string) {}// Server request (has id + method)if _, hasMethod := raw["method"]; hasMethod {+ c.hookMu.Lock()c.handleServerRequest(raw)+ c.hookMu.Unlock()return}}// Notification (no id, has method)if _, hasMethod := raw["method"]; hasMethod {+ c.hookMu.Lock()c.handleNotification(raw)+ c.hookMu.Unlock()}}diff --git a/server/pkg/agent/codex_pool.go b/server/pkg/agent/codex_pool.gonew file mode 100644index 0000000000..ffa5a0e1a9--- /dev/null+++ b/server/pkg/agent/codex_pool.go@@ -0,0 +1,986 @@+package agent++import (+ "context"+ "errors"+ "fmt"+ "io"+ "log/slog"+ "os"+ "os/exec"+ "path/filepath"+ "strings"+ "sync"+ "sync/atomic"+ "syscall"+ "time"+)++// codexSyncWriter serializes concurrent writes to a Codex app-server stdin pipe+// (lifecycle RPCs, server-request approval replies from the stdout reader, and+// mid-turn turn/steer calls).+type codexSyncWriter struct {+ mu sync.Mutex+ w io.WriteCloser+}++func (w *codexSyncWriter) Write(p []byte) (int, error) {+ w.mu.Lock()+ defer w.mu.Unlock()+ return w.w.Write(p)+}++func (w *codexSyncWriter) Close() error {+ w.mu.Lock()+ defer w.mu.Unlock()+ return w.w.Close()+}++type codexTurnHooks struct {+ cfg Config+ acceptNotification func(method string, params map[string]any) bool+ onDiscardedNotification func(method string, params map[string]any)+ onMessage func(Message)+ onAgentMessageChunk func(text string) bool+ onAgentMessage func(text, phase string)+ onFinalAnswer func(text string)+ onSemanticActivity func(description string)+ onTurnDone func(aborted bool)+ guardianRateLimitCircuit *codexGuardianRateLimitCircuit+ onGuardianRateLimit func()+ rateLimits *rateLimitTracker+ preserveUsageBaseline bool+}++func (c *codexClient) attachTurnHooks(h codexTurnHooks) {+ c.hookMu.Lock()+ defer c.hookMu.Unlock()++ c.cfg = h.cfg+ c.acceptNotification = h.acceptNotification+ c.onDiscardedNotification = h.onDiscardedNotification+ c.onMessage = h.onMessage+ c.onAgentMessageChunk = h.onAgentMessageChunk+ c.onAgentMessage = h.onAgentMessage+ c.onFinalAnswer = h.onFinalAnswer+ c.onSemanticActivity = h.onSemanticActivity+ c.onTurnDone = h.onTurnDone+ c.guardianRateLimitCircuit = h.guardianRateLimitCircuit+ c.onGuardianRateLimit = h.onGuardianRateLimit+ c.rateLimits = h.rateLimits++ c.agentMessageStreams = nil+ c.agentMessageOrder = nil+ c.turnCompleted = false+ c.setActiveTurnID("")++ c.turnErrorMu.Lock()+ c.turnError = ""+ c.turnErrorMu.Unlock()++ c.usageMu.Lock()+ c.usage = TokenUsage{}+ if !h.preserveUsageBaseline {+ c.usageTotal = codexRawTokenUsage{}+ c.usageTotalSet = false+ }+ c.usageMu.Unlock()+}++func (c *codexClient) detachTurnHooks() {+ c.hookMu.Lock()+ defer c.hookMu.Unlock()++ c.flushAgentMessageDeltas()+ c.acceptNotification = func(string, map[string]any) bool { return false }+ c.onDiscardedNotification = nil+ c.onMessage = nil+ c.onAgentMessageChunk = nil+ c.onAgentMessage = nil+ c.onFinalAnswer = nil+ c.onSemanticActivity = nil+ c.onTurnDone = nil+ c.onGuardianRateLimit = nil+ c.rateLimits = nil+ c.agentMessageStreams = nil+ c.agentMessageOrder = nil+ c.setActiveTurnID("")+}++func (c *codexClient) flushAgentMessageDeltasLocked() {+ c.hookMu.Lock()+ c.flushAgentMessageDeltas()+ c.hookMu.Unlock()+}++type warmCodexProcess struct {+ fingerprint string+ threadID string+ cmd *exec.Cmd+ stdin *codexSyncWriter+ stderrBuf *stderrTail+ client *codexClient+ stopProcess context.CancelFunc+ readerDone chan struct{}+ sessionDir string+ taskEnvFile string+ sessionTempDir string+ launchStarted time.Time+ logger *slog.Logger++ closed atomic.Bool+ closeOnce sync.Once+ cleanupConfirmed bool+}++func (p *warmCodexProcess) Fingerprint() string { return p.fingerprint }++func (p *warmCodexProcess) Alive() bool {+ if p.closed.Load() {+ return false+ }+ if p.client.getProcessErr() != nil {+ return false+ }+ select {+ case <-p.readerDone:+ return false+ default:+ return true+ }+}++func (p *warmCodexProcess) Close() bool {+ p.closeOnce.Do(func() {+ p.closed.Store(true)+ _ = ClearTaskEnvFile(p.taskEnvFile)+ _ = p.stdin.Close()++ grace := codexGracefulShutdown()+ waitCh := make(chan struct{})+ var waitErr error+ var startWait sync.Once+ startProcessWait := func() {+ startWait.Do(func() {+ go func() {+ waitErr = p.cmd.Wait()+ close(waitCh)+ }()+ })+ }++ select {+ case <-p.readerDone:+ case <-time.After(grace):+ if p.logger != nil {+ p.logger.Warn("warm codex did not close stdout after stdin EOF; forcing shutdown",+ "pid", p.cmd.Process.Pid,+ "grace", grace.String(),+ )+ }+ p.stopProcess()+ startProcessWait()+ <-waitCh+ select {+ case <-p.readerDone:+ case <-time.After(grace):+ }+ }++ startProcessWait()+ var waitReturned bool+ select {+ case <-waitCh:+ waitReturned = true+ case <-time.After(grace):+ if p.logger != nil {+ p.logger.Warn("warm codex still alive after reader exited; forcing shutdown",+ "pid", p.cmd.Process.Pid,+ "grace", grace.String(),+ )+ }+ p.stopProcess()+ <-waitCh+ waitReturned = true+ }++ p.cleanupConfirmed = waitReturned && p.cmd.ProcessState != nil && waitProcessGroupGone(p.cmd, grace)+ if codexCleanupConfirmationOverride.Load() < 0 {+ p.cleanupConfirmed = false+ }+ if p.logger != nil {+ p.logger.Info("codex lifecycle",+ "phase", "cleanup",+ "warm_pool", true,+ "pid", p.cmd.Process.Pid,+ "process_group", p.cmd.Process.Pid,+ "latency", time.Since(p.launchStarted).Round(time.Millisecond).String(),+ "reaped", p.cleanupConfirmed,+ "exit_status", codexProcessExitStatus(p.cmd.ProcessState),+ "wait_error", waitErr,+ "stderr_bytes", p.stderrBuf.TotalBytes(),+ "stderr_truncated", p.stderrBuf.TotalBytes() > codexStderrTailBytes,+ )+ }+ releaseProcessGroup(p.cmd)+ p.stopProcess()+ activeCodexLaunches.Add(-1)+ if p.sessionDir != "" {+ _ = os.RemoveAll(p.sessionDir)+ }+ })+ return p.cleanupConfirmed+}++func (b *codexBackend) executeWarmOnce(ctx context.Context, prompt string, opts ExecOptions, attempt int) (*Session, error) {+ execPath := b.cfg.ExecutablePath+ if execPath == "" {+ execPath = "codex"+ }+ if _, err := exec.LookPath(execPath); err != nil {+ return nil, fmt.Errorf("codex executable not found at %q: %w", execPath, err)+ }++ timeout := opts.Timeout+ semanticInactivityTimeout := opts.SemanticInactivityTimeout+ if semanticInactivityTimeout == 0 {+ semanticInactivityTimeout = defaultCodexSemanticInactivityTimeout+ }+ handshakeTimeout, threadHandshakeTimeout := resolveCodexHandshakeTimeouts(opts)+ runCtx, cancel := runContext(ctx, timeout)++ codexHome := strings.TrimSpace(b.cfg.Env["CODEX_HOME"])+ if codexHome != "" {+ if err := ensureCodexMcpConfig(filepath.Join(codexHome, "config.toml"), opts.McpConfig, b.cfg.Logger); err != nil {+ cancel()+ return nil, fmt.Errorf("apply codex mcp_config: %w", err)+ }+ } else if hasManagedCodexMcpConfig(opts.McpConfig) {+ cancel()+ return nil, fmt.Errorf("codex: mcp_config is set but CODEX_HOME env var is not configured; cannot apply managed MCP")+ }++ runtimeCmd := b.cfg.commandAt(execPath)+ if codexHome != "" {+ opts.ExtraArgs = filterCodexShellEnvConfigOverrides(opts.ExtraArgs, b.cfg.Logger)+ opts.CustomArgs = filterCodexShellEnvConfigOverrides(opts.CustomArgs, b.cfg.Logger)+ runtimeCmd = runtimeCmd.withFilteredPrefix(func(prefix []string) []string {+ return filterCodexShellEnvConfigOverrides(prefix, b.cfg.Logger)+ })+ }+ if hasManagedCodexMcpConfig(opts.McpConfig) {+ runtimeCmd = runtimeCmd.withFilteredPrefix(func(prefix []string) []string {+ return filterCodexCustomConfigOverrides(prefix, b.cfg.Logger)+ })+ }+ if opts.ServiceTier == codexFastServiceTier {+ runtimeCmd = runtimeCmd.withFilteredPrefix(func(prefix []string) []string {+ return stripCodexFastModeConflicts(prefix, b.cfg.Logger)+ })+ }+ codexArgs := buildCodexArgs(opts, b.cfg.Logger)++ var configFiles []string+ if codexHome != "" {+ configFiles = append(configFiles, filepath.Join(codexHome, "config.toml"))+ }+ fingerprint := computeWarmSessionFingerprint(WarmSessionFingerprintInput{+ Provider: "codex",+ Executable: execPath,+ LaunchPrefix: runtimeCmd.Prefix,+ Args: codexArgs,+ Cwd: opts.Cwd,+ Model: opts.Model,+ ThinkingLevel: opts.ThinkingLevel,+ ServiceTier: opts.ServiceTier,+ McpConfig: opts.McpConfig,+ ConfigFiles: configFiles,+ BriefHash: opts.WarmPoolBriefHash,+ Env: b.cfg.Env,+ })++ var warmProc *warmCodexProcess+ warmHit := false+ if opts.ResumeSessionID != "" {+ if acquired := b.cfg.WarmPool.Acquire("codex", opts.ResumeSessionID, fingerprint); acquired != nil {+ if candidate, ok := acquired.(*warmCodexProcess); ok {+ if err := WriteTaskEnvFile(candidate.taskEnvFile, b.cfg.Env); err != nil {+ b.cfg.Logger.Warn("warm codex: failed to refresh task env overlay; evicting", "error", err)+ candidate.Close()+ } else {+ warmProc = candidate+ warmHit = true+ }+ } else {+ acquired.Close()+ }+ }+ }++ var activeLaunches int64+ if !warmHit {+ var err error+ warmProc, activeLaunches, err = b.spawnWarmCodexProcess(runtimeCmd, codexArgs, opts, fingerprint, handshakeTimeout, threadHandshakeTimeout, attempt)+ if err != nil {+ cancel()+ return nil, err+ }+ } else {+ activeLaunches = activeCodexLaunches.Load()+ warmProc.client.handshakeTimeout = handshakeTimeout+ warmProc.client.threadHandshakeTimeout = threadHandshakeTimeout+ warmProc.client.attempt = attempt+ warmProc.client.activeLaunches = activeLaunches+ }++ codexVersion := strings.TrimSpace(b.cfg.CodexVersion)+ if codexVersion == "" {+ codexVersion = "unknown"+ }++ msgCh := make(chan Message, 256)+ resCh := make(chan Result, 1)+ semanticActivityCh := make(chan string, 256)+ guardianRateLimitTrip := make(chan struct{}, 1)+ var guardianRateLimitTripped atomic.Bool++ var outputMu sync.Mutex+ var output codexOutputSelection+ var semanticObserved atomic.Bool+ turnNotificationGate := &codexTurnNotificationGate{}+ firstItemWait := &codexFirstItemWaitObservation{}+ turnDone := make(chan bool, 1)++ c := warmProc.client+ observeMessage := func(msg Message) {+ logCodexAgentMessage(b.cfg.Logger, msg)+ activity := describeCodexSemanticActivity(msg)+ if activity == "status:running" {+ firstItemWait.start(time.Now(), c.activeTurnID())+ }+ trySendString(semanticActivityCh, activity)+ if activity != "" {+ semanticObserved.Store(true)+ }+ }++ c.attachTurnHooks(codexTurnHooks{+ cfg: b.cfg,+ acceptNotification: turnNotificationGate.accept,+ guardianRateLimitCircuit: &codexGuardianRateLimitCircuit{},+ rateLimits: newRateLimitTracker(opts.OnRateLimits),+ preserveUsageBaseline: warmHit,+ onGuardianRateLimit: func() {+ guardianRateLimitTripped.Store(true)+ b.cfg.Logger.Warn("codex Guardian approval rate-limit circuit opened",+ "task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID,+ "failure_count", codexGuardianRateLimitThreshold)+ select {+ case guardianRateLimitTrip <- struct{}{}:+ default:+ }+ },+ onDiscardedNotification: func(string, map[string]any) {+ semanticObserved.Store(true)+ },+ onMessage: func(msg Message) {+ observeMessage(msg)+ trySend(msgCh, msg)+ },+ onAgentMessageChunk: func(text string) bool {+ msg := Message{Type: MessageText, Content: text}+ observeMessage(msg)+ return trySend(msgCh, msg)+ },+ onAgentMessage: func(text, phase string) {+ outputMu.Lock()+ output.observeAgentMessage(text, phase)+ outputMu.Unlock()+ },+ onFinalAnswer: func(text string) {+ outputMu.Lock()+ output.observeFinalAnswer(text)+ outputMu.Unlock()+ },+ onSemanticActivity: func(description string) {+ semanticObserved.Store(true)+ b.cfg.Logger.Debug("codex semantic activity observed", "activity", description)+ trySendString(semanticActivityCh, description)+ },+ onTurnDone: func(aborted bool) {+ select {+ case turnDone <- aborted:+ default:+ }+ },+ })++ go func() {+ defer cancel()+ defer close(msgCh)+ defer close(resCh)++ startTime := time.Now()+ finalStatus := "completed"+ var finalError string+ var threadID string+ var resumed bool++ closeWarmProc := func() bool {+ c.detachTurnHooks()+ return warmProc.Close()+ }++ if warmHit {+ threadID = warmProc.threadID+ resumed = true+ c.setThreadID(threadID)+ b.cfg.Logger.Info("codex warm session reused",+ "task_id", b.cfg.TaskID,+ "runtime_id", b.cfg.RuntimeID,+ "pid", warmProc.cmd.Process.Pid,+ "thread_id", threadID,+ )+ trySend(msgCh, Message{Type: MessageStatus, Status: "running", SessionID: threadID})+ } else {+ // 1. Initialize handshake+ initializeStarted := time.Now()+ b.cfg.Logger.Info("codex lifecycle", "phase", "initialize_sent", "warm_pool", true, "task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID, "pid", warmProc.cmd.Process.Pid, "attempt", attempt, "active_launches", activeLaunches)+ _, err := c.request(runCtx, "initialize", map[string]any{+ "clientInfo": map[string]any{+ "name": "multica-agent-sdk",+ "title": "Multica Agent SDK",+ "version": "0.2.0",+ },+ "capabilities": map[string]any{+ "experimentalApi": true,+ },+ })+ if err != nil {+ initializeLatency := time.Since(initializeStarted)+ var handshakeErr *codexHandshakeTimeoutError+ timedOut := errors.As(err, &handshakeErr) && handshakeErr.Method == "initialize"+ if timedOut {+ signalProcessGroup(warmProc.cmd, syscall.SIGKILL)+ } else if runCtx.Err() != nil {+ warmProc.stopProcess()+ }+ cleanupConfirmed := closeWarmProc()+ finalStatus = "failed"+ finalError = fmt.Sprintf("codex initialize failed: %v", err)+ contextEnded := errors.Is(err, context.DeadlineExceeded) || errors.Is(err, context.Canceled)+ if !timedOut && !contextEnded {+ finalError = withAgentStderr(finalError, "codex", sanitizeCodexDiagnostic(warmProc.stderrBuf.Tail()))+ }+ retrySafe := timedOut && !semanticObserved.Load() && cleanupConfirmed && codexInitializeRetrySupported()+ if timedOut && !cleanupConfirmed {+ finalError += "; retry suppressed: process cleanup/reap not confirmed"+ } else if timedOut && cleanupConfirmed && !codexInitializeRetrySupported() {+ finalError += "; retry suppressed: process-tree cleanup cannot be confirmed on this platform"+ }+ b.cfg.Logger.Warn("codex lifecycle", "phase", "initialize_failure", "warm_pool", true, "task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID, "pid", warmProc.cmd.Process.Pid, "attempt", attempt, "latency", initializeLatency.Round(time.Millisecond).String(), "semantic_activity", semanticObserved.Load(), "cleanup_confirmed", cleanupConfirmed, "retry_safe", retrySafe)+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds(), codexInitializeRetrySafe: retrySafe}+ return+ }+ b.cfg.Logger.Info("codex lifecycle", "phase", "initialize_response", "warm_pool", true, "task_id", b.cfg.TaskID, "runtime_id", b.cfg.RuntimeID, "pid", warmProc.cmd.Process.Pid, "attempt", attempt, "latency", time.Since(initializeStarted).Round(time.Millisecond).String())+ c.notify("initialized")++ // 2. Start or resume thread+ threadID, resumed, err = c.startOrResumeThread(runCtx, opts, b.cfg.Logger)+ if err != nil {+ var handshakeErr *codexHandshakeTimeoutError+ timedOut := errors.As(err, &handshakeErr) && isCodexThreadSetupRPC(handshakeErr.Method)+ if timedOut {+ signalProcessGroup(warmProc.cmd, syscall.SIGKILL)+ } else if runCtx.Err() != nil {+ warmProc.stopProcess()+ }+ cleanupConfirmed := closeWarmProc()+ finalStatus = "failed"+ stderrTail := sanitizeCodexDiagnostic(warmProc.stderrBuf.Tail())+ finalError = err.Error()+ retrySafe := timedOut && cleanupConfirmed+ if retrySafe {+ finalStatus = "timeout"+ } else if timedOut {+ finalError += "; retry suppressed: process cleanup/reap not confirmed"+ }+ if c.threadSetupMethod != "" {+ classification := classifyCodexStartupStderr(stderrTail, timedOut)+ b.cfg.Logger.Warn("codex lifecycle",+ "phase", strings.ReplaceAll(c.threadSetupMethod, "/", "_")+"_failure",+ "warm_pool", true,+ "task_id", b.cfg.TaskID,+ "runtime_id", b.cfg.RuntimeID,+ "pid", warmProc.cmd.Process.Pid,+ "attempt", attempt,+ "active_launches", activeLaunches,+ "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", retrySafe,+ "retry_attempted", false,+ "stderr_model_refresh_failure_count", classification.modelRefreshFailure,+ "stderr_model_refresh_timeout_count", classification.modelRefreshTimeout,+ "stderr_mcp_init_transport_count", classification.mcpInitTransport,+ "stderr_bare_timeout_count", classification.bareTimeout,+ )+ }+ resCh <- Result{+ Status: finalStatus,+ Error: finalError,+ DurationMs: time.Since(startTime).Milliseconds(),+ ResumeRejected: isCodexResumeOverflow(opts, err),+ }+ return+ }+ c.setThreadID(threadID)+ if resumed {+ b.cfg.Logger.Info("codex thread resumed", "thread_id", threadID)+ } else {+ b.cfg.Logger.Info("codex thread started", "thread_id", threadID)+ }+ }++ // 3. Send turn and wait for completion+ turnPrompt := b.skillTurnPrompt(runCtx, c, prompt, opts)+ turnParams := map[string]any{+ "threadId": threadID,+ "input": codexTurnInput(turnPrompt, opts.ResumeExpected, resumed, opts.ResumeContinuityNotice),+ }+ applyCodexReasoningEffort(turnParams, opts.ThinkingLevel)+ applyCodexServiceTier(turnParams, opts.ServiceTier)+ waitingForTurn := true+ var timeoutDiagnostic codexTimeoutDiagnostic+ var processExitErr error+ finishFirstItemWait := func(outcome string) {+ firstItemWait.finish(+ time.Now(),+ outcome,+ classifyCodexStartupStderr(warmProc.stderrBuf.Tail(), strings.HasSuffix(outcome, "_timeout")),+ )+ }+ finishTurn := func(aborted bool) {+ waitingForTurn = false+ switch {+ case aborted:+ finishFirstItemWait("turn_aborted")+ finalStatus = "aborted"+ if errMsg := c.getTurnError(); errMsg != "" {+ finalError = errMsg+ } else {+ finalError = "turn was aborted"+ }+ default:+ if errMsg := c.getTurnError(); errMsg != "" {+ finishFirstItemWait("turn_failed")+ finalStatus = "failed"+ finalError = errMsg+ } else {+ finishFirstItemWait("turn_completed")+ }+ }+ }+ finishRunContextDone := func() {+ waitingForTurn = false+ if runCtx.Err() == context.DeadlineExceeded {+ finishFirstItemWait("execution_timeout")+ finalStatus = "timeout"+ finalError = fmt.Sprintf("codex timed out after %s", timeout)+ } else {+ finishFirstItemWait("cancelled")+ finalStatus = "aborted"+ finalError = "execution cancelled"+ }+ }+ turnNotificationGate.arm()+ _, err := c.request(runCtx, "turn/start", turnParams)+ if err != nil {+ if runCtx.Err() != nil {+ finishRunContextDone()+ if !interruptCodexTurn(c, threadID, turnDone, opts.TurnInterruptTimeout, b.cfg.Logger) {+ warmProc.stopProcess()+ }+ } else {+ select {+ case aborted := <-turnDone:+ finishTurn(aborted)+ default:+ closeWarmProc()+ finalStatus = "failed"+ finalError = withAgentStderr(fmt.Sprintf("codex turn/start failed: %v", err), "codex", sanitizeCodexDiagnostic(warmProc.stderrBuf.Tail()))+ resCh <- Result{Status: finalStatus, Error: finalError, DurationMs: time.Since(startTime).Milliseconds()}+ return+ }+ }+ }++ lastSemanticActivity := time.Now()+ lastSemanticActivityDescription := "turn/start"+ semanticTimer := time.NewTimer(semanticInactivityTimeout)+ defer semanticTimer.Stop()++ firstTurnNoProgressTimeout := codexFirstTurnNoProgressTimeout(semanticInactivityTimeout, opts.FirstTurnNoProgressTimeout)+ var firstTurnNoProgressTimer *time.Timer+ var firstTurnNoProgressTimerC <-chan time.Time+ firstTurnStarted := false+ firstTurnProgressObserved := false+ stopFirstTurnNoProgressTimer := func() {+ if firstTurnNoProgressTimer == nil {+ return+ }+ stopTimer(firstTurnNoProgressTimer)+ firstTurnNoProgressTimerC = nil+ }+ defer stopFirstTurnNoProgressTimer()++ for waitingForTurn {+ select {+ case aborted := <-turnDone:+ finishTurn(aborted)+ case <-guardianRateLimitTrip:+ waitingForTurn = false+ finishFirstItemWait("guardian_rate_limit")+ finalStatus = "failed"+ finalError = codexGuardianRateLimitError+ if !interruptCodexTurn(c, threadID, turnDone, opts.TurnInterruptTimeout, b.cfg.Logger) {+ warmProc.stopProcess()+ }+ case activity := <-semanticActivityCh:+ lastSemanticActivity = time.Now()+ lastSemanticActivityDescription = activity+ resetTimer(semanticTimer, semanticInactivityTimeout)+ if activity == "status:running" && !firstTurnStarted {+ firstTurnStarted = true+ firstItemWait.start(time.Now(), c.activeTurnID())+ firstTurnNoProgressTimer = time.NewTimer(firstTurnNoProgressTimeout)+ firstTurnNoProgressTimerC = firstTurnNoProgressTimer.C+ } else if firstTurnStarted && !firstTurnProgressObserved && isCodexFirstTurnProgressActivity(activity) {+ firstTurnProgressObserved = true+ if activity == "error:terminal" {+ finishFirstItemWait("turn_failed")+ } else {+ finishFirstItemWait("progress")+ }+ stopFirstTurnNoProgressTimer()+ }+ case <-firstTurnNoProgressTimerC:+ waitingForTurn = false+ finishFirstItemWait("no_progress_timeout")+ finalStatus = "timeout"+ turnID := c.activeTurnID()+ timeoutDiagnostic = codexTimeoutDiagnostic{+ Kind: codexTimeoutFirstTurnNoProgress,+ Timeout: firstTurnNoProgressTimeout,+ LastActivity: lastSemanticActivityDescription,+ ThreadID: threadID,+ TurnID: turnID,+ Model: opts.Model,+ }+ b.cfg.Logger.Warn(CodexFirstTurnNoProgressMarker,+ "pid", warmProc.cmd.Process.Pid,+ "thread_id", threadID,+ "turn_id", turnID,+ "timeout", firstTurnNoProgressTimeout.String(),+ "last_activity", lastSemanticActivityDescription,+ )+ case <-semanticTimer.C:+ waitingForTurn = false+ finishFirstItemWait("semantic_inactivity_timeout")+ finalStatus = "timeout"+ turnID := c.activeTurnID()+ timeoutDiagnostic = codexTimeoutDiagnostic{+ Kind: codexTimeoutSemanticInactivity,+ Timeout: semanticInactivityTimeout,+ LastActivity: lastSemanticActivityDescription,+ ThreadID: threadID,+ TurnID: turnID,+ Model: opts.Model,+ }+ b.cfg.Logger.Warn(CodexSemanticInactivityMarker,+ "pid", warmProc.cmd.Process.Pid,+ "thread_id", threadID,+ "turn_id", turnID,+ "timeout", semanticInactivityTimeout.String(),+ "last_activity", lastSemanticActivityDescription,+ "idle_for", time.Since(lastSemanticActivity).Round(time.Millisecond).String(),+ )+ case <-runCtx.Done():+ finishRunContextDone()+ if !interruptCodexTurn(c, threadID, turnDone, opts.TurnInterruptTimeout, b.cfg.Logger) {+ warmProc.stopProcess()+ }+ case <-c.processDone:+ select {+ case aborted := <-turnDone:+ finishTurn(aborted)+ default:+ if runCtx.Err() != nil {+ finishRunContextDone()+ } else {+ waitingForTurn = false+ finishFirstItemWait("process_exit")+ finalStatus = "failed"+ processExitErr = c.getProcessErr()+ if processExitErr == nil {+ processExitErr = errCodexProcessExited+ }+ finalError = processExitErr.Error()+ }+ }+ }+ }+ if guardianRateLimitTripped.Load() {+ finalStatus = "failed"+ finalError = codexGuardianRateLimitError+ }++ duration := time.Since(startTime)+ b.cfg.Logger.Info("codex finished", "pid", warmProc.cmd.Process.Pid, "warm_hit", warmHit, "status", finalStatus, "duration", duration.Round(time.Millisecond).String())++ // Flush any buffered agent message deltas and capture outputs/usage+ // before detaching hooks and parking or closing the process.+ c.detachTurnHooks()+ _ = ClearTaskEnvFile(warmProc.taskEnvFile)++ outputMu.Lock()+ finalOutput := codexDeliverableOutput(output)+ outputMu.Unlock()++ c.usageMu.Lock()+ u := c.usage+ c.usageMu.Unlock()++ canPark := finalStatus == "completed" &&+ finalError == "" &&+ !guardianRateLimitTripped.Load() &&+ processExitErr == nil &&+ threadID != "" &&+ warmProc.Alive() &&+ runCtx.Err() == nil++ var cleanupConfirmed bool+ if canPark {+ warmProc.threadID = threadID+ b.cfg.WarmPool.Park("codex", threadID, warmProc)+ } else {+ cleanupConfirmed = warmProc.Close()+ }++ if processExitErr != nil {+ finalError = withAgentStderr(processExitErr.Error(), "codex", sanitizeCodexDiagnostic(warmProc.stderrBuf.Tail()))+ }+ stderrTail := sanitizeCodexDiagnostic(warmProc.stderrBuf.Tail())+ if timeoutDiagnostic.Kind != codexTimeoutNone {+ timeoutDiagnostic.CodexVersion = detectCodexVersionForDiagnostics(context.Background(), b.cfg.commandAt(execPath), warmProc.cmd.Env, b.cfg.Logger)+ finalError = buildCodexTimeoutDiagnosticError(timeoutDiagnostic, stderrTail)+ }++ startupRefreshRetrySafe := !canPark &&+ timeoutDiagnostic.Kind == codexTimeoutFirstTurnNoProgress &&+ !firstTurnProgressObserved &&+ strings.Contains(stderrTail, codexModelCatalogRefreshFailureSignal) &&+ cleanupConfirmed && codexInitializeRetrySupported()++ if waitLatency, firstTurnID, outcome, classification, ok := firstItemWait.snapshot(); ok {+ if waitLatency < 0 {+ waitLatency = 0+ }+ if strings.HasSuffix(outcome, "_timeout") {+ classification = classifyCodexStartupStderr(stderrTail, true)+ }+ fields := []any{+ "phase", "first_item_wait",+ "warm_pool", true,+ "warm_hit", warmHit,+ "task_id", b.cfg.TaskID,+ "runtime_id", b.cfg.RuntimeID,+ "pid", warmProc.cmd.Process.Pid,+ "attempt", attempt,+ "active_launches", activeLaunches,+ "method", "turn/start",+ "thread_id", threadID,+ "turn_id", firstTurnID,+ "outcome", outcome,+ "latency", waitLatency.Round(time.Millisecond).String(),+ "latency_ms", waitLatency.Milliseconds(),+ "timeout", firstTurnNoProgressTimeout.String(),+ "semantic_inactivity_timeout", semanticInactivityTimeout.String(),+ "codex_version", codexVersion,+ "daemon_version", b.cfg.DaemonVersion,+ "cleanup_confirmed", cleanupConfirmed,+ "reaped", cleanupConfirmed,+ "retry_safe", startupRefreshRetrySafe,+ "stderr_model_refresh_failure_count", classification.modelRefreshFailure,+ "stderr_model_refresh_timeout_count", classification.modelRefreshTimeout,+ "stderr_mcp_init_transport_count", classification.mcpInitTransport,+ "stderr_bare_timeout_count", classification.bareTimeout,+ }+ switch outcome {+ case "progress", "turn_completed":+ b.cfg.Logger.Info("codex lifecycle", fields...)+ default:+ b.cfg.Logger.Warn("codex lifecycle", fields...)+ }+ }++ taskCodexHome := strings.TrimSpace(b.cfg.Env["CODEX_HOME"])+ usageMap := codexResultUsageMap(startTime, taskCodexHome, threadID, resumed, opts.Model, u)++ resCh <- Result{+ Status: finalStatus,+ Output: finalOutput,+ Error: finalError,+ SessionID: threadID,+ DurationMs: duration.Milliseconds(),+ Usage: usageMap,+ codexStartupRefreshRetrySafe: startupRefreshRetrySafe,+ }+ }()++ supplement := func(supplementCtx context.Context, instruction string) error {+ return supplementCodexTurn(supplementCtx, c, instruction)+ }+ supplementReady := func() bool {+ return c.getThreadID() != "" && c.activeTurnID() != ""+ }+ return &Session{Supplement: supplement, SupplementReady: supplementReady, Messages: msgCh, Result: resCh}, nil+}++func (b *codexBackend) spawnWarmCodexProcess(+ runtimeCmd Command,+ codexArgs []string,+ opts ExecOptions,+ fingerprint string,+ handshakeTimeout time.Duration,+ threadHandshakeTimeout time.Duration,+ attempt int,+) (*warmCodexProcess, int64, error) {+ sessionDir, err := os.MkdirTemp("", "multica-codex-warm-*")+ if err != nil {+ return nil, 0, fmt.Errorf("create warm codex session dir: %w", err)+ }+ sessionTempDir := filepath.Join(sessionDir, "tmp")+ if err := os.MkdirAll(sessionTempDir, 0o700); err != nil {+ _ = os.RemoveAll(sessionDir)+ return nil, 0, fmt.Errorf("create warm codex temp dir: %w", err)+ }+ taskEnvFile := filepath.Join(sessionDir, "task-env.json")+ if err := WriteTaskEnvFile(taskEnvFile, b.cfg.Env); err != nil {+ _ = os.RemoveAll(sessionDir)+ return nil, 0, fmt.Errorf("write warm codex task env overlay: %w", err)+ }++ processCtx, stopProcess := context.WithCancel(context.Background())+ cmd := runtimeCmd.exec(processCtx, codexArgs...)+ hideAgentWindow(cmd)+ cmd.Cancel = func() error {+ if cmd.Process != nil {+ signalProcessGroup(cmd, syscall.SIGKILL)+ }+ return nil+ }+ cmd.WaitDelay = codexProcessWaitDelay()+ b.cfg.logAgentCommand(cmd, newAgentCommandLogArgs(codexArgs, trustAgentCommandPositional(0, "app-server")))+ if opts.Cwd != "" {+ cmd.Dir = opts.Cwd+ }+ cmd.Env = buildEnv(PreparePooledChildEnv(b.cfg.Env, taskEnvFile, sessionTempDir))++ stdout, err := cmd.StdoutPipe()+ if err != nil {+ stopProcess()+ _ = os.RemoveAll(sessionDir)+ return nil, 0, fmt.Errorf("codex stdout pipe: %w", err)+ }+ stdinPipe, err := cmd.StdinPipe()+ if err != nil {+ stopProcess()+ _ = os.RemoveAll(sessionDir)+ return nil, 0, fmt.Errorf("codex stdin pipe: %w", err)+ }+ stdin := &codexSyncWriter{w: stdinPipe}+ stderrBuf := newStderrTail(io.Discard, codexStderrTailBytes)+ cmd.Stderr = stderrBuf++ if err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {+ stopProcess()+ _ = os.RemoveAll(sessionDir)+ return nil, 0, fmt.Errorf("start codex: %w", err)+ }+ activeLaunches := activeCodexLaunches.Add(1)+ for {+ maxSeen := maxActiveCodexLaunchesObserved.Load()+ if activeLaunches <= maxSeen || maxActiveCodexLaunchesObserved.CompareAndSwap(maxSeen, activeLaunches) {+ break+ }+ }+ launchStarted := time.Now()+ codexVersion := strings.TrimSpace(b.cfg.CodexVersion)+ if codexVersion == "" {+ codexVersion = "unknown"+ }+ b.cfg.Logger.Info("codex lifecycle",+ "phase", "spawn",+ "warm_pool", true,+ "task_id", b.cfg.TaskID,+ "runtime_id", b.cfg.RuntimeID,+ "pid", cmd.Process.Pid,+ "process_group", cmd.Process.Pid,+ "cwd", opts.Cwd,+ "attempt", attempt,+ "active_launches", activeLaunches,+ "codex_version", codexVersion,+ "daemon_version", b.cfg.DaemonVersion,+ )++ c := &codexClient{+ 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: func(string, map[string]any) bool { return false },+ }++ readerDone := make(chan struct{})+ go func() {+ defer close(readerDone)+ scanner := newAgentStreamScanner(stdout)+ for scanner.Scan() {+ line := strings.TrimSpace(scanner.Text())+ if line == "" {+ continue+ }+ c.handleLine(line)+ }+ c.flushAgentMessageDeltasLocked()+ if err := scanner.Err(); err != nil {+ c.markProcessExited(fmt.Errorf("%w: %w", errCodexProcessExited, err))+ return+ }+ c.markProcessExited(errCodexProcessExited)+ }()++ return &warmCodexProcess{+ fingerprint: fingerprint,+ cmd: cmd,+ stdin: stdin,+ stderrBuf: stderrBuf,+ client: c,+ stopProcess: stopProcess,+ readerDone: readerDone,+ sessionDir: sessionDir,+ taskEnvFile: taskEnvFile,+ sessionTempDir: sessionTempDir,+ launchStarted: launchStarted,+ logger: b.cfg.Logger,+ }, activeLaunches, nil+}diff --git a/server/pkg/agent/models.go b/server/pkg/agent/models.goindex a9260f7dc5..3049923102 100644--- a/server/pkg/agent/models.go+++ b/server/pkg/agent/models.go@@ -171,20 +171,31 @@ func discovered(models []Model, err error) (Catalog, error) {var errACPEffortDiscoveryIncomplete = errors.New("ACP per-model effort discovery incomplete")-// modelCache memoizes dynamic discovery calls so repeated UI loads-// don't re-shell the agent CLI. Entries expire after cacheTTL.+// modelCache memoizes dynamic discovery calls so repeated UI loads and+// pre-launch task validations don't re-shell the agent CLI.+//+// Fresh entries are served immediately until freshUntil (modelCacheTTL).+// Between freshUntil and staleUntil (modelCacheStaleTTL), cachedDiscovery+// serves the last verified catalog immediately (stale-while-revalidate) and+// kicks off at most one background refresh per cache key so task startup+// latency never stalls on a cold discovery subprocess.type modelCacheEntry struct {models []Modelunavailable []UnavailableModel- expiresAt time.Time+ freshUntil time.Time+ staleUntil time.Time}var (- modelCacheMu sync.Mutex- modelCache = map[string]modelCacheEntry{}+ modelCacheMu sync.Mutex+ modelCache = map[string]modelCacheEntry{}+ modelCacheInflight = map[string]bool{}+ modelCacheTTL = 15 * time.Minute+ modelCacheStaleTTL = 30 * time.Minute+ modelCacheNow = time.Now)-const modelCacheTTL = 60 * time.Second+const modelCacheRefreshTimeout = 30 * time.Second// ListModels returns the models supported by the given agent provider.// For providers with a known static catalog it returns the baked-in@@ -213,93 +224,93 @@ func ListModels(ctx context.Context, providerType string, runtimeCmd Command) (C// degrading to manual entry.if desc, ok := BuiltinRuntimeByID(providerType); ok {if desc.ModelDiscovery != nil {- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discovered(desc.ModelDiscovery(ctx, runtimeCmd))+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discovered(desc.ModelDiscovery(callCtx, runtimeCmd))})}return Catalog{Models: []Model{}}, nil}switch providerType {case "claude":- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discoverClaudeCatalog(ctx, runtimeCmd), nil+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discoverClaudeCatalog(callCtx, runtimeCmd), nil})case "codex":- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discoverCodexCatalog(ctx, runtimeCmd), nil+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discoverCodexCatalog(callCtx, runtimeCmd), nil})case "antigravity":// agy 1.0.6 added a `--model` flag plus an `agy models` catalog// command (MUL-3125). Enumerate it on demand like the other// dynamic-discovery backends.- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discovered(discoverAntigravityModels(ctx, runtimeCmd))+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discovered(discoverAntigravityModels(callCtx, runtimeCmd))})case "traecli":// Official TRAE CLI is ACP-native: it returns its model catalog from// session/new. Enumerate it on demand like the other ACP backends// (requires a logged-in traecli; falls back to manual entry on error).- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discovered(discoverTraecliModels(ctx, runtimeCmd))+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discovered(discoverTraecliModels(callCtx, runtimeCmd))})case "cursor":- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discoverCursorModels(ctx, runtimeCmd)+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discoverCursorModels(callCtx, runtimeCmd)})case "copilot":- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discoverCopilotModels(ctx, runtimeCmd)+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discoverCopilotModels(callCtx, runtimeCmd)})case "hermes":- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discovered(discoverHermesModels(ctx, runtimeCmd))+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discovered(discoverHermesModels(callCtx, runtimeCmd))})case "kimi":- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discovered(discoverKimiModels(ctx, runtimeCmd))+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discovered(discoverKimiModels(callCtx, runtimeCmd))})case "reasonix":- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discovered(discoverReasonixModels(ctx, runtimeCmd))+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discovered(discoverReasonixModels(callCtx, runtimeCmd))})case "dsh":- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discovered(discoverDshModels(ctx, runtimeCmd))+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discovered(discoverDshModels(callCtx, runtimeCmd))})case "kiro":- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discovered(discoverKiroModels(ctx, runtimeCmd))+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discovered(discoverKiroModels(callCtx, runtimeCmd))})case "qoder", "qoderclicn":- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discovered(discoverQoderModels(ctx, runtimeCmd, qoderDefaultBinary(providerType)))+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discovered(discoverQoderModels(callCtx, runtimeCmd, qoderDefaultBinary(providerType)))})case "opencode":- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discoverOpenCodeModels(ctx, runtimeCmd)+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discoverOpenCodeModels(callCtx, runtimeCmd)})case "codearts":- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discovered(discoverCodeArtsModels(ctx, runtimeCmd))+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discovered(discoverCodeArtsModels(callCtx, runtimeCmd))})case "deveco":- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discovered(discoverDevecoModels(ctx, runtimeCmd))+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discovered(discoverDevecoModels(callCtx, runtimeCmd))})case "pi":- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discovered(discoverPiModels(ctx, runtimeCmd))+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discovered(discoverPiModels(callCtx, runtimeCmd))})case "openclaw":- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discovered(discoverOpenclawAgents(ctx, runtimeCmd))+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discovered(discoverOpenclawAgents(callCtx, runtimeCmd))})case "codebuddy":// discoverCodebuddyModels owns the thinking annotation too, so the one// `--help` capture feeds both catalogs. Annotating out here would run// the command a second time (MUL-5549).- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discoverCodebuddyModels(ctx, runtimeCmd)+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discoverCodebuddyModels(callCtx, runtimeCmd)})case "amp":// Amp selects its own models; manual IDs select native modes.@@ -318,8 +329,8 @@ func ListModels(ctx context.Context, providerType string, runtimeCmd Command) (C// here modelled on discoverTraecliModels.return Catalog{Models: []Model{}}, nilcase "devin":- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discovered(discoverDevinModels(ctx, runtimeCmd))+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discovered(discoverDevinModels(callCtx, runtimeCmd))})case "mcode":// MCode's ACP server does not expose session-scoped model selection or@@ -329,23 +340,23 @@ func ListModels(ctx context.Context, providerType string, runtimeCmd Command) (C// Meta Muse Code advertises its catalog over MSP model/list, a// session-free query, and applies the pick through session/start// modelId (or session/setModel on a resumed session).- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discoverMuseModels(ctx, runtimeCmd)+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discoverMuseModels(callCtx, runtimeCmd)})case "grok":// xAI Grok Build is ACP-native (`grok agent stdio`); model catalog// comes from session/new. Falls back to a small static list so the// UI picker stays usable offline / unauthenticated.- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discoverGrokModels(ctx, runtimeCmd)+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discoverGrokModels(callCtx, runtimeCmd)})case "dim":// Dim (dimcode) is ACP-native (`dim acp`); its model catalog is// advertised by session/new under models.availableModels. Enumeration// requires a logged-in dim (OAuth); on any failure fall back to an// empty catalog so the UI keeps manual entry available.- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discoverDimModels(ctx, runtimeCmd)+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discoverDimModels(callCtx, runtimeCmd)})case "zeroclaw":// ZeroClaw's ACP server advertises no catalog: session/new answers@@ -369,8 +380,8 @@ func ListModels(ctx context.Context, providerType string, runtimeCmd Command) (C// discoverTraecliModels); any failure degrades to the empty catalog so// the UI keeps manual entry in the composite `providerId/modelId`// format (see splitZcodeModelSelection).- return cachedDiscovery(discoveryCacheKey(providerType, runtimeCmd), func() (Catalog, error) {- return discoverZcodeModels(ctx, runtimeCmd)+ return cachedDiscoveryWithContext(ctx, discoveryCacheKey(providerType, runtimeCmd), func(callCtx context.Context) (Catalog, error) {+ return discoverZcodeModels(callCtx, runtimeCmd)})default:return Catalog{}, fmt.Errorf("unknown agent type: %q", providerType)@@ -563,20 +574,57 @@ func modelHasKnownPrefix(model string) bool {isOpenAIReasoningSeriesID(model)}-// cachedDiscovery invokes fn and caches the result for modelCacheTTL.-// Callers build the key with discoveryCacheKey so two runtimes of the same-// protocol family never share one memo entry when they enumerate different-// binaries.+// cachedDiscovery preserves the context-free helper signature used by tests+// while sharing the stale-while-revalidate implementation below.func cachedDiscovery(key string, fn func() (Catalog, error)) (Catalog, error) {+ return cachedDiscoveryWithContext(context.Background(), key, func(context.Context) (Catalog, error) {+ return fn()+ })+}++// cachedDiscoveryWithContext invokes fn and caches verified catalogs for+// modelCacheTTL, serving stale entries up to modelCacheStaleTTL while+// refreshing at most once in the background. Callers build the key with+// discoveryCacheKey so two runtimes of the same protocol family never share+// one memo entry when they enumerate different binaries.+func cachedDiscoveryWithContext(ctx context.Context, key string, fn func(context.Context) (Catalog, error)) (Catalog, error) {+ now := modelCacheNow()modelCacheMu.Lock()- if entry, ok := modelCache[key]; ok && time.Now().Before(entry.expiresAt) {- out, unavailable := entry.models, entry.unavailable- modelCacheMu.Unlock()- return Catalog{Models: out, Unavailable: unavailable}, nil+ if entry, ok := modelCache[key]; ok {+ if now.Before(entry.freshUntil) {+ out, unavailable := entry.models, entry.unavailable+ modelCacheMu.Unlock()+ return Catalog{Models: out, Unavailable: unavailable}, nil+ }+ if now.Before(entry.staleUntil) {+ out, unavailable := entry.models, entry.unavailable+ shouldRefresh := !modelCacheInflight[key]+ if shouldRefresh {+ modelCacheInflight[key] = true+ }+ modelCacheMu.Unlock()+ if shouldRefresh {+ go func() {+ defer func() {+ modelCacheMu.Lock()+ delete(modelCacheInflight, key)+ modelCacheMu.Unlock()+ }()+ refreshCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), modelCacheRefreshTimeout)+ defer cancel()+ catalog, err := fn(refreshCtx)+ if err != nil || len(catalog.Models) == 0 || catalog.Fallback {+ return+ }+ storeModelCacheEntry(key, catalog)+ }()+ }+ return Catalog{Models: out, Unavailable: unavailable}, nil+ }}modelCacheMu.Unlock()- catalog, err := fn()+ catalog, err := fn(ctx)if err != nil {return Catalog{}, err}@@ -596,14 +644,24 @@ func cachedDiscovery(key string, fn func() (Catalog, error)) (Catalog, error) {return catalog, nil}+ storeModelCacheEntry(key, catalog)+ return catalog, nil+}++func storeModelCacheEntry(key string, catalog Catalog) {+ now := modelCacheNow()+ staleTTL := modelCacheStaleTTL+ if staleTTL < modelCacheTTL {+ staleTTL = modelCacheTTL+ }modelCacheMu.Lock()modelCache[key] = modelCacheEntry{models: catalog.Models,unavailable: catalog.Unavailable,- expiresAt: time.Now().Add(modelCacheTTL),+ freshUntil: now.Add(modelCacheTTL),+ staleUntil: now.Add(staleTTL),}modelCacheMu.Unlock()- return catalog, nil}// discoveryCacheKey scopes a discovery memo to the binary it enumerated.diff --git a/server/pkg/agent/task_env_file.go b/server/pkg/agent/task_env_file.gonew file mode 100644index 0000000000..d7a61a4287--- /dev/null+++ b/server/pkg/agent/task_env_file.go@@ -0,0 +1,188 @@+package agent++import (+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "runtime"+ "strings"+)++// TaskEnvFileEnv points a daemon-managed `multica` CLI invocation at a private+// 0o600 JSON overlay file holding the active turn's volatile per-task+// environment variables (MULTICA_TOKEN, MULTICA_TASK_ID, etc.).+//+// Warm pooled provider processes (Codex app-server, persistent Claude Code)+// outlive a single task. Rather than baking Task 1's short-lived token into the+// pooled process's static OS environment — where Turn 2 would inherit a stale+// credential and an idle process would hold a token on disk/environ — the+// daemon omits TaskEnvVolatileKeys from the pooled process's static env, sets+// MULTICA_TASK_ENV_FILE, atomically updates the file before each turn, and+// clears it as soon as the turn finishes.+const TaskEnvFileEnv = "MULTICA_TASK_ENV_FILE"++// TaskEnvVolatileKeys is the exhaustive whitelist of per-task environment+// variables that change from turn to turn within a warm provider session and+// are delivered through TaskEnvFileEnv.+//+// Enforcing this whitelist on both write and read ensures a task-env file can+// never overwrite static session/host variables such as PATH, HOME,+// MULTICA_SERVER_URL, or MULTICA_AGENT_ID.+var TaskEnvVolatileKeys = []string{+ "MULTICA_TOKEN",+ "MULTICA_TASK_ID",+ "MULTICA_TASK_CONFIG_ROOT",+ "MULTICA_TASK_SLOT",+ "MULTICA_AUTOPILOT_RUN_ID",+ "MULTICA_AUTOPILOT_ID",+ "MULTICA_QUICK_CREATE_TASK_ID",+ "MULTICA_QUICK_CREATE_ATTACHMENT_IDS",+ "MULTICA_QUICK_CREATE_DEFAULT_ASSIGNEE_TYPE",+ "MULTICA_QUICK_CREATE_DEFAULT_ASSIGNEE_ID",+}++var taskEnvVolatileKeySet = func() map[string]struct{} {+ set := make(map[string]struct{}, len(TaskEnvVolatileKeys))+ for _, key := range TaskEnvVolatileKeys {+ set[key] = struct{}{}+ }+ return set+}()++// IsTaskEnvVolatileKey reports whether key belongs to the per-turn dynamic+// environment overlay for warm pooled sessions.+func IsTaskEnvVolatileKey(key string) bool {+ _, ok := taskEnvVolatileKeySet[key]+ return ok+}++type taskEnvFilePayload struct {+ Active bool `json:"active"`+ Env map[string]string `json:"env,omitempty"`+}++// WriteTaskEnvFile atomically writes the active turn's whitelisted volatile+// variables to path (mode 0o600).+func WriteTaskEnvFile(path string, sourceEnv map[string]string) error {+ filtered := make(map[string]string, len(TaskEnvVolatileKeys))+ for _, key := range TaskEnvVolatileKeys {+ if val, ok := sourceEnv[key]; ok && val != "" {+ filtered[key] = val+ }+ }+ return writeTaskEnvFilePayload(path, taskEnvFilePayload{+ Active: true,+ Env: filtered,+ })+}++// ClearTaskEnvFile atomically marks path inactive and removes all volatile+// credentials so an idle pooled provider process holds no live task token.+func ClearTaskEnvFile(path string) error {+ return writeTaskEnvFilePayload(path, taskEnvFilePayload{Active: false})+}++func writeTaskEnvFilePayload(path string, payload taskEnvFilePayload) error {+ data, err := json.Marshal(payload)+ if err != nil {+ return fmt.Errorf("marshal task env overlay: %w", err)+ }+ dir := filepath.Dir(path)+ tmp, err := os.CreateTemp(dir, ".task-env-*.tmp")+ if err != nil {+ return fmt.Errorf("create temp task env overlay: %w", err)+ }+ tmpPath := tmp.Name()+ cleanupTmp := true+ defer func() {+ if cleanupTmp {+ _ = os.Remove(tmpPath)+ }+ }()+ if runtime.GOOS != "windows" {+ if err := tmp.Chmod(0o600); err != nil {+ _ = tmp.Close()+ return fmt.Errorf("chmod temp task env overlay: %w", err)+ }+ }+ if _, err := tmp.Write(data); err != nil {+ _ = tmp.Close()+ return fmt.Errorf("write temp task env overlay: %w", err)+ }+ if err := tmp.Close(); err != nil {+ return fmt.Errorf("close temp task env overlay: %w", err)+ }+ if err := os.Rename(tmpPath, path); err != nil {+ return fmt.Errorf("replace task env overlay: %w", err)+ }+ cleanupTmp = false+ return nil+}++// ApplyTaskEnvFileOverlay applies the dynamic per-turn task environment when+// TaskEnvFileEnv is set in the current process environment.+//+// When TaskEnvFileEnv is unset (normal cold runs and human CLI usage), this is+// a complete no-op. When set, every key in TaskEnvVolatileKeys is first cleared+// so stale values can never survive, and only whitelisted keys from an active+// overlay are populated. If the file is missing or inactive, volatile keys stay+// unset so the CLI fails closed under inDaemonManagedExecutionContext().+func ApplyTaskEnvFileOverlay() error {+ path := strings.TrimSpace(os.Getenv(TaskEnvFileEnv))+ if path == "" {+ return nil+ }+ for _, key := range TaskEnvVolatileKeys {+ _ = os.Unsetenv(key)+ }+ data, err := os.ReadFile(path)+ if err != nil {+ if os.IsNotExist(err) {+ return nil+ }+ return fmt.Errorf("read %s: %w", TaskEnvFileEnv, err)+ }+ var payload taskEnvFilePayload+ if err := json.Unmarshal(data, &payload); err != nil {+ return fmt.Errorf("parse %s: %w", TaskEnvFileEnv, err)+ }+ if !payload.Active {+ return nil+ }+ for key, val := range payload.Env {+ if !IsTaskEnvVolatileKey(key) {+ continue+ }+ if err := os.Setenv(key, val); err != nil {+ return fmt.Errorf("set %s from %s: %w", key, TaskEnvFileEnv, err)+ }+ }+ return nil+}++// PreparePooledChildEnv clones baseEnv for a long-lived pooled provider+// process: volatile per-task credentials are stripped from the static OS+// environment (they travel via taskEnvFile instead), TaskEnvFileEnv is set,+// and temp-directory variables are repointed to sessionTempDir so they outlive+// Task 1's per-task temp directory cleanup.+func PreparePooledChildEnv(baseEnv map[string]string, taskEnvFile, sessionTempDir string) map[string]string {+ out := make(map[string]string, len(baseEnv)+2)+ for k, v := range baseEnv {+ if IsTaskEnvVolatileKey(k) {+ continue+ }+ out[k] = v+ }+ out[TaskEnvFileEnv] = taskEnvFile+ if sessionTempDir != "" {+ out["TMPDIR"] = sessionTempDir+ if runtime.GOOS != "windows" {+ out["TMP"] = sessionTempDir+ out["TEMP"] = sessionTempDir+ } else if _, hasClaudeTmp := out["CLAUDE_CODE_TMPDIR"]; hasClaudeTmp {+ out["CLAUDE_CODE_TMPDIR"] = sessionTempDir+ }+ }+ return out+}diff --git a/server/pkg/agent/warm_pool.go b/server/pkg/agent/warm_pool.gonew file mode 100644index 0000000000..046d343ea0--- /dev/null+++ b/server/pkg/agent/warm_pool.go@@ -0,0 +1,431 @@+package agent++import (+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "log/slog"+ "os"+ "runtime"+ "sort"+ "strconv"+ "strings"+ "sync"+ "time"+)++const (+ // DefaultWarmPoolIdleTTL bounds how long an idle pooled provider process+ // stays alive between turns before being gracefully closed and reaped.+ DefaultWarmPoolIdleTTL = 15 * time.Minute+ // DefaultWarmPoolMaxIdle caps the number of idle provider processes held+ // across all conversations to bound host memory usage.+ DefaultWarmPoolMaxIdle = 8++ warmPoolEnvEnabled = "MULTICA_WARM_POOL"+ warmPoolEnvIdleTTL = "MULTICA_WARM_POOL_IDLE_TTL"+ warmPoolEnvMaxIdle = "MULTICA_WARM_POOL_MAX_IDLE"+)++type warmPoolKey struct {+ provider string+ sessionID string+}++type warmPoolProcess interface {+ Fingerprint() string+ Alive() bool+ Close() bool+}++type warmPoolEntry struct {+ key warmPoolKey+ proc warmPoolProcess+ parkedAt time.Time+ timer *time.Timer+}++// WarmSessionPoolConfig configures a WarmSessionPool.+type WarmSessionPoolConfig struct {+ IdleTTL time.Duration+ MaxIdle int+ Logger *slog.Logger+}++// WarmSessionPool keeps recently completed Codex app-server and Claude Code+// processes warm across turns of the same conversation so follow-up turns avoid+// process spawn, model catalog refresh, MCP initialization, and cold WebSocket+// handshakes.+//+// Security & isolation invariants:+// - Entries are keyed by (provider, sessionID) and verified against a SHA-256+// fingerprint of every session-immutable input (executable, launch args,+// cwd, model, thinking level, service tier, MCP config, settings/config+// file contents, runtime brief hash, and all non-volatile env vars including+// workspace/agent identity). Any mismatch evicts and closes the stale+// process synchronously before spawning fresh.+// - Volatile per-task credentials (MULTICA_TOKEN, MULTICA_TASK_ID, etc.) are+// never stored in the pooled process's static environment; they travel via a+// 0o600 per-session overlay file that is atomically cleared before parking.+// - Unhealthy, cancelled, timed-out, or errored turns are never parked.+type WarmSessionPool struct {+ idleTTL time.Duration+ maxIdle int+ logger *slog.Logger++ mu sync.Mutex+ closed bool+ entries map[warmPoolKey]*warmPoolEntry+}++// NewWarmSessionPool creates a new pool with bounded idle TTL and capacity.+func NewWarmSessionPool(cfg WarmSessionPoolConfig) *WarmSessionPool {+ idleTTL := cfg.IdleTTL+ if idleTTL <= 0 {+ idleTTL = DefaultWarmPoolIdleTTL+ }+ maxIdle := cfg.MaxIdle+ if maxIdle <= 0 {+ maxIdle = DefaultWarmPoolMaxIdle+ }+ logger := cfg.Logger+ if logger == nil {+ logger = slog.Default()+ }+ return &WarmSessionPool{+ idleTTL: idleTTL,+ maxIdle: maxIdle,+ logger: logger,+ entries: make(map[warmPoolKey]*warmPoolEntry),+ }+}++// NewWarmSessionPoolFromEnv creates a WarmSessionPool configured from daemon+// environment variables, or returns nil if MULTICA_WARM_POOL explicitly+// disables pooling ("0", "false", "off", "no").+func NewWarmSessionPoolFromEnv(logger *slog.Logger) *WarmSessionPool {+ if raw := strings.TrimSpace(strings.ToLower(os.Getenv(warmPoolEnvEnabled))); raw != "" {+ switch raw {+ case "0", "false", "off", "no":+ if logger != nil {+ logger.Info("warm session pool disabled by environment", "env", warmPoolEnvEnabled, "value", raw)+ }+ return nil+ }+ }+ cfg := WarmSessionPoolConfig{+ IdleTTL: DefaultWarmPoolIdleTTL,+ MaxIdle: DefaultWarmPoolMaxIdle,+ Logger: logger,+ }+ if raw := strings.TrimSpace(os.Getenv(warmPoolEnvIdleTTL)); raw != "" {+ if d, err := time.ParseDuration(raw); err == nil && d > 0 {+ cfg.IdleTTL = d+ }+ }+ if raw := strings.TrimSpace(os.Getenv(warmPoolEnvMaxIdle)); raw != "" {+ if n, err := strconv.Atoi(raw); err == nil && n > 0 {+ cfg.MaxIdle = n+ }+ }+ return NewWarmSessionPool(cfg)+}++// Acquire checks out a parked process for (provider, sessionID) if its+// fingerprint matches and it is still alive. If a parked entry exists with a+// mismatched fingerprint or dead process, it is evicted and closed before+// returning nil so the caller can spawn a fresh session cleanly.+func (p *WarmSessionPool) Acquire(provider, sessionID, fingerprint string) warmPoolProcess {+ if p == nil || provider == "" || sessionID == "" {+ return nil+ }+ key := warmPoolKey{provider: provider, sessionID: sessionID}++ p.mu.Lock()+ if p.closed {+ p.mu.Unlock()+ return nil+ }+ entry, ok := p.entries[key]+ if !ok {+ p.mu.Unlock()+ return nil+ }+ delete(p.entries, key)+ if entry.timer != nil {+ entry.timer.Stop()+ }+ p.mu.Unlock()++ if !entry.proc.Alive() {+ p.logger.Debug("warm pool: evicted dead process on acquire", "provider", provider, "session_id", sessionID)+ entry.proc.Close()+ return nil+ }+ if entry.proc.Fingerprint() != fingerprint {+ p.logger.Info("warm pool: config changed; evicting stale process", "provider", provider, "session_id", sessionID)+ entry.proc.Close()+ return nil+ }+ p.logger.Info("warm pool: session hit", "provider", provider, "session_id", sessionID)+ return entry.proc+}++// Park stores a healthy idle process in the pool under (provider, sessionID).+// Returns false (and closes proc) if the pool is closed, proc is dead, or+// sessionID is empty.+func (p *WarmSessionPool) Park(provider, sessionID string, proc warmPoolProcess) bool {+ if proc == nil {+ return false+ }+ if p == nil || provider == "" || sessionID == "" || !proc.Alive() {+ proc.Close()+ return false+ }+ key := warmPoolKey{provider: provider, sessionID: sessionID}++ var toClose []warmPoolProcess++ p.mu.Lock()+ if p.closed {+ p.mu.Unlock()+ proc.Close()+ return false+ }+ if existing, ok := p.entries[key]; ok {+ delete(p.entries, key)+ if existing.timer != nil {+ existing.timer.Stop()+ }+ toClose = append(toClose, existing.proc)+ }+ for len(p.entries) >= p.maxIdle {+ var oldestKey warmPoolKey+ var oldest *warmPoolEntry+ for k, e := range p.entries {+ if oldest == nil || e.parkedAt.Before(oldest.parkedAt) {+ oldestKey = k+ oldest = e+ }+ }+ if oldest == nil {+ break+ }+ delete(p.entries, oldestKey)+ if oldest.timer != nil {+ oldest.timer.Stop()+ }+ toClose = append(toClose, oldest.proc)+ }++ entry := &warmPoolEntry{+ key: key,+ proc: proc,+ parkedAt: time.Now(),+ }+ entry.timer = time.AfterFunc(p.idleTTL, func() {+ p.evictExact(key, entry)+ })+ p.entries[key] = entry+ p.mu.Unlock()++ for _, stale := range toClose {+ stale.Close()+ }+ p.logger.Info("warm pool: parked session", "provider", provider, "session_id", sessionID, "idle_ttl", p.idleTTL.String())+ return true+}++func (p *WarmSessionPool) evictExact(key warmPoolKey, target *warmPoolEntry) {+ p.mu.Lock()+ current, ok := p.entries[key]+ if !ok || current != target {+ p.mu.Unlock()+ return+ }+ delete(p.entries, key)+ p.mu.Unlock()++ p.logger.Info("warm pool: evicting idle session", "provider", key.provider, "session_id", key.sessionID)+ target.proc.Close()+}++// Evict removes and closes any parked process for (provider, sessionID).+func (p *WarmSessionPool) Evict(provider, sessionID string) {+ if p == nil || provider == "" || sessionID == "" {+ return+ }+ key := warmPoolKey{provider: provider, sessionID: sessionID}+ p.mu.Lock()+ entry, ok := p.entries[key]+ if ok {+ delete(p.entries, key)+ if entry.timer != nil {+ entry.timer.Stop()+ }+ }+ p.mu.Unlock()+ if ok {+ entry.proc.Close()+ }+}++// Len returns the number of currently parked idle sessions.+func (p *WarmSessionPool) Len() int {+ if p == nil {+ return 0+ }+ p.mu.Lock()+ defer p.mu.Unlock()+ return len(p.entries)+}++// Close closes the pool and terminates/reaps every parked process in parallel.+// Returns true iff every parked process confirmed clean termination.+func (p *WarmSessionPool) Close() bool {+ if p == nil {+ return true+ }+ p.mu.Lock()+ if p.closed {+ p.mu.Unlock()+ return true+ }+ p.closed = true+ entries := make([]*warmPoolEntry, 0, len(p.entries))+ for k, e := range p.entries {+ delete(p.entries, k)+ if e.timer != nil {+ e.timer.Stop()+ }+ entries = append(entries, e)+ }+ p.mu.Unlock()++ if len(entries) == 0 {+ return true+ }+ p.logger.Info("warm pool: closing idle sessions", "count", len(entries))+ var (+ wg sync.WaitGroup+ mu sync.Mutex+ allClean = true+ )+ for _, entry := range entries {+ wg.Add(1)+ go func(e *warmPoolEntry) {+ defer wg.Done()+ if !e.proc.Close() {+ mu.Lock()+ allClean = false+ mu.Unlock()+ }+ }(entry)+ }+ wg.Wait()+ return allClean+}++// WarmSessionFingerprintInput captures every session-immutable input that+// governs whether a parked process can safely serve the next turn.+type WarmSessionFingerprintInput struct {+ Provider string+ Executable string+ LaunchPrefix []string+ Args []string+ Cwd string+ Model string+ ThinkingLevel string+ ServiceTier string+ McpConfig json.RawMessage+ ConfigFiles []string // optional file paths whose bytes are hashed (e.g. ClaudeSettingsPath, CODEX_HOME/config.toml)+ BriefHash string+ Env map[string]string+ ExtraFlags []string+}++// HashWarmBrief returns a hex SHA-256 digest of a runtime brief string.+func HashWarmBrief(brief string) string {+ if brief == "" {+ return ""+ }+ sum := sha256.Sum256([]byte(brief))+ return hex.EncodeToString(sum[:])+}++func computeWarmSessionFingerprint(in WarmSessionFingerprintInput) string {+ h := sha256.New()+ writeField := func(tag, val string) {+ _, _ = h.Write([]byte(tag))+ _, _ = h.Write([]byte{0})+ _, _ = h.Write([]byte(val))+ _, _ = h.Write([]byte{0})+ }+ writeSlice := func(tag string, vals []string) {+ _, _ = h.Write([]byte(tag))+ _, _ = h.Write([]byte{0})+ for _, v := range vals {+ _, _ = h.Write([]byte(v))+ _, _ = h.Write([]byte{0})+ }+ _, _ = h.Write([]byte{1})+ }++ writeField("provider", in.Provider)+ writeField("exec", in.Executable)+ writeSlice("prefix", in.LaunchPrefix)+ writeSlice("args", in.Args)+ writeField("cwd", in.Cwd)+ writeField("model", in.Model)+ writeField("thinking", in.ThinkingLevel)+ writeField("tier", in.ServiceTier)+ writeField("mcp", strings.TrimSpace(string(in.McpConfig)))+ writeField("brief", in.BriefHash)+ writeSlice("extra", in.ExtraFlags)++ for _, path := range in.ConfigFiles {+ if path == "" {+ continue+ }+ data, err := os.ReadFile(path)+ if err != nil {+ writeField("cfgfile:"+path, "ERR:"+err.Error())+ } else {+ sum := sha256.Sum256(data)+ writeField("cfgfile:"+path, hex.EncodeToString(sum[:]))+ }+ }++ // Hash all non-volatile environment variables (excluding temp dirs and the+ // dynamic overlay path itself) so workspace, agent, CODEX_HOME, custom_env,+ // proxy URLs, and auth overrides all participate in isolation.+ keys := make([]string, 0, len(in.Env))+ for k := range in.Env {+ if isWarmPoolIgnoredEnvKey(k) {+ continue+ }+ keys = append(keys, k)+ }+ sort.Strings(keys)+ for _, k := range keys {+ writeField("env:"+k, in.Env[k])+ }++ return hex.EncodeToString(h.Sum(nil))+}++func isWarmPoolIgnoredEnvKey(key string) bool {+ if IsTaskEnvVolatileKey(key) || key == TaskEnvFileEnv {+ return true+ }+ upper := key+ if runtime.GOOS == "windows" {+ upper = strings.ToUpper(key)+ }+ switch upper {+ case "TMPDIR", "TMP", "TEMP", "CLAUDE_CODE_TMPDIR":+ return true+ default:+ return false+ }+}diff --git a/server/pkg/agent/warm_pool_test.go b/server/pkg/agent/warm_pool_test.gonew file mode 100644index 0000000000..e2b52a09dd--- /dev/null+++ b/server/pkg/agent/warm_pool_test.go@@ -0,0 +1,761 @@+package agent++import (+ "context"+ "encoding/json"+ "io"+ "log/slog"+ "os"+ "path/filepath"+ "runtime"+ "slices"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"+)++func TestTaskEnvFileOverlay(t *testing.T) {+ dir := t.TempDir()+ envFile := filepath.Join(dir, "task-env.json")++ // Write Turn 1 volatile env plus a forbidden non-volatile key that must be ignored.+ err := WriteTaskEnvFile(envFile, map[string]string{+ "MULTICA_TOKEN": "mat_turn_1",+ "MULTICA_TASK_ID": "task-1",+ "MULTICA_TASK_CONFIG_ROOT": "/tmp/cfg-1",+ "MULTICA_TASK_SLOT": "2",+ "MULTICA_QUICK_CREATE_TASK_ID": "task-1",+ "MULTICA_SERVER_URL": "https://evil.example.com",+ "PATH": "/evil/bin",+ })+ if err != nil {+ t.Fatalf("WriteTaskEnvFile turn 1: %v", err)+ }+ if runtime.GOOS != "windows" {+ info, err := os.Stat(envFile)+ if err != nil {+ t.Fatalf("stat envFile: %v", err)+ }+ if mode := info.Mode().Perm(); mode != 0o600 {+ t.Fatalf("envFile mode = %o, want 0600", mode)+ }+ }++ t.Setenv(TaskEnvFileEnv, envFile)+ t.Setenv("MULTICA_SERVER_URL", "https://real.example.com")+ t.Setenv("MULTICA_TOKEN", "mat_stale_parent")+ t.Setenv("MULTICA_AUTOPILOT_RUN_ID", "stale-autopilot")++ if err := ApplyTaskEnvFileOverlay(); err != nil {+ t.Fatalf("ApplyTaskEnvFileOverlay turn 1: %v", err)+ }+ if got := os.Getenv("MULTICA_TOKEN"); got != "mat_turn_1" {+ t.Fatalf("MULTICA_TOKEN = %q, want mat_turn_1", got)+ }+ if got := os.Getenv("MULTICA_TASK_ID"); got != "task-1" {+ t.Fatalf("MULTICA_TASK_ID = %q, want task-1", got)+ }+ if got := os.Getenv("MULTICA_AUTOPILOT_RUN_ID"); got != "" {+ t.Fatalf("stale MULTICA_AUTOPILOT_RUN_ID was not cleared: %q", got)+ }+ if got := os.Getenv("MULTICA_SERVER_URL"); got != "https://real.example.com" {+ t.Fatalf("non-volatile MULTICA_SERVER_URL overwritten: %q", got)+ }++ // Turn 2 updates token & task ID and drops MULTICA_QUICK_CREATE_TASK_ID.+ if err := WriteTaskEnvFile(envFile, map[string]string{+ "MULTICA_TOKEN": "mat_turn_2",+ "MULTICA_TASK_ID": "task-2",+ }); err != nil {+ t.Fatalf("WriteTaskEnvFile turn 2: %v", err)+ }+ if err := ApplyTaskEnvFileOverlay(); err != nil {+ t.Fatalf("ApplyTaskEnvFileOverlay turn 2: %v", err)+ }+ if got := os.Getenv("MULTICA_TOKEN"); got != "mat_turn_2" {+ t.Fatalf("MULTICA_TOKEN = %q, want mat_turn_2", got)+ }+ if got := os.Getenv("MULTICA_QUICK_CREATE_TASK_ID"); got != "" {+ t.Fatalf("MULTICA_QUICK_CREATE_TASK_ID leaked from turn 1: %q", got)+ }++ // ClearTaskEnvFile must cause all volatile keys to become unset.+ if err := ClearTaskEnvFile(envFile); err != nil {+ t.Fatalf("ClearTaskEnvFile: %v", err)+ }+ if err := ApplyTaskEnvFileOverlay(); err != nil {+ t.Fatalf("ApplyTaskEnvFileOverlay after clear: %v", err)+ }+ if got := os.Getenv("MULTICA_TOKEN"); got != "" {+ t.Fatalf("MULTICA_TOKEN still set after clear: %q", got)+ }+ if got := os.Getenv("MULTICA_TASK_ID"); got != "" {+ t.Fatalf("MULTICA_TASK_ID still set after clear: %q", got)+ }+}++type fakeWarmProc struct {+ fp string+ alive atomic.Bool+ closed atomic.Int32+}++func newFakeWarmProc(fp string) *fakeWarmProc {+ p := &fakeWarmProc{fp: fp}+ p.alive.Store(true)+ return p+}++func (p *fakeWarmProc) Fingerprint() string { return p.fp }+func (p *fakeWarmProc) Alive() bool { return p.alive.Load() }+func (p *fakeWarmProc) Close() bool {+ p.alive.Store(false)+ p.closed.Add(1)+ return true+}++func TestWarmSessionPoolLifecycle(t *testing.T) {+ t.Parallel()++ pool := NewWarmSessionPool(WarmSessionPoolConfig{+ IdleTTL: 200 * time.Millisecond,+ MaxIdle: 2,+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ })+ defer pool.Close()++ // Park & hit.+ p1 := newFakeWarmProc("fp-1")+ if !pool.Park("codex", "s1", p1) {+ t.Fatal("Park(s1) returned false")+ }+ if pool.Len() != 1 {+ t.Fatalf("Len() = %d, want 1", pool.Len())+ }+ got := pool.Acquire("codex", "s1", "fp-1")+ if got != p1 {+ t.Fatalf("Acquire(s1) = %v, want %v", got, p1)+ }+ if pool.Len() != 0 {+ t.Fatalf("Len() after acquire = %d, want 0", pool.Len())+ }++ // Fingerprint mismatch evicts and closes synchronously.+ pool.Park("codex", "s1", p1)+ if got := pool.Acquire("codex", "s1", "fp-changed"); got != nil {+ t.Fatalf("Acquire with changed fingerprint = %v, want nil", got)+ }+ if p1.closed.Load() != 1 {+ t.Fatalf("stale process close count = %d, want 1", p1.closed.Load())+ }++ // LRU eviction when MaxIdle == 2.+ pa := newFakeWarmProc("fp-a")+ pb := newFakeWarmProc("fp-b")+ pc := newFakeWarmProc("fp-c")+ pool.Park("codex", "sa", pa)+ time.Sleep(5 * time.Millisecond)+ pool.Park("codex", "sb", pb)+ time.Sleep(5 * time.Millisecond)+ pool.Park("codex", "sc", pc)+ if pa.closed.Load() != 1 {+ t.Fatalf("oldest idle entry pa was not evicted: closed=%d", pa.closed.Load())+ }+ if pool.Len() != 2 {+ t.Fatalf("Len() after LRU eviction = %d, want 2", pool.Len())+ }++ // Idle TTL expiry.+ time.Sleep(300 * time.Millisecond)+ if pool.Len() != 0 {+ t.Fatalf("Len() after idle TTL = %d, want 0", pool.Len())+ }+ if pb.closed.Load() != 1 || pc.closed.Load() != 1 {+ t.Fatalf("idle entries not closed on TTL expiry: pb=%d pc=%d", pb.closed.Load(), pc.closed.Load())+ }+}++func TestNewWarmSessionPoolFromEnvDisableSwitch(t *testing.T) {+ t.Setenv(warmPoolEnvEnabled, "0")+ if pool := NewWarmSessionPoolFromEnv(slog.New(slog.NewTextHandler(io.Discard, nil))); pool != nil {+ pool.Close()+ t.Fatal("expected nil pool when MULTICA_WARM_POOL=0")+ }++ t.Setenv(warmPoolEnvEnabled, "1")+ t.Setenv(warmPoolEnvIdleTTL, "3m")+ t.Setenv(warmPoolEnvMaxIdle, "4")+ pool := NewWarmSessionPoolFromEnv(slog.New(slog.NewTextHandler(io.Discard, nil)))+ if pool == nil {+ t.Fatal("expected non-nil pool when MULTICA_WARM_POOL=1")+ }+ defer pool.Close()+ if pool.idleTTL != 3*time.Minute || pool.maxIdle != 4 {+ t.Fatalf("pool config = (%v, %d), want (3m, 4)", pool.idleTTL, pool.maxIdle)+ }+}++func TestCodexWarmPoolReuseAndTokenIsolation(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fake binary requires a POSIX shell")+ }++ dir := t.TempDir()+ spawnLog := filepath.Join(dir, "spawns.log")+ codexHome := filepath.Join(dir, "codex-home")+ if err := os.MkdirAll(codexHome, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(codexHome, "config.toml"), []byte("model = \"gpt-6.1-sol\"\n"), 0o600); err != nil {+ t.Fatal(err)+ }++ // Fake codex app-server that serves multiple turns on the same process,+ // reads MULTICA_TOKEN from MULTICA_TASK_ENV_FILE on each turn, and reports+ // cumulative thread token usage.+ fakeCodex := filepath.Join(dir, "codex")+ script := `#!/bin/sh+printf '%s\n' "$$" >> '` + spawnLog + `'+turn_num=0+while IFS= read -r line; do+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')+ case "$line" in+ *'"method":"initialize"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"userAgent":"fake-codex"}}\n' "$id"+ ;;+ *'"method":"thread/start"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"thread":{"id":"thr-warm-1"}}}\n' "$id"+ ;;+ *'"method":"thread/resume"'*)+ printf '{"jsonrpc":"2.0","id":%s,"result":{"thread":{"id":"thr-warm-1"}}}\n' "$id"+ ;;+ *'"method":"turn/start"'*)+ turn_num=$((turn_num + 1))+ printf '{"jsonrpc":"2.0","id":%s,"result":{"turn":{"id":"turn-%s"}}}\n' "$id" "$turn_num"+ printf '{"jsonrpc":"2.0","method":"turn/started","params":{"threadId":"thr-warm-1","turn":{"id":"turn-%s"}}}\n' "$turn_num"+ tok=$(sed -n 's/.*"MULTICA_TOKEN":"\([^"]*\)".*/\1/p' "$MULTICA_TASK_ENV_FILE")+ tid=$(sed -n 's/.*"MULTICA_TASK_ID":"\([^"]*\)".*/\1/p' "$MULTICA_TASK_ENV_FILE")+ static_tok="${MULTICA_TOKEN:-EMPTY}"+ total_in=$((turn_num * 100))+ total_out=$((turn_num * 10))+ printf '{"jsonrpc":"2.0","method":"thread/tokenUsage/updated","params":{"threadId":"thr-warm-1","turnId":"turn-%s","tokenUsage":{"total":{"inputTokens":%d,"outputTokens":%d},"last":{"inputTokens":100,"outputTokens":10}}}}\n' "$turn_num" "$total_in" "$total_out"+ printf '{"jsonrpc":"2.0","method":"item/completed","params":{"threadId":"thr-warm-1","turnId":"turn-%s","item":{"type":"agentMessage","id":"msg-%s","phase":"final_answer","text":"pid=$$ turn=%s token=%s task=%s static=%s"}}}\n' "$turn_num" "$turn_num" "$turn_num" "$tok" "$tid" "$static_tok"+ printf '{"jsonrpc":"2.0","method":"turn/completed","params":{"threadId":"thr-warm-1","turn":{"id":"turn-%s","status":"completed"}}}\n' "$turn_num"+ ;;+ esac+done+`+ writeTestExecutable(t, fakeCodex, []byte(script))++ pool := NewWarmSessionPool(WarmSessionPoolConfig{+ IdleTTL: 30 * time.Second,+ MaxIdle: 4,+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ })+ defer pool.Close()++ runTurn := func(taskID, token, resumeID, model, briefHash string) Result {+ t.Helper()+ b, err := New("codex", Config{+ ExecutablePath: fakeCodex,+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ TaskID: taskID,+ WarmPool: pool,+ Env: map[string]string{+ "CODEX_HOME": codexHome,+ "MULTICA_TOKEN": token,+ "MULTICA_TASK_ID": taskID,+ "MULTICA_AGENT_ID": "agent-1",+ "MULTICA_WORKSPACE_ID": "ws-1",+ },+ })+ if err != nil {+ t.Fatalf("New(codex): %v", err)+ }+ sess, err := b.Execute(context.Background(), "hello", ExecOptions{+ Cwd: dir,+ Model: model,+ ResumeSessionID: resumeID,+ WarmPoolBriefHash: briefHash,+ Timeout: 10 * time.Second,+ })+ if err != nil {+ t.Fatalf("Execute(%s): %v", taskID, err)+ }+ for range sess.Messages {+ }+ return <-sess.Result+ }++ // Turn 1: cold spawn, gets parked.+ r1 := runTurn("task-1", "mat_turn_1", "", "gpt-6.1-sol", "brief-v1")+ if r1.Status != "completed" || r1.SessionID != "thr-warm-1" {+ t.Fatalf("Turn 1 result = %+v", r1)+ }+ if !strings.Contains(r1.Output, "turn=1 token=mat_turn_1 task=task-1 static=EMPTY") {+ t.Fatalf("Turn 1 output = %q", r1.Output)+ }+ if pool.Len() != 1 {+ t.Fatalf("pool.Len() after Turn 1 = %d, want 1", pool.Len())+ }++ // Verify idle task-env file holds NO live token while parked.+ pool.mu.Lock()+ parked := pool.entries[warmPoolKey{provider: "codex", sessionID: "thr-warm-1"}].proc.(*warmCodexProcess)+ envFilePath := parked.taskEnvFile+ pool.mu.Unlock()+ idleData, err := os.ReadFile(envFilePath)+ if err != nil {+ t.Fatalf("read idle task-env.json: %v", err)+ }+ if strings.Contains(string(idleData), "mat_turn_1") {+ t.Fatalf("idle task-env.json leaked Turn 1 token: %s", string(idleData))+ }++ // Turn 2: warm hit on SAME PID with Turn 2's fresh token and delta usage!+ r2 := runTurn("task-2", "mat_turn_2", "thr-warm-1", "gpt-6.1-sol", "brief-v1")+ if r2.Status != "completed" || r2.SessionID != "thr-warm-1" {+ t.Fatalf("Turn 2 result = %+v", r2)+ }+ if !strings.Contains(r2.Output, "turn=2 token=mat_turn_2 task=task-2 static=EMPTY") {+ t.Fatalf("Turn 2 output = %q (expected same process turn=2 with fresh token)", r2.Output)+ }+ if u := r2.Usage["gpt-6.1-sol"]; u.InputTokens != 100 || u.OutputTokens != 10 {+ t.Fatalf("Turn 2 delta usage = %+v, want input=100 output=10 (no double counting)", u)+ }++ spawns, err := os.ReadFile(spawnLog)+ if err != nil {+ t.Fatal(err)+ }+ if lines := splitNonEmptyLines(string(spawns)); len(lines) != 1 {+ t.Fatalf("expected 1 codex spawn across Turn 1 & Turn 2, got %d (%v)", len(lines), lines)+ }++ // Turn 3: changing briefHash must evict PID 1 and spawn a fresh process.+ r3 := runTurn("task-3", "mat_turn_3", "thr-warm-1", "gpt-6.1-sol", "brief-v2")+ if r3.Status != "completed" {+ t.Fatalf("Turn 3 result = %+v", r3)+ }+ if !strings.Contains(r3.Output, "turn=1 token=mat_turn_3 task=task-3") {+ t.Fatalf("Turn 3 output = %q (expected fresh spawn turn=1)", r3.Output)+ }+ spawns, _ = os.ReadFile(spawnLog)+ if lines := splitNonEmptyLines(string(spawns)); len(lines) != 2 {+ t.Fatalf("expected 2 codex spawns after brief change, got %d (%v)", len(lines), lines)+ }++ // Pool.Close() cleans up the parked process and its temp dir.+ if !pool.Close() {+ t.Fatal("pool.Close() returned false")+ }+ if pool.Len() != 0 {+ t.Fatalf("pool.Len() after Close = %d, want 0", pool.Len())+ }+}++func TestClaudeWarmPoolReuseStreamingAndTokenIsolation(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fake binary requires a POSIX shell")+ }++ dir := t.TempDir()+ spawnLog := filepath.Join(dir, "claude-spawns.log")+ fakeClaude := filepath.Join(dir, "claude")+ script := `#!/bin/sh+printf '%s\n' "$$" >> '` + spawnLog + `'+turn=0+while IFS= read -r line; do+ case "$line" in+ *'"type":"user"'*)+ turn=$((turn + 1))+ tok=$(sed -n 's/.*"MULTICA_TOKEN":"\([^"]*\)".*/\1/p' "$MULTICA_TASK_ENV_FILE")+ tid=$(sed -n 's/.*"MULTICA_TASK_ID":"\([^"]*\)".*/\1/p' "$MULTICA_TASK_ENV_FILE")+ static_tok="${MULTICA_TOKEN:-EMPTY}"+ if [ "$turn" = "1" ]; then+ printf '{"type":"system","subtype":"init","session_id":"claude-warm-1"}\n'+ fi+ # Emit partial stream_event deltas followed by the final assistant snapshot+ printf '{"type":"stream_event","event":{"type":"message_start","message":{"id":"msg-%s"}}}\n' "$turn"+ printf '{"type":"stream_event","event":{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"plan-%s"}}}\n' "$turn"+ printf '{"type":"stream_event","event":{"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"hello "}}}\n'+ printf '{"type":"stream_event","event":{"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"%s:%s:%s"}}}\n' "$tok" "$tid" "$static_tok"+ printf '{"type":"stream_event","event":{"type":"message_stop"}}\n'+ printf '{"type":"assistant","message":{"id":"msg-%s","role":"assistant","model":"claude-opus-5-5","content":[{"type":"thinking","thinking":"plan-%s"},{"type":"text","text":"hello %s:%s:%s"}]}}\n' "$turn" "$turn" "$tok" "$tid" "$static_tok"+ cum_in=$((turn * 50))+ cum_out=$((turn * 15))+ printf '{"type":"result","subtype":"success","session_id":"claude-warm-1","result":"hello %s:%s:%s","is_error":false,"modelUsage":{"claude-opus-5-5":{"inputTokens":%d,"outputTokens":%d}}}\n' "$tok" "$tid" "$static_tok" "$cum_in" "$cum_out"+ ;;+ esac+done+`+ writeTestExecutable(t, fakeClaude, []byte(script))++ pool := NewWarmSessionPool(WarmSessionPoolConfig{+ IdleTTL: 30 * time.Second,+ MaxIdle: 4,+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ })+ defer pool.Close()++ runTurn := func(taskID, token, resumeID, model string) (Result, []Message) {+ t.Helper()+ b, err := New("claude", Config{+ ExecutablePath: fakeClaude,+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ TaskID: taskID,+ WarmPool: pool,+ Env: map[string]string{+ "MULTICA_TOKEN": token,+ "MULTICA_TASK_ID": taskID,+ "MULTICA_AGENT_ID": "agent-c1",+ "MULTICA_WORKSPACE_ID": "ws-1",+ },+ })+ if err != nil {+ t.Fatalf("New(claude): %v", err)+ }+ sess, err := b.Execute(context.Background(), "say hi", ExecOptions{+ Cwd: dir,+ Model: model,+ ResumeSessionID: resumeID,+ Timeout: 10 * time.Second,+ })+ if err != nil {+ t.Fatalf("Execute(%s): %v", taskID, err)+ }+ var msgs []Message+ for m := range sess.Messages {+ msgs = append(msgs, m)+ }+ return <-sess.Result, msgs+ }++ // Turn 1: cold spawn + stream_event deltas + zero duplication against assistant snapshot.+ r1, msgs1 := runTurn("task-c1", "mat_c1", "", "claude-opus-5-5")+ if r1.Status != "completed" || r1.SessionID != "claude-warm-1" {+ t.Fatalf("Turn 1 result = %+v", r1)+ }+ if r1.Output != "hello mat_c1:task-c1:EMPTY" {+ t.Fatalf("Turn 1 output = %q", r1.Output)+ }+ var streamedText1, streamedThink1 strings.Builder+ for _, m := range msgs1 {+ if m.Type == MessageText {+ streamedText1.WriteString(m.Content)+ }+ if m.Type == MessageThinking {+ streamedThink1.WriteString(m.Content)+ }+ }+ if streamedText1.String() != "hello mat_c1:task-c1:EMPTY" {+ t.Fatalf("Turn 1 streamed text = %q (possible duplication or drop)", streamedText1.String())+ }+ if streamedThink1.String() != "plan-1" {+ t.Fatalf("Turn 1 streamed thinking = %q, want plan-1", streamedThink1.String())+ }+ if pool.Len() != 1 {+ t.Fatalf("pool.Len() after Turn 1 = %d, want 1", pool.Len())+ }++ // Turn 2: warm hit on SAME PID, fresh token, cumulative modelUsage delta subtracted!+ r2, msgs2 := runTurn("task-c2", "mat_c2", "claude-warm-1", "claude-opus-5-5")+ if r2.Status != "completed" || r2.SessionID != "claude-warm-1" {+ t.Fatalf("Turn 2 result = %+v", r2)+ }+ if r2.Output != "hello mat_c2:task-c2:EMPTY" {+ t.Fatalf("Turn 2 output = %q", r2.Output)+ }+ if u := r2.Usage["claude-opus-5-5"]; u.InputTokens != 50 || u.OutputTokens != 15 {+ t.Fatalf("Turn 2 usage = %+v, want delta input=50 output=15", u)+ }+ var streamedText2 strings.Builder+ for _, m := range msgs2 {+ if m.Type == MessageText {+ streamedText2.WriteString(m.Content)+ }+ }+ if streamedText2.String() != "hello mat_c2:task-c2:EMPTY" {+ t.Fatalf("Turn 2 streamed text = %q", streamedText2.String())+ }++ spawns, err := os.ReadFile(spawnLog)+ if err != nil {+ t.Fatal(err)+ }+ if lines := splitNonEmptyLines(string(spawns)); len(lines) != 1 {+ t.Fatalf("expected 1 claude spawn across Turn 1 & Turn 2, got %d (%v)", len(lines), lines)+ }++ // Turn 3: model change evicts warm process and spawns fresh.+ r3, _ := runTurn("task-c3", "mat_c3", "claude-warm-1", "claude-sonnet-5")+ if r3.Status != "completed" {+ t.Fatalf("Turn 3 result = %+v", r3)+ }+ spawns, _ = os.ReadFile(spawnLog)+ if lines := splitNonEmptyLines(string(spawns)); len(lines) != 2 {+ t.Fatalf("expected 2 claude spawns after model change, got %d (%v)", len(lines), lines)+ }++ pool.Close()+ if pool.Len() != 0 {+ t.Fatalf("pool.Len() after Close = %d, want 0", pool.Len())+ }+}++func TestClaudeWarmPoolErrorResultClosesStdinImmediately(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("shell-script fake binary requires a POSIX shell")+ }++ dir := t.TempDir()+ fakeClaude := filepath.Join(dir, "claude")+ // Emits an error result and keeps reading stdin until EOF, matching a live+ // stream-json Claude process. Without closing stdin immediately, this would+ // stall for the full 10s claudeErrorResultGrace() before returning.+ script := `#!/bin/sh+while IFS= read -r line; do+ case "$line" in+ *'"type":"user"'*)+ printf '{"type":"system","subtype":"init","session_id":"claude-err-1"}\n'+ case "$line" in+ *prompt_too_long*)+ printf '{"type":"result","subtype":"success","session_id":"claude-err-1","result":"context full","is_error":false,"terminal_reason":"prompt_too_long"}\n'+ ;;+ *)+ printf '{"type":"result","subtype":"error","session_id":"claude-err-1","result":"rate limit exceeded","is_error":true}\n'+ ;;+ esac+ ;;+ esac+done+`+ writeTestExecutable(t, fakeClaude, []byte(script))++ pool := NewWarmSessionPool(WarmSessionPoolConfig{+ IdleTTL: 30 * time.Second,+ MaxIdle: 4,+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ })+ defer pool.Close()++ for _, tc := range []struct {+ name string+ prompt string+ wantError string+ }{+ {name: "is_error", prompt: "trigger api error", wantError: "rate limit exceeded"},+ {name: "terminal_reason_prompt_too_long", prompt: "trigger prompt_too_long", wantError: "prompt_too_long"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ b, err := New("claude", Config{+ ExecutablePath: fakeClaude,+ Logger: slog.New(slog.NewTextHandler(io.Discard, nil)),+ TaskID: "task-err-" + tc.name,+ WarmPool: pool,+ Env: map[string]string{+ "MULTICA_TOKEN": "mat_err",+ "MULTICA_TASK_ID": "task-err-" + tc.name,+ "MULTICA_AGENT_ID": "agent-err",+ "MULTICA_WORKSPACE_ID": "ws-err",+ },+ })+ if err != nil {+ t.Fatalf("New(claude): %v", err)+ }++ start := time.Now()+ sess, err := b.Execute(context.Background(), tc.prompt, ExecOptions{+ Cwd: dir,+ Model: "claude-opus-5-5",+ Timeout: 15 * time.Second,+ })+ if err != nil {+ t.Fatalf("Execute: %v", err)+ }+ for range sess.Messages {+ }+ res := <-sess.Result+ elapsed := time.Since(start)++ if res.Status != "failed" {+ t.Fatalf("status = %q, want failed (res=%+v)", res.Status, res)+ }+ if !strings.Contains(res.Error, tc.wantError) {+ t.Fatalf("error = %q, want substring %q", res.Error, tc.wantError)+ }+ if elapsed >= 2*time.Second {+ t.Fatalf("error result took %v (expected immediate stdin EOF exit, not 10s grace wait)", elapsed)+ }+ if pool.Len() != 0 {+ t.Fatalf("errored session was parked: pool.Len() = %d", pool.Len())+ }+ })+ }+}++func TestClaudeStreamCoalescerLeadingCoalescingAndReconciliation(t *testing.T) {+ t.Parallel()++ ch := make(chan Message, 32)+ clock := time.Unix(1_700_000_000, 0)+ c := newClaudeStreamCoalescer(ch, func() time.Time { return clock })++ sendDelta := func(after time.Duration, deltaType, key, val string) {+ clock = clock.Add(after)+ raw, _ := json.Marshal(map[string]any{+ "type": "content_block_delta",+ "index": 0,+ "delta": map[string]any{+ "type": deltaType,+ key: val,+ },+ })+ c.handleEvent(raw)+ }++ // Leading text delta flushes immediately; second waits inside 50ms window;+ // third after 50ms flushes coalesced chunk.+ sendDelta(0, "text_delta", "text", "Hello ")+ sendDelta(10*time.Millisecond, "text_delta", "text", "warm ")+ sendDelta(claudeStreamFlushInterval, "text_delta", "text", "world")+ sendDelta(5*time.Millisecond, "text_delta", "text", "!")++ // Assistant snapshot arrives with an extra trailing suffix " :)" — flush + reconcile.+ b := &claudeBackend{}+ assistantMsg := claudeSDKMessage{+ Type: "assistant",+ Message: json.RawMessage(`{"id":"m1","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"Hello warm world! :)"}]}`),+ }+ turn := b.handleAssistantWithStream(assistantMsg, ch, map[string]TokenUsage{}, map[string]struct{}{}, c)+ if turn.text != "Hello warm world! :)" {+ t.Fatalf("turn.text = %q, want full text", turn.text)+ }++ close(ch)+ var chunks []string+ for m := range ch {+ if m.Type == MessageText {+ chunks = append(chunks, m.Content)+ }+ }+ want := []string{"Hello ", "warm world", "!", " :)"}+ if !slices.Equal(chunks, want) {+ t.Fatalf("streamed chunks = %q, want %q", chunks, want)+ }+}++func TestClaudeStreamCoalescerBackwardCompatWithoutStreamEvents(t *testing.T) {+ t.Parallel()++ ch := make(chan Message, 8)+ c := newClaudeStreamCoalescer(ch, nil)+ b := &claudeBackend{}++ assistantMsg := claudeSDKMessage{+ Type: "assistant",+ Message: json.RawMessage(`{"id":"m1","role":"assistant","model":"claude-opus-5-5","content":[{"type":"thinking","thinking":"hmm"},{"type":"text","text":"final answer"}]}`),+ }+ turn := b.handleAssistantWithStream(assistantMsg, ch, map[string]TokenUsage{}, map[string]struct{}{}, c)+ if turn.text != "final answer" {+ t.Fatalf("turn.text = %q, want final answer", turn.text)+ }+ close(ch)+ var got []Message+ for m := range ch {+ got = append(got, m)+ }+ if len(got) != 2 || got[0].Type != MessageThinking || got[0].Content != "hmm" || got[1].Type != MessageText || got[1].Content != "final answer" {+ t.Fatalf("unexpected legacy assistant messages: %+v", got)+ }+}++func TestCachedDiscoveryStaleWhileRevalidate(t *testing.T) {+ // Serial test: mutates package-global cache state and clock.+ origTTL := modelCacheTTL+ origStaleTTL := modelCacheStaleTTL+ origNow := modelCacheNow+ t.Cleanup(func() {+ modelCacheMu.Lock()+ modelCacheTTL = origTTL+ modelCacheStaleTTL = origStaleTTL+ modelCacheNow = origNow+ delete(modelCache, "test-swr")+ delete(modelCacheInflight, "test-swr")+ modelCacheMu.Unlock()+ })++ var clockMu sync.Mutex+ now := time.Unix(1_700_000_000, 0)+ modelCacheTTL = 10 * time.Minute+ modelCacheStaleTTL = 20 * time.Minute+ modelCacheNow = func() time.Time {+ clockMu.Lock()+ defer clockMu.Unlock()+ return now+ }+ advance := func(d time.Duration) {+ clockMu.Lock()+ now = now.Add(d)+ clockMu.Unlock()+ }++ var calls atomic.Int32+ refreshReady := make(chan struct{})+ refreshDone := make(chan struct{})++ fn := func(ctx context.Context) (Catalog, error) {+ n := calls.Add(1)+ if n == 2 {+ <-refreshReady+ defer close(refreshDone)+ return Catalog{Models: []Model{{ID: "m-v2", Label: "V2"}}}, nil+ }+ return Catalog{Models: []Model{{ID: "m-v1", Label: "V1"}}}, nil+ }++ // 1. Cold miss populates cache synchronously.+ c1, err := cachedDiscoveryWithContext(context.Background(), "test-swr", fn)+ if err != nil || len(c1.Models) != 1 || c1.Models[0].ID != "m-v1" {+ t.Fatalf("cold miss = (%+v, %v)", c1, err)+ }+ if calls.Load() != 1 {+ t.Fatalf("calls = %d, want 1", calls.Load())+ }++ // 2. Fresh hit (at +5m) serves immediately without calling fn.+ advance(5 * time.Minute)+ c2, err := cachedDiscoveryWithContext(context.Background(), "test-swr", fn)+ if err != nil || c2.Models[0].ID != "m-v1" || calls.Load() != 1 {+ t.Fatalf("fresh hit = (%+v, %v, calls=%d)", c2, err, calls.Load())+ }++ // 3. Stale hit (at +12m) returns m-v1 immediately and triggers ONE background refresh.+ advance(7 * time.Minute)+ c3, err := cachedDiscoveryWithContext(context.Background(), "test-swr", fn)+ if err != nil || c3.Models[0].ID != "m-v1" {+ t.Fatalf("stale hit = (%+v, %v)", c3, err)+ }+ // Concurrent stale call while refresh is in flight must not spawn a second refresh.+ c4, err := cachedDiscoveryWithContext(context.Background(), "test-swr", fn)+ if err != nil || c4.Models[0].ID != "m-v1" {+ t.Fatalf("second stale hit = (%+v, %v)", c4, err)+ }+ close(refreshReady)+ select {+ case <-refreshDone:+ case <-time.After(2 * time.Second):+ t.Fatal("timed out waiting for background refresh")+ }+ if calls.Load() != 2 {+ t.Fatalf("expected single-flight background refresh (calls=2), got %d", calls.Load())+ }++ // 4. Subsequent hit observes refreshed catalog m-v2.+ c5, err := cachedDiscoveryWithContext(context.Background(), "test-swr", fn)+ if err != nil || c5.Models[0].ID != "m-v2" {+ t.Fatalf("post-refresh hit = (%+v, %v)", c5, err)+ }+}