diff --git a/mobile/src/i18n/locales/de.json b/mobile/src/i18n/locales/de.json index f7973bca202..bbf7fb820a2 100644 --- a/mobile/src/i18n/locales/de.json +++ b/mobile/src/i18n/locales/de.json @@ -2041,6 +2041,8 @@ "managedAccountEnvOverride": "Dieser Claude-Start legt eigene Variablen für die Anthropic-Anmeldung fest. Diese entfernen, um ein verwaltetes Claude-Konto zu verwenden.", "managedAccountUnsupported": "Auch wenn in WSL ein Claude-Konto hinzugefügt wurde, benötigen Claude-Chats ein Claude-Konto unter Windows.", "modelUnavailable": "{{agent}} konnte {{detail}} nicht verwenden. Ein anderes Modell auswählen und erneut senden.", + "modelUnavailableUpdate": "{{agent}} konnte {{detail}} nicht verwenden. {{agent}} auf {{minimumVersion}} oder neuer aktualisieren, damit es nach einem Neustart erhalten bleibt, oder ein anderes Modell auswählen und erneut senden.", + "modelNotSelected": "{{agent}} hat kein Modell ausgewählt. Modellauswahl und {{agent}}-Anmeldung prüfen und erneut senden.", "noTurnToStop": "{{agent}} hatte keinen laufenden Durchgang, der gestoppt werden konnte.", "notDelivered": "Diese Nachricht wurde nicht zugestellt.", "notDeliveredSendAgain": "Diese Nachricht wurde nicht zugestellt. Zum Fortfahren erneut senden.", diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index 4eb7f314ba7..8551f5ec093 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -2547,6 +2547,8 @@ "providerExitedAnswer": "{{agent}} has stopped, so your answer was not sent. Send a message to continue.", "claudeEffortInvalid": "Claude effort is invalid; choose low, medium, high, xhigh, or max and send again.", "modelUnavailable": "{{agent}} couldn't use {{detail}}. Pick another model and send again.", + "modelUnavailableUpdate": "{{agent}} couldn't use {{detail}}. Update {{agent}} to {{minimumVersion}} or later to keep it after a restart, or pick another model and send again.", + "modelNotSelected": "{{agent}} has no model selected. Check your model selection and {{agent}} sign-in, then send again.", "providerRejected": "{{agent}} didn't accept this message.", "providerRejectedQuoted": "{{agent}} didn't accept this message: {{detail}}.", "attachmentEmpty": "An image on this message is empty, so the message was not sent.", diff --git a/mobile/src/i18n/locales/es.json b/mobile/src/i18n/locales/es.json index 2a8a23d00ad..fad62145526 100644 --- a/mobile/src/i18n/locales/es.json +++ b/mobile/src/i18n/locales/es.json @@ -2115,6 +2115,8 @@ "managedAccountEnvOverride": "Este inicio de Claude define sus propias variables de inicio de sesión de Anthropic. Quítelas para usar una cuenta de Claude administrada.", "managedAccountUnsupported": "Mientras haya una cuenta de Claude agregada en WSL, los chats de Claude necesitan una cuenta de Claude de Windows.", "modelUnavailable": "{{agent}} no pudo usar {{detail}}. Elige otro modelo y vuelve a enviar el mensaje.", + "modelUnavailableUpdate": "{{agent}} no pudo usar {{detail}}. Actualiza {{agent}} a {{minimumVersion}} o posterior para conservarlo tras un reinicio, o elige otro modelo y vuelve a enviar el mensaje.", + "modelNotSelected": "{{agent}} no tiene ningún modelo seleccionado. Revisa la selección de modelo y el inicio de sesión de {{agent}}, y vuelve a enviar el mensaje.", "noTurnToStop": "{{agent}} no tenía ningún turno en curso que detener.", "notDelivered": "Este mensaje no se entregó.", "notDeliveredSendAgain": "Este mensaje no se entregó. Vuelva a enviarlo para continuar.", diff --git a/mobile/src/i18n/locales/fr.json b/mobile/src/i18n/locales/fr.json index e09d9ccb143..a5a4116c898 100644 --- a/mobile/src/i18n/locales/fr.json +++ b/mobile/src/i18n/locales/fr.json @@ -2116,6 +2116,8 @@ "managedAccountEnvOverride": "Ce lancement de Claude définit ses propres variables de connexion Anthropic. Supprimez-les pour utiliser un compte Claude géré.", "managedAccountUnsupported": "Un compte Claude a été ajouté dans WSL, mais les chats Claude nécessitent un compte Claude sous Windows.", "modelUnavailable": "{{agent}} n'a pas pu utiliser {{detail}}. Choisissez un autre modèle, puis renvoyez le message.", + "modelUnavailableUpdate": "{{agent}} n'a pas pu utiliser {{detail}}. Mettez à jour {{agent}} vers {{minimumVersion}} ou une version ultérieure pour le conserver après un redémarrage, ou choisissez un autre modèle, puis renvoyez le message.", + "modelNotSelected": "{{agent}} n'a aucun modèle sélectionné. Vérifiez la sélection du modèle et la connexion à {{agent}}, puis renvoyez le message.", "noTurnToStop": "{{agent}} n'avait aucun tour en cours à arrêter.", "notDelivered": "Ce message n'a pas été remis.", "notDeliveredSendAgain": "Ce message n'a pas été remis. Renvoyez-le pour continuer.", diff --git a/mobile/src/i18n/locales/ja.json b/mobile/src/i18n/locales/ja.json index 049b4bb1bab..cc6fbf9a55b 100644 --- a/mobile/src/i18n/locales/ja.json +++ b/mobile/src/i18n/locales/ja.json @@ -2045,6 +2045,8 @@ "managedAccountEnvOverride": "この Claude の起動では独自の Anthropic サインイン変数が設定されています。管理対象の Claude アカウントを使用するには、それらを削除してください。", "managedAccountUnsupported": "WSL に Claude アカウントが追加されていますが、Claude チャットには Windows の Claude アカウントが必要です。", "modelUnavailable": "{{agent}} は {{detail}} を使用できませんでした。別のモデルを選択して、もう一度送信してください。", + "modelUnavailableUpdate": "{{agent}} は {{detail}} を使用できませんでした。再起動後も維持するには {{agent}} を {{minimumVersion}} 以降に更新するか、別のモデルを選択して、もう一度送信してください。", + "modelNotSelected": "{{agent}} でモデルが選択されていません。モデルの選択と {{agent}} のサインインを確認して、もう一度送信してください。", "noTurnToStop": "{{agent}} には停止できる実行中のターンがありませんでした。", "notDelivered": "このメッセージは配信されませんでした。", "notDeliveredSendAgain": "このメッセージは配信されませんでした。続けるには、もう一度送信してください。", diff --git a/mobile/src/i18n/locales/ko.json b/mobile/src/i18n/locales/ko.json index b9a8fa2f3c5..3f71803143b 100644 --- a/mobile/src/i18n/locales/ko.json +++ b/mobile/src/i18n/locales/ko.json @@ -2045,6 +2045,8 @@ "managedAccountEnvOverride": "이 Claude 실행은 자체 Anthropic 로그인 변수를 설정합니다. 관리되는 Claude 계정을 사용하려면 해당 변수를 제거하세요.", "managedAccountUnsupported": "WSL에 Claude 계정이 추가되어 있는 동안에는 Claude 채팅에 Windows Claude 계정이 필요합니다.", "modelUnavailable": "{{agent}}이(가) {{detail}}을(를) 사용하지 못했습니다. 다른 모델을 선택하고 다시 보내세요.", + "modelUnavailableUpdate": "{{agent}}이(가) {{detail}}을(를) 사용하지 못했습니다. 다시 시작한 후에도 유지하려면 {{agent}}을(를) {{minimumVersion}} 이상으로 업데이트하거나, 다른 모델을 선택하고 다시 보내세요.", + "modelNotSelected": "{{agent}}에 선택된 모델이 없습니다. 모델 선택과 {{agent}} 로그인을 확인한 후 다시 보내세요.", "noTurnToStop": "{{agent}}에 중지할 실행 중인 턴이 없었습니다.", "notDelivered": "이 메시지는 전달되지 않았습니다.", "notDeliveredSendAgain": "이 메시지는 전달되지 않았습니다. 계속하려면 다시 보내세요.", diff --git a/mobile/src/i18n/locales/pt.json b/mobile/src/i18n/locales/pt.json index 57399510ac8..2550d2a52d3 100644 --- a/mobile/src/i18n/locales/pt.json +++ b/mobile/src/i18n/locales/pt.json @@ -2107,6 +2107,8 @@ "managedAccountEnvOverride": "Esta inicialização do Claude define suas próprias variáveis de login da Anthropic. Remova-as para usar uma conta gerenciada do Claude.", "managedAccountUnsupported": "Embora uma conta do Claude tenha sido adicionada no WSL, os chats do Claude precisam de uma conta do Claude no Windows.", "modelUnavailable": "{{agent}} não conseguiu usar {{detail}}. Selecione outro modelo e envie novamente.", + "modelUnavailableUpdate": "{{agent}} não conseguiu usar {{detail}}. Atualize o {{agent}} para {{minimumVersion}} ou posterior para mantê-lo após reiniciar, ou selecione outro modelo e envie novamente.", + "modelNotSelected": "{{agent}} não tem nenhum modelo selecionado. Verifique a seleção de modelo e o login do {{agent}} e envie novamente.", "noTurnToStop": "{{agent}} não tinha nenhuma interação em andamento para interromper.", "notDelivered": "Esta mensagem não foi entregue.", "notDeliveredSendAgain": "Esta mensagem não foi entregue. Envie-a novamente para continuar.", diff --git a/mobile/src/i18n/locales/ru.json b/mobile/src/i18n/locales/ru.json index 938242d3be9..71794e16172 100644 --- a/mobile/src/i18n/locales/ru.json +++ b/mobile/src/i18n/locales/ru.json @@ -2173,6 +2173,8 @@ "managedAccountEnvOverride": "При этом запуске Claude используются собственные переменные окружения для входа в Anthropic. Удалите их, чтобы использовать управляемую учётную запись Claude.", "managedAccountUnsupported": "Хотя учётная запись Claude добавлена в WSL, для чатов Claude нужна учётная запись Claude в Windows.", "modelUnavailable": "{{agent}} не смог использовать {{detail}}. Выберите другую модель и отправьте сообщение снова.", + "modelUnavailableUpdate": "{{agent}} не смог использовать {{detail}}. Обновите {{agent}} до {{minimumVersion}} или новее, чтобы сохранить его после перезапуска, или выберите другую модель и отправьте сообщение снова.", + "modelNotSelected": "У {{agent}} не выбрана модель. Проверьте выбор модели и вход в {{agent}}, затем отправьте сообщение снова.", "noTurnToStop": "{{agent}} сейчас не выполняет задачу, которую можно остановить.", "notDelivered": "Это сообщение не доставлено.", "notDeliveredSendAgain": "Это сообщение не доставлено. Отправьте его снова, чтобы продолжить.", diff --git a/mobile/src/i18n/locales/tr.json b/mobile/src/i18n/locales/tr.json index a0538c725eb..4383a4366f3 100644 --- a/mobile/src/i18n/locales/tr.json +++ b/mobile/src/i18n/locales/tr.json @@ -2041,6 +2041,8 @@ "managedAccountEnvOverride": "Bu Claude başlatma işlemi kendi Anthropic oturum değişkenlerini tanımlıyor. Yönetilen bir Claude hesabını kullanmak için bunları kaldırın.", "managedAccountUnsupported": "WSL'de bir Claude hesabı eklenmiş olsa da Claude sohbetleri Windows'ta bir Claude hesabı gerektirir.", "modelUnavailable": "{{agent}}, {{detail}} modelini kullanamadı. Başka bir model seçip yeniden gönderin.", + "modelUnavailableUpdate": "{{agent}}, {{detail}} modelini kullanamadı. Yeniden başlatmadan sonra korumak için {{agent}} uygulamasını {{minimumVersion}} veya üzerine güncelleyin ya da başka bir model seçip yeniden gönderin.", + "modelNotSelected": "{{agent}} için seçili bir model yok. Model seçimini ve {{agent}} oturumunu kontrol edip yeniden gönderin.", "noTurnToStop": "{{agent}} için durdurulacak bir tur çalışmıyordu.", "notDelivered": "Bu mesaj iletilmedi.", "notDeliveredSendAgain": "Bu mesaj iletilmedi. Devam etmek için yeniden gönderin.", diff --git a/mobile/src/i18n/locales/zh-Hant.json b/mobile/src/i18n/locales/zh-Hant.json index 525359fb1af..1ecc7416281 100644 --- a/mobile/src/i18n/locales/zh-Hant.json +++ b/mobile/src/i18n/locales/zh-Hant.json @@ -2037,6 +2037,8 @@ "managedAccountEnvOverride": "此次 Claude 啟動設定了自己的 Anthropic 登入變數。請移除這些變數以使用受管理的 Claude 帳戶。", "managedAccountUnsupported": "雖然已在 WSL 中新增 Claude 帳戶,Claude 聊天仍需要 Windows Claude 帳戶。", "modelUnavailable": "{{agent}} 無法使用 {{detail}}。請選擇其他模型並重新傳送。", + "modelUnavailableUpdate": "{{agent}} 無法使用 {{detail}}。請將 {{agent}} 更新到 {{minimumVersion}} 或更新版本,以便重新啟動後繼續使用;或選擇其他模型並重新傳送。", + "modelNotSelected": "{{agent}} 沒有選擇模型。請檢查模型選擇和 {{agent}} 登入狀態,然後重新傳送。", "noTurnToStop": "{{agent}} 沒有正在執行的輪次可停止。", "notDelivered": "此訊息未送達。", "notDeliveredSendAgain": "此訊息未送達。請重新傳送以繼續。", diff --git a/mobile/src/i18n/locales/zh.json b/mobile/src/i18n/locales/zh.json index 582c3abeb4f..a56db21f453 100644 --- a/mobile/src/i18n/locales/zh.json +++ b/mobile/src/i18n/locales/zh.json @@ -2045,6 +2045,8 @@ "managedAccountEnvOverride": "此次 Claude 启动设置了自己的 Anthropic 登录变量。请移除这些变量以使用受管理的 Claude 账户。", "managedAccountUnsupported": "虽然已在 WSL 中添加 Claude 账户,但 Claude 聊天仍需使用 Windows 中的 Claude 账户。", "modelUnavailable": "{{agent}} 无法使用 {{detail}}。请选择其他模型并重新发送。", + "modelUnavailableUpdate": "{{agent}} 无法使用 {{detail}}。请将 {{agent}} 更新到 {{minimumVersion}} 或更高版本,以便重启后继续使用;或者选择其他模型并重新发送。", + "modelNotSelected": "{{agent}} 没有选择模型。请检查模型选择和 {{agent}} 登录状态,然后重新发送。", "noTurnToStop": "{{agent}} 没有正在运行的轮次可停止。", "notDelivered": "此消息未送达。", "notDeliveredSendAgain": "此消息未送达。请重新发送以继续。", diff --git a/mobile/src/session/agent-session-failure-copy.test.ts b/mobile/src/session/agent-session-failure-copy.test.ts index 3bb50d21b30..13d469e14f9 100644 --- a/mobile/src/session/agent-session-failure-copy.test.ts +++ b/mobile/src/session/agent-session-failure-copy.test.ts @@ -1,7 +1,12 @@ -import { expect, it } from 'vitest' +import { afterEach, expect, it } from 'vitest' import { agentSessionFailureSentence } from '../../../src/shared/agent-session/failures/agent-session-failure-words' +import { activateMobileUiLocale } from '../i18n/mobile-i18n' import { sayMobileAgentSessionFailure } from './agent-session-failure-copy' +afterEach(async () => { + await activateMobileUiLocale('en') +}) + it('gives new-chat guidance while keeping a missing conversation diagnostic private', () => { expect( agentSessionFailureSentence( @@ -15,3 +20,36 @@ it('gives new-chat guidance while keeping a missing conversation diagnostic priv ) ).toBe("Claude couldn't find this chat's saved conversation. Start a new chat to continue.") }) + +it.each([ + [ + 'en', + 'OMP has no model selected. Check your model selection and OMP sign-in, then send again.', + "OMP couldn't use @worker_be. Update OMP to 18.1.9 or later to keep it after a restart, or pick another model and send again." + ], + [ + 'de', + 'OMP hat kein Modell ausgewählt. Modellauswahl und OMP-Anmeldung prüfen und erneut senden.', + expect.stringContaining('OMP auf 18.1.9 oder neuer aktualisieren') + ] +] as const)( + 'words a missing OMP model and the update hint on the phone (%s)', + async (locale, none, update) => { + await activateMobileUiLocale(locale) + const say = (fact: Parameters[0]) => + agentSessionFailureSentence( + fact, + 'rejection', + { agentName: 'OMP' }, + sayMobileAgentSessionFailure + ) + expect(say({ kind: 'modelNotSelected' })).toBe(none) + expect( + say({ + kind: 'modelUnavailable', + detail: { text: '@worker_be', audience: 'log' }, + agentUpdate: '18.1.9' + }) + ).toEqual(update) + } +) diff --git a/mobile/src/session/agent-session-send-failure-copy.ts b/mobile/src/session/agent-session-send-failure-copy.ts index 66d1d44b90c..1564774d712 100644 --- a/mobile/src/session/agent-session-send-failure-copy.ts +++ b/mobile/src/session/agent-session-send-failure-copy.ts @@ -41,6 +41,18 @@ export const SEND_FAILURE_COPY = { "{{agent}} couldn't use {{detail}}. Pick another model and send again.", values ), + modelNotSelected: (values) => + translate( + 'session.failure.modelNotSelected', + '{{agent}} has no model selected. Check your model selection and {{agent}} sign-in, then send again.', + values + ), + modelUnavailableUpdate: (values) => + translate( + 'session.failure.modelUnavailableUpdate', + "{{agent}} couldn't use {{detail}}. Update {{agent}} to {{minimumVersion}} or later to keep it after a restart, or pick another model and send again.", + values + ), providerRejected: (values) => translate('session.failure.providerRejected', "{{agent}} didn't accept this message.", values), providerRejectedQuoted: (values) => diff --git a/src/cli/specs/agent-launch.ts b/src/cli/specs/agent-launch.ts index 092db3ca542..ac1ef1870ff 100644 --- a/src/cli/specs/agent-launch.ts +++ b/src/cli/specs/agent-launch.ts @@ -22,7 +22,7 @@ export const AGENT_LAUNCH_COMMAND_SPECS: CommandSpec[] = [ 'Starts the agent the way a new agent tab does: as a chat when your Chat | CLI choice for the agent is Chat and the agent and host support it, otherwise as a terminal. The result says which (`outcome.kind`) and why (`receipt.detail`).', '--surface chat|terminal picks for this launch instead of your setting. --surface terminal always runs the agent CLI; --surface chat is refused when Orca can establish before starting anything that this agent cannot open as a chat there. If support cannot be checked, the launch can fall back to a terminal. If chat becomes unavailable after creating a workspace, Orca keeps the workspace, setup and default tabs, then opens a terminal; the receipt explains the fallback.', '--worktree defaults to the native folder workspace or worktree containing the current directory. For a new checkout with its agent, use `orca worktree create --agent`.', - '--model takes a provider model id and --effort a reasoning effort for that model; --effort requires --model. They apply to either surface.', + '--model takes a provider model id (OMP also takes its model roles and selectors) and --effort a reasoning effort for that model; --effort requires --model. They apply to either surface.', 'The tab opens without switching focus; pass --focus to switch to it.', 'If the launch reply is lost, re-issue the same command from the same directory on the same host with --retry-launch from the error. Never retry as a fresh launch; older hosts require inspecting the workspace first.' ], diff --git a/src/cli/specs/orchestration-worker-specs.ts b/src/cli/specs/orchestration-worker-specs.ts index a3f03163344..b4f7dfc12f5 100644 --- a/src/cli/specs/orchestration-worker-specs.ts +++ b/src/cli/specs/orchestration-worker-specs.ts @@ -41,7 +41,7 @@ export const ORCHESTRATION_WORKER_COMMAND_SPECS: CommandSpec[] = [ "Reusing a settled worker's terminal with --terminal before its autoReleaseAt cancels that automatic release; after it, the start is refused while the release runs.", 'A terminal the user kept open takes --terminal work and stays kept open.', '--agent takes an Orca agent id enabled on the worker server, such as claude, codex, cursor, antigravity, muse, zcode, opencode, or opencode2.', - '--model supports Claude, Codex, Cursor, Antigravity, Grok, and Muse opaque provider model ids; --effort requires --model. OMP accepts --model only; --effort is unsupported. Neither can combine with --terminal. OpenCode model selection requires an existing worktree, a verified execution-host CLI, and an available model; effort is unsupported. Other agents, including zcode, launch with the model from their own config.', + '--model supports Claude, Codex, Cursor, Antigravity, Grok, and Muse opaque provider model ids; --effort requires --model. OMP also takes its model roles and selectors (such as @worker or provider/model:level), with --effort as its thinking level. Neither can combine with --terminal. OpenCode model selection requires an existing worktree, a verified execution-host CLI, and an available model; effort is unsupported. Other agents, including zcode, launch with the model from their own config.', 'Finished workers close on their own unless started with --keep-open; a worker started in a new worktree (new-child or new-top-level) is kept open, so release it when no one will use its chat.', 'New worktrees use agent-first creation and default --setup to run. Repository start-immediately runs setup beside the agent; wait-for-setup gates agent readiness and task input.', 'New worktrees without --name get the name Orca gives an unnamed workspace; the receipt names it. Servers older than this change still require --name.', diff --git a/src/main/acp/acp-dialects/acp-dialect.ts b/src/main/acp/acp-dialects/acp-dialect.ts index 9b636f44c83..804b0ab02a2 100644 --- a/src/main/acp/acp-dialects/acp-dialect.ts +++ b/src/main/acp/acp-dialects/acp-dialect.ts @@ -75,6 +75,8 @@ export type AcpTurnEnding = { durationMs?: number failureDetail?: string notSignedIn?: boolean + /** The agent had no model for the prompt; why (selection or sign-in) is unknown. */ + modelNotSelected?: boolean usageLimit?: AgentSessionUsageLimit /** Structured error data shows the model provider failed; runtime only. */ providerFailure?: boolean @@ -84,6 +86,11 @@ export type AcpTurnEnding = { /** Undefined means a normally ended /compact succeeded. */ export type AcpCompactionReply = { outcome: 'skipped' | 'failed'; detail: string } +/** What the agent's own model command reported: the model it now runs, or why it refused. */ +export type AcpModelCommandReply = + | { applied: string } + | { refused: 'notSignedIn' | 'modelUnavailable'; detail: string } + /** Hooks interpret extensions; lifecycle and row identity stay shared. */ export type AcpDialect = { /** Effort replaces part of the native composite model selection. */ @@ -145,6 +152,17 @@ export type AcpDialect = { hookBlock?(meta: unknown): AcpHookBlock | undefined failedTurnText?(stopReason: string): string compactionReply?(text: string): AcpCompactionReply | undefined + /** The agent's own model command resolves selections its model option cannot name. */ + modelCommand?: { + /** Only the model option's own "unknown model" refusal sends the value to the command. */ + refusedByOption(error: AcpAgentError): boolean + /** The prompt failed because no model resolved, not because the agent is signed out. */ + noModel(error: AcpAgentError): boolean + /** The first release whose command resolves what its option refuses; older ones take ids only. */ + resolvesSelectorsFrom: string + text(value: string): string + reply(text: string): AcpModelCommandReply + } /** Hide these commands and reject command-only prompts before dispatch. */ withheldCommands?: readonly string[] /** Which session rows are the agent's own built-ins, as this process's initialize response proves. */ diff --git a/src/main/acp/acp-dialects/omp-dialect.ts b/src/main/acp/acp-dialects/omp-dialect.ts index 185fc50792d..45d8f4f3eb7 100644 --- a/src/main/acp/acp-dialects/omp-dialect.ts +++ b/src/main/acp/acp-dialects/omp-dialect.ts @@ -1,13 +1,14 @@ import { z } from 'zod' import type { ToolCallContent, ToolCallUpdate } from '../generated/acp-protocol.generated' import type { AcpAgentError } from '../acp-errors' -import type { AcpCompactionReply, AcpDialect } from './acp-dialect' +import type { AcpCompactionReply, AcpDialect, AcpModelCommandReply } from './acp-dialect' // Read raw result text instead of the repeated command echo in content. // Only timed foreground completion implies exit zero; service/background launches prove no exit. const textBlockSchema = z.looseObject({ type: z.literal('text'), text: z.string() }) const promptErrorDataSchema = z.looseObject({ details: z.string() }) -const SIGNED_OUT_DETAIL_PREFIXES = ['No model selected.\n\nUse /login', 'No API key found for '] +// "No model selected" is not one: a launch selector OMP never resolved says it too (modelNotSelected). +const SIGNED_OUT_DETAIL_PREFIXES = ['No API key found for '] const CANCEL_CLEANUP_TIMED_OUT = 'ACP cancel cleanup timed out' const toolResultSchema = z.looseObject({ content: z.array(z.unknown()), @@ -106,6 +107,22 @@ function compactionReply(text: string): AcpCompactionReply | undefined { : { outcome: 'failed', detail: reply } } +// `/model` (builtin-modes.ts) says "Model set to p/id." only after the model and any :level apply. +const MODEL_SET = /^Model set to (\S+)\.$/ + +function modelCommandReply(text: string): AcpModelCommandReply { + const reply = text.trim() + const applied = MODEL_SET.exec(reply)?.[1] + if (applied) { + return { applied } + } + // A failure after the switch still says "Failed to set model"; the value stays unapplied. + return { + refused: /\bNo API key\b/.test(reply) ? 'notSignedIn' : 'modelUnavailable', + detail: reply + } +} + function errorDetails(error: AcpAgentError): string | undefined { return error.code === -32603 ? promptErrorDataSchema.safeParse(error.data).data?.details @@ -119,6 +136,16 @@ export const OMP_ACP_DIALECT: AcpDialect = { clientCapabilities: { elicitation: { form: {} } }, normalizeToolUpdate, compactionReply, + modelCommand: { + // #setModelById (acp-agent.ts) takes listed provider/id values only. + refusedByOption: (error) => errorDetails(error)?.startsWith('Unknown ACP model: ') === true, + // A launch selector OMP deferred and never resolved leaves the session without a model. + noModel: (error) => errorDetails(error)?.startsWith('No model selected.') === true, + // Checked against published packages: 18.1.8's `/model` matches ids, 18.1.9's resolves roles. + resolvesSelectorsFrom: '18.1.9', + text: (value) => `/model ${value}`, + reply: modelCommandReply + }, authenticationRequired: (error) => { const details = errorDetails(error) return ( diff --git a/src/main/acp/acp-launch-specs.ts b/src/main/acp/acp-launch-specs.ts index d68e023cf34..176095feca6 100644 --- a/src/main/acp/acp-launch-specs.ts +++ b/src/main/acp/acp-launch-specs.ts @@ -123,7 +123,10 @@ export type AcpLaunchSpec = { command: string /** The terminal agent's Command setting may name a different program than this chat server. */ ignoreAgentCommandSetting?: true - args(input: { fullAccess: boolean; pluginDir: string | null }): string[] + /** `model` is the chat's saved model, passed only to specs that launch with it. */ + args(input: { fullAccess: boolean; pluginDir: string | null; model?: string }): string[] + /** The ACP model option cannot name every selection the CLI resolves, so the launch line carries it. */ + launchesWithModel?: true /** Applied after the account and user environment. */ env: Readonly> /** Scrubs inherited Orca plumbing and returns keys to omit entirely. */ @@ -257,7 +260,13 @@ const OMP_LAUNCH_SPEC: AcpLaunchSpec = { agent: 'omp', command: 'omp', // Full access approves permission requests individually. - args: ({ pluginDir }) => ['acp', ...(pluginDir ? ['--plugin-dir', pluginDir] : [])], + args: ({ pluginDir, model }) => [ + 'acp', + ...(pluginDir ? ['--plugin-dir', pluginDir] : []), + ...(model ? ['--model', model] : []) + ], + // ACP takes listed provider/id values only; the CLI also resolves roles, fallbacks and :level. + launchesWithModel: true, // Answering forms marks the session as having a UI, so `pty: true` bash would open a TUI // overlay ACP cannot draw and fail; OMP's own headless modes set this too. env: { PI_NO_PTY: '1' }, diff --git a/src/main/acp/acp-message-execution-options.ts b/src/main/acp/acp-message-execution-options.ts index f1900066fc6..14840d3aac4 100644 --- a/src/main/acp/acp-message-execution-options.ts +++ b/src/main/acp/acp-message-execution-options.ts @@ -1,10 +1,13 @@ import { + agentSessionFailureFact, providerDiagnostic, withProviderDiagnostic } from '../../shared/agent-session/failures/agent-session-failure' import type { AgentSessionExecutionOptions } from '../../shared/agent-session/options/agent-session-execution-options' import { AgentSessionOptionRejectedError } from '../native-chat/agent-session-wire/structured-agent-session-option-error' +import { compareAppVersions } from '../../shared/app-version' import { AcpAgentError } from './acp-errors' +import { AcpModelCommandRefusedError } from './acp-model-command' import type { AcpStructuredSession } from './acp-structured-session' import { acpAuthenticationRequired, @@ -17,7 +20,9 @@ export async function applyAcpMessageOptions( options: AgentSessionExecutionOptions | undefined, setOption: (key: 'model' | 'effort', value: string) => Promise, isCurrent: () => boolean, - signal?: AbortSignal + signal?: AbortSignal, + /** The agent's own model command, tried only once the agent rejects the model option. */ + modelCommand?: (value: string) => Promise ): Promise { if (!options) { return true @@ -28,12 +33,26 @@ export async function applyAcpMessageOptions( continue } try { - await setOption(key, value) + await setOption(key, value).catch((error: unknown) => + key === 'model' && + modelCommand && + error instanceof AcpAgentError && + session.spec.dialect.modelCommand?.refusedByOption(error) && + isCurrent() + ? modelCommand(value) + : Promise.reject(error) + ) } catch (error) { signal?.throwIfAborted() if (!isCurrent()) { return false } + if (error instanceof AgentSessionOptionRejectedError) { + throw error + } + if (error instanceof AcpModelCommandRefusedError) { + throw modelCommandRefusal(error, value, await acpAgentUpdate(session)) + } if (error instanceof AcpAgentError) { const detail = acpPromptErrorDetail(session.spec.dialect, error) const rejection = acpAuthenticationRequired(session.spec.dialect, error) @@ -52,3 +71,32 @@ export async function applyAcpMessageOptions( } return true } + +/** Orca's own words name the agent and the next step; the agent's reply stays a diagnostic. */ +function modelCommandRefusal( + error: AcpModelCommandRefusedError, + value: string, + agentUpdate: string | undefined +): Error { + const { refused, detail } = error.reply + const fact = + refused === 'notSignedIn' + ? agentSessionFailureFact('notSignedIn') + : agentSessionFailureFact('modelUnavailable', { + detail: providerDiagnostic(value, 'log'), + ...(agentUpdate ? { agentUpdate } : {}) + }) + return withProviderDiagnostic( + new AgentSessionOptionRejectedError(error, 'optionRejected', fact), + providerDiagnostic(detail, 'log') + ) +} + +/** The release to update to, when the running agent reports one older than its command needs. */ +async function acpAgentUpdate(session: AcpStructuredSession): Promise { + const needed = session.spec.dialect.modelCommand?.resolvesSelectorsFrom + const running = needed + ? (await session.connection.initialize().catch(() => null))?.agentInfo?.version + : undefined + return needed && running && compareAppVersions(running, needed) < 0 ? needed : undefined +} diff --git a/src/main/acp/acp-model-command-host.test.ts b/src/main/acp/acp-model-command-host.test.ts new file mode 100644 index 00000000000..91fbdf20a66 --- /dev/null +++ b/src/main/acp/acp-model-command-host.test.ts @@ -0,0 +1,81 @@ +import { afterEach, expect, it } from 'vitest' +import { closeProviderTimelineRigs } from '../native-chat/agent-session-timeline/provider-timeline-assembler-test-support' +import { + CALLER, + envelope +} from '../native-chat/agent-session-wire/structured-agent-session-host-test-harness' +import { + HOST_TEST_SESSION as SESSION, + hostTestAttachParams +} from '../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { OMP_ACP_DIALECT } from './acp-dialects/omp-dialect' +import { acpLaunchSpecFor } from './acp-launch-specs' +import type { FakeFrame } from './acp-scripted-agent.test-support' +import { PROVIDER_SESSION, waitFor } from './acp-structured-adapter.test-support' +import { framesOf, openHostRig, send } from './acp-structured-host.test-support' + +afterEach(closeProviderTimelineRigs) + +const isCommand = (frame: FakeFrame) => JSON.stringify(frame.params).includes('/model @worker_be') + +// The host delivers one send at a time, so a send behind a role's hidden /model waits for it. +it('holds a later send until the role command before it has answered', async () => { + const grok = acpLaunchSpecFor('grok')! + const spec = { ...grok, dialect: { ...grok.dialect, modelCommand: OMP_ACP_DIALECT.modelCommand } } + const held: FakeFrame[] = [] + const { host, rig, ready } = await openHostRig({ + spec, + script: (agent) => { + agent.on('session/set_config_option', (frame) => + agent.fail(frame, -32603, 'Internal error', { details: 'Unknown ACP model: @worker_be' }) + ) + agent.on('session/prompt', (frame) => { + if (isCommand(frame)) { + held.push(frame) + } + }) + } + }) + expect( + await host.attach( + CALLER, + hostTestAttachParams(null, { + provider: 'grok', + agent: 'grok', + providerHandle: undefined, + accountHome: { variable: 'GROK_HOME', path: '/grok' } + }) + ) + ).toMatchObject({ ok: true }) + await ready() + const fields = { key: 'model', value: '@worker_be' } + expect( + await host.setOption(CALLER, { + envelope: envelope('agentSession.setOption', fields), + ...fields + }) + ).toMatchObject({ ok: true }) + await send(host, 'C on the role') + await send(host, 'D right after') + await waitFor(() => expect(held).toHaveLength(1)) + await rig.settle() + // Only the command has reached OMP; D's controls and prompt wait behind it. + expect(framesOf(rig.child(), 'session/prompt').map(isCommand)).toEqual([true]) + const writesBefore = framesOf(rig.child(), 'session/set_config_option').length + rig.child().agent.notify('session/update', { + sessionId: PROVIDER_SESSION, + update: { + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: 'Model set to grok-4.6.' } + } + }) + rig.child().agent.reply(held[0]!, { stopReason: 'end_turn' }) + await waitFor(() => expect(framesOf(rig.child(), 'session/prompt')).toHaveLength(2)) + const c = framesOf(rig.child(), 'session/prompt')[1]! + rig.child().agent.reply(c, { stopReason: 'end_turn' }) + await waitFor(() => expect(framesOf(rig.child(), 'session/prompt')).toHaveLength(3)) + expect(framesOf(rig.child(), 'session/prompt').map(isCommand)).toEqual([true, false, false]) + // D carries the same role, already applied: no second write, no second command. + expect(framesOf(rig.child(), 'session/set_config_option')).toHaveLength(writesBefore) + await host.close(SESSION, 'user-close') +}) diff --git a/src/main/acp/acp-model-command.test.ts b/src/main/acp/acp-model-command.test.ts new file mode 100644 index 00000000000..5ec2a3e3077 --- /dev/null +++ b/src/main/acp/acp-model-command.test.ts @@ -0,0 +1,279 @@ +import { describe, expect, it, vi } from 'vitest' +import { agentSessionFailureWords } from '../../shared/agent-session/failures/agent-session-failure-words' +import type { AgentSessionOptionRejectedError } from '../native-chat/agent-session-wire/structured-agent-session-option-error' +import { OMP_ACP_DIALECT } from './acp-dialects/omp-dialect' +import { AcpAgentError } from './acp-errors' +import { acpLaunchSpecFor } from './acp-launch-specs' +import { applyAcpMessageOptions } from './acp-message-execution-options' +import { acpNoModelSelected, withAcpModelFallback } from './acp-model-command' +import { writeAcpSessionOption } from './acp-session-option-write' +import type { AcpSessionEvent } from './acp-session-runtime' +import { AcpStructuredOptions } from './acp-structured-options' +import { routeAcpSessionEvent, type AcpStructuredSession } from './acp-structured-session' +import type { SessionConfigOption, SessionUpdate } from './generated/acp-protocol.generated' + +const config = (model: string, thinking: string): SessionConfigOption[] => [ + { + id: 'model', + name: 'Model', + category: 'model', + type: 'select', + currentValue: model, + options: [ + { value: 'p/a', name: 'A' }, + { value: 'p/b', name: 'B' } + ] + }, + { + id: 'thinking', + name: 'Thinking', + category: 'thought_level', + type: 'select', + currentValue: thinking, + options: [ + { value: 'low', name: 'Low' }, + { value: 'high', name: 'High' } + ] + } +] + +// No turn runs and nothing stops, so the command never waits or withdraws. +const idleTurns = { + running: false, + withdrawalEpoch: 0, + withdrawnSince: () => null, + holdSteer: () => () => undefined +} + +const event = (update: SessionUpdate): AcpSessionEvent => ({ + kind: 'known', + notification: { sessionId: 'omp-1', update } +}) + +// OMP 18.15 `/model`: reply text, then its explicit config push, then end_turn (acp-agent.ts:1263-1295). +function rig(updates: SessionUpdate[], version = '18.15.0') { + const options = new AcpStructuredOptions(OMP_ACP_DIALECT) + options.adoptSession({ configOptions: config('p/a', 'low') }, 'loaded') + const lane = { translator: { sessionEvent: vi.fn(() => []) }, apply: vi.fn() } + const prompt = vi.fn(async () => { + for (const update of updates) { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: routing reads only the lane's translator and apply, which this fake provides. + routeAcpSessionEvent({ lane, options } as never, event(update), 1) + } + return { stopReason: 'end_turn' } + }) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the send path reads only spec, options, the idle turns and connection.prompt/initialize, which this fake provides. + const session = { + spec: acpLaunchSpecFor('omp')!, + options, + turns: idleTurns, + connection: { prompt, initialize: async () => ({ agentInfo: { name: 'omp', version } }) } + } as unknown as AcpStructuredSession + const send = (model: string) => + withAcpModelFallback(session, { agent: 'omp', timeoutMs: 1_000 }, (fallback) => + applyAcpMessageOptions( + session, + { model }, + async () => { + throw new AcpAgentError(-32603, 'Internal error', { + details: `Unknown ACP model: ${model}` + }) + }, + () => true, + undefined, + fallback.command + ) + ) + return { options, lane, prompt, send } +} + +const reply = (text: string): SessionUpdate => ({ + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text } +}) +const pushed = (model: string, thinking: string): SessionUpdate => ({ + sessionUpdate: 'config_option_update', + configOptions: config(model, thinking) +}) + +describe("OMP's own model command", () => { + it('applies a role the model option refuses through /model, without anything reaching the chat', async () => { + const { options, lane, prompt, send } = rig([ + reply('Model set to p/b.'), + { sessionUpdate: 'session_info_update', title: 'chat' }, + pushed('p/b', 'high') + ]) + await expect(send('@worker_be:high')).resolves.toBe(true) + expect(prompt).toHaveBeenCalledWith([{ type: 'text', text: '/model @worker_be:high' }]) + expect(options.appliedInput.get('model')).toBe('@worker_be:high') + // Only the config push reaches the lane; the reply and title notice belong to the command. + expect(lane.translator.sessionEvent).toHaveBeenCalledTimes(1) + expect(options.read().current.model).toBe('p/b') + }) + + it.each([ + ['18.15.0', "OMP couldn't use @worker_be. Pick another model and send again."], + [ + '17.0.5', + "OMP couldn't use @worker_be. Update OMP to 18.1.9 or later to keep it after a restart, or pick another model and send again." + ] + ])( + "names the agent and the next step when OMP %s can't use the role, and leaves it unapplied", + async (version, words) => { + // A failure can follow the model's own switch; it still counts as not applied. + const { options, send } = rig( + [pushed('p/b', 'low'), reply('Failed to set model: prompt rebuild failed')], + version + ) + const error: AgentSessionOptionRejectedError = await send('@worker_be').catch((e) => e) + expect( + agentSessionFailureWords(error.rejection!, { surface: 'rejection', agentName: 'OMP' }) + .reason + ).toBe(words) + expect(options.appliedInput.has('model')).toBe(false) + } + ) + + it('applies the role again on the next send once OMP moves off what it resolved to', async () => { + const { options, prompt, send } = rig([reply('Model set to p/b.'), pushed('p/b', 'high')]) + await send('@worker_be:high') + // Its own late echo is not a change; the role stays applied. + options.adoptConfigOptions(config('p/b', 'high')) + await send('@worker_be:high') + expect(prompt).toHaveBeenCalledTimes(1) + // Native `/model p/b:low`: same model, other thinking, so the selector no longer holds. + options.adoptConfigOptions(config('p/b', 'low')) + await send('@worker_be:high') + expect(prompt).toHaveBeenCalledTimes(2) + }) + + it('does not re-send a role the session already runs from its launch line', async () => { + const options = new AcpStructuredOptions(OMP_ACP_DIALECT) + options.adoptSession({ configOptions: config('p/a', 'low') }, 'new') + options.adoptLaunchModel('@worker_be') + const setOption = vi.fn(async () => undefined) + const command = vi.fn(async () => undefined) + await expect( + applyAcpMessageOptions( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: with the effort write accepted, the send path reads only session.options. + { options } as unknown as AcpStructuredSession, + { model: '@worker_be', effort: 'medium' }, + setOption, + () => true, + undefined, + command + ) + ).resolves.toBe(true) + expect(setOption.mock.calls).toEqual([['effort', 'medium']]) + expect(command).not.toHaveBeenCalled() + }) + + it('retires launch-line proof on a native model change, but keeps ordinary control proof', async () => { + const options = new AcpStructuredOptions(OMP_ACP_DIALECT) + options.adoptSession({ configOptions: config('p/a', 'high') }, 'new') + options.adoptLaunchModel('@worker_be') + // The launch line already applied the role, so the first send writes nothing for it. + expect(options.appliedInput.get('model')).toBe('@worker_be') + options.adoptConfigOptions(config('p/b', 'high')) + expect(options.appliedInput.has('model')).toBe(false) + // A successful model option write keeps the shipped rule: observations never override it. + await writeAcpSessionOption( + { + setConfigOption: async () => ({ configOptions: config('p/a', 'high') }), + setModel: vi.fn() + }, + options, + options.write('model', 'p/a')!, + { agent: 'omp', key: 'model', value: 'p/a', timeoutMs: 1_000 } + ) + options.adoptConfigOptions(config('p/b', 'low')) + expect(options.appliedInput.get('model')).toBe('p/a') + }) + + it.each(['aborted', 'timed out'] as const)( + 'leaves the role unapplied and retires OMP when the command is %s', + async (ending) => { + const options = new AcpStructuredOptions(OMP_ACP_DIALECT) + options.adoptSession({ configOptions: config('p/a', 'low') }, 'loaded') + const late = Promise.withResolvers() + const retired = vi.fn() + const aborted = new AbortController() + // A genuine late success: OMP's reply, its config push and a normal end, after Orca gave up. + const prompt = async () => { + await late.promise + options.commandReply += 'Model set to p/b.' + options.adoptConfigOptions(config('p/b', 'low')) + return { stopReason: 'end_turn' } + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the command reads only spec, options, the idle turns and connection.prompt, which this fake provides. + const session = { + spec: acpLaunchSpecFor('omp')!, + options, + turns: idleTurns, + connection: { prompt } + } as unknown as AcpStructuredSession + const bound = { + agent: 'omp', + timeoutMs: ending === 'timed out' ? 1 : 1_000, + signal: aborted.signal, + onUncertain: retired + } + const pending = withAcpModelFallback(session, bound, (fallback) => + fallback.command!('@worker_be') + ) + if (ending === 'aborted') { + aborted.abort() + } + await expect(pending).rejects.toThrow() + expect(retired).toHaveBeenCalledOnce() + // A late success cannot restore proof the abort retired. + late.resolve() + await new Promise((resolve) => setTimeout(resolve, 0)) + expect(options.appliedInput.has('model')).toBe(false) + expect(options.writing).toBe(0) + } + ) + + it('says a cancelled command left the message unsent', async () => { + const cancelled = rig([]) + cancelled.prompt.mockResolvedValue({ stopReason: 'cancelled' }) + const error: AgentSessionOptionRejectedError = await cancelled + .send('@worker_be') + .catch((e) => e) + expect(error.rejection).toMatchObject({ kind: 'cancelled', neverReachedAgent: true }) + }) + + it('says OMP had no model, not that it is signed out, and applies the role again next send', async () => { + const options = new AcpStructuredOptions(OMP_ACP_DIALECT) + // A typo'd launch role: OMP defers it, never resolves it, and still lists models[0] as current. + options.adoptSession({ configOptions: config('p/a', 'low') }, 'new') + options.adoptLaunchModel('@worker_bee') + // OMP's prompt error with no model (agent-session.ts), the same text a signed-out OMP gives. + const noModel = new AcpAgentError(-32603, 'Internal error', { + details: + 'No model selected.\n\nUse /login, set an API key environment variable, or create ~/.omp/agent/models.yml\n\nThen use /model to select a model.' + }) + // OMP's own text stays in the log only; the user sees Orca's sentence. + expect(acpNoModelSelected(OMP_ACP_DIALECT, options, noModel)).toEqual({ + kind: 'modelNotSelected', + detail: { audience: 'log', text: expect.stringContaining('No model selected.') } + }) + expect(OMP_ACP_DIALECT.authenticationRequired!(noModel)).toBe(false) + // The saved selection stays; its proof is gone, so the next send writes it again. + const setOption = vi.fn(async () => undefined) + await applyAcpMessageOptions( + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: with the write accepted, the send path reads only session.options. + { options } as unknown as AcpStructuredSession, + { model: '@worker_bee' }, + setOption, + () => true + ) + expect(setOption).toHaveBeenCalledWith('model', '@worker_bee') + // An explicit missing key is still a sign-in problem. + const noKey = new AcpAgentError(-32603, 'Internal error', { + details: 'No API key found for openai.\n\nUse /login' + }) + expect(acpNoModelSelected(OMP_ACP_DIALECT, options, noKey)).toBeUndefined() + expect(OMP_ACP_DIALECT.authenticationRequired!(noKey)).toBe(true) + }) +}) diff --git a/src/main/acp/acp-model-command.ts b/src/main/acp/acp-model-command.ts new file mode 100644 index 00000000000..e52abfc79a0 --- /dev/null +++ b/src/main/acp/acp-model-command.ts @@ -0,0 +1,184 @@ +// Apply a model through the agent's own model command, which resolves the roles and selectors +// its model option refuses (OMP: `/model` shares `--model`'s resolver; the option takes listed ids). + +import { + agentSessionFailureFact, + providerDiagnostic, + type SubmissionRejectionFact +} from '../../shared/agent-session/failures/agent-session-failure' +import { acpPromptErrorDetail } from './acp-turn-failures' +import type { AcpAgentError } from './acp-errors' +import { acpAgentName } from './acp-structured-agent-definitions' +import { AgentSessionOptionRejectedError } from '../native-chat/agent-session-wire/structured-agent-session-option-error' +import type { AcpModelCommandReply } from './acp-dialects/acp-dialect' +import { boundAcpOptionWrite, type AcpOptionWriteBound } from './acp-session-option-write' +import type { AcpSessionEvent } from './acp-session-runtime' +import type { AcpStructuredOptions } from './acp-structured-options' +import type { AcpStructuredSession } from './acp-structured-session' +import { + ACP_OPTION_WRITE_TIMEOUT_MS, + type AcpStructuredSessionAdapterDeps +} from './acp-structured-session-adapter-deps' + +export class AcpModelCommandRefusedError extends Error { + constructor(readonly reply: Extract) { + super(reply.detail) + this.name = 'AcpModelCommandRefusedError' + } +} + +type AcpModelCommandSession = Pick< + AcpStructuredSession, + 'spec' | 'connection' | 'options' | 'turns' +> + +async function applyAcpModelCommand( + session: AcpModelCommandSession, + value: string, + bound: AcpOptionWriteBound, + throwIfWithdrawn: () => void +): Promise { + const command = session.spec.dialect.modelCommand + if (!command) { + throw new Error(`${bound.agent} has no model command`) + } + // The command is a prompt, so a steer still interrupts the running answer before it is sent. + if (session.turns.running) { + await session.turns.whenIdle(bound.signal) + } + throwIfWithdrawn() + const { options } = session + await boundAcpOptionWrite(options, { ...bound, key: 'model', value }, async () => { + options.commandReply = '' + try { + const result = await session.connection.prompt([{ type: 'text', text: command.text(value) }]) + const reply = command.reply(options.commandReply) + // Only a normally ended command that reports its model counts; anything else leaves it unapplied. + if (result.stopReason !== 'end_turn') { + throw new AgentSessionOptionRejectedError( + `${bound.agent} model command ended ${result.stopReason}`, + 'optionRejected', + agentSessionFailureFact('cancelled', { neverReachedAgent: true }) + ) + } + if (!('applied' in reply)) { + // A Stop it already reached outranks the agent's refusal: the message was never sent. + throwIfWithdrawn() + throw new AcpModelCommandRefusedError(reply) + } + const { applied } = reply + return () => applied + } finally { + options.commandReply = null + } + }) +} + +/** Option writes and the model command share one deadline, and an unanswered one retires the child. */ +export function acpOptionWriteBound( + deps: Pick, + session: Pick, + signal: AbortSignal | undefined, + onUncertain: (error: Error) => void +): AcpOptionWriteBound { + return { + agent: session.spec.agent, + timeoutMs: deps.optionWriteTimeoutMs ?? ACP_OPTION_WRITE_TIMEOUT_MS, + ...(signal ? { signal } : {}), + onUncertain + } +} + +type AcpModelFallback = ReturnType + +/** A send that falls back to the agent's model command is a held steer from then until it is + * admitted: a Stop or teardown since its option writes began withdraws it, unsent. Sends that never + * fall back keep their usual Stop rules. */ +export async function withAcpModelFallback( + session: AcpModelCommandSession, + bound: AcpOptionWriteBound, + prepare: (fallback: AcpModelFallback) => Promise +): Promise { + const fallback = acpModelFallback(session, bound) + try { + return await prepare(fallback) + } finally { + fallback.release() + } +} + +function acpModelFallback(session: AcpModelCommandSession, bound: AcpOptionWriteBound) { + const epoch = session.turns.withdrawalEpoch + let release: (() => void) | null = null + const throwIfWithdrawn = (): void => { + const withdrawn = session.turns.withdrawnSince(epoch) + if (withdrawn) { + throw acpWithdrawnSteer(acpAgentName(session.spec.agent), withdrawn === 'ended') + } + } + const done = (): void => { + release?.() + release = null + } + return { + command: session.spec.dialect.modelCommand + ? async (value: string): Promise => { + release ??= session.turns.holdSteer() + await applyAcpModelCommand(session, value, bound, throwIfWithdrawn) + } + : undefined, + /** Checks in the admission step itself, which may wait before committing. */ + admitting: (commit: () => void) => (): void => { + if (release) { + throwIfWithdrawn() + } + // Admitted, it is an ordinary steer; still held, it would cancel itself as it starts. + done() + commit() + }, + release: done + } +} + +/** True when the event is the hidden model command's output, which the chat must not show. */ +export function absorbsAcpModelCommandOutput( + options: AcpStructuredOptions, + event: AcpSessionEvent +): boolean { + if (options.commandReply === null) { + return false + } + const update = event.kind === 'known' ? event.notification.update : undefined + if (update?.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text') { + options.commandReply += update.content.text + } + return ( + update?.sessionUpdate !== 'config_option_update' && + update?.sessionUpdate !== 'available_commands_update' + ) +} + +/** OMP says "No model selected" whether a launch selector never resolved or it lacks a sign-in, + * so the refusal states only that; the next send applies the chat's selection again. */ +export function acpNoModelSelected( + dialect: AcpStructuredSession['spec']['dialect'], + options: AcpStructuredOptions, + error: AcpAgentError +): SubmissionRejectionFact | undefined { + if (!dialect.modelCommand?.noModel(error)) { + return undefined + } + options.invalidateInput('model') + return agentSessionFailureFact('modelNotSelected', { + detail: providerDiagnostic(acpPromptErrorDetail(dialect, error), 'log') + }) +} + +/** A role steer a Stop or teardown reached while it prepared: it never reached the agent. */ +export function acpWithdrawnSteer(agentName: string, ended: boolean): Error { + return new AgentSessionOptionRejectedError( + `${agentName} stopped before this message was sent`, + 'optionRejected', + agentSessionFailureFact(ended ? 'providerExited' : 'cancelled', { neverReachedAgent: true }) + ) +} diff --git a/src/main/acp/acp-prompt-turns.ts b/src/main/acp/acp-prompt-turns.ts index a05e1a0bf3b..c34b815fe07 100644 --- a/src/main/acp/acp-prompt-turns.ts +++ b/src/main/acp/acp-prompt-turns.ts @@ -6,12 +6,7 @@ import { type AcpCompactionFrame } from './acp-compaction-turn' import type { AcpDialect, AcpTurnEnding } from './acp-dialects/acp-dialect' -import { - acpAuthenticationRequired, - acpPromptErrorDetail, - type AcpTurnFailures -} from './acp-turn-failures' -import { AcpAgentError } from './acp-errors' +import { acpPromptFailureEnding, type AcpTurnFailures } from './acp-turn-failures' import { hookOutcomeRowBody } from '../../shared/agent-session/journal/agent-session-hook-outcome' import type { SessionUpdate } from './generated/acp-protocol.generated' @@ -43,17 +38,7 @@ export class AcpPromptTurns { at: number, failures: AcpTurnFailures ): AcpTurnEnding | ProviderTimelineEvent[] { - const detail = - error instanceof AcpAgentError ? acpPromptErrorDetail(this.dialect, error) : undefined - const failure = - error instanceof AcpAgentError ? this.dialect.promptFailure?.(error, at) : undefined - const ending = { - ...failure, - stopReason: failure?.stopReason ?? 'error', - at, - failureDetail: detail, - notSignedIn: acpAuthenticationRequired(this.dialect, error) - } + const ending = acpPromptFailureEnding(this.dialect, error, at) if (this.current?.clientMessageId !== clientMessageId) { // A late answer may supply a failure reason missing from the provider's end. return this.last?.clientMessageId === clientMessageId && failures.has(this.last.turn) diff --git a/src/main/acp/acp-session-option-write.ts b/src/main/acp/acp-session-option-write.ts index 1063284a78e..d13ce3e71d2 100644 --- a/src/main/acp/acp-session-option-write.ts +++ b/src/main/acp/acp-session-option-write.ts @@ -2,19 +2,34 @@ import { abortSignalReason } from '../../shared/abort-signal-reason' import type { AcpStructuredConnection } from './acp-structured-connection' import type { AcpOptionWrite, AcpStructuredOptions } from './acp-structured-options' -/** Only the current, still-awaited write may establish reusable option proof. */ +export type AcpOptionWriteBound = { + agent: string + timeoutMs: number + signal?: AbortSignal + onUncertain?: (error: Error) => void +} + export function writeAcpSessionOption( connection: Pick, options: AcpStructuredOptions, write: AcpOptionWrite, - bound: { - agent: string - timeoutMs: number - signal?: AbortSignal - key: string - value: string - onUncertain?: (error: Error) => void - } + bound: AcpOptionWriteBound & { key: string; value: string } +): Promise { + return boundAcpOptionWrite(options, bound, () => + write.method === 'config' + ? connection + .setConfigOption(write.configId, write.value) + .then((result) => () => options.adoptConfigOptions(result.configOptions)) + : connection.setModel(write.modelId).then(() => () => options.adoptModel(write.modelId)) + ) +} + +/** Only the current, still-awaited write may establish reusable option proof. */ +export function boundAcpOptionWrite( + options: AcpStructuredOptions, + bound: AcpOptionWriteBound & { key: string; value: string }, + /** Resolves to the proof's adoption; a returned model marks selector proof. */ + send: () => Promise<() => string | void> ): Promise { const { agent, timeoutMs, signal } = bound if (signal?.aborted) { @@ -22,24 +37,16 @@ export function writeAcpSessionOption( } const revision = ++options.writeRevision options.invalidateInput(bound.key) - const adopt = (apply: () => void): void => { + options.writing += 1 + let completed = false + const applied = send().then((apply) => { + completed = true if (options.writeRevision !== revision) { throw new Error(`${agent} option write was superseded`) } - apply() - options.appliedInput.set(bound.key, write.method === 'config' ? write.value : write.modelId) - } - let completed = false - const applied = - write.method === 'config' - ? connection.setConfigOption(write.configId, write.value).then((result) => { - completed = true - adopt(() => options.adoptConfigOptions(result.configOptions)) - }) - : connection.setModel(write.modelId).then(() => { - completed = true - adopt(() => options.adoptModel(write.modelId)) - }) + const resolved = apply() + options.adoptOwnWrite(bound.key, bound.value, resolved ?? undefined) + }) void applied.catch(() => { completed = true }) @@ -64,9 +71,15 @@ export function writeAcpSessionOption( () => fail(new Error(`${agent} did not answer an option write within ${timeoutMs}ms`)), timeoutMs ) + let settled = false const settle = (): void => { + if (settled) { + return + } + settled = true clearTimeout(timer) signal?.removeEventListener('abort', onAbort) + options.writing -= 1 } signal?.addEventListener('abort', onAbort, { once: true }) applied.then(() => { diff --git a/src/main/acp/acp-session-reopen-failure.ts b/src/main/acp/acp-session-reopen-failure.ts index 6e653694eac..744118de44f 100644 --- a/src/main/acp/acp-session-reopen-failure.ts +++ b/src/main/acp/acp-session-reopen-failure.ts @@ -1,6 +1,15 @@ import { agentSessionFailureFact } from '../../shared/agent-session/failures/agent-session-failure' import { agentSessionFailureWords } from '../../shared/agent-session/failures/agent-session-failure-words' -import type { AgentSessionProviderHandleLink } from '../../shared/agent-session/lifecycle/agent-session-provider-handle' +import type { + AgentSessionProviderHandleChain, + AgentSessionProviderHandleLink +} from '../../shared/agent-session/lifecycle/agent-session-provider-handle' +import { parseAgentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' +import type { JournalLoad } from '../native-chat/agent-session-journal/journal-open' +import { + providerTimelineKeyPart, + spelledProviderTimelineItemKey +} from '../native-chat/agent-session-timeline/provider-timeline-identity' import type { ProviderTimelineEvent } from '../native-chat/agent-session-timeline/provider-timeline-event' import { AcpAuthRequiredError, AcpRpcError } from './acp-errors' import type { AcpStructuredLaunch } from './acp-structured-launch-resolution' @@ -62,3 +71,40 @@ export function acpSessionNotRestoredRow( } ] } + +/** Retry missing loss-warning rows on successful starts; unreadable journals suppress new warnings. */ +export function acpUnannouncedLosses( + readJournal: (sessionId: string) => JournalLoad | null, + sessionId: string, + chain: AgentSessionProviderHandleChain +): string[] { + const lost = chain.flatMap((link) => + link.replaces?.reason === 'restore-failed' ? [link.replaces.key] : [] + ) + if (lost.length === 0) { + return [] + } + let load: JournalLoad | null + try { + load = readJournal(sessionId) + } catch { + return [] + } + if (!load) { + return lost + } + if (load.damage || load.newer) { + return [] + } + const written = new Set() + for (const itemId of load.state.items.keys()) { + const identity = parseAgentJournalItemKey(itemId) + const spelled = + identity?.provider === 'legacy' ? spelledProviderTimelineItemKey(identity.recordId) : null + if (spelled !== null) { + written.add(spelled) + } + } + // Warnings survive even if the replacement session that wrote them is superseded. + return lost.filter((key) => !written.has(providerTimelineKeyPart(acpSessionNotRestoredItem(key)))) +} diff --git a/src/main/acp/acp-structured-compaction.test.ts b/src/main/acp/acp-structured-compaction.test.ts index e5f9505f156..37a28dae66a 100644 --- a/src/main/acp/acp-structured-compaction.test.ts +++ b/src/main/acp/acp-structured-compaction.test.ts @@ -269,6 +269,24 @@ describe('ACP compaction settlement', () => { expect((await rig.rig.rows()).filter((row) => row.body.kind === 'status')).toHaveLength(1) }) + it('says OMP has no model selected, as a send does', async () => { + // OMP says this both signed out and for a launch selector it never resolved. + const { rig, command, prompt } = await compact(OMP) + rig.child().agent.fail(prompt, -32603, 'Internal error', { + details: 'No model selected.\n\nUse /login to sign in.' + }) + const { turn, inside } = await ended(rig, command) + expect(turn).toMatchObject({ state: 'completed', outcome: 'failure' }) + expect(inside).toEqual([ + expect.objectContaining({ + tone: 'error', + failure: expect.objectContaining({ kind: 'modelNotSelected' }) + }) + ]) + // The agent's own failure, so cards waiting behind the compaction stay held. + expect(rig.rig.journal.inputOrder.newestTurn.failure()).toBeGreaterThan(0) + }) + it('ends a stopped compaction as cancelled, with no result row', async () => { const { rig, command, prompt } = await compact(GROK) const { agent } = rig.child() diff --git a/src/main/acp/acp-structured-handshake.ts b/src/main/acp/acp-structured-handshake.ts index 8037b45e491..098bd2cbb72 100644 --- a/src/main/acp/acp-structured-handshake.ts +++ b/src/main/acp/acp-structured-handshake.ts @@ -24,6 +24,7 @@ import type { AcpStructuredOptions } from './acp-structured-options' import type { AcpStructuredPrompts } from './acp-structured-prompts' import type { AcpStructuredSessionAdapterDeps } from './acp-structured-session-adapter-deps' import { AcpStructuredTurns, type AcpStructuredTurnsDeps } from './acp-structured-turns' +import { acpNoModelSelected } from './acp-model-command' import { assertAcpStartingSession, isAcpReadySession, @@ -146,6 +147,10 @@ export async function initializeAcpStructuredSession( started.kind === 'new' ? 'new' : 'loaded' ) } + // A load restores the conversation's own model, so only a new session runs the launch choice. + if (started.kind === 'new' && launch.launchModel) { + options.adoptLaunchModel(launch.launchModel) + } const link: AgentSessionProviderHandleLink = { linkId: deps.mintLinkId?.() ?? `${spec.agent}-${acquire.fence}-${started.sessionId}`.slice(0, 128), @@ -188,7 +193,8 @@ export async function initializeAcpStructuredSession( agentName, now, settle: onSettled, - sessionLost: input.onSessionLost + sessionLost: input.onSessionLost, + modelRefusal: (error) => acpNoModelSelected(spec.dialect, options, error) }) }) if (!isAcpReadySession(child)) { diff --git a/src/main/acp/acp-structured-launch-resolution.test.ts b/src/main/acp/acp-structured-launch-resolution.test.ts index b784899eb5d..a9c7193821f 100644 --- a/src/main/acp/acp-structured-launch-resolution.test.ts +++ b/src/main/acp/acp-structured-launch-resolution.test.ts @@ -32,6 +32,7 @@ import { import { acpLaunchSpecFor } from './acp-launch-specs' const GROK = acpLaunchSpecFor('grok')! +const OMP = acpLaunchSpecFor('omp')! const identity = { sessionId: 'session-alpha-1', workspaceId: 'workspace-1', @@ -50,6 +51,25 @@ function grokRecord(overrides: Partial = {}): AgentSessionRe } } +function ompRecord(options: Record, resumes: boolean): AgentSessionRecord { + return grokRecord({ + provider: 'omp', + accountHome: { variable: 'PI_CODING_AGENT_DIR', path: '/home/user/.omp/agent' }, + options, + providerHandleChain: resumes + ? [ + { + linkId: 'link-created', + origin: 'created', + mintedAtFence: 1, + observedAt: 1, + handle: { transport: 'acp', agent: 'omp', nativeId: 'omp-1' } + } + ] + : [] + }) +} + function journalWithTurns(...providerSessions: string[]): JournalLoad { const state = createJournalReducerState(identity.sessionId, 'epoch-1') providerSessions.forEach((providerSession, index) => { @@ -68,11 +88,15 @@ function journalWithTurns(...providerSessions: string[]): JournalLoad { return { state, newer: null, damage: null } } -function resolver(record: AgentSessionRecord, readJournal: () => JournalLoad | null = () => null) { +function resolver( + record: AgentSessionRecord, + readJournal: () => JournalLoad | null = () => null, + spec = GROK +) { const searched: (string | null | undefined)[] = [] return { searched, - resolve: createAcpStructuredLaunchResolver(GROK, { + resolve: createAcpStructuredLaunchResolver(spec, { store: { getRecord: () => record, pinLaunchDirectory: vi.fn() }, readJournal, resolveWorkspacePath: async () => '/repo/worktree', @@ -238,6 +262,22 @@ describe('ACP launch resolution', () => { rmSync(root, { recursive: true, force: true }) } }) + it('starts a new OMP chat with its saved model on the launch line, where OMP resolves roles', async () => { + const start = (resumes: boolean) => + resolver( + ompRecord({ model: '@worker_be', effort: 'medium' }, resumes), + () => null, + OMP + ).resolve({ identity }) + const fresh = await start(false) + expect(fresh.args.slice(-2)).toEqual(['--model', '@worker_be']) + expect(fresh.args).not.toContain('--thinking') + expect(fresh.launchModel).toBe('@worker_be') + // A load restores the conversation's own model; the session applies the saved one instead. + const resumed = await start(true) + expect(resumed.args).not.toContain('--model') + expect(resumed.launchModel).toBeUndefined() + }) }) describe('ACP launch folder of a floating chat', () => { diff --git a/src/main/acp/acp-structured-launch-resolution.ts b/src/main/acp/acp-structured-launch-resolution.ts index 665b1d2e862..4729c293a49 100644 --- a/src/main/acp/acp-structured-launch-resolution.ts +++ b/src/main/acp/acp-structured-launch-resolution.ts @@ -12,11 +12,7 @@ import { import { delimiter } from 'node:path' import { homedir } from 'node:os' -import { parseAgentJournalItemKey } from '../../shared/agent-session/journal/agent-session-journal-item-key' -import { - agentSessionProviderHandleChainHead, - type AgentSessionProviderHandleChain -} from '../../shared/agent-session/lifecycle/agent-session-provider-handle' +import { agentSessionProviderHandleChainHead } from '../../shared/agent-session/lifecycle/agent-session-provider-handle' import { agentSessionProviderHandleKey } from '../../shared/agent-session/lifecycle/agent-session-provider-handle-encoding' import type { AgentSessionAccountHome } from '../../shared/agent-session/lifecycle/agent-session-account-home' import type { resolveCliCommand } from '../../shared/node-cli-command-resolution' @@ -29,11 +25,7 @@ import { import { hasExplicitTuiLaunchCommand } from '../../shared/agent-launch/startup/tui-agent-launch-command-override' import { readAgentJournalTurn } from '../../shared/agent-session/lifecycle/agent-session-turn-record' import type { JournalLoad } from '../native-chat/agent-session-journal/journal-open' -import { - isProviderTimelineTurnInNamespace, - providerTimelineKeyPart, - spelledProviderTimelineItemKey -} from '../native-chat/agent-session-timeline/provider-timeline-identity' +import { isProviderTimelineTurnInNamespace } from '../native-chat/agent-session-timeline/provider-timeline-identity' import type { StructuredAgentLaunchPartResolver } from '../runtime/agent-session/launch/structured-agent-launch-composition' import { STRUCTURED_CHILD_ENV_TO_DELETE } from '../runtime/agent-session/environment/structured-session-child-env' import { @@ -42,7 +34,7 @@ import { withNativeChatVisualsEnv } from '../native-chat/native-chat-visuals-delivery' import type { AcpLaunchSpec } from './acp-launch-specs' -import { acpSessionNotRestoredItem } from './acp-session-reopen-failure' +import { acpUnannouncedLosses } from './acp-session-reopen-failure' import { loadAcpVisualsSkill, type AcpLaunchVisualsDeps } from './acp-structured-launch-visuals' export type AcpStructuredLaunch = StructuredAgentCommand & { @@ -53,6 +45,8 @@ export type AcpStructuredLaunch = StructuredAgentCommand & { env: Record envToDelete: string[] fullAccess: boolean + /** The saved model the launch line carries. */ + launchModel?: string resume: { sessionId: string key: string @@ -210,13 +204,18 @@ export function acpStructuredLaunchPart( : null const fullAccess = basis.permissionMode === 'full-access' const head = agentSessionProviderHandleChainHead(record.providerHandleChain) + // A load restores the conversation's own model, and a stale role there would stop the agent + // before it opens; resumed chats apply their model through the session instead. + const model = spec.launchesWithModel && !head ? record.options?.model : undefined + const args = spec.args({ fullAccess, pluginDir: skill?.pluginDir ?? null, model }) return { launch: { spec, command, prefixArgs, - args: [...prefixArgs, ...spec.args({ fullAccess, pluginDir: skill?.pluginDir ?? null })], + args: [...prefixArgs, ...args], fullAccess, + ...(model ? { launchModel: model } : {}), resume: head ? { sessionId: head.handle.nativeId, @@ -225,7 +224,11 @@ export function acpStructuredLaunchPart( head.origin === 'created' && nothingExchangedOn(deps.readJournal, identity.sessionId, head.handle.nativeId), unannouncedLosses: () => - unannouncedLosses(deps.readJournal, identity.sessionId, record.providerHandleChain) + acpUnannouncedLosses( + deps.readJournal, + identity.sessionId, + record.providerHandleChain + ) } : null }, @@ -267,40 +270,3 @@ function nothingExchangedOn( } return true } - -/** Retry missing loss-warning rows on successful starts; unreadable journals suppress new warnings. */ -function unannouncedLosses( - readJournal: AcpStructuredLaunchPartDeps['readJournal'], - sessionId: string, - chain: AgentSessionProviderHandleChain -): string[] { - const lost = chain.flatMap((link) => - link.replaces?.reason === 'restore-failed' ? [link.replaces.key] : [] - ) - if (lost.length === 0) { - return [] - } - let load: JournalLoad | null - try { - load = readJournal(sessionId) - } catch { - return [] - } - if (!load) { - return lost - } - if (load.damage || load.newer) { - return [] - } - const written = new Set() - for (const itemId of load.state.items.keys()) { - const identity = parseAgentJournalItemKey(itemId) - const spelled = - identity?.provider === 'legacy' ? spelledProviderTimelineItemKey(identity.recordId) : null - if (spelled !== null) { - written.add(spelled) - } - } - // Warnings survive even if the replacement session that wrote them is superseded. - return lost.filter((key) => !written.has(providerTimelineKeyPart(acpSessionNotRestoredItem(key)))) -} diff --git a/src/main/acp/acp-structured-model-unavailable.test.ts b/src/main/acp/acp-structured-model-unavailable.test.ts index 8e72306881b..2ce109180a5 100644 --- a/src/main/acp/acp-structured-model-unavailable.test.ts +++ b/src/main/acp/acp-structured-model-unavailable.test.ts @@ -9,7 +9,11 @@ import { hostTestAttachParams } from '../native-chat/agent-session-wire/structured-agent-session-host-test-data' import { acpLaunchSpecFor } from './acp-launch-specs' -import { GROK_CONFIG_OPTIONS, waitFor } from './acp-structured-adapter.test-support' +import { + GROK_CONFIG_OPTIONS, + PROVIDER_SESSION, + waitFor +} from './acp-structured-adapter.test-support' import { framesOf, openHostRig, send } from './acp-structured-host.test-support' import { z } from 'zod' @@ -31,9 +35,12 @@ const refusals = [ code: -32603, message: 'Internal error', data: { details: 'Unknown ACP model: retired' }, - kind: 'providerRejected', + // The option refuses an unlisted value, so OMP's own /model (builtin-modes.ts) gets it next. + commandReply: + 'Unknown model: retired. Use ACP `session/setModel` for picker-driven selection or list available models with /model.', + kind: 'modelUnavailable', modelRefusal: true, - reason: "OMP didn't accept this message: Unknown ACP model: retired." + reason: "OMP couldn't use retired. Pick another model and send again." }, { agent: 'grok', @@ -75,7 +82,20 @@ it.each(refusals)( const spec = acpLaunchSpecFor(failure.agent)! const { host, rig, store, ready } = await openHostRig({ spec, - script: (agent) => + script: (agent) => { + agent.on('session/prompt', (frame) => { + const text = JSON.stringify(frame.params) + if ('commandReply' in failure && text.includes('/model retired')) { + agent.notify('session/update', { + sessionId: PROVIDER_SESSION, + update: { + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: failure.commandReply } + } + }) + agent.reply(frame, { stopReason: 'end_turn' }) + } + }) agent.on('session/set_config_option', (frame) => { const { configId, value } = z .object({ configId: z.string(), value: z.string() }) @@ -90,6 +110,7 @@ it.each(refusals)( }) } }) + } }) const attached = await host.attach( CALLER, @@ -114,6 +135,11 @@ it.each(refusals)( }) ).toMatchObject({ ok: true }) } + // Only the hidden model command may reach OMP; the refused messages never do. + const commands = () => + framesOf(rig.child(), 'session/prompt').filter((frame) => + JSON.stringify(frame.params).includes('/model retired') + ) await pick('retired') const attempts = failure.modelRefusal ? ['first attempt', 'second attempt'] : ['first attempt'] for (const text of attempts) { @@ -137,7 +163,7 @@ it.each(refusals)( expect((await host.readOptions(SESSION, { readsWithoutModel: true })).current.model).toBe( 'retired' ) - expect(framesOf(rig.child(), 'session/prompt')).toHaveLength(0) + expect(commands()).toHaveLength(framesOf(rig.child(), 'session/prompt').length) } const failed = await host.journalSnapshot(SESSION) expect( @@ -147,14 +173,17 @@ it.each(refusals)( expect( rows.filter((row) => row.body.kind === 'status' && row.body.failure?.kind === failure.kind) ).toHaveLength(0) + // The hidden command's reply is OMP's raw text: never a row, a turn or unread. + expect(JSON.stringify(rows)).not.toContain('Unknown model:') if (!failure.modelRefusal) { await host.close(SESSION, 'user-close') return } await pick('grok-4.7') await send(host, 'after a new pick') - await waitFor(() => expect(framesOf(rig.child(), 'session/prompt')).toHaveLength(1)) - const prompt = framesOf(rig.child(), 'session/prompt')[0]! + const sent = commands().length + await waitFor(() => expect(framesOf(rig.child(), 'session/prompt')).toHaveLength(sent + 1)) + const prompt = framesOf(rig.child(), 'session/prompt').at(-1)! rig.child().agent.reply(prompt, { stopReason: 'end_turn' }) await rig.settle() expect(store.getRecord(SESSION)?.options?.model).toBe('grok-4.7') diff --git a/src/main/acp/acp-structured-options.ts b/src/main/acp/acp-structured-options.ts index 90dea27e7cb..b14cf50c74d 100644 --- a/src/main/acp/acp-structured-options.ts +++ b/src/main/acp/acp-structured-options.ts @@ -73,6 +73,13 @@ export class AcpStructuredOptions { readonly appliedInput = new Map() readonly applied = new Map() writeRevision = 0 + /** Orca's own writes in flight; config changes outside them are the agent's own. */ + writing = 0 + /** While Orca's hidden model command runs, its reply belongs to it, never to the chat. */ + commandReply: string | null = null + // What a launch-line or model-command selection resolved to. The agent never echoes the raw + // selector, so a concrete change away from this retires it; ordinary control proof never does. + private selectorProof: Readonly> | null = null invalidateInput(key: string): void { this.appliedInput.delete(key) @@ -96,6 +103,26 @@ export class AcpStructuredOptions { this.models = response.models ?? null this.resolvesConfig = origin === 'new' this.appliedInput.clear() + this.selectorProof = null + } + + /** The session runs a model the launch line applied, so sends need not write it again. */ + adoptLaunchModel(model: string): void { + this.appliedInput.set('model', model) + this.picked.add('model') + this.selectorProof = this.currentValues() + } + + /** `resolvedModel` marks selector proof: the model the agent's own command reported. */ + adoptOwnWrite(key: string, value: string, resolvedModel?: string): void { + this.appliedInput.set(key, value) + if (resolvedModel !== undefined) { + this.selectorProof = { ...this.currentValues(), model: resolvedModel } + } else if (key === 'model') { + this.selectorProof = null + } else if (this.selectorProof) { + this.selectorProof = { ...this.selectorProof, effort: this.currentValues().effort } + } } notePick(key: string): void { @@ -103,8 +130,22 @@ export class AcpStructuredOptions { } adoptConfigOptions(configOptions: SessionConfigOption[] | null | undefined): void { - if (configOptions) { - this.configOptions = configOptions + if (!configOptions) { + return + } + this.configOptions = configOptions + const proof = this.selectorProof + if (!proof || this.writing > 0) { + return + } + // A role or :level selector carries thinking too; missing values are no concrete change. + const now = this.currentValues() + const drifted = (key: string) => + now[key] !== undefined && proof[key] !== undefined && now[key] !== proof[key] + if (drifted('model') || drifted('effort')) { + this.selectorProof = null + this.appliedInput.delete('model') + this.appliedInput.delete('effort') } } @@ -260,6 +301,14 @@ export class AcpStructuredOptions { return this.select('mode')?.id ?? 'mode' } + // Only the running values, so config notifications don't project the whole catalog again. + private currentValues(): Readonly> { + return { + model: (this.select('model')?.currentValue ?? this.models?.currentModelId) || undefined, + effort: this.select('thought_level')?.currentValue + } + } + private select(category: string): SelectOption | null { const option = this.configOptions.find( (entry) => entry.category === category || (category === 'model' && entry.id === 'model') diff --git a/src/main/acp/acp-structured-session-adapter.ts b/src/main/acp/acp-structured-session-adapter.ts index 60e3ad798df..0c8f588aae2 100644 --- a/src/main/acp/acp-structured-session-adapter.ts +++ b/src/main/acp/acp-structured-session-adapter.ts @@ -25,12 +25,12 @@ import { AgentSessionOptionRejectedError } from '../native-chat/agent-session-wi import * as stop from './acp-structured-stop' import { acpDispatchPrompt } from './acp-prompt-content' import { - ACP_OPTION_WRITE_TIMEOUT_MS, ACP_STOP_GRACE_MS, type AcpStructuredSessionAdapterDeps } from './acp-structured-session-adapter-deps' import { readAcpLiveOptions } from './acp-structured-options' import { writeAcpSessionOption } from './acp-session-option-write' +import { acpOptionWriteBound, withAcpModelFallback } from './acp-model-command' import { stopAcpChildren, acpChildStopCapabilities } from './acp-structured-child-stop' import * as childState from './acp-structured-child' import { AcpStructuredChildren } from './acp-structured-child-lifecycle' @@ -195,29 +195,33 @@ export class AcpStructuredSessionAdapter implements SessionAdapter { const { sessionId, fence, signal } = input signal?.throwIfAborted() input.onInputPreparation?.() - const optionsApplied = await applyAcpMessageOptions( - session, - input.executionOptions, - (key, value) => this.setOption({ sessionId, fence, key, value, signal }), - () => - this.children.sessions.get(input.sessionId) === session && session.journalClosed === null, - signal - ) - if (!optionsApplied) { - return rejectedAcpDispatch(session) - } - input.signal?.throwIfAborted() - await input.beforeDispatch?.() - input.signal?.throwIfAborted() - await admitStructuredAgentSessionInput(input.admitFreshInput, () => - session.turns.dispatch({ - clientMessageId: input.clientMessageId, - prompt, - requestedAt: input.requestedAt ?? this.now() - }) - ) - // Admission precedes provider confirmation of the send. - return { state: 'admitted' } + return withAcpModelFallback(session, this.writeBound(session, signal), async (fallback) => { + const optionsApplied = await applyAcpMessageOptions( + session, + input.executionOptions, + (key, value) => this.setOption({ sessionId, fence, key, value, signal }), + () => + this.children.sessions.get(input.sessionId) === session && session.journalClosed === null, + signal, + fallback.command + ) + if (!optionsApplied) { + return rejectedAcpDispatch(session) + } + input.signal?.throwIfAborted() + await input.beforeDispatch?.() + input.signal?.throwIfAborted() + const commit = fallback.admitting(() => + session.turns.dispatch({ + clientMessageId: input.clientMessageId, + prompt, + requestedAt: input.requestedAt ?? this.now() + }) + ) + await admitStructuredAgentSessionInput(input.admitFreshInput, commit) + // Admission precedes provider confirmation of the send. + return { state: 'admitted' } + }) } compact: NonNullable = async (input) => @@ -257,17 +261,14 @@ export class AcpStructuredSessionAdapter implements SessionAdapter { } session.options.notePick(input.key) // Bound option writes so they cannot hold the session queue indefinitely. - await writeAcpSessionOption(session.connection, session.options, write, { - key: input.key, - value: input.value, - agent: session.spec.agent, - timeoutMs: this.deps.optionWriteTimeoutMs ?? ACP_OPTION_WRITE_TIMEOUT_MS, - ...(input.signal ? { signal: input.signal } : {}), - onUncertain: (error) => this.children.connectionLost(session, error) - }) + const bound = { ...this.writeBound(session, input.signal), key: input.key, value: input.value } + await writeAcpSessionOption(session.connection, session.options, write, bound) return session.options.reported() } + private writeBound = (session: AcpStructuredSession, signal?: AbortSignal) => + acpOptionWriteBound(this.deps, session, signal, (e) => this.children.connectionLost(session, e)) + canSetOptionWhileIdle = (input: SetOptionInput): boolean => childState.canSetAcpOptionWhileIdle(this.children.sessions.get(input.sessionId), input) diff --git a/src/main/acp/acp-structured-session.ts b/src/main/acp/acp-structured-session.ts index 2449615e485..6180e0932be 100644 --- a/src/main/acp/acp-structured-session.ts +++ b/src/main/acp/acp-structured-session.ts @@ -16,6 +16,7 @@ import type { AcpLaunchSpec } from './acp-launch-specs' import type { AcpChildStops } from './acp-dialects/acp-dialect' import { acpAgentName } from './acp-structured-agent-definitions' import type { AcpSessionEvent } from './acp-session-runtime' +import { absorbsAcpModelCommandOutput } from './acp-model-command' import type { AcpStructuredConnection } from './acp-structured-connection' import type { AcpStructuredLane } from './acp-structured-lane' import type { AcpStructuredOptions } from './acp-structured-options' @@ -62,6 +63,9 @@ export function routeAcpSessionEvent( session.options.adoptConfigOptions(update.configOptions) } } + if (absorbsAcpModelCommandOutput(session.options, event)) { + return + } const { translator } = session.lane session.lane.apply( reattaching diff --git a/src/main/acp/acp-structured-sign-in.test.ts b/src/main/acp/acp-structured-sign-in.test.ts index 6f710ab8231..5f0eb05e3fb 100644 --- a/src/main/acp/acp-structured-sign-in.test.ts +++ b/src/main/acp/acp-structured-sign-in.test.ts @@ -133,9 +133,10 @@ it.each([ 'No API key found for anthropic.\n\nUse /login, set an API key environment variable, or create /host/agent.db', 'notSignedIn' ], + // OMP says this for an unresolved launch selector as well as when signed out. [ 'No model selected.\n\nUse /login, set an API key environment variable, or create /host/agent.db\n\nThen use /model to select a model.', - 'notSignedIn' + 'modelNotSelected' ], ['No model selected', undefined], ['Rate limit exceeded', undefined], @@ -160,5 +161,9 @@ it.each([ ({ body }) => body.kind === 'status' && body.tone === 'error' ) expect(row?.body.kind === 'status' ? row.body.failure?.kind : undefined).toBe(kind) - expect(row?.body.kind === 'status' ? row.body.text : '').toContain(detail) + expect(row?.body.kind === 'status' ? row.body.text : '').toContain( + kind === 'modelNotSelected' + ? 'OMP has no model selected. Check your model selection and OMP sign-in, then send again.' + : detail + ) }) diff --git a/src/main/acp/acp-structured-steer.test.ts b/src/main/acp/acp-structured-steer.test.ts index faddbcd9802..ce925dbfb56 100644 --- a/src/main/acp/acp-structured-steer.test.ts +++ b/src/main/acp/acp-structured-steer.test.ts @@ -10,10 +10,13 @@ import { envelope } from '../native-chat/agent-session-wire/structured-agent-session-host-test-harness' import { HOST_TEST_SESSION as SESSION } from '../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import type { StructuredAgentSessionAdmitFreshInput } from '../native-chat/agent-session-wire/structured-agent-session-input-admission' import type { AcpScriptedAgent, FakeFrame } from './acp-scripted-agent.test-support' import { awaitAcpTurnEnd } from './acp-structured-stop' +import { OMP_ACP_DIALECT } from './acp-dialects/omp-dialect' import { isAcpReadySession } from './acp-structured-child' import { + GROK, openAcpAdapterRig, PROVIDER_SESSION, replyChunk, @@ -54,6 +57,75 @@ function answersCancels(agent: AcpScriptedAgent): void { }) } +// OMP: the model option refuses a role, and its own /model resolves it (builtin-modes.ts). +async function openRoleRig( + hold: { holdOption?: boolean; holdCommand?: boolean; commandReply?: string } = {} +) { + const spec = { ...GROK, dialect: { ...GROK.dialect, modelCommand: OMP_ACP_DIALECT.modelCommand } } + const held = { option: () => {}, command: () => {} } + const rig = await openAcpAdapterRig({ + spec, + script: (agent) => { + agent.on('session/set_config_option', (frame) => { + const refuse = () => + agent.fail(frame, -32603, 'Internal error', { details: 'Unknown ACP model: @worker_be' }) + if (hold.holdOption) { + held.option = refuse + } else { + refuse() + } + }) + agent.on('session/prompt', (frame) => { + if (!JSON.stringify(frame.params).includes('/model @worker_be')) { + return + } + const answer = () => { + agent.notify('session/update', { + sessionId: PROVIDER_SESSION, + update: { + sessionUpdate: 'agent_message_chunk', + content: { type: 'text', text: hold.commandReply ?? 'Model set to grok-4.6.' } + } + }) + agent.reply(frame, { stopReason: 'end_turn' }) + } + if (hold.holdCommand) { + held.command = answer + } else { + answer() + } + }) + } + }) + await rig.acquire() + return { rig, release: { option: () => held.option(), command: () => held.command() } } +} + +type AdapterRig = Awaited> + +function sendRole( + rig: AdapterRig, + clientMessageId: string, + admitFreshInput?: StructuredAgentSessionAdmitFreshInput +) { + return rig.adapter.dispatch({ + sessionId: ADAPTER_SESSION, + clientMessageId, + body: message('hello'), + fence: 1, + executionOptions: { model: '@worker_be' }, + ...(admitFreshInput ? { admitFreshInput } : {}) + }) +} + +function promptsSent(rig: AdapterRig): string[] { + return rig + .sent('session/prompt') + .map((frame) => + JSON.stringify(frame.params).includes('/model @worker_be') ? 'command' : promptIdOf(frame) + ) +} + describe('permission changes with already admitted ACP input', () => { it('releases deadline and abort waiters without disturbing the active input', async () => { const rig = await openAcpAdapterRig() @@ -196,6 +268,101 @@ describe('a send while a Grok prompt runs', () => { expect(rig.settled.map((settled) => settled.clientMessageId)).toEqual(['first', 'steer-1']) }) + it('runs a role steer the model option refuses in its place: the steer ahead is cancelled first', async () => { + const { rig } = await openRoleRig() + await sendHello(rig, 'first') + await rig.frame('session/prompt') + await rig.settle() + await sendHello(rig, 'steer-1') + const role = sendRole(rig, 'steer-2') + await rig.settle() + answersCancels(rig.child().agent) + rig.child().agent.reply(rig.sent('session/prompt')[0]!, { stopReason: 'cancelled' }) + await expect(role).resolves.toEqual({ state: 'admitted' }) + await rig.frame('session/prompt', 3) + expect(promptsSent(rig)).toEqual([ + 'prompt:first', + 'prompt:steer-1', + 'command', + 'prompt:steer-2' + ]) + // steer-1 started and was cancelled for the newer steer, never left to answer in full. + expect(rig.sent('session/cancel')).toHaveLength(2) + }) + + // No abort signal in these: the withdrawal itself must notice the Stop. + it.each(['while it waits', 'while its model option is answered'] as const)( + 'sends nothing more for a role steer that a Stop reaches %s', + async (when) => { + const { rig, release } = await openRoleRig({ holdOption: when !== 'while it waits' }) + await sendHello(rig, 'first') + const first = await rig.frame('session/prompt') + await rig.settle() + const role = sendRole(rig, 'role').catch((error: unknown) => error) + await rig.settle() + await rig.adapter.cancelTurn({ sessionId: ADAPTER_SESSION, fence: 1 }) + rig.child().agent.reply(first, { stopReason: 'cancelled' }) + await rig.settle() + // Refused only after the turn ahead ended: no wait is left to notice the Stop. + release.option() + expect(await role).toMatchObject({ + rejection: { kind: 'cancelled', neverReachedAgent: true } + }) + expect(promptsSent(rig)).toEqual(['prompt:first']) + // A Stop covers only what it reached; the next message goes out. + await expect(sendHello(rig, 'later')).resolves.toEqual({ state: 'admitted' }) + await rig.frame('session/prompt', 1) + } + ) + + it.each([ + ['its model command runs', 'Model set to grok-4.6.'], + // OMP's own refusal after the Stop must not be worded as the model's failure. + ['its model command runs', 'Failed to set model: prompt rebuild failed'], + ['it waits to be admitted', 'Model set to grok-4.6.'] + ] as const)( + 'withdraws a role steer a Stop reaches while %s (%s), with no turn running', + async (when, commandReply) => { + const admitted = Promise.withResolvers() + const holdCommand = when === 'its model command runs' + const { rig, release } = await openRoleRig({ holdCommand, commandReply }) + const role = sendRole(rig, 'role', async (enqueue) => { + await admitted.promise + return enqueue('own', false) + }) + await rig.frame('session/prompt') + await rig.settle() + await expect( + rig.adapter.cancelTurn({ sessionId: ADAPTER_SESSION, fence: 1 }) + ).resolves.toEqual({ cancelled: true }) + release.command() + admitted.resolve() + await expect(role).rejects.toMatchObject({ + rejection: { kind: 'cancelled', neverReachedAgent: true } + }) + expect(promptsSent(rig)).toEqual(['command']) + } + ) + + it('refuses a Stop with no turn running while an idle role send waits on its model option', async () => { + // Before the fallback this is an ordinary send: with nothing to stop, Stop is refused, not + // accepted and ignored. The host's Stop aborts the send's signal instead + // (acp-structured-host-option-hang.test.ts). + const { rig, release } = await openRoleRig({ holdOption: true }) + const role = sendRole(rig, 'role') + await waitFor(() => expect(rig.sent('session/set_config_option')).toHaveLength(1)) + await expect(rig.adapter.cancelTurn({ sessionId: ADAPTER_SESSION, fence: 1 })).resolves.toEqual( + { + cancelled: false, + refusal: { turnNotRunning: true } + } + ) + release.option() + await expect(role).resolves.toEqual({ state: 'admitted' }) + await rig.frame('session/prompt', 1) + expect(promptsSent(rig)).toEqual(['command', 'prompt:role']) + }) + it('withdraws a steer a Stop reaches before its cancel lands', async () => { const rig = await openAcpAdapterRig() await rig.acquire() diff --git a/src/main/acp/acp-structured-turns.ts b/src/main/acp/acp-structured-turns.ts index 0a571a68be7..70648f8700c 100644 --- a/src/main/acp/acp-structured-turns.ts +++ b/src/main/acp/acp-structured-turns.ts @@ -2,7 +2,6 @@ import { agentSessionFailureFact, - providerDiagnostic, type SubmissionRejectionFact } from '../../shared/agent-session/failures/agent-session-failure' import { @@ -18,6 +17,7 @@ import { acpCompactPrompt } from './acp-compaction-turn' import { AcpAgentError, AcpAuthRequiredError, AcpConnectionClosedError } from './acp-errors' import type { AcpStructuredConnection } from './acp-structured-connection' import type { AcpStructuredLane } from './acp-structured-lane' +import { acpPromptRejection } from './acp-turn-failures' import type { ContentBlock } from './generated/acp-protocol.generated' export type AcpDispatchSettlement = { clientMessageId: string } & ( @@ -37,6 +37,8 @@ export type AcpStructuredTurnsDeps = { settle: (settlement: AcpDispatchSettlement) => void /** Replace the child so the next send reopens the session. */ sessionLost: (error: Error) => void + /** The agent had no model for the prompt, which it may word like a sign-in failure. */ + modelRefusal?: (error: AcpAgentError) => SubmissionRejectionFact | undefined } export class AcpStructuredTurns { @@ -48,6 +50,10 @@ export class AcpStructuredTurns { private readonly idleWaiters = new Set<() => void>() private ended = false private stopAt: number | null = null + // Steers still preparing their controls; they hold their place like queued steers. + private preparingSteers = 0 + // Counts Stops: finish() clears stopAt before a preparing steer can see it. + private withdrawals = 0 constructor(private readonly deps: AcpStructuredTurnsDeps) {} @@ -74,7 +80,11 @@ export class AcpStructuredTurns { } get holdsSteers(): boolean { - return this.steers.length > 0 + return this.steers.length > 0 || this.preparingSteers > 0 + } + + get withdrawalEpoch(): number { + return this.withdrawals } get stopped(): boolean { @@ -127,6 +137,19 @@ export class AcpStructuredTurns { }) } + /** A steer whose controls must run as a prompt first holds its place until released: Stop + * reaches it, and answers ahead of it are cancelled as they start, as for any newer steer. */ + holdSteer(): () => void { + this.preparingSteers += 1 + this.cancelForSteer() + return () => void this.preparingSteers-- + } + + /** A Stop or teardown since `epoch` withdraws a preparing steer like any held steer. */ + withdrawnSince(epoch: number): 'stopped' | 'ended' | null { + return this.ended ? 'ended' : this.withdrawals === epoch ? null : 'stopped' + } + dispatch(send: Send): void { this.unsettled.add(send.clientMessageId) if (this.active) { @@ -175,6 +198,7 @@ export class AcpStructuredTurns { } private withdrawSteers(): boolean { + this.withdrawals += 1 const withdrawn = this.steers.splice(0) for (const send of withdrawn) { this.reject( @@ -219,7 +243,7 @@ export class AcpStructuredTurns { ? { promptId, requestId: promptId } : undefined const answered = this.deps.connection.prompt(send.prompt, meta) - if (this.steers.length > 0) { + if (this.steers.length > 0 || this.preparingSteers > 0) { this.cancelForSteer() } answered.then( @@ -257,15 +281,11 @@ export class AcpStructuredTurns { private agentFailed(send: Send, error: AcpAgentError): void { const { lane } = this.deps const refusal = lane.translator.promptRefused(send.clientMessageId, error) + // Also retires the proof of a model the agent turned out not to have. + const noModel = this.deps.modelRefusal?.(error) if (refusal !== null) { - const detail = providerDiagnostic(refusal, 'person') - this.reject( - send.clientMessageId, - agentSessionFailureFact( - lane.translator.authenticationRequired(error) ? 'notSignedIn' : 'providerRejected', - detail ? { detail } : {} - ) - ) + const signedOut = lane.translator.authenticationRequired(error) + this.reject(send.clientMessageId, acpPromptRejection(refusal, signedOut, noModel)) } else { lane.apply(lane.translator.promptFailed(send.clientMessageId, error, this.deps.now())) } diff --git a/src/main/acp/acp-turn-failures.ts b/src/main/acp/acp-turn-failures.ts index 4182ffe49a4..30cbf3bfcdf 100644 --- a/src/main/acp/acp-turn-failures.ts +++ b/src/main/acp/acp-turn-failures.ts @@ -21,12 +21,18 @@ export function acpStopReasonFailed(stopReason: string): boolean { export type AcpTurnFailureReport = Pick< AcpTurnEnding, - 'stopReason' | 'failureDetail' | 'notSignedIn' | 'usageLimit' | 'providerFailure' + | 'stopReason' + | 'failureDetail' + | 'notSignedIn' + | 'modelNotSelected' + | 'usageLimit' + | 'providerFailure' > export type AcpTurnFailureEvidence = { text: string notSignedIn: boolean + modelNotSelected?: boolean usageLimited: boolean providerFailure: boolean usageLimit?: AgentSessionUsageLimit @@ -39,6 +45,7 @@ export function mergeAcpTurnFailureEvidence( stopReason, failureDetail: text, notSignedIn, + modelNotSelected, usageLimit, providerFailure }: AcpTurnFailureReport @@ -49,6 +56,7 @@ export function mergeAcpTurnFailureEvidence( previous?.text || (text === undefined ? '' : (providerDiagnostic(text, 'person')?.text ?? '')), notSignedIn: authenticationRequired, + modelNotSelected: modelNotSelected === true || previous?.modelNotSelected === true, usageLimited: !authenticationRequired && (stopReason === 'rate_limit' || previous?.usageLimited === true), providerFailure: providerFailure === true || previous?.providerFailure === true, @@ -58,7 +66,12 @@ export function mergeAcpTurnFailureEvidence( /** Agents report their own refusals as errors too; only these causes make a failure the provider's. */ export function acpProviderFailed(evidence: AcpTurnFailureEvidence): boolean { - return evidence.notSignedIn || evidence.usageLimited || evidence.providerFailure + return ( + evidence.notSignedIn || + evidence.modelNotSelected === true || + evidence.usageLimited || + evidence.providerFailure + ) } /** Prefer provider error details over generic messages such as Internal error. */ @@ -88,6 +101,24 @@ export function acpAuthenticationRequired(dialect: AcpDialect, error: unknown): ) } +/** What a failed prompt request says about its turn's ending. */ +export function acpPromptFailureEnding( + dialect: AcpDialect, + error: Error, + at: number +): AcpTurnEnding { + const agentError = error instanceof AcpAgentError ? error : undefined + const failure = agentError ? dialect.promptFailure?.(agentError, at) : undefined + return { + ...failure, + stopReason: failure?.stopReason ?? 'error', + at, + failureDetail: agentError ? acpPromptErrorDetail(dialect, agentError) : undefined, + notSignedIn: acpAuthenticationRequired(dialect, error), + modelNotSelected: agentError ? dialect.modelCommand?.noModel(agentError) === true : false + } +} + export function acpSignInRequiredFailure( dialect: AcpDialect, error: AcpAgentError @@ -96,6 +127,22 @@ export function acpSignInRequiredFailure( return agentSessionFailureFact('notSignedIn', detail ? { detail } : {}) } +/** Why the agent refused a prompt, as the person is told; a missing model outranks its sign-in wording. */ +export function acpPromptRejection( + refusal: string, + signedOut: boolean, + noModel: SubmissionRejectionFact | undefined +): SubmissionRejectionFact { + if (noModel) { + return noModel + } + const detail = providerDiagnostic(refusal, 'person') + return agentSessionFailureFact( + signedOut ? 'notSignedIn' : 'providerRejected', + detail ? { detail } : {} + ) +} + /** Deduplicate failure rows by turn, accepting later reasons when earlier reports lacked one. */ export class AcpTurnFailures { private readonly rows = new BoundedMap({ @@ -150,6 +197,7 @@ export class AcpTurnFailures { written && written.text === (diagnostic?.text ?? '') && written.notSignedIn === authenticationRequired && + written.modelNotSelected === evidence.modelNotSelected && written.usageLimited === usageLimited && written.usageLimit?.resetsAt === limit?.resetsAt && written.usageLimit?.window === limit?.window @@ -159,12 +207,14 @@ export class AcpTurnFailures { this.rows.set(turn, evidence) const failure = authenticationRequired ? agentSessionFailureFact('notSignedIn', { detail: diagnostic }) - : usageLimited - ? agentSessionFailureFact('usageLimitReached', { - detail: diagnostic, - usageLimit: limit - }) - : null + : evidence.modelNotSelected + ? agentSessionFailureFact('modelNotSelected') + : usageLimited + ? agentSessionFailureFact('usageLimitReached', { + detail: diagnostic, + usageLimit: limit + }) + : null return [ { type: 'item.update', diff --git a/src/main/runtime/rpc/methods/orchestration/worker/worker-launch-preferences.test.ts b/src/main/runtime/rpc/methods/orchestration/worker/worker-launch-preferences.test.ts index 713da174fd4..735c2f17e52 100644 --- a/src/main/runtime/rpc/methods/orchestration/worker/worker-launch-preferences.test.ts +++ b/src/main/runtime/rpc/methods/orchestration/worker/worker-launch-preferences.test.ts @@ -39,14 +39,23 @@ describe('orchestration worker launch preferences', () => { }) }) - it('rejects OMP effort until its model options support it', () => { + it('passes an OMP role and thinking level to the launch arguments', () => { + const launch = resolveWorkerLaunchPreferences({ + agent: 'omp', + model: '@worker_be', + effort: 'medium' + }) + + expect(launch.preferences).toEqual({ model: '@worker_be', effort: 'medium' }) + expect(resolveAgentSessionOptionLaunch('omp', launch.preferences, [], false).args).toEqual([ + '--model', + '@worker_be', + '--thinking', + 'medium' + ]) expect(() => - resolveWorkerLaunchPreferences({ - agent: 'omp', - model: 'google-vertex/claude-haiku-4-5@20251001', - effort: 'low' - }) - ).toThrow('does not support effort low') + resolveWorkerLaunchPreferences({ agent: 'omp', model: '@worker_be', effort: 'turbo' }) + ).toThrow('does not support effort turbo') }) it('passes an opaque Claude model and portable effort through the shared catalog', () => { diff --git a/src/renderer/src/components/native-chat/agent-session-availability-words-text.ts b/src/renderer/src/components/native-chat/agent-session-availability-words-text.ts index 6f0d7d65def..50df24379af 100644 --- a/src/renderer/src/components/native-chat/agent-session-availability-words-text.ts +++ b/src/renderer/src/components/native-chat/agent-session-availability-words-text.ts @@ -20,6 +20,8 @@ type AvailabilityCopyId = Extract< | 'cliMissingInWslDistro' | 'cliTooOld' | 'modelUnavailable' + | 'modelUnavailableUpdate' + | 'modelNotSelected' > export const AVAILABILITY_PIECES: Record< @@ -82,6 +84,18 @@ export const AVAILABILITY_PIECES: Record< COPY.modelUnavailable, values ), + modelNotSelected: (values) => + translate( + 'components.native-chat.failureWords.modelNotSelected', + COPY.modelNotSelected, + values + ), + modelUnavailableUpdate: (values) => + translate( + 'components.native-chat.failureWords.modelUnavailableUpdate', + COPY.modelUnavailableUpdate, + values + ), cliMissing: (values) => translate('components.native-chat.failureWords.cliMissing', COPY.cliMissing, values), cliMissingInWslDistro: (values) => diff --git a/src/renderer/src/components/native-chat/agent-session-failure-words-text.test.ts b/src/renderer/src/components/native-chat/agent-session-failure-words-text.test.ts new file mode 100644 index 00000000000..6ae76e2cb93 --- /dev/null +++ b/src/renderer/src/components/native-chat/agent-session-failure-words-text.test.ts @@ -0,0 +1,41 @@ +import { afterEach, expect, it } from 'vitest' +import { i18n } from '@/i18n/i18n' +import { agentSessionFailureSentence } from '../../../../shared/agent-session/failures/agent-session-failure-words' +import { sayAgentSessionFailureTranslated } from './agent-session-failure-words-text' + +afterEach(async () => { + await i18n.changeLanguage('en') +}) + +it.each([ + [ + 'en', + 'OMP has no model selected. Check your model selection and OMP sign-in, then send again.', + "OMP couldn't use @worker_be. Update OMP to 18.1.9 or later to keep it after a restart, or pick another model and send again." + ], + [ + 'zh', + 'OMP 没有选择模型。请检查模型选择和 OMP 登录状态,然后重新发送。', + expect.stringContaining('请将 OMP 更新到 18.1.9 或更高版本') + ] +] as const)( + 'words a missing OMP model and the update hint on desktop (%s)', + async (locale, none, update) => { + await i18n.changeLanguage(locale) + const say = (fact: Parameters[0]) => + agentSessionFailureSentence( + fact, + 'rejection', + { agentName: 'OMP' }, + sayAgentSessionFailureTranslated + ) + expect(say({ kind: 'modelNotSelected' })).toBe(none) + expect( + say({ + kind: 'modelUnavailable', + detail: { text: '@worker_be', audience: 'log' }, + agentUpdate: '18.1.9' + }) + ).toEqual(update) + } +) diff --git a/src/renderer/src/i18n/en-runtime-required.json b/src/renderer/src/i18n/en-runtime-required.json index d5833dc7916..1a67856fecf 100644 --- a/src/renderer/src/i18n/en-runtime-required.json +++ b/src/renderer/src/i18n/en-runtime-required.json @@ -1598,6 +1598,8 @@ "managedAccountEnvOverride": "This Claude launch sets its own Anthropic sign-in variables. Remove them to use a managed Claude account.", "managedAccountUnsupported": "While a Claude account is added in WSL, Claude chats need a Windows Claude account.", "modelUnavailable": "{{agent}} couldn't use {{detail}}. Pick another model and send again.", + "modelUnavailableUpdate": "{{agent}} couldn't use {{detail}}. Update {{agent}} to {{minimumVersion}} or later to keep it after a restart, or pick another model and send again.", + "modelNotSelected": "{{agent}} has no model selected. Check your model selection and {{agent}} sign-in, then send again.", "noTurnToStop": "{{agent}} had no turn running to stop.", "notDelivered": "This message was not delivered.", "notDeliveredSendAgain": "This message was not delivered. Send it again to continue.", diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index b590eadccbb..3431fc1945a 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -19687,6 +19687,8 @@ "providerExitedAnswer": "{{agent}} has stopped, so your answer was not sent. Send a message to continue.", "claudeEffortInvalid": "Claude effort is invalid; choose low, medium, high, xhigh, or max and send again.", "modelUnavailable": "{{agent}} couldn't use {{detail}}. Pick another model and send again.", + "modelUnavailableUpdate": "{{agent}} couldn't use {{detail}}. Update {{agent}} to {{minimumVersion}} or later to keep it after a restart, or pick another model and send again.", + "modelNotSelected": "{{agent}} has no model selected. Check your model selection and {{agent}} sign-in, then send again.", "providerRejected": "{{agent}} didn't accept this message.", "providerRejectedQuoted": "{{agent}} didn't accept this message: {{detail}}.", "attachmentEmpty": "An image on this message is empty, so the message was not sent.", diff --git a/src/renderer/src/i18n/locales/zh-Hant.json b/src/renderer/src/i18n/locales/zh-Hant.json index fdc7e6e3e4b..f2cedee2ac8 100644 --- a/src/renderer/src/i18n/locales/zh-Hant.json +++ b/src/renderer/src/i18n/locales/zh-Hant.json @@ -18903,6 +18903,8 @@ "providerExitedRejection": "{{agent}} 在傳送此訊息前已停止。", "providerExitedAnswer": "{{agent}} 已停止,因此您的回答未傳送。傳送訊息以繼續。", "modelUnavailable": "{{agent}} 無法使用 {{detail}}。請選擇其他模型並重新傳送。", + "modelUnavailableUpdate": "{{agent}} 無法使用 {{detail}}。請將 {{agent}} 更新到 {{minimumVersion}} 或更新版本,以便重新啟動後繼續使用;或選擇其他模型並重新傳送。", + "modelNotSelected": "{{agent}} 沒有選擇模型。請檢查模型選擇和 {{agent}} 登入狀態,然後重新傳送。", "providerRejected": "{{agent}} 未接受此訊息。", "providerRejectedQuoted": "{{agent}} 未接受此訊息:{{detail}}。", "attachmentEmpty": "此訊息中的一張圖片為空,因此訊息未傳送。", diff --git a/src/renderer/src/i18n/locales/zh.json b/src/renderer/src/i18n/locales/zh.json index c7bac3bed6e..9d6efbd61aa 100644 --- a/src/renderer/src/i18n/locales/zh.json +++ b/src/renderer/src/i18n/locales/zh.json @@ -18440,6 +18440,8 @@ "providerExitedRejection": "{{agent}} 在发送此消息前已停止。", "providerExitedAnswer": "{{agent}} 已停止,因此您的回答未发送。发送消息以继续。", "modelUnavailable": "{{agent}} 无法使用 {{detail}}。请选择其他模型并重新发送。", + "modelUnavailableUpdate": "{{agent}} 无法使用 {{detail}}。请将 {{agent}} 更新到 {{minimumVersion}} 或更高版本,以便重启后继续使用;或者选择其他模型并重新发送。", + "modelNotSelected": "{{agent}} 没有选择模型。请检查模型选择和 {{agent}} 登录状态,然后重新发送。", "providerRejected": "{{agent}} 未接受此消息。", "providerRejectedQuoted": "{{agent}} 未接受此消息:{{detail}}。", "attachmentEmpty": "此消息中的一张图片为空,因此消息未发送。", diff --git a/src/shared/agent-session/failures/agent-session-failure-copy.ts b/src/shared/agent-session/failures/agent-session-failure-copy.ts index a1a8f1d6d78..9bd1f0a15e9 100644 --- a/src/shared/agent-session/failures/agent-session-failure-copy.ts +++ b/src/shared/agent-session/failures/agent-session-failure-copy.ts @@ -102,6 +102,10 @@ export const AGENT_SESSION_FAILURE_COPY = { claudeEffortInvalid: 'Claude effort is invalid; choose low, medium, high, xhigh, or max and send again.', modelUnavailable: "{{agent}} couldn't use {{detail}}. Pick another model and send again.", + modelNotSelected: + '{{agent}} has no model selected. Check your model selection and {{agent}} sign-in, then send again.', + modelUnavailableUpdate: + "{{agent}} couldn't use {{detail}}. Update {{agent}} to {{minimumVersion}} or later to keep it after a restart, or pick another model and send again.", providerRejected: "{{agent}} didn't accept this message.", pluginInputRequired: '{{agent}} stopped because the "{{plugin}}" plugin is waiting for input in a terminal pane. Disable the plugin for chat sessions, or run the task in a {{agent}} terminal.', diff --git a/src/shared/agent-session/failures/agent-session-failure-details.ts b/src/shared/agent-session/failures/agent-session-failure-details.ts new file mode 100644 index 00000000000..7f8ef05d5d8 --- /dev/null +++ b/src/shared/agent-session/failures/agent-session-failure-details.ts @@ -0,0 +1,49 @@ +// Readers for fact details that stand alone, apart from the fact's own shape. + +import { isValidAppVersion } from '../../app-version' + +/** Which of Orca's checks an image failed. A new one needs a sentence before it compiles. */ +export const AGENT_SESSION_ATTACHMENT_PROBLEM_REASONS = [ + 'empty', + 'tooLarge', + 'tooMany', + 'totalTooLarge', + 'unsupportedType', + 'notAFile', + 'noSource' +] as const +export type AgentSessionAttachmentProblemReason = + (typeof AGENT_SESSION_ATTACHMENT_PROBLEM_REASONS)[number] + +export type AgentSessionAttachmentProblem = { + reason: AgentSessionAttachmentProblemReason + /** The limit it broke: bytes for `tooLarge` and `totalTooLarge`, a count for `tooMany`. */ + limit?: number +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +export function readAttachmentProblem(value: unknown): AgentSessionAttachmentProblem | undefined { + if (!isRecord(value)) { + return undefined + } + const reason = AGENT_SESSION_ATTACHMENT_PROBLEM_REASONS.find((known) => known === value.reason) + if (!reason) { + return undefined + } + const limit = value.limit + return typeof limit === 'number' && Number.isFinite(limit) && limit > 0 + ? { reason, limit } + : { reason } +} + +const AGENT_UPDATE_MAX_LENGTH = 64 + +/** A release the agent must reach: a bounded version, never free text. */ +export function readAgentUpdate(value: unknown): value is string { + return ( + typeof value === 'string' && value.length <= AGENT_UPDATE_MAX_LENGTH && isValidAppVersion(value) + ) +} diff --git a/src/shared/agent-session/failures/agent-session-failure-fact-schema.ts b/src/shared/agent-session/failures/agent-session-failure-fact-schema.ts index 5ca1d0eaf4e..44c21f7510c 100644 --- a/src/shared/agent-session/failures/agent-session-failure-fact-schema.ts +++ b/src/shared/agent-session/failures/agent-session-failure-fact-schema.ts @@ -8,5 +8,6 @@ export const AgentSessionFailureFactSchema = z.object({ argumentProblem: z .object({ agent: z.string(), option: z.string(), problem: z.string() }) .optional(), - requestTimeout: z.looseObject({}).optional() + requestTimeout: z.looseObject({}).optional(), + agentUpdate: z.string().max(64).optional() }) diff --git a/src/shared/agent-session/failures/agent-session-failure-words.ts b/src/shared/agent-session/failures/agent-session-failure-words.ts index 960209f50d0..fe50b8a9e02 100644 --- a/src/shared/agent-session/failures/agent-session-failure-words.ts +++ b/src/shared/agent-session/failures/agent-session-failure-words.ts @@ -196,8 +196,13 @@ const FAILURE_SENTENCES = { ), restartFailed: couldNot('couldNotRestart'), claudeEffortInvalid: (_context, _fact, _surface, say) => say('claudeEffortInvalid'), - modelUnavailable: (context, fact, _surface, say) => - say('modelUnavailable', { ...agent(say, context), detail: fact.detail?.text ?? 'this model' }), + modelUnavailable: (context, fact, _surface, say) => { + const words = { ...agent(say, context), detail: fact.detail?.text ?? 'this model' } + return fact.agentUpdate + ? say('modelUnavailableUpdate', { ...words, minimumVersion: fact.agentUpdate }) + : say('modelUnavailable', words) + }, + modelNotSelected: (context, _fact, _surface, say) => say('modelNotSelected', agent(say, context)), providerRejected: (context, fact, _surface, say) => quotingPersonDetail( say, diff --git a/src/shared/agent-session/failures/agent-session-failure.ts b/src/shared/agent-session/failures/agent-session-failure.ts index 3cdce390fb8..60981877dbc 100644 --- a/src/shared/agent-session/failures/agent-session-failure.ts +++ b/src/shared/agent-session/failures/agent-session-failure.ts @@ -1,3 +1,8 @@ +import { + readAgentUpdate, + readAttachmentProblem, + type AgentSessionAttachmentProblem +} from './agent-session-failure-details' import type { AgentSessionAccountKind } from '../agent-session-availability' import { readAgentSessionArgumentProblem, @@ -49,6 +54,8 @@ export const AGENT_SESSION_FAILURE_KINDS = [ 'providerRejected', 'pluginInputRequired', 'modelUnavailable', + /** The agent had no model when the message reached it; why (selection, sign-in) is unknown. */ + 'modelNotSelected', 'claudeEffortInvalid', 'attachmentInvalid', 'attachmentUnreadable', @@ -132,24 +139,11 @@ export type ProviderDiagnostic = { /** Bound stderr dumps to the lease exit-reason cap so diagnostics always fit the record. */ export const MAX_PROVIDER_DIAGNOSTIC_CHARS = 512 -/** Which of Orca's checks an image failed. A new one needs a sentence before it compiles. */ -export const AGENT_SESSION_ATTACHMENT_PROBLEM_REASONS = [ - 'empty', - 'tooLarge', - 'tooMany', - 'totalTooLarge', - 'unsupportedType', - 'notAFile', - 'noSource' -] as const -export type AgentSessionAttachmentProblemReason = - (typeof AGENT_SESSION_ATTACHMENT_PROBLEM_REASONS)[number] - -export type AgentSessionAttachmentProblem = { - reason: AgentSessionAttachmentProblemReason - /** The limit it broke: bytes for `tooLarge` and `totalTooLarge`, a count for `tooMany`. */ - limit?: number -} +export { + AGENT_SESSION_ATTACHMENT_PROBLEM_REASONS, + type AgentSessionAttachmentProblem, + type AgentSessionAttachmentProblemReason +} from './agent-session-failure-details' /** What the provider said it is retrying, in its own fields. */ export type AgentSessionProviderRetry = { @@ -187,6 +181,9 @@ export type AgentSessionFailureFact = { backgroundStop?: AgentSessionBackgroundStop /** On `startFailed`: the provider request that got no answer before Orca's deadline. */ requestTimeout?: AgentSessionRequestTimeout + /** On `modelUnavailable`: the first agent release that can use what was refused, when the + * running agent reported an older one. A fixed capability boundary, never the installed version. */ + agentUpdate?: string } export type AgentSessionBackgroundStop = 'task' | 'all' @@ -224,6 +221,7 @@ export function agentSessionFailureFact( neverReachedAgent?: true backgroundStop?: AgentSessionBackgroundStop requestTimeout?: AgentSessionRequestTimeout + agentUpdate?: string } = {} ): AgentSessionFailureFact & { kind: TKind } { // Re-bounded here, so no writer can store more than the cap however it built the detail. @@ -241,7 +239,10 @@ export function agentSessionFailureFact( ...(extra.argumentProblem ? { argumentProblem: extra.argumentProblem } : {}), ...(extra.neverReachedAgent ? { neverReachedAgent: true as const } : {}), ...(extra.backgroundStop ? { backgroundStop: extra.backgroundStop } : {}), - ...(extra.requestTimeout ? { requestTimeout: extra.requestTimeout } : {}) + ...(extra.requestTimeout ? { requestTimeout: extra.requestTimeout } : {}), + ...(kind === 'modelUnavailable' && readAgentUpdate(extra.agentUpdate) + ? { agentUpdate: extra.agentUpdate } + : {}) } } @@ -257,20 +258,6 @@ export function isProviderDiagnostic(value: unknown): value is ProviderDiagnosti ) } -function readAttachmentProblem(value: unknown): AgentSessionAttachmentProblem | undefined { - if (!isRecord(value)) { - return undefined - } - const reason = AGENT_SESSION_ATTACHMENT_PROBLEM_REASONS.find((known) => known === value.reason) - if (!reason) { - return undefined - } - const limit = value.limit - return typeof limit === 'number' && Number.isFinite(limit) && limit > 0 - ? { reason, limit } - : { reason } -} - /** A retry as a reader meets it; undefined when it names no field. */ export function readProviderRetry(value: unknown): AgentSessionProviderRetry | undefined { if (!isRecord(value)) { @@ -325,7 +312,8 @@ export function readAgentSessionFailureFact(value: unknown): AgentSessionFailure ...(value.backgroundStop === 'task' || value.backgroundStop === 'all' ? { backgroundStop: value.backgroundStop } : {}), - ...(requestTimeout ? { requestTimeout } : {}) + ...(requestTimeout ? { requestTimeout } : {}), + ...(readAgentUpdate(value.agentUpdate) ? { agentUpdate: value.agentUpdate } : {}) }) } diff --git a/src/shared/agent-session/failures/structured-agent-session-rejection-words.test.ts b/src/shared/agent-session/failures/structured-agent-session-rejection-words.test.ts index 1c8d9f2dc7d..be30f3255b7 100644 --- a/src/shared/agent-session/failures/structured-agent-session-rejection-words.test.ts +++ b/src/shared/agent-session/failures/structured-agent-session-rejection-words.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest' import type { AgentSessionFailureFact } from './agent-session-failure' +import { AgentSessionFailureFactSchema } from './agent-session-failure-fact-schema' import type { AgentJournalSubmission } from '../journal/agent-session-journal-types' import { agentSessionWriteNoticeEnglish } from './agent-session-refusal-notice' import { @@ -57,3 +58,43 @@ describe('the line under a recorded rejection', () => { expect(line('Written by the host.', signedOut)).toBe('Your message was not sent.') }) }) + +// Clients reword a recorded rejection from its fact and their own `{ agentName }` alone. +describe('an agent update the refused model needs', () => { + const rejected = (rejection: unknown) => + agentSessionWriteNoticeEnglish( + structuredAgentSessionRecordedRejectionParts( + { + clientMessageId: 'sent', + fence: 1, + payloadFingerprint: 'sent', + dispatchState: 'rejected', + providerItemId: null, + reason: 'Written by the host.', + submittedAt: 1, + resolvedAt: 2, + rejection: AgentSessionFailureFactSchema.parse(rejection) + } satisfies AgentJournalSubmission, + { agentName: 'OMP' }, + [] + ) + ) + const fact = (agentUpdate?: string) => ({ + kind: 'modelUnavailable', + detail: { text: '@worker_be', audience: 'log' }, + ...(agentUpdate === undefined ? {} : { agentUpdate }) + }) + + it('survives the journal and names the release to update to', () => { + expect(rejected(fact('18.1.9'))).toContain( + "OMP couldn't use @worker_be. Update OMP to 18.1.9 or later to keep it after a restart, or pick another model and send again." + ) + expect(rejected(fact())).toContain( + "OMP couldn't use @worker_be. Pick another model and send again." + ) + }) + + it("keeps the host's sentence when the release is not a version this reader can place", () => { + expect(rejected(fact('latest'))).toContain('Written by the host.') + }) +}) diff --git a/src/shared/agent-session/options/agent-session-option-catalog-omp.test.ts b/src/shared/agent-session/options/agent-session-option-catalog-omp.test.ts index 1cf96e96785..365e8e1af07 100644 --- a/src/shared/agent-session/options/agent-session-option-catalog-omp.test.ts +++ b/src/shared/agent-session/options/agent-session-option-catalog-omp.test.ts @@ -1,8 +1,8 @@ import { describe, expect, it } from 'vitest' import './agent-session-option-catalog-omp' -import './agent-session-option-launch' import '../../native-chat/input/native-chat-session-option-commands' import { parseOmpModelList } from '../../omp-model-list-probe' +import { resolveAgentSessionOptionLaunch } from './agent-session-option-launch' const LISTING = JSON.stringify({ models: [ @@ -68,3 +68,15 @@ describe('omp model list probe', () => { } }) }) + +describe('omp thinking', () => { + it.each(['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'auto'])( + 'launches OMP with every level its --thinking takes (%s)', + (effort) => { + expect(resolveAgentSessionOptionLaunch('omp', { effort }, [], false).args).toEqual([ + '--thinking', + effort + ]) + } + ) +}) diff --git a/src/shared/agent-session/options/agent-session-option-catalog-omp.ts b/src/shared/agent-session/options/agent-session-option-catalog-omp.ts index 2a297073f4d..32f15ff8eb2 100644 --- a/src/shared/agent-session/options/agent-session-option-catalog-omp.ts +++ b/src/shared/agent-session/options/agent-session-option-catalog-omp.ts @@ -1,5 +1,9 @@ import { agentChoiceCliApply } from '../../agent-launch/choices/agent-choice-cli-apply' -import type { AgentSessionOptionCatalog, CatalogModel } from './agent-session-option-catalog-types' +import type { + AgentSessionOptionCatalog, + CatalogModel, + CatalogOption +} from './agent-session-option-catalog-types' import { parseOmpModelList } from '../../omp-model-list-probe' /** Private enrichment-gate parser with option-free rows; actual probes parse through agent-model-probe-spec.ts. */ @@ -7,6 +11,33 @@ function parseOmpCatalogModels(stdout: string): CatalogModel[] { return parseOmpModelList(stdout).map((model) => ({ ...model, options: [] })) } +// Every level `omp --thinking` accepts. +const OMP_THINKING: CatalogOption = { + id: 'effort', + label: 'Thinking', + category: 'thought_level', + kind: { + type: 'select', + choices: [ + { value: 'off', label: 'Off' }, + { value: 'minimal', label: 'Minimal' }, + { value: 'low', label: 'Low' }, + { value: 'medium', label: 'Medium' }, + { value: 'high', label: 'High' }, + { value: 'xhigh', label: 'Extra high' }, + { value: 'max', label: 'Max' }, + { value: 'auto', label: 'Auto' } + ], + // OMP's own config decides the level when none is sent; no listed choice stands for it. + defaultValue: '' + }, + apply: agentChoiceCliApply( + 'omp', + [{ kind: 'value', names: ['--thinking'], lift: 'separate-and-long-equals' }], + '--thinking' + ) +} + export const OMP_SESSION_OPTION_CATALOG: AgentSessionOptionCatalog = { supportsWorkerLaunchPreferences: true, // OMP models depend on configured provider keys; unknown /model IDs fail. Seed none, discover picker rows, and retain the hook-reported current model. @@ -28,5 +59,6 @@ export const OMP_SESSION_OPTION_CATALOG: AgentSessionOptionCatalog = { }, // Saved model IDs remain launch selections even when discovery no longer lists them. discoveredModelsAreAuthoritative: true, + unknownModelOptions: [OMP_THINKING], listModels: { command: 'omp models --json', parse: parseOmpCatalogModels } } diff --git a/src/shared/agent-session/requests/structured-agent-session-dispatch-rejection.test.ts b/src/shared/agent-session/requests/structured-agent-session-dispatch-rejection.test.ts index 63ca6dc5a8d..ac2f783cd16 100644 --- a/src/shared/agent-session/requests/structured-agent-session-dispatch-rejection.test.ts +++ b/src/shared/agent-session/requests/structured-agent-session-dispatch-rejection.test.ts @@ -36,7 +36,9 @@ describe('classifyDispatchRejection', () => { ['writeFailed', 'transport', 'failure'], ['queueFull', 'transport', 'failure'], // The chat's state refused a queued command when its turn to run came. - ['commandRefused', 'content', 'failure'] + ['commandRefused', 'content', 'failure'], + // The agent had no model for the message: its own refusal, not a lost send. + ['modelNotSelected', 'content', 'failure'] ] as const)('reads the written %s rejection as %s, verdict %s', (kind, category, verdict) => { const written = agentSessionFailureWords(agentSessionFailureFact(kind), { surface: 'rejection', diff --git a/src/shared/agent-session/requests/structured-agent-session-dispatch-rejection.ts b/src/shared/agent-session/requests/structured-agent-session-dispatch-rejection.ts index cb4c4b58589..84958e89c46 100644 --- a/src/shared/agent-session/requests/structured-agent-session-dispatch-rejection.ts +++ b/src/shared/agent-session/requests/structured-agent-session-dispatch-rejection.ts @@ -89,6 +89,7 @@ const KIND_CATEGORY = { restartFailed: 'startFailed', providerRejected: 'content', modelUnavailable: 'content', + modelNotSelected: 'content', claudeEffortInvalid: 'content', attachmentInvalid: 'content', attachmentUnreadable: 'content', @@ -131,6 +132,7 @@ const KIND_VERDICT = { restartFailed: 'failure', providerRejected: 'failure', modelUnavailable: 'failure', + modelNotSelected: 'failure', claudeEffortInvalid: 'failure', attachmentInvalid: 'failure', attachmentUnreadable: 'failure',