diff --git a/docs-site/src/content/docs/ja/reference/configuration/agents.md b/docs-site/src/content/docs/ja/reference/configuration/agents.md index 2b185b81c4..964d729d73 100644 --- a/docs-site/src/content/docs/ja/reference/configuration/agents.md +++ b/docs-site/src/content/docs/ja/reference/configuration/agents.md @@ -28,13 +28,15 @@ description: マルチエージェント サーフェス、委任ガイダンス ## ロスターとガイダンス -有効な v2 ロスターは、v2 と互換性があり、挿入されたカタログに存在する、構成され、ピッカーに表示され、優先順位で並べ替えられた最初の 5 つのモデルです。 V2 の適格性は、明示的な `"v2"`、`null`、または欠落しているアップストリーム ピンを適格なものとして扱います。実際の `"v1"` ピンは除外されます。除外されたエントリは設定に残るため、後で適格になる可能性があります。 +有効な v2 ロスターは、設定済みでピッカーに表示され、優先順位で並べ替えられた最初の 5 つのモデルのうち、挿入されたカタログに存在し、明示的に `"disabled"` とされていないモデルです。明示的な `"v2"` ピンは再帰的なワーカーをサポートし、`"v1"`、`null`、ピンの省略はリーフワーカーとして引き続き適格です。除外されたエントリは設定に残るため、後で適格になる可能性があります。 表面検出はツール形状を使用します。 `send_input`、`resume_agent`、または `close_agent` を持つ名前空間付き `spawn_agent` は v1 です。 `send_message`、`followup_task`、`interrupt_agent`、または `list_agents` を備えたフラット `spawn_agent` は v2 です。 V1 ガイダンスは、`max` または `ultra` でのみプロアクティブ テキストです。 V2 は、優先モデル、適格なロスター、またはフォールバック チェーンが存在する場合にのみ、プロキシ作成の開発者メッセージを受信します。組み込みの v2 ガイダンスには 700 文字のバジェットがあり、必要に応じて最初にロスターが削除されます。ガイダンスはリプレイ プレフィックス全体で重複排除され、後続の `compaction_trigger` の前に挿入されます。 -`injectionModel` および `injectionEffort` は、ネイティブデフォルト同期が有効になっていない限り、推奨事項です。組み込みの v2 テキストは、サポートされているモデル/エフォートのオーバーライドを `fork_turns: "none"` を使用して `spawn_agent` に渡すように Codex に要求します。カスタム `injectionPrompt` は、欠落している値を空の文字列に置き換えます。 +組み込みの v2 サブエージェントガイダンスとカスタム `injectionPrompt` 本文は、どちらも `` を使用し、Codex ネイティブの `` メッセージとは区別されます。組み込みテキストは、解決済みの優先モデル、ロスター、フォールバックチェーンを示しますが、委任、モデルのオーバーライド、`fork_turns` は指示しません。カスタム本文のプレースホルダー置換と内容は維持されます。`injectionModel` および `injectionEffort` は、ネイティブデフォルト同期が有効になっていない限り推奨事項であり、カスタムプレースホルダーの欠落値は引き続き空の文字列に置き換えられます。 + +リプレイの重複排除では、タグの種類ごとに最新のテキストとの完全一致を確認します。両方の値が新しいプロキシのタグを使用する場合、カスタムガイダンスから組み込み形式へ戻すと、その時点の内容が追加されます。途中でネイティブモードが変わっても、変更のないプロキシガイダンスは重複追加されません。既存のネイティブメッセージと旧タグ付きの履歴は保持されます。ラッパーの変更によって過去のメッセージの作成者が判明したり、以前の指示が取り消されたりするわけではありません。複数バージョンが混在する履歴は、旧タグだけでは分類できず、そのような履歴での設定変更の検出は保証されません。 ## ネイティブ Codex のデフォルト同期 diff --git a/docs-site/src/content/docs/ko/reference/configuration/agents.md b/docs-site/src/content/docs/ko/reference/configuration/agents.md index 1c999536f2..104393d28a 100644 --- a/docs-site/src/content/docs/ko/reference/configuration/agents.md +++ b/docs-site/src/content/docs/ko/reference/configuration/agents.md @@ -28,13 +28,15 @@ description: 멀티 에이전트 표면, 위임 안내, 선호 모델, 대체 ## 로스터와 안내 -실제 v2 로스터는 설정되어 있고, 선택기에 보이며, 우선순위로 정렬된 상위 다섯 모델 중 v2와 호환되고 주입된 카탈로그에 존재하는 모델입니다. v2 적격성은 명시적인 `"v2"`, `null`, 또는 생략된 상위 고정값을 적격으로 보고, 실제 `"v1"` 고정값은 제외합니다. 제외된 항목은 나중에 적격이 될 수 있도록 설정에 그대로 남습니다. +실제 v2 로스터는 설정되어 있고, 선택기에 보이며, 우선순위로 정렬된 상위 다섯 모델 중 주입된 카탈로그에 존재하고 명시적으로 `"disabled"`로 표시되지 않은 모델입니다. 명시적인 `"v2"` 고정값은 재귀 작업자를 지원하며, `"v1"`, `null`, 생략된 고정값도 하위 작업을 다시 위임하지 않는 작업자로 참여할 수 있습니다. 제외된 항목은 나중에 적격이 될 수 있도록 설정에 그대로 남습니다. 표면 판별은 도구 형태를 기준으로 합니다. 네임스페이스가 붙은 `spawn_agent`에 `send_input`, `resume_agent`, `close_agent`가 있으면 v1입니다. 평평한 `spawn_agent`에 `send_message`, `followup_task`, `interrupt_agent`, `list_agents`가 있으면 v2입니다. V1 안내는 `max` 또는 `ultra`에서만 선제 텍스트로 제공됩니다. V2는 선호 모델, 적격 로스터, 대체 체인 중 하나가 있을 때만 프록시가 작성한 개발자 메시지를 받습니다. 내장 v2 안내에는 700자 예산이 있고, 필요하면 로스터를 먼저 줄입니다. 안내는 replay prefix 전반에서 중복 제거되며, 뒤에 오는 `compaction_trigger` 앞에 삽입됩니다. -`injectionModel`과 `injectionEffort`는 네이티브 기본값 동기화가 활성화되지 않으면 권고 수준입니다. 내장 v2 텍스트는 Codex에게 지원되는 모델/노력 오버라이드를 `fork_turns: "none"`과 함께 `spawn_agent`로 전달하라고 요청합니다. 사용자 지정 `injectionPrompt`는 누락된 값을 빈 문자열로 대체합니다. +내장 v2 서브에이전트 안내와 사용자 지정 `injectionPrompt` 본문은 모두 ``를 사용하며, Codex 네이티브 `` 메시지와 구분됩니다. 내장 텍스트는 결정된 선호 모델, 모델 목록, 대체 체인을 알리지만 위임, 모델 오버라이드, `fork_turns`를 지시하지는 않습니다. 사용자 지정 본문의 자리표시자 치환과 내용은 유지됩니다. `injectionModel`과 `injectionEffort`는 네이티브 기본값 동기화가 활성화되지 않으면 계속 권고 수준이며, 사용자 지정 자리표시자의 누락된 값은 빈 문자열로 대체됩니다. + +replay 중복 제거는 각 태그 계열의 가장 최근 텍스트와 정확히 일치하는지 비교합니다. 두 값 모두 새 프록시 태그 계열을 사용하는 경우, 사용자 지정 안내에서 내장 형식으로 돌아오면 현재 안내가 추가됩니다. 그 사이에 네이티브 모드가 바뀌어도 변경되지 않은 프록시 안내가 중복 추가되지는 않습니다. 기존 네이티브 메시지와 예전 태그가 붙은 이력은 보존됩니다. 래퍼 변경으로 과거 메시지의 작성자가 판별되거나 이전 지침이 철회되는 것은 아닙니다. 여러 버전이 섞인 이력은 예전 태그만으로 분류할 수 없으며, 이러한 이력에서 설정 전환이 감지된다고 보장하지 않습니다. ## Codex 기본값 동기화 diff --git a/docs-site/src/content/docs/reference/configuration/agents.md b/docs-site/src/content/docs/reference/configuration/agents.md index f3caea02f2..57e9ab7d8e 100644 --- a/docs-site/src/content/docs/reference/configuration/agents.md +++ b/docs-site/src/content/docs/reference/configuration/agents.md @@ -75,9 +75,9 @@ loudly when the installed Codex build does not know the flag yet. ## Roster and guidance The effective v2 roster is the configured, picker-visible, priority-sorted first five models that -are compatible with v2 and present in the injected catalog. V2 eligibility treats an explicit `"v2"`, -`null`, or absent upstream pin as eligible; a real `"v1"` pin is excluded. Excluded entries remain in -configuration so they can become eligible later. +are present in the injected catalog and are not explicitly marked `"disabled"`. An explicit `"v2"` +pin supports recursive workers; `"v1"`, `null`, and absent pins remain eligible as leaf workers. +Excluded entries remain in configuration so they can become eligible later. Surface detection uses tool shape. A namespaced `spawn_agent` with `send_input`, `resume_agent`, or `close_agent` is v1. A flat `spawn_agent` with `send_message`, `followup_task`, `interrupt_agent`, or @@ -88,9 +88,19 @@ message only when a preferred model, eligible roster, or fallback chain exists. has a 700-character budget and drops the roster first if necessary. Guidance is deduplicated across replay prefixes and inserted before a trailing `compaction_trigger`. -`injectionModel` and `injectionEffort` are advisory unless native-default sync is enabled. The built-in -v2 text asks Codex to pass supported model/effort overrides to `spawn_agent` with -`fork_turns: "none"`. A custom `injectionPrompt` substitutes missing values with an empty string. +Both built-in v2 subagent guidance and custom `injectionPrompt` bodies use +``, separate from Codex's native `` messages. +Built-in text reports the resolved preferred model, roster, and fallback chain without prescribing +delegation, model overrides, or `fork_turns`. Custom bodies retain their placeholder substitution +and content. `injectionModel` and `injectionEffort` remain advisory unless native-default sync is +enabled; missing custom placeholder values are still replaced with an empty string. + +Replay deduplication compares the latest exact text in each tag family. When both values use the +new proxy family, switching custom guidance back to the built-in form appends the current value; +intervening native mode changes do not duplicate unchanged proxy guidance. Existing native and +legacy-tagged history is preserved. This wrapper change does not identify the author of old +messages or revoke prior instructions. Mixed-version histories cannot be classified from the +legacy tag alone, and transition detection across such histories is not guaranteed. ## Native Codex default sync diff --git a/docs-site/src/content/docs/ru/reference/configuration/agents.md b/docs-site/src/content/docs/ru/reference/configuration/agents.md index a3a0bc434b..b33ac85841 100644 --- a/docs-site/src/content/docs/ru/reference/configuration/agents.md +++ b/docs-site/src/content/docs/ru/reference/configuration/agents.md @@ -36,10 +36,10 @@ custom prompt на этом API передаётся полем `prompt`. ## Roster и guidance Эффективный ростер v2 — это настроенные, видимые в picker'е, отсортированные по priority первые -пять моделей, совместимых с v2 и присутствующих во внедряемом каталоге. Для v2 запись считается -допустимой, если upstream pin равен `"v2"`, `null` либо вовсе отсутствует; реальный pin `"v1"` -исключает модель. Исключённые записи всё равно остаются в конфигурации, чтобы позже снова стать -допустимыми. +пять моделей, присутствующих во внедряемом каталоге и не отмеченных явно как `"disabled"`. +Явный pin `"v2"` поддерживает рекурсивных подагентов; `"v1"`, `null` и отсутствующий pin +остаются допустимыми для подагентов без дальнейшего делегирования. Исключённые записи остаются +в конфигурации, чтобы позже снова стать допустимыми. Определение surface основано на форме tool'ов. Namespaced `spawn_agent` вместе с `send_input`, `resume_agent` или `close_agent` — это v1. Плоский `spawn_agent` вместе с `send_message`, @@ -51,10 +51,22 @@ roster или fallback chain. Встроенное guidance v2 ограниче сначала удаляет roster. Guidance дедуплицируется по replay-prefix и вставляется перед завершающим `compaction_trigger`. -`injectionModel` и `injectionEffort` носят рекомендательный характер, если только не включён -native-default sync. Встроенный текст v2 просит Codex передавать поддерживаемые override'ы model -и effort в `spawn_agent` с `fork_turns: "none"`. В custom `injectionPrompt` отсутствующие значения -подставляются как пустая строка. +И встроенные указания v2 для подагентов, и пользовательские тела `injectionPrompt` используют +``, отдельно от нативных сообщений Codex ``. +Встроенный текст сообщает итоговую предпочтительную модель, список моделей и цепочку резервных +моделей, но не предписывает делегирование, переопределение модели или `fork_turns`. Подстановка +значений в плейсхолдеры и содержимое пользовательских тел сохраняются. `injectionModel` и +`injectionEffort` остаются рекомендациями, если не включена синхронизация нативных значений по +умолчанию; отсутствующие значения пользовательских плейсхолдеров заменяются пустой строкой. + +Дедупликация replay проверяет точное совпадение с последним текстом в каждой группе тегов. +Если оба значения используют новую группу тегов прокси, при возврате от пользовательских указаний +к встроенной форме добавляется её текущее содержимое; промежуточные изменения нативного режима +не дублируют неизменившиеся указания прокси. +Существующая история нативных сообщений и сообщений со старым тегом сохраняется. Изменение +обёртки не устанавливает автора старых сообщений и не отменяет прежние инструкции; историю +со смешанными версиями нельзя классифицировать только по старому тегу, и обнаружение переходов +в такой истории не гарантируется. ## Синхронизация native default'ов Codex diff --git a/docs-site/src/content/docs/zh-cn/reference/configuration/agents.md b/docs-site/src/content/docs/zh-cn/reference/configuration/agents.md index 1c8d71eeca..ec67917fd0 100644 --- a/docs-site/src/content/docs/zh-cn/reference/configuration/agents.md +++ b/docs-site/src/content/docs/zh-cn/reference/configuration/agents.md @@ -28,13 +28,15 @@ description: 多代理界面、委派引导、首选模型、回退链、原生 ## 名单与引导 -有效的 v2 名单,是已配置、在选择器中可见、按优先级排序的前五个模型中,和 v2 兼容且存在于注入目录中的那些模型。v2 资格判定会把显式的 `"v2"`、`null`,或缺失的上游固定值视为可用;真正的 `"v1"` 固定值会被排除。被排除的条目仍会保留在配置中,以便将来重新变为可用。 +有效的 v2 名单,是已配置、在选择器中可见、按优先级排序的前五个模型中,存在于注入目录且未明确标记为 `"disabled"` 的模型。显式的 `"v2"` 标记支持递归子代理;`"v1"`、`null` 和缺失的标记仍可作为叶子子代理。被排除的条目仍会保留在配置中,以便将来重新变为可用。 界面检测使用工具形状来判断。带命名空间的 `spawn_agent`,如果具有 `send_input`、`resume_agent` 或 `close_agent`,就是 v1。平铺的 `spawn_agent`,如果具有 `send_message`、`followup_task`、`interrupt_agent` 或 `list_agents`,就是 v2。 V1 引导只会在 `max` 或 `ultra` 时以主动文本形式出现。V2 只有在存在首选模型、可用名单或回退链时,才会收到代理生成的开发者消息。内置 v2 引导有 700 个字符的预算,必要时会先删减名单。引导会在 replay prefix 之间去重,并插入到末尾的 `compaction_trigger` 之前。 -除非启用了原生默认值同步,`injectionModel` 和 `injectionEffort` 都只是建议。内置 v2 文本会要求 Codex 使用 `fork_turns: "none"` 将受支持的模型/effort 覆盖传给 `spawn_agent`。自定义 `injectionPrompt` 会把缺失值替换为空字符串。 +内置 v2 子代理引导和自定义 `injectionPrompt` 正文都使用 ``,与 Codex 原生的 `` 消息区分开来。内置文本会说明解析后的首选模型、名单和回退链,但不会指示委派、模型覆盖或 `fork_turns`。自定义正文的占位符替换和内容保持不变。除非启用了原生默认值同步,`injectionModel` 和 `injectionEffort` 仍只是建议;自定义占位符的缺失值仍替换为空字符串。 + +replay 去重会分别与每类标签的最新文本进行精确比较。当两个值都使用新的代理标签时,从自定义引导切回内置形式会追加当前的引导内容;期间原生模式的变化不会导致未改变的代理引导被重复添加。现有的原生消息历史和带旧标签的历史都会保留。更换包装标签并不能确定旧消息的作者,也不会撤销先前的指令;对于混合版本的历史,不能仅凭旧标签进行分类,也不保证检测到这类历史中的设置切换。 ## Codex 原生默认值同步 diff --git a/src/server/responses/collaboration.ts b/src/server/responses/collaboration.ts index 8d8ce42e7f..e01a79cea8 100644 --- a/src/server/responses/collaboration.ts +++ b/src/server/responses/collaboration.ts @@ -241,6 +241,9 @@ export const PROACTIVE_MULTI_AGENT_MODE_TEXT = [ "This mode remains active until a later multi-agent mode developer message changes it.", ].join(" "); +const OPENCODEX_SUBAGENT_GUIDANCE_OPEN_TAG = ""; +const OPENCODEX_SUBAGENT_GUIDANCE_CLOSE_TAG = ""; + export function isV1CollabSurface(parsed: OcxParsedRequest): boolean { return collabSurface(parsed) === "v1"; } @@ -468,18 +471,15 @@ export async function multiAgentGuidanceText( // fallback only for explicit routed/account-qualified ids. const promptModel = preferred?.model ?? (injectionModel?.includes("/") ? injectionModel : undefined); - return `${applyInjectionPlaceholders(injectionPrompt, promptModel, injectionEffort, roster, fallbackGuidance)}`; + return `${OPENCODEX_SUBAGENT_GUIDANCE_OPEN_TAG}${applyInjectionPlaceholders(injectionPrompt, promptModel, injectionEffort, roster, fallbackGuidance)}${OPENCODEX_SUBAGENT_GUIDANCE_CLOSE_TAG}`; } if (!preferred && roster === "" && fallbackGuidance === "") return null; - let text = "When the active spawn_agent tool supports optional \"model\" or \"reasoning_effort\" overrides, " - + "use only models listed for this collaboration surface. " - + "When setting either override, set fork_turns to \"none\" " - + "(or a positive turn count such as \"3\"; full-history forks reject overrides) " - + "and make the task message self-contained."; + let text = "OpenCodex sub-agent routing metadata for this collaboration surface. " + + "This metadata does not override Codex delegation or model-selection rules."; if (preferred) { text += ` Preferred sub-agent: model "${preferred.model}"` + (injectionEffort ? `, reasoning_effort "${injectionEffort}"` : "") - + " — use it unless the user names another."; + + "."; } text += fallbackGuidance; text += roster; @@ -487,7 +487,7 @@ export async function multiAgentGuidanceText( // Roster is the only unbounded part — drop it before breaking the budget. text = text.slice(0, text.length - roster.length); } - return `${text}`; + return `${OPENCODEX_SUBAGENT_GUIDANCE_OPEN_TAG}${text}${OPENCODEX_SUBAGENT_GUIDANCE_CLOSE_TAG}`; } const effort = parsed.options.reasoning; @@ -544,6 +544,17 @@ function isGeneratedDeveloperItem(item: unknown, text: string): boolean { return generatedDeveloperText(item) === text; } +function generatedGuidanceFamily(text: string): "multi_agent_mode" | "opencodex_subagent_guidance" | undefined { + if (text.startsWith("") && text.endsWith("")) { + return "multi_agent_mode"; + } + if (text.startsWith(OPENCODEX_SUBAGENT_GUIDANCE_OPEN_TAG) + && text.endsWith(OPENCODEX_SUBAGENT_GUIDANCE_CLOSE_TAG)) { + return "opencodex_subagent_guidance"; + } + return undefined; +} + function isDeveloperPrefixItem(item: unknown): boolean { if (!isRecord(item)) return false; if (item.type === "additional_tools") return item.role === "developer"; @@ -583,13 +594,13 @@ export function injectDeveloperMessage(parsed: OcxParsedRequest, text: string): const devItem = { type: "message", role: "developer", content: [{ type: "input_text", text }] }; if (rawInput) { const replayPrefix = rawInput.slice(0, replayPrefixLen); - const taggedGuidance = text.startsWith("") && text.endsWith(""); - const lastTaggedGuidance = taggedGuidance + const guidanceFamily = generatedGuidanceFamily(text); + const lastTaggedGuidance = guidanceFamily ? replayPrefix.map(generatedDeveloperText) - .filter(item => item?.startsWith("") && item.endsWith("")) + .filter(item => item !== undefined && generatedGuidanceFamily(item) === guidanceFamily) .at(-1) : undefined; - if (taggedGuidance ? lastTaggedGuidance === text : replayPrefix.some(item => isGeneratedDeveloperItem(item, text))) { + if (guidanceFamily ? lastTaggedGuidance === text : replayPrefix.some(item => isGeneratedDeveloperItem(item, text))) { return; } } diff --git a/src/types/config.ts b/src/types/config.ts index 017d01a94a..0b0a2b2b98 100644 --- a/src/types/config.ts +++ b/src/types/config.ts @@ -469,8 +469,8 @@ export interface OcxConfig { */ syncCodexSubagentDefaults?: boolean; /** - * Optional reasoning effort the delegation prompt tells the agent to pass in spawn_agent calls - * (`reasoning_effort` argument). Only meaningful while `injectionModel` is set; validated against + * Optional reasoning effort reported as advisory metadata in v2 sub-agent guidance. + * It does not prescribe spawn overrides. Only meaningful while `injectionModel` is set; validated against * the Codex ladder (src/reasoning-effort.ts CODEX_REASONING_LEVELS) at the API boundary. */ injectionEffort?: string; @@ -513,7 +513,7 @@ export interface OcxConfig { streamMode?: "auto" | "legacy-tee" | "eager-relay"; /** * Custom override for the injected v2 multi-agent guidance body (the text inside - * the tags). After guidance is enabled and the v2 surface and + * the tags). After guidance is enabled and the v2 surface and * catalog-state gates pass, a configured injectionModel is sufficient to render it; * otherwise an eligible roster or fallback is required. Placeholders: `{{model}}` -> the * effective preferred model for the request (a bare native model is account-qualified diff --git a/tests/codex-integration/multi-agent-compat.test.ts b/tests/codex-integration/multi-agent-compat.test.ts index 9430ab657a..6b3d1374b2 100644 --- a/tests/codex-integration/multi-agent-compat.test.ts +++ b/tests/codex-integration/multi-agent-compat.test.ts @@ -267,7 +267,7 @@ describe("multiAgentGuidanceText", () => { } }); - test("v2 built-in guidance is schema-agnostic and keeps fork rules", async () => { + test("v2 built-in guidance reports routing metadata without replacing native delegation rules", async () => { const dir = codexHomeFixture(V2_ON); catalogFixture(dir, [{ slug: "anthropic/claude-sonnet-5", @@ -279,10 +279,13 @@ describe("multiAgentGuidanceText", () => { { injectionModel: "anthropic/claude-sonnet-5" }, ); - expect(text).toContain("When the active spawn_agent tool supports optional"); - expect(text).toContain("use only models listed for this collaboration surface"); - expect(text).toContain("fork_turns"); - expect(text).toContain('"none"'); + expect(text).toStartWith(""); + expect(text).toEndWith(""); + expect(text).toContain("OpenCodex sub-agent routing metadata"); + expect(text).toContain("does not override Codex delegation or model-selection rules"); + expect(text).not.toContain("fork_turns"); + expect(text).not.toContain("use it unless"); + expect(text).not.toContain(""); expect(text).not.toMatch(/hidden/i); expect(text).not.toMatch(/not in the schema/i); expect(text).not.toMatch(/never claim/i); @@ -384,7 +387,7 @@ describe("multiAgentGuidanceText", () => { injectionPrompt: "Use {{model}}.", }, ); - expect(custom).toBe('Use team/gpt-5.6-sol.'); + expect(custom).toBe('Use team/gpt-5.6-sol.'); const exactBare = await multiAgentGuidanceText( parsedFixture({ tools: [{ name: "spawn_agent" }] }), @@ -403,7 +406,7 @@ describe("multiAgentGuidanceText", () => { injectionPrompt: "Use {{model}}.", }, ); - expect(exactBareCustom).toBe("Use local-fast."); + expect(exactBareCustom).toBe("Use local-fast."); const bareParent = await multiAgentGuidanceText( parsedFixture({ tools: [{ name: "spawn_agent" }] }), @@ -449,7 +452,7 @@ describe("multiAgentGuidanceText", () => { injectionPrompt: "Use {{model}}.", }, ); - expect(ambiguousCustom).toBe("Use ."); + expect(ambiguousCustom).toBe("Use ."); expect(ambiguousCustom).not.toContain("gpt-5.6-sol"); }); @@ -508,7 +511,7 @@ describe("multiAgentGuidanceText", () => { injectionModel: "gpt-5.6-sol", injectionPrompt: "Use {{model}}.", }, - )).toBe("Use ."); + )).toBe("Use ."); }); test("effective roster applies alias, visibility, v2 compatibility, stable priority, cap, and diagnostics", async () => { @@ -612,7 +615,7 @@ describe("multiAgentGuidanceText", () => { { injectionModel: "anthropic/claude-sonnet-5" }, ); expect(text).toContain('"anthropic/claude-sonnet-5"'); - expect(text).toContain("fork_turns"); + expect(text).toContain("OpenCodex sub-agent routing metadata"); expect(text).not.toContain("Proactive multi-agent delegation is active"); // and WITHOUT an injectionModel it stays silent (codex-rs owns the v2 Proactive text) expect(await multiAgentGuidanceText(parsedFixture({ reasoning: "ultra", tools: nativeV2 }))).toBeNull(); @@ -654,7 +657,7 @@ describe("multiAgentGuidanceText", () => { injectionEffort: "xhigh", subagentModels: ["gpt-5.6-terra"], }); - expect(text).toContain("When the active spawn_agent tool supports optional"); + expect(text).toContain("OpenCodex sub-agent routing metadata"); expect(text).not.toMatch(/hidden|not in the schema|never claim/i); expect(text).toContain('(reasoning_effort high/max/ultra): "gpt-5.6-terra"'); }); @@ -738,8 +741,8 @@ describe("multiAgentGuidanceText", () => { // gpt-5.6-luna carries upstream's "v1" pin, which is now an eligible LEAF worker // (codex-rs 6d4d9442c), so it joins the substituted roster. expect(text).toBe( - 'CUSTOM model=raw/preferred-model effort=max' - + ' Available models (reasoning_effort high/max): "gpt-5.6-terra", "gpt-5.6-luna".', + 'CUSTOM model=raw/preferred-model effort=max' + + ' Available models (reasoning_effort high/max): "gpt-5.6-terra", "gpt-5.6-luna".', ); }); @@ -778,14 +781,14 @@ describe("multiAgentGuidanceText", () => { expect(await multiAgentGuidanceText(parsedFixture({ reasoning: "medium", tools: v2Tools }))).toBeNull(); }); - test("v2 surface + roster alone (no injectionModel) fires with the argument-acceptance preamble", async () => { + test("v2 surface + roster alone (no injectionModel) reports routing metadata", async () => { const dir = codexHomeFixture(V2_ON); catalogFixture(dir, [{ slug: "gpt-5.6-terra", efforts: ["high", "max", "ultra"] }]); const text = await multiAgentGuidanceText( parsedFixture({ reasoning: "medium", tools: [{ name: "spawn_agent" }] }), { subagentModels: ["gpt-5.6-terra"] }, ); - expect(text).toContain("When the active spawn_agent tool supports optional"); + expect(text).toContain("OpenCodex sub-agent routing metadata"); expect(text).not.toMatch(/hidden|not in the schema|never claim/i); expect(text).toContain('(reasoning_effort high/max/ultra): "gpt-5.6-terra"'); expect(text).not.toContain("Preferred sub-agent"); @@ -861,7 +864,7 @@ describe("multiAgentGuidanceText", () => { subagentModels: ["gpt-5.5", "opencode-go/glm-5.2", "anthropic/claude-opus-4-6", "gpt-5.6-sol", "gpt-5.6-terra"], }, ); - const body = text!.replace(/^/, "").replace(/<\/multi_agent_mode>$/, ""); + const body = text!.replace(/^/, "").replace(/<\/opencodex_subagent_guidance>$/, ""); expect(body.length).toBeLessThanOrEqual(700); expect(body).toContain("Available models"); // roster fits inside the budget }); @@ -1182,6 +1185,96 @@ describe("injectDeveloperMessage", () => { expect((replay._rawBody as { input: unknown[] }).input.at(-1)).toEqual(generatedItem(guidanceA)); }); + test("proxy guidance dedup records a metadata A-B-A transition", () => { + const metadataA = "A"; + const metadataB = "B"; + const current = { type: "message", role: "user", content: "current turn" }; + const rawInput = [generatedItem(metadataA), generatedItem(metadataB), current]; + const parsed = parseRequest({ model: "gpt-5.5", input: rawInput, previous_response_id: "resp_1" }); + parsed._replayPrefixLen = 2; + parsed._continuationConversationMessageIndex = 2; + + injectDeveloperMessage(parsed, metadataA); + + expect(rawInput).toEqual([generatedItem(metadataA), generatedItem(metadataB), generatedItem(metadataA), current]); + expect(parsed.context.messages.map(message => message.content)).toEqual([metadataA, metadataB, metadataA, "current turn"]); + }); + + test("proxy guidance dedup preserves intervening native mode changes", () => { + const nativeA = "Native policy A"; + const nativeB = "Native policy B"; + const metadata = "Routing metadata"; + const rawInput = [generatedItem(nativeA), generatedItem(metadata), generatedItem(nativeB), { role: "user", content: "work" }]; + const before = structuredClone(rawInput); + const parsed = parseRequest({ model: "gpt-5.5", input: rawInput }); + parsed._replayPrefixLen = 3; + + injectDeveloperMessage(parsed, metadata); + + expect(rawInput).toEqual(before); + expect(parsed.context.messages.map(message => message.content)).toEqual([nativeA, metadata, nativeB, "work"]); + }); + + test("native mode dedup ignores later proxy guidance", () => { + const native = "Native policy"; + const metadata = "Routing metadata"; + const rawInput = [generatedItem(native), generatedItem(metadata), { role: "user", content: "work" }]; + const before = structuredClone(rawInput); + const parsed = parseRequest({ model: "gpt-5.5", input: rawInput }); + parsed._replayPrefixLen = 2; + + injectDeveloperMessage(parsed, native); + + expect(rawInput).toEqual(before); + expect(countExact(rawInput, native)).toBe(1); + }); + + test("restores default v2 guidance after a custom prompt without changing the custom body", async () => { + const dir = codexHomeFixture(V2_ON); + catalogFixture(dir, [{ slug: "gpt-5.6-terra", efforts: ["high", "max"], multiAgentVersion: "v2" }]); + const fixture = parsedFixture({ tools: [{ name: "spawn_agent" }] }); + const options = { injectionModel: "gpt-5.6-terra", injectionEffort: "high" }; + const metadata = await multiAgentGuidanceText(fixture, options); + const custom = await multiAgentGuidanceText(fixture, { + ...options, + injectionPrompt: "Custom {{model}} effort={{effort}}\nKeep {{unknown}}.", + }); + expect(metadata).not.toBeNull(); + const current = { type: "message", role: "user", content: "current turn" }; + const rawInput = [generatedItem(metadata!), generatedItem(custom!), current]; + const parsed = parseRequest({ model: "gpt-5.5", input: rawInput, previous_response_id: "resp_1" }); + parsed._replayPrefixLen = 2; + parsed._continuationConversationMessageIndex = 2; + + injectDeveloperMessage(parsed, (await multiAgentGuidanceText(fixture, options))!); + + expect(rawInput).toEqual([generatedItem(metadata!), generatedItem(custom!), generatedItem(metadata!), current]); + expect(parsed.context.messages.map(message => message.content)).toEqual([metadata, custom, metadata, "current turn"]); + expect(custom).toBe("Custom gpt-5.6-terra effort=high\nKeep {{unknown}}."); + }); + + const legacyBuiltIn = 'When the active spawn_agent tool supports optional "model" or "reasoning_effort" overrides, ' + + 'use only models listed for this collaboration surface. When setting either override, set fork_turns to "none" ' + + '(or a positive turn count such as "3"; full-history forks reject overrides) and make the task message self-contained.' + + ' Preferred sub-agent: model "gpt-5.6-terra", reasoning_effort "high" — use it unless the user names another.'; + test.each([ + ["built-in", legacyBuiltIn], + ["custom", "Operator-authored legacy prompt."], + ])("preserves legacy %s and native policy when first injecting new proxy guidance", (_kind, legacy) => { + const native = "Native delegation policy"; + const metadata = "Routing metadata"; + const current = { type: "message", role: "user", content: "work" }; + const prefix = [generatedItem(legacy), generatedItem(native)]; + const rawInput = [...prefix, current]; + const parsed = parseRequest({ model: "gpt-5.5", input: rawInput }); + parsed._replayPrefixLen = prefix.length; + + injectDeveloperMessage(parsed, metadata); + + expect(rawInput).toEqual([...prefix, generatedItem(metadata), current]); + expect(parsed.context.messages.map(message => message.content)).toEqual([legacy, native, metadata, "work"]); + }); + test("exact-guidance predicate rejects every near-match replay-prefix shape (#326)", () => { const nearMatches: Array<[string, unknown]> = [ ["non-record item", null],